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 dso = FindKernelDsoOrNew();
143 } else {
144 dso = FindKernelModuleDsoOrNew(filename, start_addr, start_addr + len);
145 }
146 InsertMap(kernel_maps_, MapEntry(start_addr, len, pgoff, dso, true));
147 }
148
FindKernelDsoOrNew()149 Dso* ThreadTree::FindKernelDsoOrNew() {
150 if (!kernel_dso_) {
151 kernel_dso_ = Dso::CreateDso(DSO_KERNEL, DEFAULT_KERNEL_MMAP_NAME);
152 }
153 return kernel_dso_.get();
154 }
155
FindKernelModuleDsoOrNew(const std::string & filename,uint64_t memory_start,uint64_t memory_end)156 Dso* ThreadTree::FindKernelModuleDsoOrNew(const std::string& filename, uint64_t memory_start,
157 uint64_t memory_end) {
158 auto it = module_dso_tree_.find(filename);
159 if (it == module_dso_tree_.end()) {
160 module_dso_tree_[filename] =
161 Dso::CreateKernelModuleDso(filename, memory_start, memory_end, FindKernelDsoOrNew());
162 it = module_dso_tree_.find(filename);
163 }
164 return it->second.get();
165 }
166
AddThreadMap(int pid,int tid,uint64_t start_addr,uint64_t len,uint64_t pgoff,const std::string & filename,uint32_t flags)167 void ThreadTree::AddThreadMap(int pid, int tid, uint64_t start_addr, uint64_t len, uint64_t pgoff,
168 const std::string& filename, uint32_t flags) {
169 ThreadEntry* thread = FindThreadOrNew(pid, tid);
170 Dso* dso = FindUserDsoOrNew(filename, start_addr);
171 CHECK(dso != nullptr);
172 InsertMap(*thread->maps, MapEntry(start_addr, len, pgoff, dso, false, flags));
173 }
174
AddThreadMapsForDsoSymbols(ThreadEntry * thread,Dso * dso)175 void ThreadTree::AddThreadMapsForDsoSymbols(ThreadEntry* thread, Dso* dso) {
176 const uint64_t page_size = GetPageSize();
177
178 auto maps = thread->maps;
179
180 uint64_t map_start = 0;
181 uint64_t map_end = 0;
182
183 // Dso symbols are sorted by address. Walk and calculate containing pages.
184 for (const auto& sym : dso->GetSymbols()) {
185 uint64_t sym_map_start = AlignDown(sym.addr, page_size);
186 uint64_t sym_map_end = Align(sym.addr + sym.len, page_size);
187
188 if (map_end < sym_map_start) {
189 if (map_start < map_end) {
190 InsertMap(*maps, MapEntry(map_start, map_end - map_start, map_start, dso, false, 0));
191 }
192 map_start = sym_map_start;
193 }
194 if (map_end < sym_map_end) {
195 map_end = sym_map_end;
196 }
197 }
198
199 if (map_start < map_end) {
200 InsertMap(*maps, MapEntry(map_start, map_end - map_start, map_start, dso, false, 0));
201 }
202 }
203
FindUserDsoOrNew(const std::string & filename,uint64_t start_addr,DsoType dso_type)204 Dso* ThreadTree::FindUserDsoOrNew(const std::string& filename, uint64_t start_addr,
205 DsoType dso_type) {
206 auto it = user_dso_tree_.find(filename);
207 if (it == user_dso_tree_.end()) {
208 bool force_64bit = start_addr > UINT_MAX;
209 std::unique_ptr<Dso> dso = Dso::CreateDso(dso_type, filename, force_64bit);
210 if (!dso) {
211 return nullptr;
212 }
213 auto pair = user_dso_tree_.insert(std::make_pair(filename, std::move(dso)));
214 CHECK(pair.second);
215 it = pair.first;
216 }
217 return it->second.get();
218 }
219
AddSymbolsForProcess(int pid,std::vector<Symbol> * symbols)220 void ThreadTree::AddSymbolsForProcess(int pid, std::vector<Symbol>* symbols) {
221 auto name = GetSymbolMapDsoName(pid);
222
223 auto dso = FindUserDsoOrNew(name, 0, DSO_SYMBOL_MAP_FILE);
224 dso->SetSymbols(symbols);
225
226 auto thread = FindThreadOrNew(pid, pid);
227 AddThreadMapsForDsoSymbols(thread, dso);
228 }
229
AllocateMap(const MapEntry & entry)230 const MapEntry* ThreadTree::AllocateMap(const MapEntry& entry) {
231 map_storage_.emplace_back(new MapEntry(entry));
232 return map_storage_.back().get();
233 }
234
RemoveFirstPartOfMapEntry(const MapEntry * entry,uint64_t new_start_addr)235 static MapEntry RemoveFirstPartOfMapEntry(const MapEntry* entry, uint64_t new_start_addr) {
236 MapEntry result = *entry;
237 result.start_addr = new_start_addr;
238 result.len -= result.start_addr - entry->start_addr;
239 result.pgoff += result.start_addr - entry->start_addr;
240 return result;
241 }
242
RemoveSecondPartOfMapEntry(const MapEntry * entry,uint64_t new_len)243 static MapEntry RemoveSecondPartOfMapEntry(const MapEntry* entry, uint64_t new_len) {
244 MapEntry result = *entry;
245 result.len = new_len;
246 return result;
247 }
248
249 // Insert a new map entry in a MapSet. If some existing map entries overlap the new map entry,
250 // then remove the overlapped parts.
InsertMap(MapSet & maps,const MapEntry & entry)251 void ThreadTree::InsertMap(MapSet& maps, const MapEntry& entry) {
252 std::map<uint64_t, const MapEntry*>& map = maps.maps;
253 auto it = map.lower_bound(entry.start_addr);
254 // Remove overlapped entry with start_addr < entry.start_addr.
255 if (it != map.begin()) {
256 auto it2 = it;
257 --it2;
258 if (it2->second->get_end_addr() > entry.get_end_addr()) {
259 map.emplace(entry.get_end_addr(),
260 AllocateMap(RemoveFirstPartOfMapEntry(it2->second, entry.get_end_addr())));
261 }
262 if (it2->second->get_end_addr() > entry.start_addr) {
263 it2->second =
264 AllocateMap(RemoveSecondPartOfMapEntry(it2->second, entry.start_addr - it2->first));
265 }
266 }
267 // Remove overlapped entries with start_addr >= entry.start_addr.
268 while (it != map.end() && it->second->get_end_addr() <= entry.get_end_addr()) {
269 it = map.erase(it);
270 }
271 if (it != map.end() && it->second->start_addr < entry.get_end_addr()) {
272 map.emplace(entry.get_end_addr(),
273 AllocateMap(RemoveFirstPartOfMapEntry(it->second, entry.get_end_addr())));
274 map.erase(it);
275 }
276 // Insert the new entry.
277 map.emplace(entry.start_addr, AllocateMap(entry));
278 maps.version++;
279 }
280
FindMapByAddr(uint64_t addr) const281 const MapEntry* MapSet::FindMapByAddr(uint64_t addr) const {
282 auto it = maps.upper_bound(addr);
283 if (it != maps.begin()) {
284 --it;
285 if (it->second->get_end_addr() > addr) {
286 return it->second;
287 }
288 }
289 return nullptr;
290 }
291
FindMap(const ThreadEntry * thread,uint64_t ip,bool in_kernel)292 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip, bool in_kernel) {
293 const MapEntry* result = nullptr;
294 if (!in_kernel) {
295 result = thread->maps->FindMapByAddr(ip);
296 } else {
297 result = kernel_maps_.FindMapByAddr(ip);
298 }
299 return result != nullptr ? result : &unknown_map_;
300 }
301
FindMap(const ThreadEntry * thread,uint64_t ip)302 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip) {
303 const MapEntry* result = thread->maps->FindMapByAddr(ip);
304 if (result != nullptr) {
305 return result;
306 }
307 result = kernel_maps_.FindMapByAddr(ip);
308 return result != nullptr ? result : &unknown_map_;
309 }
310
FindSymbol(const MapEntry * map,uint64_t ip,uint64_t * pvaddr_in_file,Dso ** pdso)311 const Symbol* ThreadTree::FindSymbol(const MapEntry* map, uint64_t ip, uint64_t* pvaddr_in_file,
312 Dso** pdso) {
313 uint64_t vaddr_in_file = 0;
314 const Symbol* symbol = nullptr;
315 Dso* dso = map->dso;
316 if (map->flags & map_flags::PROT_JIT_SYMFILE_MAP) {
317 vaddr_in_file = ip;
318 } else {
319 vaddr_in_file = dso->IpToVaddrInFile(ip, map->start_addr, map->pgoff);
320 }
321 symbol = dso->FindSymbol(vaddr_in_file);
322 if (symbol == nullptr && dso->type() == DSO_KERNEL_MODULE) {
323 // If the ip address hits the vmlinux, or hits a kernel module, but we can't find its symbol
324 // in the kernel module file, then find its symbol in /proc/kallsyms or vmlinux.
325 vaddr_in_file = ip;
326 dso = FindKernelDsoOrNew();
327 symbol = dso->FindSymbol(vaddr_in_file);
328 }
329
330 if (symbol == nullptr) {
331 if (show_ip_for_unknown_symbol_) {
332 std::string name = android::base::StringPrintf("%s%s[+%" PRIx64 "]",
333 (show_mark_for_unknown_symbol_ ? "*" : ""),
334 dso->FileName().c_str(), vaddr_in_file);
335 dso->AddUnknownSymbol(vaddr_in_file, name);
336 symbol = dso->FindSymbol(vaddr_in_file);
337 CHECK(symbol != nullptr);
338 } else {
339 symbol = &unknown_symbol_;
340 }
341 }
342 if (pvaddr_in_file != nullptr) {
343 *pvaddr_in_file = vaddr_in_file;
344 }
345 if (pdso != nullptr) {
346 *pdso = dso;
347 }
348 return symbol;
349 }
350
FindKernelSymbol(uint64_t ip)351 const Symbol* ThreadTree::FindKernelSymbol(uint64_t ip) {
352 const MapEntry* map = FindMap(nullptr, ip, true);
353 return FindSymbol(map, ip, nullptr);
354 }
355
ClearThreadAndMap()356 void ThreadTree::ClearThreadAndMap() {
357 thread_tree_.clear();
358 thread_comm_storage_.clear();
359 kernel_maps_.maps.clear();
360 map_storage_.clear();
361 }
362
AddDsoInfo(FileFeature & file)363 bool ThreadTree::AddDsoInfo(FileFeature& file) {
364 DsoType dso_type = file.type;
365 Dso* dso = nullptr;
366 if (dso_type == DSO_KERNEL) {
367 dso = FindKernelDsoOrNew();
368 } else if (dso_type == DSO_KERNEL_MODULE) {
369 dso = FindKernelModuleDsoOrNew(file.path, 0, 0);
370 } else {
371 dso = FindUserDsoOrNew(file.path, 0, dso_type);
372 }
373 if (!dso) {
374 return false;
375 }
376 dso->SetMinExecutableVaddr(file.min_vaddr, file.file_offset_of_min_vaddr);
377 dso->SetSymbols(&file.symbols);
378 for (uint64_t offset : file.dex_file_offsets) {
379 dso->AddDexFileOffset(offset);
380 }
381 return true;
382 }
383
AddDexFileOffset(const std::string & file_path,uint64_t dex_file_offset)384 void ThreadTree::AddDexFileOffset(const std::string& file_path, uint64_t dex_file_offset) {
385 Dso* dso = FindUserDsoOrNew(file_path, 0, DSO_DEX_FILE);
386 dso->AddDexFileOffset(dex_file_offset);
387 }
388
Update(const Record & record)389 void ThreadTree::Update(const Record& record) {
390 if (record.type() == PERF_RECORD_MMAP) {
391 const MmapRecord& r = *static_cast<const MmapRecord*>(&record);
392 if (r.InKernel()) {
393 AddKernelMap(r.data->addr, r.data->len, r.data->pgoff, r.filename);
394 } else {
395 AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len, r.data->pgoff, r.filename);
396 }
397 } else if (record.type() == PERF_RECORD_MMAP2) {
398 const Mmap2Record& r = *static_cast<const Mmap2Record*>(&record);
399 if (r.InKernel()) {
400 AddKernelMap(r.data->addr, r.data->len, r.data->pgoff, r.filename);
401 } else {
402 std::string filename =
403 (r.filename == DEFAULT_EXECNAME_FOR_THREAD_MMAP) ? "[unknown]" : r.filename;
404 AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len, r.data->pgoff, filename,
405 r.data->prot);
406 }
407 } else if (record.type() == PERF_RECORD_COMM) {
408 const CommRecord& r = *static_cast<const CommRecord*>(&record);
409 SetThreadName(r.data->pid, r.data->tid, r.comm);
410 } else if (record.type() == PERF_RECORD_FORK) {
411 const ForkRecord& r = *static_cast<const ForkRecord*>(&record);
412 ForkThread(r.data->pid, r.data->tid, r.data->ppid, r.data->ptid);
413 } else if (record.type() == PERF_RECORD_EXIT) {
414 if (!disable_thread_exit_records_) {
415 const ExitRecord& r = *static_cast<const ExitRecord*>(&record);
416 ExitThread(r.data->pid, r.data->tid);
417 }
418 } else if (record.type() == SIMPLE_PERF_RECORD_KERNEL_SYMBOL) {
419 const auto& r = *static_cast<const KernelSymbolRecord*>(&record);
420 Dso::SetKallsyms(std::string(r.kallsyms, r.kallsyms_size));
421 }
422 }
423
GetAllDsos() const424 std::vector<Dso*> ThreadTree::GetAllDsos() const {
425 std::vector<Dso*> result;
426 if (kernel_dso_) {
427 result.push_back(kernel_dso_.get());
428 }
429 for (auto& p : module_dso_tree_) {
430 result.push_back(p.second.get());
431 }
432 for (auto& p : user_dso_tree_) {
433 result.push_back(p.second.get());
434 }
435 result.push_back(unknown_dso_.get());
436 return result;
437 }
438
439 } // namespace simpleperf
440