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 "dso.h"
18 
19 #include <stdlib.h>
20 #include <string.h>
21 
22 #include <algorithm>
23 #include <limits>
24 #include <memory>
25 #include <vector>
26 
27 #include <android-base/file.h>
28 #include <android-base/logging.h>
29 #include <android-base/strings.h>
30 
31 #include "environment.h"
32 #include "read_apk.h"
33 #include "read_dex_file.h"
34 #include "read_elf.h"
35 #include "utils.h"
36 
37 namespace simpleperf_dso_impl {
38 
RemovePathSeparatorSuffix(const std::string & path)39 std::string RemovePathSeparatorSuffix(const std::string& path) {
40   // Don't remove path separator suffix for '/'.
41   if (android::base::EndsWith(path, OS_PATH_SEPARATOR) && path.size() > 1u) {
42     return path.substr(0, path.size() - 1);
43   }
44   return path;
45 }
46 
Reset()47 void DebugElfFileFinder::Reset() {
48   vdso_64bit_.clear();
49   vdso_32bit_.clear();
50   symfs_dir_.clear();
51   build_id_to_file_map_.clear();
52 }
53 
SetSymFsDir(const std::string & symfs_dir)54 bool DebugElfFileFinder::SetSymFsDir(const std::string& symfs_dir) {
55   symfs_dir_ = RemovePathSeparatorSuffix(symfs_dir);
56   if (!IsDir(symfs_dir_)) {
57     LOG(ERROR) << "Invalid symfs_dir '" << symfs_dir_ << "'";
58     return false;
59   }
60   std::string build_id_list_file = symfs_dir_ + OS_PATH_SEPARATOR + "build_id_list";
61   std::string build_id_list;
62   if (android::base::ReadFileToString(build_id_list_file, &build_id_list)) {
63     for (auto& line : android::base::Split(build_id_list, "\n")) {
64       std::vector<std::string> items = android::base::Split(line, "=");
65       if (items.size() == 2u) {
66         build_id_to_file_map_[items[0]] = symfs_dir_ + OS_PATH_SEPARATOR + items[1];
67       }
68     }
69   }
70   return true;
71 }
72 
AddSymbolDir(const std::string & symbol_dir)73 bool DebugElfFileFinder::AddSymbolDir(const std::string& symbol_dir) {
74   if (!IsDir(symbol_dir)) {
75     LOG(ERROR) << "Invalid symbol dir " << symbol_dir;
76     return false;
77   }
78   std::string dir = RemovePathSeparatorSuffix(symbol_dir);
79   CollectBuildIdInDir(dir);
80   return true;
81 }
82 
CollectBuildIdInDir(const std::string & dir)83 void DebugElfFileFinder::CollectBuildIdInDir(const std::string& dir) {
84   for (const std::string& entry : GetEntriesInDir(dir)) {
85     std::string path = dir + OS_PATH_SEPARATOR + entry;
86     if (IsDir(path)) {
87       CollectBuildIdInDir(path);
88     } else {
89       BuildId build_id;
90       if (GetBuildIdFromElfFile(path, &build_id) == ElfStatus::NO_ERROR) {
91         build_id_to_file_map_[build_id.ToString()] = path;
92       }
93     }
94   }
95 }
96 
SetVdsoFile(const std::string & vdso_file,bool is_64bit)97 void DebugElfFileFinder::SetVdsoFile(const std::string& vdso_file, bool is_64bit) {
98   if (is_64bit) {
99     vdso_64bit_ = vdso_file;
100   } else {
101     vdso_32bit_ = vdso_file;
102   }
103 }
104 
FindDebugFile(const std::string & dso_path,bool force_64bit,BuildId & build_id)105 std::string DebugElfFileFinder::FindDebugFile(const std::string& dso_path, bool force_64bit,
106                                               BuildId& build_id) {
107   if (dso_path == "[vdso]") {
108     if (force_64bit && !vdso_64bit_.empty()) {
109       return vdso_64bit_;
110     } else if (!force_64bit && !vdso_32bit_.empty()) {
111       return vdso_32bit_;
112     }
113   }
114   auto check_path = [&](const std::string& path) {
115     BuildId debug_build_id;
116     if (GetBuildIdFromDsoPath(path, &debug_build_id)) {
117       if (!build_id.IsEmpty() || GetBuildIdFromDsoPath(dso_path, &build_id)) {
118         if (build_id == debug_build_id) {
119           return true;
120         }
121       }
122     }
123     return false;
124   };
125 
126   // 1. Try build_id_to_file_map.
127   if (!build_id_to_file_map_.empty()) {
128     if (!build_id.IsEmpty() || GetBuildIdFromDsoPath(dso_path, &build_id)) {
129       auto it = build_id_to_file_map_.find(build_id.ToString());
130       if (it != build_id_to_file_map_.end() && check_path(it->second)) {
131         return it->second;
132       }
133     }
134   }
135   // 2. Try concatenating symfs_dir and dso_path.
136   if (!symfs_dir_.empty()) {
137     std::string path = GetPathInSymFsDir(dso_path);
138     if (check_path(path)) {
139       return path;
140     }
141   }
142   // 3. Try concatenating /usr/lib/debug and dso_path.
143   // Linux host can store debug shared libraries in /usr/lib/debug.
144   if (check_path("/usr/lib/debug" + dso_path)) {
145     return "/usr/lib/debug" + dso_path;
146   }
147   return dso_path;
148 }
149 
GetPathInSymFsDir(const std::string & path)150 std::string DebugElfFileFinder::GetPathInSymFsDir(const std::string& path) {
151   auto add_symfs_prefix = [&](const std::string& path) {
152     if (android::base::StartsWith(path, OS_PATH_SEPARATOR)) {
153       return symfs_dir_ + path;
154     }
155     return symfs_dir_ + OS_PATH_SEPARATOR + path;
156   };
157   if (OS_PATH_SEPARATOR == '/') {
158     return add_symfs_prefix(path);
159   }
160   // Paths in recorded perf.data uses '/' as path separator. When reporting on Windows, it needs
161   // to be converted to '\\'.
162   auto tuple = SplitUrlInApk(path);
163   if (std::get<0>(tuple)) {
164     std::string apk_path = std::get<1>(tuple);
165     std::string entry_path = std::get<2>(tuple);
166     std::replace(apk_path.begin(), apk_path.end(), '/', OS_PATH_SEPARATOR);
167     return GetUrlInApk(add_symfs_prefix(apk_path), entry_path);
168   }
169   std::string elf_path = path;
170   std::replace(elf_path.begin(), elf_path.end(), '/', OS_PATH_SEPARATOR);
171   return add_symfs_prefix(elf_path);
172 }
173 }  // namespace simpleperf_dso_imp
174 
175 static OneTimeFreeAllocator symbol_name_allocator;
176 
Symbol(std::string_view name,uint64_t addr,uint64_t len)177 Symbol::Symbol(std::string_view name, uint64_t addr, uint64_t len)
178     : addr(addr),
179       len(len),
180       name_(symbol_name_allocator.AllocateString(name)),
181       demangled_name_(nullptr),
182       dump_id_(UINT_MAX) {
183 }
184 
DemangledName() const185 const char* Symbol::DemangledName() const {
186   if (demangled_name_ == nullptr) {
187     const std::string s = Dso::Demangle(name_);
188     if (s == name_) {
189       demangled_name_ = name_;
190     } else {
191       demangled_name_ = symbol_name_allocator.AllocateString(s);
192     }
193   }
194   return demangled_name_;
195 }
196 
197 bool Dso::demangle_ = true;
198 std::string Dso::vmlinux_;
199 std::string Dso::kallsyms_;
200 bool Dso::read_kernel_symbols_from_proc_;
201 std::unordered_map<std::string, BuildId> Dso::build_id_map_;
202 size_t Dso::dso_count_;
203 uint32_t Dso::g_dump_id_;
204 simpleperf_dso_impl::DebugElfFileFinder Dso::debug_elf_file_finder_;
205 
SetDemangle(bool demangle)206 void Dso::SetDemangle(bool demangle) { demangle_ = demangle; }
207 
208 extern "C" char* __cxa_demangle(const char* mangled_name, char* buf, size_t* n,
209                                 int* status);
210 
Demangle(const std::string & name)211 std::string Dso::Demangle(const std::string& name) {
212   if (!demangle_) {
213     return name;
214   }
215   int status;
216   bool is_linker_symbol = (name.find(linker_prefix) == 0);
217   const char* mangled_str = name.c_str();
218   if (is_linker_symbol) {
219     mangled_str += linker_prefix.size();
220   }
221   std::string result = name;
222   char* demangled_name = __cxa_demangle(mangled_str, nullptr, nullptr, &status);
223   if (status == 0) {
224     if (is_linker_symbol) {
225       result = std::string("[linker]") + demangled_name;
226     } else {
227       result = demangled_name;
228     }
229     free(demangled_name);
230   } else if (is_linker_symbol) {
231     result = std::string("[linker]") + mangled_str;
232   }
233   return result;
234 }
235 
SetSymFsDir(const std::string & symfs_dir)236 bool Dso::SetSymFsDir(const std::string& symfs_dir) {
237   return debug_elf_file_finder_.SetSymFsDir(symfs_dir);
238 }
239 
AddSymbolDir(const std::string & symbol_dir)240 bool Dso::AddSymbolDir(const std::string& symbol_dir) {
241   return debug_elf_file_finder_.AddSymbolDir(symbol_dir);
242 }
243 
SetVmlinux(const std::string & vmlinux)244 void Dso::SetVmlinux(const std::string& vmlinux) { vmlinux_ = vmlinux; }
245 
SetBuildIds(const std::vector<std::pair<std::string,BuildId>> & build_ids)246 void Dso::SetBuildIds(
247     const std::vector<std::pair<std::string, BuildId>>& build_ids) {
248   std::unordered_map<std::string, BuildId> map;
249   for (auto& pair : build_ids) {
250     LOG(DEBUG) << "build_id_map: " << pair.first << ", "
251                << pair.second.ToString();
252     map.insert(pair);
253   }
254   build_id_map_ = std::move(map);
255 }
256 
SetVdsoFile(const std::string & vdso_file,bool is_64bit)257 void Dso::SetVdsoFile(const std::string& vdso_file, bool is_64bit) {
258   debug_elf_file_finder_.SetVdsoFile(vdso_file, is_64bit);
259 }
260 
FindExpectedBuildIdForPath(const std::string & path)261 BuildId Dso::FindExpectedBuildIdForPath(const std::string& path) {
262   auto it = build_id_map_.find(path);
263   if (it != build_id_map_.end()) {
264     return it->second;
265   }
266   return BuildId();
267 }
268 
GetExpectedBuildId()269 BuildId Dso::GetExpectedBuildId() {
270   return FindExpectedBuildIdForPath(path_);
271 }
272 
Dso(DsoType type,const std::string & path,const std::string & debug_file_path)273 Dso::Dso(DsoType type, const std::string& path, const std::string& debug_file_path)
274     : type_(type),
275       path_(path),
276       debug_file_path_(debug_file_path),
277       is_loaded_(false),
278       dump_id_(UINT_MAX),
279       symbol_dump_id_(0),
280       symbol_warning_loglevel_(android::base::WARNING) {
281   size_t pos = path.find_last_of("/\\");
282   if (pos != std::string::npos) {
283     file_name_ = path.substr(pos + 1);
284   } else {
285     file_name_ = path;
286   }
287   dso_count_++;
288 }
289 
~Dso()290 Dso::~Dso() {
291   if (--dso_count_ == 0) {
292     // Clean up global variables when no longer used.
293     symbol_name_allocator.Clear();
294     demangle_ = true;
295     vmlinux_.clear();
296     kallsyms_.clear();
297     read_kernel_symbols_from_proc_ = false;
298     build_id_map_.clear();
299     g_dump_id_ = 0;
300     debug_elf_file_finder_.Reset();
301   }
302 }
303 
CreateDumpId()304 uint32_t Dso::CreateDumpId() {
305   CHECK(!HasDumpId());
306   return dump_id_ = g_dump_id_++;
307 }
308 
CreateSymbolDumpId(const Symbol * symbol)309 uint32_t Dso::CreateSymbolDumpId(const Symbol* symbol) {
310   CHECK(!symbol->HasDumpId());
311   symbol->dump_id_ = symbol_dump_id_++;
312   return symbol->dump_id_;
313 }
314 
FindSymbol(uint64_t vaddr_in_dso)315 const Symbol* Dso::FindSymbol(uint64_t vaddr_in_dso) {
316   if (!is_loaded_) {
317     Load();
318   }
319   auto it = std::upper_bound(symbols_.begin(), symbols_.end(),
320                              Symbol("", vaddr_in_dso, 0),
321                              Symbol::CompareValueByAddr);
322   if (it != symbols_.begin()) {
323     --it;
324     if (it->addr <= vaddr_in_dso && (it->addr + it->len > vaddr_in_dso)) {
325       return &*it;
326     }
327   }
328   if (!unknown_symbols_.empty()) {
329     auto it = unknown_symbols_.find(vaddr_in_dso);
330     if (it != unknown_symbols_.end()) {
331       return &it->second;
332     }
333   }
334   return nullptr;
335 }
336 
SetSymbols(std::vector<Symbol> * symbols)337 void Dso::SetSymbols(std::vector<Symbol>* symbols) {
338   symbols_ = std::move(*symbols);
339   symbols->clear();
340 }
341 
AddUnknownSymbol(uint64_t vaddr_in_dso,const std::string & name)342 void Dso::AddUnknownSymbol(uint64_t vaddr_in_dso, const std::string& name) {
343   unknown_symbols_.insert(std::make_pair(vaddr_in_dso, Symbol(name, vaddr_in_dso, 1)));
344 }
345 
IsForJavaMethod()346 bool Dso::IsForJavaMethod() {
347   if (type_ == DSO_DEX_FILE) {
348     return true;
349   }
350   if (type_ == DSO_ELF_FILE) {
351     // JIT symfiles for JITed Java methods are dumped as temporary files, whose name are in format
352     // "TemporaryFile-XXXXXX".
353     size_t pos = path_.rfind('/');
354     pos = (pos == std::string::npos) ? 0 : pos + 1;
355     return strncmp(&path_[pos], "TemporaryFile", strlen("TemporaryFile")) == 0;
356   }
357   return false;
358 }
359 
Load()360 void Dso::Load() {
361   is_loaded_ = true;
362   std::vector<Symbol> symbols = LoadSymbols();
363   if (symbols_.empty()) {
364     symbols_ = std::move(symbols);
365   } else {
366     std::vector<Symbol> merged_symbols;
367     std::set_union(symbols_.begin(), symbols_.end(), symbols.begin(), symbols.end(),
368                    std::back_inserter(merged_symbols), Symbol::CompareValueByAddr);
369     symbols_ = std::move(merged_symbols);
370   }
371 }
372 
ReportReadElfSymbolResult(ElfStatus result,const std::string & path,const std::string & debug_file_path,android::base::LogSeverity warning_loglevel=android::base::WARNING)373 static void ReportReadElfSymbolResult(ElfStatus result, const std::string& path,
374     const std::string& debug_file_path,
375     android::base::LogSeverity warning_loglevel = android::base::WARNING) {
376   if (result == ElfStatus::NO_ERROR) {
377     LOG(VERBOSE) << "Read symbols from " << debug_file_path << " successfully";
378   } else if (result == ElfStatus::NO_SYMBOL_TABLE) {
379     if (path == "[vdso]") {
380       // Vdso only contains dynamic symbol table, and we can't change that.
381       return;
382     }
383     // Lacking symbol table isn't considered as an error but worth reporting.
384     LOG(warning_loglevel) << debug_file_path << " doesn't contain symbol table";
385   } else {
386     LOG(warning_loglevel) << "failed to read symbols from " << debug_file_path << ": " << result;
387   }
388 }
389 
SortAndFixSymbols(std::vector<Symbol> & symbols)390 static void SortAndFixSymbols(std::vector<Symbol>& symbols) {
391   std::sort(symbols.begin(), symbols.end(), Symbol::CompareValueByAddr);
392   Symbol* prev_symbol = nullptr;
393   for (auto& symbol : symbols) {
394     if (prev_symbol != nullptr && prev_symbol->len == 0) {
395       prev_symbol->len = symbol.addr - prev_symbol->addr;
396     }
397     prev_symbol = &symbol;
398   }
399 }
400 
401 class DexFileDso : public Dso {
402  public:
DexFileDso(const std::string & path,const std::string & debug_file_path)403   DexFileDso(const std::string& path, const std::string& debug_file_path)
404       : Dso(DSO_DEX_FILE, path, debug_file_path) {}
405 
AddDexFileOffset(uint64_t dex_file_offset)406   void AddDexFileOffset(uint64_t dex_file_offset) override {
407     auto it = std::lower_bound(dex_file_offsets_.begin(), dex_file_offsets_.end(),
408                                dex_file_offset);
409     if (it != dex_file_offsets_.end() && *it == dex_file_offset) {
410       return;
411     }
412     dex_file_offsets_.insert(it, dex_file_offset);
413   }
414 
DexFileOffsets()415   const std::vector<uint64_t>* DexFileOffsets() override {
416     return &dex_file_offsets_;
417   }
418 
IpToVaddrInFile(uint64_t ip,uint64_t map_start,uint64_t map_pgoff)419   uint64_t IpToVaddrInFile(uint64_t ip, uint64_t map_start, uint64_t map_pgoff) override {
420     return ip - map_start + map_pgoff;
421   }
422 
LoadSymbols()423   std::vector<Symbol> LoadSymbols() override {
424     std::vector<Symbol> symbols;
425     std::vector<DexFileSymbol> dex_file_symbols;
426     auto tuple = SplitUrlInApk(debug_file_path_);
427     bool status = false;
428     if (std::get<0>(tuple)) {
429       std::unique_ptr<ArchiveHelper> ahelper = ArchiveHelper::CreateInstance(std::get<1>(tuple));
430       ZipEntry entry;
431       std::vector<uint8_t> data;
432       if (ahelper &&
433           ahelper->FindEntry(std::get<2>(tuple), &entry) && ahelper->GetEntryData(entry, &data)) {
434         status = ReadSymbolsFromDexFileInMemory(data.data(), data.size(), dex_file_offsets_,
435                                                 &dex_file_symbols);
436       }
437     } else {
438       status = ReadSymbolsFromDexFile(debug_file_path_, dex_file_offsets_, &dex_file_symbols);
439     }
440     if (!status) {
441       android::base::LogSeverity level = symbols_.empty() ? android::base::WARNING
442                                                           : android::base::DEBUG;
443       LOG(level) << "Failed to read symbols from " << debug_file_path_;
444       return symbols;
445     }
446     LOG(VERBOSE) << "Read symbols from " << debug_file_path_ << " successfully";
447     for (auto& symbol : dex_file_symbols) {
448       symbols.emplace_back(symbol.name, symbol.offset, symbol.len);
449     }
450     SortAndFixSymbols(symbols);
451     return symbols;
452   }
453 
454  private:
455   std::vector<uint64_t> dex_file_offsets_;
456 };
457 
458 class ElfDso : public Dso {
459  public:
ElfDso(const std::string & path,const std::string & debug_file_path)460   ElfDso(const std::string& path, const std::string& debug_file_path)
461       : Dso(DSO_ELF_FILE, path, debug_file_path) {}
462 
SetMinExecutableVaddr(uint64_t min_vaddr,uint64_t file_offset)463   void SetMinExecutableVaddr(uint64_t min_vaddr, uint64_t file_offset) override {
464     min_vaddr_ = min_vaddr;
465     file_offset_of_min_vaddr_ = file_offset;
466   }
467 
GetMinExecutableVaddr(uint64_t * min_vaddr,uint64_t * file_offset)468   void GetMinExecutableVaddr(uint64_t* min_vaddr, uint64_t* file_offset) override {
469     if (type_ == DSO_DEX_FILE) {
470       return dex_file_dso_->GetMinExecutableVaddr(min_vaddr, file_offset);
471     }
472     if (min_vaddr_ == uninitialized_value) {
473       min_vaddr_ = 0;
474       BuildId build_id = GetExpectedBuildId();
475       uint64_t addr;
476       uint64_t offset;
477       ElfStatus result;
478       auto tuple = SplitUrlInApk(debug_file_path_);
479       if (std::get<0>(tuple)) {
480         EmbeddedElf* elf = ApkInspector::FindElfInApkByName(std::get<1>(tuple),
481                                                             std::get<2>(tuple));
482         if (elf == nullptr) {
483           result = ElfStatus::FILE_NOT_FOUND;
484         } else {
485           result = ReadMinExecutableVirtualAddressFromEmbeddedElfFile(
486               elf->filepath(), elf->entry_offset(), elf->entry_size(), build_id, &addr, &offset);
487         }
488       } else {
489         result = ReadMinExecutableVirtualAddressFromElfFile(debug_file_path_, build_id, &addr,
490                                                             &offset);
491       }
492       if (result != ElfStatus::NO_ERROR) {
493         LOG(WARNING) << "failed to read min virtual address of "
494                      << GetDebugFilePath() << ": " << result;
495       } else {
496         min_vaddr_ = addr;
497         file_offset_of_min_vaddr_ = offset;
498       }
499     }
500     *min_vaddr = min_vaddr_;
501     *file_offset = file_offset_of_min_vaddr_;
502   }
503 
IpToVaddrInFile(uint64_t ip,uint64_t map_start,uint64_t map_pgoff)504   uint64_t IpToVaddrInFile(uint64_t ip, uint64_t map_start, uint64_t map_pgoff) override {
505     if (type_ == DSO_DEX_FILE) {
506       return dex_file_dso_->IpToVaddrInFile(ip, map_start, map_pgoff);
507     }
508     uint64_t min_vaddr;
509     uint64_t file_offset_of_min_vaddr;
510     GetMinExecutableVaddr(&min_vaddr, &file_offset_of_min_vaddr);
511     if (file_offset_of_min_vaddr == uninitialized_value) {
512       return ip - map_start + min_vaddr;
513     }
514     // Apps may make part of the executable segment of a shared library writeable, which can
515     // generate multiple executable segments at runtime. So use map_pgoff to calculate
516     // vaddr_in_file.
517     return ip - map_start + map_pgoff - file_offset_of_min_vaddr + min_vaddr;
518   }
519 
AddDexFileOffset(uint64_t dex_file_offset)520   void AddDexFileOffset(uint64_t dex_file_offset) override {
521     if (type_ == DSO_ELF_FILE) {
522       // When simpleperf does unwinding while recording, it processes mmap records before reading
523       // dex file linked list (via JITDebugReader). To process mmap records, it creates Dso
524       // objects of type ELF_FILE. Then after reading dex file linked list, it realizes some
525       // ELF_FILE Dso objects should actually be DEX_FILE, because they have dex file offsets.
526       // So here converts ELF_FILE Dso into DEX_FILE Dso.
527       type_ = DSO_DEX_FILE;
528       dex_file_dso_.reset(new DexFileDso(path_, path_));
529     }
530     dex_file_dso_->AddDexFileOffset(dex_file_offset);
531   }
532 
DexFileOffsets()533   const std::vector<uint64_t>* DexFileOffsets() override {
534     return dex_file_dso_ ? dex_file_dso_->DexFileOffsets() : nullptr;
535   }
536 
537  protected:
LoadSymbols()538   std::vector<Symbol> LoadSymbols() override {
539     if (dex_file_dso_) {
540       return dex_file_dso_->LoadSymbols();
541     }
542     std::vector<Symbol> symbols;
543     BuildId build_id = GetExpectedBuildId();
544     auto symbol_callback = [&](const ElfFileSymbol& symbol) {
545       if (symbol.is_func || (symbol.is_label && symbol.is_in_text_section)) {
546         symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
547       }
548     };
549     ElfStatus status;
550     std::tuple<bool, std::string, std::string> tuple = SplitUrlInApk(debug_file_path_);
551     if (std::get<0>(tuple)) {
552       EmbeddedElf* elf = ApkInspector::FindElfInApkByName(std::get<1>(tuple), std::get<2>(tuple));
553       if (elf == nullptr) {
554         status = ElfStatus::FILE_NOT_FOUND;
555       } else {
556         status = ParseSymbolsFromEmbeddedElfFile(elf->filepath(), elf->entry_offset(),
557                                                  elf->entry_size(), build_id, symbol_callback);
558       }
559     } else {
560       status = ParseSymbolsFromElfFile(debug_file_path_, build_id, symbol_callback);
561     }
562     ReportReadElfSymbolResult(status, path_, debug_file_path_,
563                               symbols_.empty() ? android::base::WARNING : android::base::DEBUG);
564     SortAndFixSymbols(symbols);
565     return symbols;
566   }
567 
568  private:
569   static constexpr uint64_t uninitialized_value = std::numeric_limits<uint64_t>::max();
570 
571   uint64_t min_vaddr_ = uninitialized_value;
572   uint64_t file_offset_of_min_vaddr_ = uninitialized_value;
573   std::unique_ptr<DexFileDso> dex_file_dso_;
574 };
575 
576 class KernelDso : public Dso {
577  public:
KernelDso(const std::string & path,const std::string & debug_file_path)578   KernelDso(const std::string& path, const std::string& debug_file_path)
579       : Dso(DSO_KERNEL, path, debug_file_path) {}
580 
IpToVaddrInFile(uint64_t ip,uint64_t,uint64_t)581   uint64_t IpToVaddrInFile(uint64_t ip, uint64_t, uint64_t) override {
582     return ip;
583   }
584 
585  protected:
LoadSymbols()586   std::vector<Symbol> LoadSymbols() override {
587     std::vector<Symbol> symbols;
588     BuildId build_id = GetExpectedBuildId();
589     if (!vmlinux_.empty()) {
590       auto symbol_callback = [&](const ElfFileSymbol& symbol) {
591         if (symbol.is_func) {
592           symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
593         }
594       };
595       ElfStatus status = ParseSymbolsFromElfFile(vmlinux_, build_id, symbol_callback);
596       ReportReadElfSymbolResult(status, path_, vmlinux_);
597     } else if (!kallsyms_.empty()) {
598       symbols = ReadSymbolsFromKallsyms(kallsyms_);
599     } else if (read_kernel_symbols_from_proc_ || !build_id.IsEmpty()) {
600       // Try /proc/kallsyms only when asked to do so, or when build id matches.
601       // Otherwise, it is likely to use /proc/kallsyms on host for perf.data recorded on device.
602       bool can_read_kallsyms = true;
603       if (!build_id.IsEmpty()) {
604         BuildId real_build_id;
605         if (!GetKernelBuildId(&real_build_id) || build_id != real_build_id) {
606           LOG(DEBUG) << "failed to read symbols from /proc/kallsyms: Build id mismatch";
607           can_read_kallsyms = false;
608         }
609       }
610       if (can_read_kallsyms) {
611         std::string kallsyms;
612         if (!android::base::ReadFileToString("/proc/kallsyms", &kallsyms)) {
613           LOG(DEBUG) << "failed to read /proc/kallsyms";
614         } else {
615           symbols = ReadSymbolsFromKallsyms(kallsyms);
616         }
617       }
618     }
619     SortAndFixSymbols(symbols);
620     if (!symbols.empty()) {
621       symbols.back().len = std::numeric_limits<uint64_t>::max() - symbols.back().addr;
622     }
623     return symbols;
624   }
625 
626  private:
ReadSymbolsFromKallsyms(std::string & kallsyms)627   std::vector<Symbol> ReadSymbolsFromKallsyms(std::string& kallsyms) {
628     std::vector<Symbol> symbols;
629     auto symbol_callback = [&](const KernelSymbol& symbol) {
630       if (strchr("TtWw", symbol.type) && symbol.addr != 0u) {
631         symbols.emplace_back(symbol.name, symbol.addr, 0);
632       }
633       return false;
634     };
635     ProcessKernelSymbols(kallsyms, symbol_callback);
636     if (symbols.empty()) {
637       LOG(WARNING) << "Symbol addresses in /proc/kallsyms on device are all zero. "
638                       "`echo 0 >/proc/sys/kernel/kptr_restrict` if possible.";
639     }
640     return symbols;
641   }
642 };
643 
644 class KernelModuleDso : public Dso {
645  public:
KernelModuleDso(const std::string & path,const std::string & debug_file_path)646   KernelModuleDso(const std::string& path, const std::string& debug_file_path)
647       : Dso(DSO_KERNEL_MODULE, path, debug_file_path) {}
648 
IpToVaddrInFile(uint64_t ip,uint64_t map_start,uint64_t)649   uint64_t IpToVaddrInFile(uint64_t ip, uint64_t map_start, uint64_t) override {
650     return ip - map_start;
651   }
652 
653  protected:
LoadSymbols()654   std::vector<Symbol> LoadSymbols() override {
655     std::vector<Symbol> symbols;
656     BuildId build_id = GetExpectedBuildId();
657     auto symbol_callback = [&](const ElfFileSymbol& symbol) {
658       if (symbol.is_func || symbol.is_in_text_section) {
659         symbols.emplace_back(symbol.name, symbol.vaddr, symbol.len);
660       }
661     };
662     ElfStatus status = ParseSymbolsFromElfFile(debug_file_path_, build_id, symbol_callback);
663     ReportReadElfSymbolResult(status, path_, debug_file_path_,
664                               symbols_.empty() ? android::base::WARNING : android::base::DEBUG);
665     SortAndFixSymbols(symbols);
666     return symbols;
667   }
668 };
669 
670 class UnknownDso : public Dso {
671  public:
UnknownDso(const std::string & path)672   UnknownDso(const std::string& path) : Dso(DSO_UNKNOWN_FILE, path, path) {}
673 
IpToVaddrInFile(uint64_t ip,uint64_t,uint64_t)674   uint64_t IpToVaddrInFile(uint64_t ip, uint64_t, uint64_t) override {
675     return ip;
676   }
677 
678  protected:
LoadSymbols()679   std::vector<Symbol> LoadSymbols() override {
680     return std::vector<Symbol>();
681   }
682 };
683 
CreateDso(DsoType dso_type,const std::string & dso_path,bool force_64bit)684 std::unique_ptr<Dso> Dso::CreateDso(DsoType dso_type, const std::string& dso_path,
685                                     bool force_64bit) {
686   switch (dso_type) {
687     case DSO_ELF_FILE: {
688       BuildId build_id = FindExpectedBuildIdForPath(dso_path);
689       return std::unique_ptr<Dso>(new ElfDso(dso_path,
690           debug_elf_file_finder_.FindDebugFile(dso_path, force_64bit, build_id)));
691     }
692     case DSO_KERNEL:
693       return std::unique_ptr<Dso>(new KernelDso(dso_path, dso_path));
694     case DSO_KERNEL_MODULE:
695       return std::unique_ptr<Dso>(new KernelModuleDso(dso_path, dso_path));
696     case DSO_DEX_FILE:
697       return std::unique_ptr<Dso>(new DexFileDso(dso_path, dso_path));
698     case DSO_UNKNOWN_FILE:
699       return std::unique_ptr<Dso>(new UnknownDso(dso_path));
700     default:
701       LOG(FATAL) << "Unexpected dso_type " << static_cast<int>(dso_type);
702   }
703   return nullptr;
704 }
705 
DsoTypeToString(DsoType dso_type)706 const char* DsoTypeToString(DsoType dso_type) {
707   switch (dso_type) {
708     case DSO_KERNEL:
709       return "dso_kernel";
710     case DSO_KERNEL_MODULE:
711       return "dso_kernel_module";
712     case DSO_ELF_FILE:
713       return "dso_elf_file";
714     case DSO_DEX_FILE:
715       return "dso_dex_file";
716     default:
717       return "unknown";
718   }
719 }
720 
GetBuildIdFromDsoPath(const std::string & dso_path,BuildId * build_id)721 bool GetBuildIdFromDsoPath(const std::string& dso_path, BuildId* build_id) {
722   auto tuple = SplitUrlInApk(dso_path);
723   ElfStatus result;
724   if (std::get<0>(tuple)) {
725     EmbeddedElf* elf = ApkInspector::FindElfInApkByName(std::get<1>(tuple), std::get<2>(tuple));
726     if (elf == nullptr) {
727       result = ElfStatus::FILE_NOT_FOUND;
728     } else {
729       result = GetBuildIdFromEmbeddedElfFile(elf->filepath(), elf->entry_offset(),
730                                              elf->entry_size(), build_id);
731     }
732   } else {
733     result = GetBuildIdFromElfFile(dso_path, build_id);
734   }
735   return result == ElfStatus::NO_ERROR;
736 }
737