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 
29 namespace simpleperf {
30 
SetThreadName(int pid,int tid,const std::string & comm)31 void ThreadTree::SetThreadName(int pid, int tid, const std::string& comm) {
32   ThreadEntry* thread = FindThreadOrNew(pid, tid);
33   if (comm != thread->comm) {
34     thread_comm_storage_.push_back(
35         std::unique_ptr<std::string>(new std::string(comm)));
36     thread->comm = thread_comm_storage_.back()->c_str();
37   }
38 }
39 
ForkThread(int pid,int tid,int ppid,int ptid)40 void ThreadTree::ForkThread(int pid, int tid, int ppid, int ptid) {
41   ThreadEntry* parent = FindThreadOrNew(ppid, ptid);
42   ThreadEntry* child = FindThreadOrNew(pid, tid);
43   child->comm = parent->comm;
44   if (pid != ppid) {
45     // Copy maps from parent process.
46     if (child->maps->maps.empty()) {
47       *child->maps = *parent->maps;
48     } else {
49       CHECK_NE(child->maps, parent->maps);
50       for (auto& pair : parent->maps->maps) {
51         InsertMap(*child->maps, *pair.second);
52       }
53     }
54   }
55 }
56 
FindThread(int tid)57 ThreadEntry* ThreadTree::FindThread(int tid) {
58   if (auto it = thread_tree_.find(tid); it != thread_tree_.end()) {
59     return it->second.get();
60   }
61   return nullptr;
62 }
63 
FindThreadOrNew(int pid,int tid)64 ThreadEntry* ThreadTree::FindThreadOrNew(int pid, int tid) {
65   auto it = thread_tree_.find(tid);
66   if (it != thread_tree_.end() && pid == it->second.get()->pid) {
67     return it->second.get();
68   }
69   if (it != thread_tree_.end()) {
70     ExitThread(it->second.get()->pid, tid);
71   }
72   return CreateThread(pid, tid);
73 }
74 
CreateThread(int pid,int tid)75 ThreadEntry* ThreadTree::CreateThread(int pid, int tid) {
76   const char* comm;
77   std::shared_ptr<MapSet> maps;
78   if (pid == tid) {
79     comm = "unknown";
80     maps.reset(new MapSet);
81   } else {
82     // Share maps among threads in the same thread group.
83     ThreadEntry* process = FindThreadOrNew(pid, pid);
84     comm = process->comm;
85     maps = process->maps;
86   }
87   ThreadEntry* thread = new ThreadEntry{
88     pid, tid,
89     comm,
90     maps,
91   };
92   auto pair = thread_tree_.insert(std::make_pair(tid, std::unique_ptr<ThreadEntry>(thread)));
93   CHECK(pair.second);
94   return thread;
95 }
96 
ExitThread(int pid,int tid)97 void ThreadTree::ExitThread(int pid, int tid) {
98   auto it = thread_tree_.find(tid);
99   if (it != thread_tree_.end() && pid == it->second.get()->pid) {
100     thread_tree_.erase(it);
101   }
102 }
103 
AddKernelMap(uint64_t start_addr,uint64_t len,uint64_t pgoff,const std::string & filename)104 void ThreadTree::AddKernelMap(uint64_t start_addr, uint64_t len, uint64_t pgoff,
105                               const std::string& filename) {
106   // kernel map len can be 0 when record command is not run in supervisor mode.
107   if (len == 0) {
108     return;
109   }
110   Dso* dso = FindKernelDsoOrNew(filename);
111   InsertMap(kernel_maps_, MapEntry(start_addr, len, pgoff, dso, true));
112 }
113 
FindKernelDsoOrNew(const std::string & filename)114 Dso* ThreadTree::FindKernelDsoOrNew(const std::string& filename) {
115   if (filename == DEFAULT_KERNEL_MMAP_NAME ||
116       filename == DEFAULT_KERNEL_MMAP_NAME_PERF) {
117     return kernel_dso_.get();
118   }
119   auto it = module_dso_tree_.find(filename);
120   if (it == module_dso_tree_.end()) {
121     module_dso_tree_[filename] = Dso::CreateDso(DSO_KERNEL_MODULE, filename);
122     it = module_dso_tree_.find(filename);
123   }
124   return it->second.get();
125 }
126 
AddThreadMap(int pid,int tid,uint64_t start_addr,uint64_t len,uint64_t pgoff,const std::string & filename,uint32_t flags)127 void ThreadTree::AddThreadMap(int pid, int tid, uint64_t start_addr, uint64_t len,
128                               uint64_t pgoff, const std::string& filename, uint32_t flags) {
129   ThreadEntry* thread = FindThreadOrNew(pid, tid);
130   Dso* dso = FindUserDsoOrNew(filename, start_addr);
131   InsertMap(*thread->maps, MapEntry(start_addr, len, pgoff, dso, false, flags));
132 }
133 
FindUserDsoOrNew(const std::string & filename,uint64_t start_addr,DsoType dso_type)134 Dso* ThreadTree::FindUserDsoOrNew(const std::string& filename, uint64_t start_addr,
135                                   DsoType dso_type) {
136   auto it = user_dso_tree_.find(filename);
137   if (it == user_dso_tree_.end()) {
138     bool force_64bit = start_addr > UINT_MAX;
139     std::unique_ptr<Dso> dso = Dso::CreateDso(dso_type, filename, force_64bit);
140     auto pair = user_dso_tree_.insert(std::make_pair(filename, std::move(dso)));
141     CHECK(pair.second);
142     it = pair.first;
143   }
144   return it->second.get();
145 }
146 
AllocateMap(const MapEntry & entry)147 const MapEntry* ThreadTree::AllocateMap(const MapEntry& entry) {
148   map_storage_.emplace_back(new MapEntry(entry));
149   return map_storage_.back().get();
150 }
151 
RemoveFirstPartOfMapEntry(const MapEntry * entry,uint64_t new_start_addr)152 static MapEntry RemoveFirstPartOfMapEntry(const MapEntry* entry, uint64_t new_start_addr) {
153   MapEntry result = *entry;
154   result.start_addr = new_start_addr;
155   result.len -= result.start_addr - entry->start_addr;
156   result.pgoff += result.start_addr - entry->start_addr;
157   return result;
158 }
159 
RemoveSecondPartOfMapEntry(const MapEntry * entry,uint64_t new_len)160 static MapEntry RemoveSecondPartOfMapEntry(const MapEntry* entry, uint64_t new_len) {
161   MapEntry result = *entry;
162   result.len = new_len;
163   return result;
164 }
165 
166 // Insert a new map entry in a MapSet. If some existing map entries overlap the new map entry,
167 // then remove the overlapped parts.
InsertMap(MapSet & maps,const MapEntry & entry)168 void ThreadTree::InsertMap(MapSet& maps, const MapEntry& entry) {
169   std::map<uint64_t, const MapEntry*>& map = maps.maps;
170   auto it = map.lower_bound(entry.start_addr);
171   // Remove overlapped entry with start_addr < entry.start_addr.
172   if (it != map.begin()) {
173     auto it2 = it;
174     --it2;
175     if (it2->second->get_end_addr() > entry.get_end_addr()) {
176       map.emplace(entry.get_end_addr(),
177                   AllocateMap(RemoveFirstPartOfMapEntry(it2->second, entry.get_end_addr())));
178     }
179     if (it2->second->get_end_addr() > entry.start_addr) {
180       it2->second =
181           AllocateMap(RemoveSecondPartOfMapEntry(it2->second, entry.start_addr - it2->first));
182     }
183   }
184   // Remove overlapped entries with start_addr >= entry.start_addr.
185   while (it != map.end() && it->second->get_end_addr() <= entry.get_end_addr()) {
186     it = map.erase(it);
187   }
188   if (it != map.end() && it->second->start_addr < entry.get_end_addr()) {
189     map.emplace(entry.get_end_addr(),
190                 AllocateMap(RemoveFirstPartOfMapEntry(it->second, entry.get_end_addr())));
191     map.erase(it);
192   }
193   // Insert the new entry.
194   map.emplace(entry.start_addr, AllocateMap(entry));
195   maps.version++;
196 }
197 
FindMapByAddr(const MapSet & maps,uint64_t addr)198 static const MapEntry* FindMapByAddr(const MapSet& maps, uint64_t addr) {
199   auto it = maps.maps.upper_bound(addr);
200   if (it != maps.maps.begin()) {
201     --it;
202     if (it->second->get_end_addr() > addr) {
203       return it->second;
204     }
205   }
206   return nullptr;
207 }
208 
FindMap(const ThreadEntry * thread,uint64_t ip,bool in_kernel)209 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip, bool in_kernel) {
210   const MapEntry* result = nullptr;
211   if (!in_kernel) {
212     result = FindMapByAddr(*thread->maps, ip);
213   } else {
214     result = FindMapByAddr(kernel_maps_, ip);
215   }
216   return result != nullptr ? result : &unknown_map_;
217 }
218 
FindMap(const ThreadEntry * thread,uint64_t ip)219 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip) {
220   const MapEntry* result = FindMapByAddr(*thread->maps, ip);
221   if (result != nullptr) {
222     return result;
223   }
224   result = FindMapByAddr(kernel_maps_, ip);
225   return result != nullptr ? result : &unknown_map_;
226 }
227 
FindSymbol(const MapEntry * map,uint64_t ip,uint64_t * pvaddr_in_file,Dso ** pdso)228 const Symbol* ThreadTree::FindSymbol(const MapEntry* map, uint64_t ip,
229                                      uint64_t* pvaddr_in_file, Dso** pdso) {
230   uint64_t vaddr_in_file = 0;
231   const Symbol* symbol = nullptr;
232   Dso* dso = map->dso;
233   if (map->flags & map_flags::PROT_JIT_SYMFILE_MAP) {
234     vaddr_in_file = ip;
235   } else {
236     vaddr_in_file = dso->IpToVaddrInFile(ip, map->start_addr, map->pgoff);
237   }
238   symbol = dso->FindSymbol(vaddr_in_file);
239   if (symbol == nullptr && dso->type() == DSO_KERNEL_MODULE) {
240     // If the ip address hits the vmlinux, or hits a kernel module, but we can't find its symbol
241     // in the kernel module file, then find its symbol in /proc/kallsyms or vmlinux.
242     vaddr_in_file = ip;
243     dso = kernel_dso_.get();
244     symbol = dso->FindSymbol(vaddr_in_file);
245   }
246 
247   if (symbol == nullptr) {
248     if (show_ip_for_unknown_symbol_) {
249       std::string name = android::base::StringPrintf(
250           "%s%s[+%" PRIx64 "]", (show_mark_for_unknown_symbol_ ? "*" : ""),
251           dso->FileName().c_str(), vaddr_in_file);
252       dso->AddUnknownSymbol(vaddr_in_file, name);
253       symbol = dso->FindSymbol(vaddr_in_file);
254       CHECK(symbol != nullptr);
255     } else {
256       symbol = &unknown_symbol_;
257     }
258   }
259   if (pvaddr_in_file != nullptr) {
260     *pvaddr_in_file = vaddr_in_file;
261   }
262   if (pdso != nullptr) {
263     *pdso = dso;
264   }
265   return symbol;
266 }
267 
FindKernelSymbol(uint64_t ip)268 const Symbol* ThreadTree::FindKernelSymbol(uint64_t ip) {
269   const MapEntry* map = FindMap(nullptr, ip, true);
270   return FindSymbol(map, ip, nullptr);
271 }
272 
ClearThreadAndMap()273 void ThreadTree::ClearThreadAndMap() {
274   thread_tree_.clear();
275   thread_comm_storage_.clear();
276   kernel_maps_.maps.clear();
277   map_storage_.clear();
278 }
279 
AddDsoInfo(const std::string & file_path,uint32_t file_type,uint64_t min_vaddr,uint64_t file_offset_of_min_vaddr,std::vector<Symbol> * symbols,const std::vector<uint64_t> & dex_file_offsets)280 void ThreadTree::AddDsoInfo(const std::string& file_path, uint32_t file_type,
281                             uint64_t min_vaddr, uint64_t file_offset_of_min_vaddr,
282                             std::vector<Symbol>* symbols,
283                             const std::vector<uint64_t>& dex_file_offsets) {
284   DsoType dso_type = static_cast<DsoType>(file_type);
285   Dso* dso = nullptr;
286   if (dso_type == DSO_KERNEL || dso_type == DSO_KERNEL_MODULE) {
287     dso = FindKernelDsoOrNew(file_path);
288   } else {
289     dso = FindUserDsoOrNew(file_path, 0, dso_type);
290   }
291   dso->SetMinExecutableVaddr(min_vaddr, file_offset_of_min_vaddr);
292   dso->SetSymbols(symbols);
293   for (uint64_t offset : dex_file_offsets) {
294     dso->AddDexFileOffset(offset);
295   }
296 }
297 
AddDexFileOffset(const std::string & file_path,uint64_t dex_file_offset)298 void ThreadTree::AddDexFileOffset(const std::string& file_path, uint64_t dex_file_offset) {
299   Dso* dso = FindUserDsoOrNew(file_path, 0, DSO_DEX_FILE);
300   dso->AddDexFileOffset(dex_file_offset);
301 }
302 
Update(const Record & record)303 void ThreadTree::Update(const Record& record) {
304   if (record.type() == PERF_RECORD_MMAP) {
305     const MmapRecord& r = *static_cast<const MmapRecord*>(&record);
306     if (r.InKernel()) {
307       AddKernelMap(r.data->addr, r.data->len, r.data->pgoff, r.filename);
308     } else {
309       AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len, r.data->pgoff, r.filename);
310     }
311   } else if (record.type() == PERF_RECORD_MMAP2) {
312     const Mmap2Record& r = *static_cast<const Mmap2Record*>(&record);
313     if (r.InKernel()) {
314       AddKernelMap(r.data->addr, r.data->len, r.data->pgoff, r.filename);
315     } else {
316       std::string filename = (r.filename == DEFAULT_EXECNAME_FOR_THREAD_MMAP)
317                                  ? "[unknown]"
318                                  : r.filename;
319       AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len, r.data->pgoff, filename,
320                    r.data->prot);
321     }
322   } else if (record.type() == PERF_RECORD_COMM) {
323     const CommRecord& r = *static_cast<const CommRecord*>(&record);
324     SetThreadName(r.data->pid, r.data->tid, r.comm);
325   } else if (record.type() == PERF_RECORD_FORK) {
326     const ForkRecord& r = *static_cast<const ForkRecord*>(&record);
327     ForkThread(r.data->pid, r.data->tid, r.data->ppid, r.data->ptid);
328   } else if (record.type() == PERF_RECORD_EXIT) {
329     const ExitRecord& r = *static_cast<const ExitRecord*>(&record);
330     ExitThread(r.data->pid, r.data->tid);
331   } else if (record.type() == SIMPLE_PERF_RECORD_KERNEL_SYMBOL) {
332     const auto& r = *static_cast<const KernelSymbolRecord*>(&record);
333     Dso::SetKallsyms(std::move(r.kallsyms));
334   }
335 }
336 
GetAllDsos() const337 std::vector<Dso*> ThreadTree::GetAllDsos() const {
338   std::vector<Dso*> result;
339   result.push_back(kernel_dso_.get());
340   for (auto& p : module_dso_tree_) {
341     result.push_back(p.second.get());
342   }
343   for (auto& p : user_dso_tree_) {
344     result.push_back(p.second.get());
345   }
346   result.push_back(unknown_dso_.get());
347   return result;
348 }
349 
350 }  // namespace simpleperf
351