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 
operator ()(const MapEntry * map1,const MapEntry * map2) const31 bool 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 
SetThreadName(int pid,int tid,const std::string & comm)48 void 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 
ForkThread(int pid,int tid,int ppid,int ptid)57 void 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 
FindThreadOrNew(int pid,int tid)67 ThreadEntry* 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 
CreateThread(int pid,int tid)82 ThreadEntry* 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 
AddKernelMap(uint64_t start_addr,uint64_t len,uint64_t pgoff,uint64_t time,const std::string & filename)102 void 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 
FindKernelDsoOrNew(const std::string & filename)116 Dso* 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 
AddThreadMap(int pid,int tid,uint64_t start_addr,uint64_t len,uint64_t pgoff,uint64_t time,const std::string & filename)129 void 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);
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 
FindUserDsoOrNew(const std::string & filename)141 Dso* ThreadTree::FindUserDsoOrNew(const std::string& filename) {
142   auto it = user_dso_tree_.find(filename);
143   if (it == user_dso_tree_.end()) {
144     user_dso_tree_[filename] = Dso::CreateDso(DSO_ELF_FILE, filename);
145     it = user_dso_tree_.find(filename);
146   }
147   return it->second.get();
148 }
149 
AllocateMap(const MapEntry & value)150 MapEntry* ThreadTree::AllocateMap(const MapEntry& value) {
151   MapEntry* map = new MapEntry(value);
152   map_storage_.push_back(std::unique_ptr<MapEntry>(map));
153   return map;
154 }
155 
FixOverlappedMap(MapSet * maps,const MapEntry * map)156 void ThreadTree::FixOverlappedMap(MapSet* maps, const MapEntry* map) {
157   for (auto it = maps->begin(); it != maps->end();) {
158     if ((*it)->start_addr >= map->get_end_addr()) {
159       // No more overlapped maps.
160       break;
161     }
162     if ((*it)->get_end_addr() <= map->start_addr) {
163       ++it;
164     } else {
165       MapEntry* old = *it;
166       if (old->start_addr < map->start_addr) {
167         MapEntry* before = AllocateMap(
168             MapEntry(old->start_addr, map->start_addr - old->start_addr,
169                      old->pgoff, old->time, old->dso, old->in_kernel));
170         maps->insert(before);
171       }
172       if (old->get_end_addr() > map->get_end_addr()) {
173         MapEntry* after = AllocateMap(MapEntry(
174             map->get_end_addr(), old->get_end_addr() - map->get_end_addr(),
175             map->get_end_addr() - old->start_addr + old->pgoff, old->time,
176             old->dso, old->in_kernel));
177         maps->insert(after);
178       }
179 
180       it = maps->erase(it);
181     }
182   }
183 }
184 
IsAddrInMap(uint64_t addr,const MapEntry * map)185 static bool IsAddrInMap(uint64_t addr, const MapEntry* map) {
186   return (addr >= map->start_addr && addr < map->get_end_addr());
187 }
188 
FindMapByAddr(const MapSet & maps,uint64_t addr)189 static MapEntry* FindMapByAddr(const MapSet& maps, uint64_t addr) {
190   // Construct a map_entry which is strictly after the searched map_entry, based
191   // on MapComparator.
192   MapEntry find_map(addr, std::numeric_limits<uint64_t>::max(), 0,
193                     std::numeric_limits<uint64_t>::max(), nullptr, false);
194   auto it = maps.upper_bound(&find_map);
195   if (it != maps.begin() && IsAddrInMap(addr, *--it)) {
196     return *it;
197   }
198   return nullptr;
199 }
200 
FindMap(const ThreadEntry * thread,uint64_t ip,bool in_kernel)201 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip,
202                                     bool in_kernel) {
203   MapEntry* result = nullptr;
204   if (!in_kernel) {
205     result = FindMapByAddr(*thread->maps, ip);
206   } else {
207     result = FindMapByAddr(kernel_maps_, ip);
208   }
209   return result != nullptr ? result : &unknown_map_;
210 }
211 
FindMap(const ThreadEntry * thread,uint64_t ip)212 const MapEntry* ThreadTree::FindMap(const ThreadEntry* thread, uint64_t ip) {
213   MapEntry* result = FindMapByAddr(*thread->maps, ip);
214   if (result != nullptr) {
215     return result;
216   }
217   result = FindMapByAddr(kernel_maps_, ip);
218   return result != nullptr ? result : &unknown_map_;
219 }
220 
FindSymbol(const MapEntry * map,uint64_t ip,uint64_t * pvaddr_in_file,Dso ** pdso)221 const Symbol* ThreadTree::FindSymbol(const MapEntry* map, uint64_t ip,
222                                      uint64_t* pvaddr_in_file, Dso** pdso) {
223   uint64_t vaddr_in_file;
224   Dso* dso = map->dso;
225   vaddr_in_file = ip - map->start_addr + map->dso->MinVirtualAddress();
226   const Symbol* symbol = dso->FindSymbol(vaddr_in_file);
227   if (symbol == nullptr && map->in_kernel && dso != kernel_dso_.get()) {
228     // It is in a kernel module, but we can't find the kernel module file, or
229     // the kernel module file contains no symbol. Try finding the symbol in
230     // /proc/kallsyms.
231     vaddr_in_file = ip;
232     dso = kernel_dso_.get();
233     symbol = dso->FindSymbol(vaddr_in_file);
234   }
235   if (symbol == nullptr) {
236     if (show_ip_for_unknown_symbol_) {
237       std::string name = android::base::StringPrintf(
238           "%s%s[+%" PRIx64 "]", (show_mark_for_unknown_symbol_ ? "*" : ""),
239           dso->FileName().c_str(), vaddr_in_file);
240       dso->AddUnknownSymbol(vaddr_in_file, name);
241       symbol = dso->FindSymbol(vaddr_in_file);
242       CHECK(symbol != nullptr);
243     } else {
244       symbol = &unknown_symbol_;
245     }
246   }
247   if (pvaddr_in_file != nullptr) {
248     *pvaddr_in_file = vaddr_in_file;
249   }
250   if (pdso != nullptr) {
251     *pdso = dso;
252   }
253   return symbol;
254 }
255 
FindKernelSymbol(uint64_t ip)256 const Symbol* ThreadTree::FindKernelSymbol(uint64_t ip) {
257   const MapEntry* map = FindMap(nullptr, ip, true);
258   return FindSymbol(map, ip, nullptr);
259 }
260 
ClearThreadAndMap()261 void ThreadTree::ClearThreadAndMap() {
262   thread_tree_.clear();
263   thread_comm_storage_.clear();
264   map_set_storage_.clear();
265   kernel_maps_.clear();
266   map_storage_.clear();
267 }
268 
AddDsoInfo(const std::string & file_path,uint32_t file_type,uint64_t min_vaddr,std::vector<Symbol> * symbols)269 void ThreadTree::AddDsoInfo(const std::string& file_path, uint32_t file_type,
270                             uint64_t min_vaddr, std::vector<Symbol>* symbols) {
271   DsoType dso_type = static_cast<DsoType>(file_type);
272   Dso* dso = nullptr;
273   if (dso_type == DSO_KERNEL || dso_type == DSO_KERNEL_MODULE) {
274     dso = FindKernelDsoOrNew(file_path);
275   } else {
276     dso = FindUserDsoOrNew(file_path);
277   }
278   dso->SetMinVirtualAddress(min_vaddr);
279   dso->SetSymbols(symbols);
280 }
281 
Update(const Record & record)282 void ThreadTree::Update(const Record& record) {
283   if (record.type() == PERF_RECORD_MMAP) {
284     const MmapRecord& r = *static_cast<const MmapRecord*>(&record);
285     if (r.InKernel()) {
286       AddKernelMap(r.data->addr, r.data->len, r.data->pgoff,
287                    r.sample_id.time_data.time, r.filename);
288     } else {
289       AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len,
290                    r.data->pgoff, r.sample_id.time_data.time, r.filename);
291     }
292   } else if (record.type() == PERF_RECORD_MMAP2) {
293     const Mmap2Record& r = *static_cast<const Mmap2Record*>(&record);
294     if (r.InKernel()) {
295       AddKernelMap(r.data->addr, r.data->len, r.data->pgoff,
296                    r.sample_id.time_data.time, r.filename);
297     } else {
298       std::string filename = (r.filename == DEFAULT_EXECNAME_FOR_THREAD_MMAP)
299                                  ? "[unknown]"
300                                  : r.filename;
301       AddThreadMap(r.data->pid, r.data->tid, r.data->addr, r.data->len,
302                    r.data->pgoff, r.sample_id.time_data.time, filename);
303     }
304   } else if (record.type() == PERF_RECORD_COMM) {
305     const CommRecord& r = *static_cast<const CommRecord*>(&record);
306     SetThreadName(r.data->pid, r.data->tid, r.comm);
307   } else if (record.type() == PERF_RECORD_FORK) {
308     const ForkRecord& r = *static_cast<const ForkRecord*>(&record);
309     ForkThread(r.data->pid, r.data->tid, r.data->ppid, r.data->ptid);
310   } else if (record.type() == SIMPLE_PERF_RECORD_KERNEL_SYMBOL) {
311     const auto& r = *static_cast<const KernelSymbolRecord*>(&record);
312     Dso::SetKallsyms(std::move(r.kallsyms));
313   }
314 }
315 
GetAllDsos() const316 std::vector<Dso*> ThreadTree::GetAllDsos() const {
317   std::vector<Dso*> result;
318   result.push_back(kernel_dso_.get());
319   for (auto& p : module_dso_tree_) {
320     result.push_back(p.second.get());
321   }
322   for (auto& p : user_dso_tree_) {
323     result.push_back(p.second.get());
324   }
325   return result;
326 }
327 
328 }  // namespace simpleperf
329