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 #include <android-base/strings.h>
26
27 #include "perf_event.h"
28 #include "record.h"
29 #include "record_file.h"
30 #include "utils.h"
31
32 namespace simpleperf {
33 namespace {
34
35 // Real map file path depends on where the process can create files.
36 // For example, app can create files only in its data directory.
37 // Use normalized name inherited from pid instead.
GetSymbolMapDsoName(int pid)38 std::string GetSymbolMapDsoName(int pid) {
39 return android::base::StringPrintf("perf-%d.map", pid);
40 }
41
42 } // namespace
43
SetThreadName(int pid,int tid,const std::string & comm)44 void ThreadTree::SetThreadName(int pid, int tid, const std::string& comm) {
45 ThreadEntry* thread = FindThreadOrNew(pid, tid);
46 if (comm != thread->comm) {
47 thread_comm_storage_.push_back(std::unique_ptr<std::string>(new std::string(comm)));
48 thread->comm = thread_comm_storage_.back()->c_str();
49 }
50 }
51
ForkThread(int pid,int tid,int ppid,int ptid)52 bool ThreadTree::ForkThread(int pid, int tid, int ppid, int ptid) {
53 // Check thread ID.
54 if (tid == ptid) {
55 return false;
56 }
57 // Check thread group ID (pid here) as in https://linux.die.net/man/2/clone2.
58 if (pid != tid && pid != ppid) {
59 return false;
60 }
61 ThreadEntry* parent = FindThreadOrNew(ppid, ptid);
62 ThreadEntry* child = FindThreadOrNew(pid, tid);
63 child->comm = parent->comm;
64 if (pid != ppid) {
65 // Copy maps from parent process.
66 if (child->maps->maps.empty()) {
67 *child->maps = *parent->maps;
68 } else {
69 CHECK_NE(child->maps, parent->maps);
70 for (auto& pair : parent->maps->maps) {
71 InsertMap(*child->maps, *pair.second);
72 }
73 }
74 }
75 return true;
76 }
77
FindThread(int tid) const78 ThreadEntry* ThreadTree::FindThread(int tid) const {
79 if (auto it = thread_tree_.find(tid); it != thread_tree_.end()) {
80 return it->second.get();
81 }
82 return nullptr;
83 }
84
FindThreadOrNew(int pid,int tid)85 ThreadEntry* ThreadTree::FindThreadOrNew(int pid, int tid) {
86 auto it = thread_tree_.find(tid);
87 if (it != thread_tree_.end() && pid == it->second.get()->pid) {
88 return it->second.get();
89 }
90 if (it != thread_tree_.end()) {
91 ExitThread(it->second.get()->pid, tid);
92 }
93 return CreateThread(pid, tid);
94 }
95
CreateThread(int pid,int tid)96 ThreadEntry* ThreadTree::CreateThread(int pid, int tid) {
97 const char* comm;
98 std::shared_ptr<MapSet> maps;
99 if (pid == tid) {
100 comm = "unknown";
101 maps.reset(new MapSet);
102 } else {
103 // Share maps among threads in the same thread group.
104 ThreadEntry* process = FindThreadOrNew(pid, pid);
105 comm = process->comm;
106 maps = process->maps;
107 }
108 ThreadEntry* thread = new ThreadEntry{
109 pid,
110 tid,
111 comm,
112 maps,
113 };
114 auto pair = thread_tree_.insert(std::make_pair(tid, std::unique_ptr<ThreadEntry>(thread)));
115 CHECK(pair.second);
116 if (pid == tid) {
117 // If there is a symbol map dso for the process, add maps for the symbols.
118 auto name = GetSymbolMapDsoName(pid);
119 auto it = user_dso_tree_.find(name);
120 if (it != user_dso_tree_.end()) {
121 AddThreadMapsForDsoSymbols(thread, it->second.get());
122 }
123 }
124 return thread;
125 }
126
ExitThread(int pid,int tid)127 void ThreadTree::ExitThread(int pid, int tid) {
128 auto it = thread_tree_.find(tid);
129 if (it != thread_tree_.end() && pid == it->second.get()->pid) {
130 thread_tree_.erase(it);
131 }
132 }
133
AddKernelMap(uint64_t start_addr,uint64_t len,uint64_t pgoff,const std::string & filename)134 void ThreadTree::AddKernelMap(uint64_t start_addr, uint64_t len, uint64_t pgoff,
135 const std::string& filename) {
136 // kernel map len can be 0 when record command is not run in supervisor mode.
137 if (len == 0) {
138 return;
139 }
140 Dso* dso;
141 if (android::base::StartsWith(filename, DEFAULT_KERNEL_MMAP_NAME) ||
142 android::base::StartsWith(filename, DEFAULT_KERNEL_BPF_MMAP_NAME)) {
143 dso = FindKernelDsoOrNew();
144 } else {
145 dso = FindKernelModuleDsoOrNew(filename, start_addr, start_addr + len);
146 }
147 InsertMap(kernel_maps_, MapEntry(start_addr, len, pgoff, dso, true));
148 }
149
FindKernelDsoOrNew()150 Dso* ThreadTree::FindKernelDsoOrNew() {
151 if (!kernel_dso_) {
152 kernel_dso_ = Dso::CreateDso(DSO_KERNEL, DEFAULT_KERNEL_MMAP_NAME);
153 }
154 return kernel_dso_.get();
155 }
156
FindKernelModuleDsoOrNew(const std::string & filename,uint64_t memory_start,uint64_t memory_end)157 Dso* ThreadTree::FindKernelModuleDsoOrNew(const std::string& filename, uint64_t memory_start,
158 uint64_t memory_end) {
159 auto it = module_dso_tree_.find(filename);
160 if (it == module_dso_tree_.end()) {
161 module_dso_tree_[filename] =
162 Dso::CreateKernelModuleDso(filename, memory_start, memory_end, FindKernelDsoOrNew());
163 it = module_dso_tree_.find(filename);
164 }
165 return it->second.get();
166 }
167
AddThreadMap(int pid,int tid,uint64_t start_addr,uint64_t len,uint64_t pgoff,const std::string & filename,uint32_t flags)168 void ThreadTree::AddThreadMap(int pid, int tid, uint64_t start_addr, uint64_t len, uint64_t pgoff,
169 const std::string& filename, uint32_t flags) {
170 ThreadEntry* thread = FindThreadOrNew(pid, tid);
171 Dso* dso = FindUserDsoOrNew(filename, start_addr);
172 CHECK(dso != nullptr);
173 InsertMap(*thread->maps, MapEntry(start_addr, len, pgoff, dso, false, flags));
174 }
175
AddThreadMapsForDsoSymbols(ThreadEntry * thread,Dso * dso)176 void ThreadTree::AddThreadMapsForDsoSymbols(ThreadEntry* thread, Dso* dso) {
177 const uint64_t page_size = GetPageSize();
178
179 auto maps = thread->maps;
180
181 uint64_t map_start = 0;
182 uint64_t map_end = 0;
183
184 // Dso symbols are sorted by address. Walk and calculate containing pages.
185 for (const auto& sym : dso->GetSymbols()) {
186 uint64_t sym_map_start = AlignDown(sym.addr, page_size);
187 uint64_t sym_map_end = Align(sym.addr + sym.len, page_size);
188
189 if (map_end < sym_map_start) {
190 if (map_start < map_end) {
191 InsertMap(*maps, MapEntry(map_start, map_end - map_start, map_start, dso, false, 0));
192 }
193 map_start = sym_map_start;
194 }
195 if (map_end < sym_map_end) {
196 map_end = sym_map_end;
197 }
198 }
199
200 if (map_start < map_end) {
201 InsertMap(*maps, MapEntry(map_start, map_end - map_start, map_start, dso, false, 0));
202 }
203 }
204
FindUserDso(const std::string & filename)205 Dso* ThreadTree::FindUserDso(const std::string& filename) {
206 auto it = user_dso_tree_.find(filename);
207 if (it == user_dso_tree_.end()) {
208 return nullptr;
209 }
210 return it->second.get();
211 }
212
FindUserDsoOrNew(const std::string & filename,uint64_t start_addr,DsoType dso_type)213 Dso* ThreadTree::FindUserDsoOrNew(const std::string& filename, uint64_t start_addr,
214 DsoType dso_type) {
215 auto it = user_dso_tree_.find(filename);
216 if (it == user_dso_tree_.end()) {
217 bool force_64bit = start_addr > UINT_MAX;
218 std::unique_ptr<Dso> dso = Dso::CreateDso(dso_type, filename, force_64bit);
219 if (!dso) {
220 return nullptr;
221 }
222 auto pair = user_dso_tree_.insert(std::make_pair(filename, std::move(dso)));
223 CHECK(pair.second);
224 it = pair.first;
225 }
226 return it->second.get();
227 }
228
AddSymbolsForProcess(int pid,std::vector<Symbol> * symbols)229 void ThreadTree::AddSymbolsForProcess(int pid, std::vector<Symbol>* symbols) {
230 auto name = GetSymbolMapDsoName(pid);
231
232 auto dso = FindUserDsoOrNew(name, 0, DSO_SYMBOL_MAP_FILE);
233 dso->SetSymbols(symbols);
234
235 auto thread = FindThreadOrNew(pid, pid);
236 AddThreadMapsForDsoSymbols(thread, dso);
237 }
238
AllocateMap(const MapEntry & entry)239 const MapEntry* ThreadTree::AllocateMap(const MapEntry& entry) {
240 map_storage_.emplace_back(new MapEntry(entry));
241 return map_storage_.back().get();
242 }
243
RemoveFirstPartOfMapEntry(const MapEntry * entry,uint64_t new_start_addr)244 static MapEntry RemoveFirstPartOfMapEntry(const MapEntry* entry, uint64_t new_start_addr) {
245 MapEntry result = *entry;
246 result.start_addr = new_start_addr;
247 result.len -= result.start_addr - entry->start_addr;
248 result.pgoff += result.start_addr - entry->start_addr;
249 return result;
250 }
251
RemoveSecondPartOfMapEntry(const MapEntry * entry,uint64_t new_len)252 static MapEntry RemoveSecondPartOfMapEntry(const MapEntry* entry, uint64_t new_len) {
253 MapEntry result = *entry;
254 result.len = new_len;
255 return result;
256 }
257
258 // Insert a new map entry in a MapSet. If some existing map entries overlap the new map entry,
259 // then remove the overlapped parts.
InsertMap(MapSet & maps,const MapEntry & entry)260 void ThreadTree::InsertMap(MapSet& maps, const MapEntry& entry) {
261 std::map<uint64_t, const MapEntry*>& map = maps.maps;
262 auto it = map.lower_bound(entry.start_addr);
263 // Remove overlapped entry with start_addr < entry.start_addr.
264 if (it != map.begin()) {
265 auto it2 = it;
266 --it2;
267 if (it2->second->get_end_addr() > entry.get_end_addr()) {
268 map.emplace(entry.get_end_addr(),
269 AllocateMap(RemoveFirstPartOfMapEntry(it2->second, entry.get_end_addr())));
270 }
271 if (it2->second->get_end_addr() > entry.start_addr) {
272 it2->second =
273 AllocateMap(RemoveSecondPartOfMapEntry(it2->second, entry.start_addr - it2->first));
274 }
275 }
276 // Remove overlapped entries with start_addr >= entry.start_addr.
277 while (it != map.end() && it->second->get_end_addr() <= entry.get_end_addr()) {
278 it = map.erase(it);
279 }
280 if (it != map.end() && it->second->start_addr < entry.get_end_addr()) {
281 map.emplace(entry.get_end_addr(),
282 AllocateMap(RemoveFirstPartOfMapEntry(it->second, entry.get_end_addr())));
283 map.erase(it);
284 }
285 // Insert the new entry.
286 map.emplace(entry.start_addr, AllocateMap(entry));
287 maps.version++;
288 }
289
FindMapByAddr(uint64_t addr) const290 const MapEntry* MapSet::FindMapByAddr(uint64_t addr) const {
291 auto it = maps.upper_bound(addr);
292 if (it != maps.begin()) {
293 --it;
294 if (it->second->get_end_addr() > addr) {
295 return it->second;
296 }
297 }
298 return nullptr;
299 }
300
FindMap(const ThreadEntry * thread,uint64_t ip,bool in_kernel)301 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip, bool in_kernel) {
302 const MapEntry* result = nullptr;
303 if (!in_kernel) {
304 result = thread->maps->FindMapByAddr(ip);
305 } else {
306 result = kernel_maps_.FindMapByAddr(ip);
307 }
308 return result != nullptr ? result : &unknown_map_;
309 }
310
FindMap(const ThreadEntry * thread,uint64_t ip)311 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip) {
312 const MapEntry* result = thread->maps->FindMapByAddr(ip);
313 if (result != nullptr) {
314 return result;
315 }
316 result = kernel_maps_.FindMapByAddr(ip);
317 return result != nullptr ? result : &unknown_map_;
318 }
319
FindSymbol(const MapEntry * map,uint64_t ip,uint64_t * pvaddr_in_file,Dso ** pdso)320 const Symbol* ThreadTree::FindSymbol(const MapEntry* map, uint64_t ip, uint64_t* pvaddr_in_file,
321 Dso** pdso) {
322 uint64_t vaddr_in_file = 0;
323 const Symbol* symbol = nullptr;
324 Dso* dso = map->dso;
325 if (map->flags & map_flags::PROT_JIT_SYMFILE_MAP) {
326 vaddr_in_file = ip;
327 } else {
328 vaddr_in_file = dso->IpToVaddrInFile(ip, map->start_addr, map->pgoff);
329 }
330 symbol = dso->FindSymbol(vaddr_in_file);
331 if (symbol == nullptr && dso->type() == DSO_KERNEL_MODULE) {
332 // If the ip address hits the vmlinux, or hits a kernel module, but we can't find its symbol
333 // in the kernel module file, then find its symbol in /proc/kallsyms or vmlinux.
334 vaddr_in_file = ip;
335 dso = FindKernelDsoOrNew();
336 symbol = dso->FindSymbol(vaddr_in_file);
337 }
338
339 if (symbol == nullptr) {
340 if (show_ip_for_unknown_symbol_) {
341 std::string name = android::base::StringPrintf("%s%s[+%" PRIx64 "]",
342 (show_mark_for_unknown_symbol_ ? "*" : ""),
343 dso->FileName().c_str(), vaddr_in_file);
344 dso->AddUnknownSymbol(vaddr_in_file, name);
345 symbol = dso->FindSymbol(vaddr_in_file);
346 CHECK(symbol != nullptr);
347 } else {
348 symbol = &unknown_symbol_;
349 }
350 }
351 if (pvaddr_in_file != nullptr) {
352 *pvaddr_in_file = vaddr_in_file;
353 }
354 if (pdso != nullptr) {
355 *pdso = dso;
356 }
357 return symbol;
358 }
359
FindKernelSymbol(uint64_t ip)360 const Symbol* ThreadTree::FindKernelSymbol(uint64_t ip) {
361 const MapEntry* map = FindMap(nullptr, ip, true);
362 return FindSymbol(map, ip, nullptr);
363 }
364
ClearThreadAndMap()365 void ThreadTree::ClearThreadAndMap() {
366 thread_tree_.clear();
367 thread_comm_storage_.clear();
368 kernel_maps_.maps.clear();
369 map_storage_.clear();
370 }
371
AddDsoInfo(FileFeature & file)372 bool ThreadTree::AddDsoInfo(FileFeature& file) {
373 DsoType dso_type = file.type;
374 Dso* dso = nullptr;
375 if (dso_type == DSO_KERNEL) {
376 dso = FindKernelDsoOrNew();
377 } else if (dso_type == DSO_KERNEL_MODULE) {
378 dso = FindKernelModuleDsoOrNew(file.path, 0, 0);
379 } else {
380 dso = FindUserDsoOrNew(file.path, 0, dso_type);
381 }
382 if (!dso) {
383 return false;
384 }
385 dso->SetMinExecutableVaddr(file.min_vaddr, file.file_offset_of_min_vaddr);
386 dso->SetSymbols(&file.symbols);
387 for (uint64_t offset : file.dex_file_offsets) {
388 dso->AddDexFileOffset(offset);
389 }
390 return true;
391 }
392
AddDexFileOffset(const std::string & file_path,uint64_t dex_file_offset)393 void ThreadTree::AddDexFileOffset(const std::string& file_path, uint64_t dex_file_offset) {
394 Dso* dso = FindUserDsoOrNew(file_path, 0, DSO_DEX_FILE);
395 dso->AddDexFileOffset(dex_file_offset);
396 }
397
Update(const Record & record)398 void ThreadTree::Update(const Record& record) {
399 if (record.type() == PERF_RECORD_MMAP) {
400 const MmapRecord& r = *static_cast<const MmapRecord*>(&record);
401 if (r.InKernel()) {
402 AddKernelMap(r.data->addr, r.data->len, r.data->pgoff, r.filename);
403 } else {
404 AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len, r.data->pgoff, r.filename);
405 }
406 } else if (record.type() == PERF_RECORD_MMAP2) {
407 const Mmap2Record& r = *static_cast<const Mmap2Record*>(&record);
408 if (r.InKernel()) {
409 AddKernelMap(r.data->addr, r.data->len, r.data->pgoff, r.filename);
410 } else {
411 std::string filename =
412 (r.filename == DEFAULT_EXECNAME_FOR_THREAD_MMAP) ? "[unknown]" : r.filename;
413 AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len, r.data->pgoff, filename,
414 r.data->prot);
415 }
416 } else if (record.type() == PERF_RECORD_COMM) {
417 const CommRecord& r = *static_cast<const CommRecord*>(&record);
418 SetThreadName(r.data->pid, r.data->tid, r.comm);
419 } else if (record.type() == PERF_RECORD_FORK) {
420 const ForkRecord& r = *static_cast<const ForkRecord*>(&record);
421 ForkThread(r.data->pid, r.data->tid, r.data->ppid, r.data->ptid);
422 } else if (record.type() == PERF_RECORD_EXIT) {
423 if (!disable_thread_exit_records_) {
424 const ExitRecord& r = *static_cast<const ExitRecord*>(&record);
425 ExitThread(r.data->pid, r.data->tid);
426 }
427 } else if (record.type() == SIMPLE_PERF_RECORD_KERNEL_SYMBOL) {
428 const auto& r = *static_cast<const KernelSymbolRecord*>(&record);
429 Dso::SetKallsyms(std::string(r.kallsyms, r.kallsyms_size));
430 }
431 }
432
GetAllDsos() const433 std::vector<Dso*> ThreadTree::GetAllDsos() const {
434 std::vector<Dso*> result;
435 if (kernel_dso_) {
436 result.push_back(kernel_dso_.get());
437 }
438 for (auto& p : module_dso_tree_) {
439 result.push_back(p.second.get());
440 }
441 for (auto& p : user_dso_tree_) {
442 result.push_back(p.second.get());
443 }
444 result.push_back(unknown_dso_.get());
445 return result;
446 }
447
448 } // namespace simpleperf
449