thread_tree.cpp revision 547c60e4dd29c5788d5948ad348acf33a55d6ed6
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "thread_tree.h"
18
19#include <limits>
20
21#include <base/logging.h>
22
23#include "environment.h"
24#include "perf_event.h"
25#include "record.h"
26
27bool MapComparator::operator()(const MapEntry* map1, const MapEntry* map2) const {
28  if (map1->start_addr != map2->start_addr) {
29    return map1->start_addr < map2->start_addr;
30  }
31  if (map1->get_end_addr() != map2->get_end_addr()) {
32    return map1->get_end_addr() < map2->get_end_addr();
33  }
34  if (map1->time != map2->time) {
35    return map1->time < map2->time;
36  }
37  return false;
38}
39
40void ThreadTree::AddThread(int pid, int tid, const std::string& comm) {
41  auto it = thread_tree_.find(tid);
42  if (it == thread_tree_.end()) {
43    ThreadEntry* thread = new ThreadEntry{
44        pid, tid,
45        "unknown",                             // comm
46        std::set<MapEntry*, MapComparator>(),  // maps
47    };
48    auto pair = thread_tree_.insert(std::make_pair(tid, std::unique_ptr<ThreadEntry>(thread)));
49    CHECK(pair.second);
50    it = pair.first;
51  }
52  thread_comm_storage_.push_back(std::unique_ptr<std::string>(new std::string(comm)));
53  it->second->comm = thread_comm_storage_.back()->c_str();
54}
55
56void ThreadTree::ForkThread(int pid, int tid, int ppid, int ptid) {
57  ThreadEntry* parent = FindThreadOrNew(ppid, ptid);
58  ThreadEntry* child = FindThreadOrNew(pid, tid);
59  child->comm = parent->comm;
60  child->maps = parent->maps;
61}
62
63ThreadEntry* ThreadTree::FindThreadOrNew(int pid, int tid) {
64  auto it = thread_tree_.find(tid);
65  if (it == thread_tree_.end()) {
66    AddThread(pid, tid, "unknown");
67    it = thread_tree_.find(tid);
68  } else {
69    if (pid != it->second.get()->pid) {
70      // TODO: b/22185053.
71      LOG(DEBUG) << "unexpected (pid, tid) pair: expected (" << it->second.get()->pid << ", " << tid
72                 << "), actual (" << pid << ", " << tid << ")";
73    }
74  }
75  return it->second.get();
76}
77
78void ThreadTree::AddKernelMap(uint64_t start_addr, uint64_t len, uint64_t pgoff, uint64_t time,
79                              const std::string& filename) {
80  // kernel map len can be 0 when record command is not run in supervisor mode.
81  if (len == 0) {
82    return;
83  }
84  Dso* dso = FindKernelDsoOrNew(filename);
85  MapEntry* map = AllocateMap(MapEntry(start_addr, len, pgoff, time, dso));
86  FixOverlappedMap(&kernel_map_tree_, map);
87  auto pair = kernel_map_tree_.insert(map);
88  CHECK(pair.second);
89}
90
91Dso* ThreadTree::FindKernelDsoOrNew(const std::string& filename) {
92  if (filename == DEFAULT_KERNEL_MMAP_NAME) {
93    if (kernel_dso_ == nullptr) {
94      kernel_dso_ = Dso::CreateDso(DSO_KERNEL);
95    }
96    return kernel_dso_.get();
97  }
98  auto it = module_dso_tree_.find(filename);
99  if (it == module_dso_tree_.end()) {
100    module_dso_tree_[filename] = Dso::CreateDso(DSO_KERNEL_MODULE, filename);
101    it = module_dso_tree_.find(filename);
102  }
103  return it->second.get();
104}
105
106void ThreadTree::AddThreadMap(int pid, int tid, uint64_t start_addr, uint64_t len, uint64_t pgoff,
107                              uint64_t time, const std::string& filename) {
108  ThreadEntry* thread = FindThreadOrNew(pid, tid);
109  Dso* dso = FindUserDsoOrNew(filename);
110  MapEntry* map = AllocateMap(MapEntry(start_addr, len, pgoff, time, dso));
111  FixOverlappedMap(&thread->maps, map);
112  auto pair = thread->maps.insert(map);
113  CHECK(pair.second);
114}
115
116Dso* ThreadTree::FindUserDsoOrNew(const std::string& filename) {
117  auto it = user_dso_tree_.find(filename);
118  if (it == user_dso_tree_.end()) {
119    user_dso_tree_[filename] = Dso::CreateDso(DSO_ELF_FILE, filename);
120    it = user_dso_tree_.find(filename);
121  }
122  return it->second.get();
123}
124
125MapEntry* ThreadTree::AllocateMap(const MapEntry& value) {
126  MapEntry* map = new MapEntry(value);
127  map_storage_.push_back(std::unique_ptr<MapEntry>(map));
128  return map;
129}
130
131void ThreadTree::FixOverlappedMap(std::set<MapEntry*, MapComparator>* map_set, const MapEntry* map) {
132  for (auto it = map_set->begin(); it != map_set->end();) {
133    if ((*it)->start_addr >= map->get_end_addr()) {
134      // No more overlapped maps.
135      break;
136    }
137    if ((*it)->get_end_addr() <= map->start_addr) {
138      ++it;
139    } else {
140      MapEntry* old = *it;
141      if (old->start_addr < map->start_addr) {
142        MapEntry* before = AllocateMap(MapEntry(old->start_addr, map->start_addr - old->start_addr,
143                                                old->pgoff, old->time, old->dso));
144        map_set->insert(before);
145      }
146      if (old->get_end_addr() > map->get_end_addr()) {
147        MapEntry* after = AllocateMap(
148            MapEntry(map->get_end_addr(), old->get_end_addr() - map->get_end_addr(),
149                     map->get_end_addr() - old->start_addr + old->pgoff, old->time, old->dso));
150        map_set->insert(after);
151      }
152
153      it = map_set->erase(it);
154    }
155  }
156}
157
158static bool IsAddrInMap(uint64_t addr, const MapEntry* map) {
159  return (addr >= map->start_addr && addr < map->get_end_addr());
160}
161
162static MapEntry* FindMapByAddr(const std::set<MapEntry*, MapComparator>& maps, uint64_t addr) {
163  // Construct a map_entry which is strictly after the searched map_entry, based on MapComparator.
164  MapEntry find_map(addr, std::numeric_limits<uint64_t>::max(), 0,
165                    std::numeric_limits<uint64_t>::max(), nullptr);
166  auto it = maps.upper_bound(&find_map);
167  if (it != maps.begin() && IsAddrInMap(addr, *--it)) {
168    return *it;
169  }
170  return nullptr;
171}
172
173const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip, bool in_kernel) {
174  MapEntry* result = nullptr;
175  if (!in_kernel) {
176    result = FindMapByAddr(thread->maps, ip);
177  } else {
178    result = FindMapByAddr(kernel_map_tree_, ip);
179  }
180  return result != nullptr ? result : &unknown_map_;
181}
182
183const Symbol* ThreadTree::FindSymbol(const MapEntry* map, uint64_t ip) {
184  uint64_t vaddr_in_file;
185  if (map->dso == kernel_dso_.get()) {
186    vaddr_in_file = ip;
187  } else {
188    vaddr_in_file = ip - map->start_addr + map->dso->MinVirtualAddress();
189  }
190  const Symbol* symbol = map->dso->FindSymbol(vaddr_in_file);
191  if (symbol == nullptr) {
192    symbol = &unknown_symbol_;
193  }
194  return symbol;
195}
196
197void BuildThreadTree(const Record& record, ThreadTree* thread_tree) {
198  if (record.header.type == PERF_RECORD_MMAP) {
199    const MmapRecord& r = *static_cast<const MmapRecord*>(&record);
200    if ((r.header.misc & PERF_RECORD_MISC_CPUMODE_MASK) == PERF_RECORD_MISC_KERNEL) {
201      thread_tree->AddKernelMap(r.data.addr, r.data.len, r.data.pgoff, r.sample_id.time_data.time,
202                                r.filename);
203    } else {
204      thread_tree->AddThreadMap(r.data.pid, r.data.tid, r.data.addr, r.data.len, r.data.pgoff,
205                                r.sample_id.time_data.time, r.filename);
206    }
207  } else if (record.header.type == PERF_RECORD_MMAP2) {
208    const Mmap2Record& r = *static_cast<const Mmap2Record*>(&record);
209    if ((r.header.misc & PERF_RECORD_MISC_CPUMODE_MASK) == PERF_RECORD_MISC_KERNEL) {
210      thread_tree->AddKernelMap(r.data.addr, r.data.len, r.data.pgoff, r.sample_id.time_data.time,
211                                r.filename);
212    } else {
213      std::string filename =
214          (r.filename == DEFAULT_EXECNAME_FOR_THREAD_MMAP) ? "[unknown]" : r.filename;
215      thread_tree->AddThreadMap(r.data.pid, r.data.tid, r.data.addr, r.data.len, r.data.pgoff,
216                                r.sample_id.time_data.time, filename);
217    }
218  } else if (record.header.type == PERF_RECORD_COMM) {
219    const CommRecord& r = *static_cast<const CommRecord*>(&record);
220    thread_tree->AddThread(r.data.pid, r.data.tid, r.comm);
221  } else if (record.header.type == PERF_RECORD_FORK) {
222    const ForkRecord& r = *static_cast<const ForkRecord*>(&record);
223    thread_tree->ForkThread(r.data.pid, r.data.tid, r.data.ppid, r.data.ptid);
224  }
225}
226