thread_tree.cpp revision 52190a377feeb1dccaae5034c51f0130c24dea09
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 <inttypes.h>
20
21#include <limits>
22
23#include <android-base/logging.h>
24#include <android-base/stringprintf.h>
25
26#include "perf_event.h"
27#include "record.h"
28
29namespace simpleperf {
30
31bool MapComparator::operator()(const MapEntry* map1,
32                               const MapEntry* map2) const {
33  if (map1->start_addr != map2->start_addr) {
34    return map1->start_addr < map2->start_addr;
35  }
36  // Compare map->len instead of map->get_end_addr() here. Because we set map's
37  // len to std::numeric_limits<uint64_t>::max() in FindMapByAddr(), which makes
38  // map->get_end_addr() overflow.
39  if (map1->len != map2->len) {
40    return map1->len < map2->len;
41  }
42  if (map1->time != map2->time) {
43    return map1->time < map2->time;
44  }
45  return false;
46}
47
48void ThreadTree::SetThreadName(int pid, int tid, const std::string& comm) {
49  ThreadEntry* thread = FindThreadOrNew(pid, tid);
50  if (comm != thread->comm) {
51    thread_comm_storage_.push_back(
52        std::unique_ptr<std::string>(new std::string(comm)));
53    thread->comm = thread_comm_storage_.back()->c_str();
54  }
55}
56
57void ThreadTree::ForkThread(int pid, int tid, int ppid, int ptid) {
58  ThreadEntry* parent = FindThreadOrNew(ppid, ptid);
59  ThreadEntry* child = FindThreadOrNew(pid, tid);
60  child->comm = parent->comm;
61  if (pid != ppid) {
62    // Copy maps from parent process.
63    *child->maps = *parent->maps;
64  }
65}
66
67ThreadEntry* ThreadTree::FindThreadOrNew(int pid, int tid) {
68  auto it = thread_tree_.find(tid);
69  if (it == thread_tree_.end()) {
70    return CreateThread(pid, tid);
71  } else {
72    if (pid != it->second.get()->pid) {
73      // TODO: b/22185053.
74      LOG(DEBUG) << "unexpected (pid, tid) pair: expected ("
75                 << it->second.get()->pid << ", " << tid << "), actual (" << pid
76                 << ", " << tid << ")";
77    }
78  }
79  return it->second.get();
80}
81
82ThreadEntry* ThreadTree::CreateThread(int pid, int tid) {
83  MapSet* maps = nullptr;
84  if (pid == tid) {
85    maps = new MapSet;
86    map_set_storage_.push_back(std::unique_ptr<MapSet>(maps));
87  } else {
88    // Share maps among threads in the same thread group.
89    ThreadEntry* process = FindThreadOrNew(pid, pid);
90    maps = process->maps;
91  }
92  ThreadEntry* thread = new ThreadEntry{
93    pid, tid,
94    "unknown",
95    maps,
96  };
97  auto pair = thread_tree_.insert(std::make_pair(tid, std::unique_ptr<ThreadEntry>(thread)));
98  CHECK(pair.second);
99  return thread;
100}
101
102void ThreadTree::AddKernelMap(uint64_t start_addr, uint64_t len, uint64_t pgoff,
103                              uint64_t time, const std::string& filename) {
104  // kernel map len can be 0 when record command is not run in supervisor mode.
105  if (len == 0) {
106    return;
107  }
108  Dso* dso = FindKernelDsoOrNew(filename);
109  MapEntry* map =
110      AllocateMap(MapEntry(start_addr, len, pgoff, time, dso, true));
111  FixOverlappedMap(&kernel_maps_, map);
112  auto pair = kernel_maps_.insert(map);
113  CHECK(pair.second);
114}
115
116Dso* ThreadTree::FindKernelDsoOrNew(const std::string& filename) {
117  if (filename == DEFAULT_KERNEL_MMAP_NAME ||
118      filename == DEFAULT_KERNEL_MMAP_NAME_PERF) {
119    return kernel_dso_.get();
120  }
121  auto it = module_dso_tree_.find(filename);
122  if (it == module_dso_tree_.end()) {
123    module_dso_tree_[filename] = Dso::CreateDso(DSO_KERNEL_MODULE, filename);
124    it = module_dso_tree_.find(filename);
125  }
126  return it->second.get();
127}
128
129void ThreadTree::AddThreadMap(int pid, int tid, uint64_t start_addr,
130                              uint64_t len, uint64_t pgoff, uint64_t time,
131                              const std::string& filename) {
132  ThreadEntry* thread = FindThreadOrNew(pid, tid);
133  Dso* dso = FindUserDsoOrNew(filename, start_addr);
134  MapEntry* map =
135      AllocateMap(MapEntry(start_addr, len, pgoff, time, dso, false));
136  FixOverlappedMap(thread->maps, map);
137  auto pair = thread->maps->insert(map);
138  CHECK(pair.second);
139}
140
141Dso* ThreadTree::FindUserDsoOrNew(const std::string& filename, uint64_t start_addr) {
142  auto it = user_dso_tree_.find(filename);
143  if (it == user_dso_tree_.end()) {
144    bool force_64bit = start_addr > UINT_MAX;
145    user_dso_tree_[filename] = Dso::CreateDso(DSO_ELF_FILE, filename, force_64bit);
146    it = user_dso_tree_.find(filename);
147  }
148  return it->second.get();
149}
150
151MapEntry* ThreadTree::AllocateMap(const MapEntry& value) {
152  MapEntry* map = new MapEntry(value);
153  map_storage_.push_back(std::unique_ptr<MapEntry>(map));
154  return map;
155}
156
157void ThreadTree::FixOverlappedMap(MapSet* maps, const MapEntry* map) {
158  for (auto it = maps->begin(); it != maps->end();) {
159    if ((*it)->start_addr >= map->get_end_addr()) {
160      // No more overlapped maps.
161      break;
162    }
163    if ((*it)->get_end_addr() <= map->start_addr) {
164      ++it;
165    } else {
166      MapEntry* old = *it;
167      if (old->start_addr < map->start_addr) {
168        MapEntry* before = AllocateMap(
169            MapEntry(old->start_addr, map->start_addr - old->start_addr,
170                     old->pgoff, old->time, old->dso, old->in_kernel));
171        maps->insert(before);
172      }
173      if (old->get_end_addr() > map->get_end_addr()) {
174        MapEntry* after = AllocateMap(MapEntry(
175            map->get_end_addr(), old->get_end_addr() - map->get_end_addr(),
176            map->get_end_addr() - old->start_addr + old->pgoff, old->time,
177            old->dso, old->in_kernel));
178        maps->insert(after);
179      }
180
181      it = maps->erase(it);
182    }
183  }
184}
185
186static bool IsAddrInMap(uint64_t addr, const MapEntry* map) {
187  return (addr >= map->start_addr && addr < map->get_end_addr());
188}
189
190static MapEntry* FindMapByAddr(const MapSet& maps, uint64_t addr) {
191  // Construct a map_entry which is strictly after the searched map_entry, based
192  // on MapComparator.
193  MapEntry find_map(addr, std::numeric_limits<uint64_t>::max(), 0,
194                    std::numeric_limits<uint64_t>::max(), nullptr, false);
195  auto it = maps.upper_bound(&find_map);
196  if (it != maps.begin() && IsAddrInMap(addr, *--it)) {
197    return *it;
198  }
199  return nullptr;
200}
201
202const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip,
203                                    bool in_kernel) {
204  MapEntry* result = nullptr;
205  if (!in_kernel) {
206    result = FindMapByAddr(*thread->maps, ip);
207  } else {
208    result = FindMapByAddr(kernel_maps_, ip);
209  }
210  return result != nullptr ? result : &unknown_map_;
211}
212
213const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip) {
214  MapEntry* result = FindMapByAddr(*thread->maps, ip);
215  if (result != nullptr) {
216    return result;
217  }
218  result = FindMapByAddr(kernel_maps_, ip);
219  return result != nullptr ? result : &unknown_map_;
220}
221
222const Symbol* ThreadTree::FindSymbol(const MapEntry* map, uint64_t ip,
223                                     uint64_t* pvaddr_in_file, Dso** pdso) {
224  uint64_t vaddr_in_file;
225  Dso* dso = map->dso;
226  vaddr_in_file = ip - map->start_addr + map->dso->MinVirtualAddress();
227  const Symbol* symbol = dso->FindSymbol(vaddr_in_file);
228  if (symbol == nullptr && map->in_kernel && dso != kernel_dso_.get()) {
229    // It is in a kernel module, but we can't find the kernel module file, or
230    // the kernel module file contains no symbol. Try finding the symbol in
231    // /proc/kallsyms.
232    vaddr_in_file = ip;
233    dso = kernel_dso_.get();
234    symbol = dso->FindSymbol(vaddr_in_file);
235  }
236  if (symbol == nullptr) {
237    if (show_ip_for_unknown_symbol_) {
238      std::string name = android::base::StringPrintf(
239          "%s%s[+%" PRIx64 "]", (show_mark_for_unknown_symbol_ ? "*" : ""),
240          dso->FileName().c_str(), vaddr_in_file);
241      dso->AddUnknownSymbol(vaddr_in_file, name);
242      symbol = dso->FindSymbol(vaddr_in_file);
243      CHECK(symbol != nullptr);
244    } else {
245      symbol = &unknown_symbol_;
246    }
247  }
248  if (pvaddr_in_file != nullptr) {
249    *pvaddr_in_file = vaddr_in_file;
250  }
251  if (pdso != nullptr) {
252    *pdso = dso;
253  }
254  return symbol;
255}
256
257const Symbol* ThreadTree::FindKernelSymbol(uint64_t ip) {
258  const MapEntry* map = FindMap(nullptr, ip, true);
259  return FindSymbol(map, ip, nullptr);
260}
261
262void ThreadTree::ClearThreadAndMap() {
263  thread_tree_.clear();
264  thread_comm_storage_.clear();
265  map_set_storage_.clear();
266  kernel_maps_.clear();
267  map_storage_.clear();
268}
269
270void ThreadTree::AddDsoInfo(const std::string& file_path, uint32_t file_type,
271                            uint64_t min_vaddr, std::vector<Symbol>* symbols) {
272  DsoType dso_type = static_cast<DsoType>(file_type);
273  Dso* dso = nullptr;
274  if (dso_type == DSO_KERNEL || dso_type == DSO_KERNEL_MODULE) {
275    dso = FindKernelDsoOrNew(file_path);
276  } else {
277    dso = FindUserDsoOrNew(file_path);
278  }
279  dso->SetMinVirtualAddress(min_vaddr);
280  dso->SetSymbols(symbols);
281}
282
283void ThreadTree::Update(const Record& record) {
284  if (record.type() == PERF_RECORD_MMAP) {
285    const MmapRecord& r = *static_cast<const MmapRecord*>(&record);
286    if (r.InKernel()) {
287      AddKernelMap(r.data->addr, r.data->len, r.data->pgoff,
288                   r.sample_id.time_data.time, r.filename);
289    } else {
290      AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len,
291                   r.data->pgoff, r.sample_id.time_data.time, r.filename);
292    }
293  } else if (record.type() == PERF_RECORD_MMAP2) {
294    const Mmap2Record& r = *static_cast<const Mmap2Record*>(&record);
295    if (r.InKernel()) {
296      AddKernelMap(r.data->addr, r.data->len, r.data->pgoff,
297                   r.sample_id.time_data.time, r.filename);
298    } else {
299      std::string filename = (r.filename == DEFAULT_EXECNAME_FOR_THREAD_MMAP)
300                                 ? "[unknown]"
301                                 : r.filename;
302      AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len,
303                   r.data->pgoff, r.sample_id.time_data.time, filename);
304    }
305  } else if (record.type() == PERF_RECORD_COMM) {
306    const CommRecord& r = *static_cast<const CommRecord*>(&record);
307    SetThreadName(r.data->pid, r.data->tid, r.comm);
308  } else if (record.type() == PERF_RECORD_FORK) {
309    const ForkRecord& r = *static_cast<const ForkRecord*>(&record);
310    ForkThread(r.data->pid, r.data->tid, r.data->ppid, r.data->ptid);
311  } else if (record.type() == SIMPLE_PERF_RECORD_KERNEL_SYMBOL) {
312    const auto& r = *static_cast<const KernelSymbolRecord*>(&record);
313    Dso::SetKallsyms(std::move(r.kallsyms));
314  }
315}
316
317std::vector<Dso*> ThreadTree::GetAllDsos() const {
318  std::vector<Dso*> result;
319  result.push_back(kernel_dso_.get());
320  for (auto& p : module_dso_tree_) {
321    result.push_back(p.second.get());
322  }
323  for (auto& p : user_dso_tree_) {
324    result.push_back(p.second.get());
325  }
326  result.push_back(unknown_dso_.get());
327  return result;
328}
329
330std::vector<const ThreadEntry*> ThreadTree::GetAllThreads() const {
331  std::vector<const ThreadEntry*> threads;
332  for (auto& pair : thread_tree_) {
333    threads.push_back(pair.second.get());
334  }
335  return threads;
336}
337
338}  // namespace simpleperf
339