1 /*
2  * Copyright (C) 2019 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 "src/profiling/symbolizer/local_symbolizer.h"
18 
19 #include <fcntl.h>
20 
21 #include <memory>
22 #include <sstream>
23 #include <string>
24 #include <vector>
25 
26 #include "perfetto/base/build_config.h"
27 #include "perfetto/base/compiler.h"
28 #include "perfetto/base/logging.h"
29 #include "perfetto/ext/base/file_utils.h"
30 #include "perfetto/ext/base/optional.h"
31 #include "perfetto/ext/base/scoped_file.h"
32 #include "perfetto/ext/base/string_utils.h"
33 #include "src/profiling/symbolizer/filesystem.h"
34 #include "src/profiling/symbolizer/scoped_read_mmap.h"
35 
36 namespace perfetto {
37 namespace profiling {
38 
39 // TODO(fmayer): Fix up name. This suggests it always returns a symbolizer or
40 // dies, which isn't the case.
LocalSymbolizerOrDie(std::vector<std::string> binary_path,const char * mode)41 std::unique_ptr<Symbolizer> LocalSymbolizerOrDie(
42     std::vector<std::string> binary_path,
43     const char* mode) {
44   std::unique_ptr<Symbolizer> symbolizer;
45 
46   if (!binary_path.empty()) {
47 #if PERFETTO_BUILDFLAG(PERFETTO_LOCAL_SYMBOLIZER)
48     std::unique_ptr<BinaryFinder> finder;
49     if (!mode || strncmp(mode, "find", 4) == 0)
50       finder.reset(new LocalBinaryFinder(std::move(binary_path)));
51     else if (strncmp(mode, "index", 5) == 0)
52       finder.reset(new LocalBinaryIndexer(std::move(binary_path)));
53     else
54       PERFETTO_FATAL("Invalid symbolizer mode [find | index]: %s", mode);
55     symbolizer.reset(new LocalSymbolizer(std::move(finder)));
56 #else
57     base::ignore_result(mode);
58     PERFETTO_FATAL("This build does not support local symbolization.");
59 #endif
60   }
61   return symbolizer;
62 }
63 
64 }  // namespace profiling
65 }  // namespace perfetto
66 
67 #if PERFETTO_BUILDFLAG(PERFETTO_LOCAL_SYMBOLIZER)
68 #include "perfetto/ext/base/string_splitter.h"
69 #include "perfetto/ext/base/string_utils.h"
70 #include "perfetto/ext/base/utils.h"
71 
72 #include <inttypes.h>
73 #include <signal.h>
74 #include <sys/stat.h>
75 #include <sys/types.h>
76 
77 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
78 constexpr const char* kDefaultSymbolizer = "llvm-symbolizer.exe";
79 #else
80 constexpr const char* kDefaultSymbolizer = "llvm-symbolizer";
81 #endif
82 
83 namespace perfetto {
84 namespace profiling {
85 
GetLines(std::function<int64_t (char *,size_t)> fn_read)86 std::vector<std::string> GetLines(
87     std::function<int64_t(char*, size_t)> fn_read) {
88   std::vector<std::string> lines;
89   char buffer[512];
90   int64_t rd = 0;
91   // Cache the partial line of the previous read.
92   std::string last_line;
93   while ((rd = fn_read(buffer, sizeof(buffer))) > 0) {
94     std::string data(buffer, static_cast<size_t>(rd));
95     // Create stream buffer of last partial line + new data
96     std::stringstream stream(last_line + data);
97     std::string line;
98     last_line = "";
99     while (std::getline(stream, line)) {
100       // Return from reading when we read an empty line.
101       if (line.empty()) {
102         return lines;
103       } else if (stream.eof()) {
104         // Cache off the partial line when we hit end of stream.
105         last_line += line;
106         break;
107       } else {
108         lines.push_back(line);
109       }
110     }
111   }
112   if (rd == -1) {
113     PERFETTO_ELOG("Failed to read data from subprocess.");
114   }
115   return lines;
116 }
117 
118 namespace {
119 // We cannot just include elf.h, as that only exists on Linux, and we want to
120 // allow symbolization on other platforms as well. As we only need a small
121 // subset, it is easiest to define the constants and structs ourselves.
122 constexpr auto PT_LOAD = 1;
123 constexpr auto PF_X = 1;
124 constexpr auto SHT_NOTE = 7;
125 constexpr auto NT_GNU_BUILD_ID = 3;
126 constexpr auto ELFCLASS32 = 1;
127 constexpr auto ELFCLASS64 = 2;
128 constexpr auto ELFMAG0 = 0x7f;
129 constexpr auto ELFMAG1 = 'E';
130 constexpr auto ELFMAG2 = 'L';
131 constexpr auto ELFMAG3 = 'F';
132 constexpr auto EI_MAG0 = 0;
133 constexpr auto EI_MAG1 = 1;
134 constexpr auto EI_MAG2 = 2;
135 constexpr auto EI_MAG3 = 3;
136 constexpr auto EI_CLASS = 4;
137 
138 struct Elf32 {
139   using Addr = uint32_t;
140   using Half = uint16_t;
141   using Off = uint32_t;
142   using Sword = int32_t;
143   using Word = uint32_t;
144   struct Ehdr {
145     unsigned char e_ident[16];
146     Half e_type;
147     Half e_machine;
148     Word e_version;
149     Addr e_entry;
150     Off e_phoff;
151     Off e_shoff;
152     Word e_flags;
153     Half e_ehsize;
154     Half e_phentsize;
155     Half e_phnum;
156     Half e_shentsize;
157     Half e_shnum;
158     Half e_shstrndx;
159   };
160   struct Shdr {
161     Word sh_name;
162     Word sh_type;
163     Word sh_flags;
164     Addr sh_addr;
165     Off sh_offset;
166     Word sh_size;
167     Word sh_link;
168     Word sh_info;
169     Word sh_addralign;
170     Word sh_entsize;
171   };
172   struct Nhdr {
173     Word n_namesz;
174     Word n_descsz;
175     Word n_type;
176   };
177   struct Phdr {
178     uint32_t p_type;
179     Off p_offset;
180     Addr p_vaddr;
181     Addr p_paddr;
182     uint32_t p_filesz;
183     uint32_t p_memsz;
184     uint32_t p_flags;
185     uint32_t p_align;
186   };
187 };
188 
189 struct Elf64 {
190   using Addr = uint64_t;
191   using Half = uint16_t;
192   using SHalf = int16_t;
193   using Off = uint64_t;
194   using Sword = int32_t;
195   using Word = uint32_t;
196   using Xword = uint64_t;
197   using Sxword = int64_t;
198   struct Ehdr {
199     unsigned char e_ident[16];
200     Half e_type;
201     Half e_machine;
202     Word e_version;
203     Addr e_entry;
204     Off e_phoff;
205     Off e_shoff;
206     Word e_flags;
207     Half e_ehsize;
208     Half e_phentsize;
209     Half e_phnum;
210     Half e_shentsize;
211     Half e_shnum;
212     Half e_shstrndx;
213   };
214   struct Shdr {
215     Word sh_name;
216     Word sh_type;
217     Xword sh_flags;
218     Addr sh_addr;
219     Off sh_offset;
220     Xword sh_size;
221     Word sh_link;
222     Word sh_info;
223     Xword sh_addralign;
224     Xword sh_entsize;
225   };
226   struct Nhdr {
227     Word n_namesz;
228     Word n_descsz;
229     Word n_type;
230   };
231   struct Phdr {
232     uint32_t p_type;
233     uint32_t p_flags;
234     Off p_offset;
235     Addr p_vaddr;
236     Addr p_paddr;
237     uint64_t p_filesz;
238     uint64_t p_memsz;
239     uint64_t p_align;
240   };
241 };
242 
243 template <typename E>
GetShdr(void * mem,const typename E::Ehdr * ehdr,size_t i)244 typename E::Shdr* GetShdr(void* mem, const typename E::Ehdr* ehdr, size_t i) {
245   return reinterpret_cast<typename E::Shdr*>(
246       static_cast<char*>(mem) + ehdr->e_shoff + i * sizeof(typename E::Shdr));
247 }
248 
249 template <typename E>
GetPhdr(void * mem,const typename E::Ehdr * ehdr,size_t i)250 typename E::Phdr* GetPhdr(void* mem, const typename E::Ehdr* ehdr, size_t i) {
251   return reinterpret_cast<typename E::Phdr*>(
252       static_cast<char*>(mem) + ehdr->e_phoff + i * sizeof(typename E::Phdr));
253 }
254 
InRange(const void * base,size_t total_size,const void * ptr,size_t size)255 bool InRange(const void* base,
256              size_t total_size,
257              const void* ptr,
258              size_t size) {
259   return ptr >= base && static_cast<const char*>(ptr) + size <=
260                             static_cast<const char*>(base) + total_size;
261 }
262 
263 template <typename E>
GetLoadBias(void * mem,size_t size)264 base::Optional<uint64_t> GetLoadBias(void* mem, size_t size) {
265   const typename E::Ehdr* ehdr = static_cast<typename E::Ehdr*>(mem);
266   if (!InRange(mem, size, ehdr, sizeof(typename E::Ehdr))) {
267     PERFETTO_ELOG("Corrupted ELF.");
268     return base::nullopt;
269   }
270   for (size_t i = 0; i < ehdr->e_phnum; ++i) {
271     typename E::Phdr* phdr = GetPhdr<E>(mem, ehdr, i);
272     if (!InRange(mem, size, phdr, sizeof(typename E::Phdr))) {
273       PERFETTO_ELOG("Corrupted ELF.");
274       return base::nullopt;
275     }
276     if (phdr->p_type == PT_LOAD && phdr->p_flags & PF_X) {
277       return phdr->p_vaddr - phdr->p_offset;
278     }
279   }
280   return 0u;
281 }
282 
283 template <typename E>
GetBuildId(void * mem,size_t size)284 base::Optional<std::string> GetBuildId(void* mem, size_t size) {
285   const typename E::Ehdr* ehdr = static_cast<typename E::Ehdr*>(mem);
286   if (!InRange(mem, size, ehdr, sizeof(typename E::Ehdr))) {
287     PERFETTO_ELOG("Corrupted ELF.");
288     return base::nullopt;
289   }
290   for (size_t i = 0; i < ehdr->e_shnum; ++i) {
291     typename E::Shdr* shdr = GetShdr<E>(mem, ehdr, i);
292     if (!InRange(mem, size, shdr, sizeof(typename E::Shdr))) {
293       PERFETTO_ELOG("Corrupted ELF.");
294       return base::nullopt;
295     }
296 
297     if (shdr->sh_type != SHT_NOTE)
298       continue;
299 
300     auto offset = shdr->sh_offset;
301     while (offset < shdr->sh_offset + shdr->sh_size) {
302       typename E::Nhdr* nhdr =
303           reinterpret_cast<typename E::Nhdr*>(static_cast<char*>(mem) + offset);
304 
305       if (!InRange(mem, size, nhdr, sizeof(typename E::Nhdr))) {
306         PERFETTO_ELOG("Corrupted ELF.");
307         return base::nullopt;
308       }
309       if (nhdr->n_type == NT_GNU_BUILD_ID && nhdr->n_namesz == 4) {
310         char* name = reinterpret_cast<char*>(nhdr) + sizeof(*nhdr);
311         if (!InRange(mem, size, name, 4)) {
312           PERFETTO_ELOG("Corrupted ELF.");
313           return base::nullopt;
314         }
315         if (memcmp(name, "GNU", 3) == 0) {
316           const char* value = reinterpret_cast<char*>(nhdr) + sizeof(*nhdr) +
317                               base::AlignUp<4>(nhdr->n_namesz);
318 
319           if (!InRange(mem, size, value, nhdr->n_descsz)) {
320             PERFETTO_ELOG("Corrupted ELF.");
321             return base::nullopt;
322           }
323           return std::string(value, nhdr->n_descsz);
324         }
325       }
326       offset += sizeof(*nhdr) + base::AlignUp<4>(nhdr->n_namesz) +
327                 base::AlignUp<4>(nhdr->n_descsz);
328     }
329   }
330   return base::nullopt;
331 }
332 
SplitBuildID(const std::string & hex_build_id)333 std::string SplitBuildID(const std::string& hex_build_id) {
334   if (hex_build_id.size() < 3) {
335     PERFETTO_DFATAL_OR_ELOG("Invalid build-id (< 3 char) %s",
336                             hex_build_id.c_str());
337     return {};
338   }
339 
340   return hex_build_id.substr(0, 2) + "/" + hex_build_id.substr(2);
341 }
342 
IsElf(const char * mem,size_t size)343 bool IsElf(const char* mem, size_t size) {
344   if (size <= EI_MAG3)
345     return false;
346   return (mem[EI_MAG0] == ELFMAG0 && mem[EI_MAG1] == ELFMAG1 &&
347           mem[EI_MAG2] == ELFMAG2 && mem[EI_MAG3] == ELFMAG3);
348 }
349 
350 struct BuildIdAndLoadBias {
351   std::string build_id;
352   uint64_t load_bias;
353 };
354 
GetBuildIdAndLoadBias(const char * fname,size_t size)355 base::Optional<BuildIdAndLoadBias> GetBuildIdAndLoadBias(const char* fname,
356                                                          size_t size) {
357   static_assert(EI_CLASS > EI_MAG3, "mem[EI_MAG?] accesses are in range.");
358   if (size <= EI_CLASS)
359     return base::nullopt;
360   ScopedReadMmap map(fname, size);
361   if (!map.IsValid()) {
362     PERFETTO_PLOG("mmap");
363     return base::nullopt;
364   }
365   char* mem = static_cast<char*>(*map);
366 
367   if (!IsElf(mem, size))
368     return base::nullopt;
369 
370   base::Optional<std::string> build_id;
371   base::Optional<uint64_t> load_bias;
372   switch (mem[EI_CLASS]) {
373     case ELFCLASS32:
374       build_id = GetBuildId<Elf32>(mem, size);
375       load_bias = GetLoadBias<Elf32>(mem, size);
376       break;
377     case ELFCLASS64:
378       build_id = GetBuildId<Elf64>(mem, size);
379       load_bias = GetLoadBias<Elf64>(mem, size);
380       break;
381     default:
382       return base::nullopt;
383   }
384   if (build_id && load_bias) {
385     return BuildIdAndLoadBias{*build_id, *load_bias};
386   }
387   return base::nullopt;
388 }
389 
BuildIdIndex(std::vector<std::string> dirs)390 std::map<std::string, FoundBinary> BuildIdIndex(std::vector<std::string> dirs) {
391   std::map<std::string, FoundBinary> result;
392   WalkDirectories(std::move(dirs), [&result](const char* fname, size_t size) {
393     char magic[EI_MAG3 + 1];
394     // Scope file access. On windows OpenFile opens an exclusive lock.
395     // This lock needs to be released before mapping the file.
396     {
397       base::ScopedFile fd(base::OpenFile(fname, O_RDONLY));
398       if (!fd) {
399         PERFETTO_PLOG("Failed to open %s", fname);
400         return;
401       }
402       ssize_t rd = base::Read(*fd, &magic, sizeof(magic));
403       if (rd != sizeof(magic)) {
404         PERFETTO_PLOG("Failed to read %s", fname);
405         return;
406       }
407       if (!IsElf(magic, static_cast<size_t>(rd))) {
408         PERFETTO_DLOG("%s not an ELF.", fname);
409         return;
410       }
411     }
412     base::Optional<BuildIdAndLoadBias> build_id_and_load_bias =
413         GetBuildIdAndLoadBias(fname, size);
414     if (build_id_and_load_bias) {
415       result.emplace(build_id_and_load_bias->build_id,
416                      FoundBinary{fname, build_id_and_load_bias->load_bias});
417     }
418   });
419   return result;
420 }
421 
422 }  // namespace
423 
ParseLlvmSymbolizerLine(const std::string & line,std::string * file_name,uint32_t * line_no)424 bool ParseLlvmSymbolizerLine(const std::string& line,
425                              std::string* file_name,
426                              uint32_t* line_no) {
427   size_t col_pos = line.rfind(':');
428   if (col_pos == std::string::npos || col_pos == 0)
429     return false;
430   size_t row_pos = line.rfind(':', col_pos - 1);
431   if (row_pos == std::string::npos || row_pos == 0)
432     return false;
433   *file_name = line.substr(0, row_pos);
434   auto line_no_str = line.substr(row_pos + 1, col_pos - row_pos - 1);
435 
436   base::Optional<int32_t> opt_parsed_line_no = base::StringToInt32(line_no_str);
437   if (!opt_parsed_line_no || *opt_parsed_line_no < 0)
438     return false;
439   *line_no = static_cast<uint32_t>(*opt_parsed_line_no);
440   return true;
441 }
442 
443 BinaryFinder::~BinaryFinder() = default;
444 
LocalBinaryIndexer(std::vector<std::string> roots)445 LocalBinaryIndexer::LocalBinaryIndexer(std::vector<std::string> roots)
446     : buildid_to_file_(BuildIdIndex(std::move(roots))) {}
447 
FindBinary(const std::string & abspath,const std::string & build_id)448 base::Optional<FoundBinary> LocalBinaryIndexer::FindBinary(
449     const std::string& abspath,
450     const std::string& build_id) {
451   auto it = buildid_to_file_.find(build_id);
452   if (it != buildid_to_file_.end())
453     return it->second;
454   PERFETTO_ELOG("Could not find Build ID: %s (file %s).",
455                 base::ToHex(build_id).c_str(), abspath.c_str());
456   return base::nullopt;
457 }
458 
459 LocalBinaryIndexer::~LocalBinaryIndexer() = default;
460 
LocalBinaryFinder(std::vector<std::string> roots)461 LocalBinaryFinder::LocalBinaryFinder(std::vector<std::string> roots)
462     : roots_(std::move(roots)) {}
463 
FindBinary(const std::string & abspath,const std::string & build_id)464 base::Optional<FoundBinary> LocalBinaryFinder::FindBinary(
465     const std::string& abspath,
466     const std::string& build_id) {
467   auto p = cache_.emplace(abspath, base::nullopt);
468   if (!p.second)
469     return p.first->second;
470 
471   base::Optional<FoundBinary>& cache_entry = p.first->second;
472 
473   for (const std::string& root_str : roots_) {
474     cache_entry = FindBinaryInRoot(root_str, abspath, build_id);
475     if (cache_entry)
476       return cache_entry;
477   }
478   PERFETTO_ELOG("Could not find %s (Build ID: %s).", abspath.c_str(),
479                 base::ToHex(build_id).c_str());
480   return cache_entry;
481 }
482 
IsCorrectFile(const std::string & symbol_file,const std::string & build_id)483 base::Optional<FoundBinary> LocalBinaryFinder::IsCorrectFile(
484     const std::string& symbol_file,
485     const std::string& build_id) {
486   if (!base::FileExists(symbol_file)) {
487     return base::nullopt;
488   }
489   // Openfile opens the file with an exclusive lock on windows.
490   size_t size = GetFileSize(symbol_file);
491 
492   if (size == 0) {
493     return base::nullopt;
494   }
495 
496   base::Optional<BuildIdAndLoadBias> build_id_and_load_bias =
497       GetBuildIdAndLoadBias(symbol_file.c_str(), size);
498   if (!build_id_and_load_bias)
499     return base::nullopt;
500   if (build_id_and_load_bias->build_id != build_id) {
501     return base::nullopt;
502   }
503   return FoundBinary{symbol_file, build_id_and_load_bias->load_bias};
504 }
505 
FindBinaryInRoot(const std::string & root_str,const std::string & abspath,const std::string & build_id)506 base::Optional<FoundBinary> LocalBinaryFinder::FindBinaryInRoot(
507     const std::string& root_str,
508     const std::string& abspath,
509     const std::string& build_id) {
510   constexpr char kApkPrefix[] = "base.apk!";
511 
512   std::string filename;
513   std::string dirname;
514 
515   for (base::StringSplitter sp(abspath, '/'); sp.Next();) {
516     if (!dirname.empty())
517       dirname += "/";
518     dirname += filename;
519     filename = sp.cur_token();
520   }
521 
522   // Return the first match for the following options:
523   // * absolute path of library file relative to root.
524   // * absolute path of library file relative to root, but with base.apk!
525   //   removed from filename.
526   // * only filename of library file relative to root.
527   // * only filename of library file relative to root, but with base.apk!
528   //   removed from filename.
529   // * in the subdirectory .build-id: the first two hex digits of the build-id
530   //   as subdirectory, then the rest of the hex digits, with ".debug"appended.
531   //   See
532   //   https://fedoraproject.org/wiki/RolandMcGrath/BuildID#Find_files_by_build_ID
533   //
534   // For example, "/system/lib/base.apk!foo.so" with build id abcd1234,
535   // is looked for at
536   // * $ROOT/system/lib/base.apk!foo.so
537   // * $ROOT/system/lib/foo.so
538   // * $ROOT/base.apk!foo.so
539   // * $ROOT/foo.so
540   // * $ROOT/.build-id/ab/cd1234.debug
541 
542   base::Optional<FoundBinary> result;
543 
544   std::string symbol_file = root_str + "/" + dirname + "/" + filename;
545   result = IsCorrectFile(symbol_file, build_id);
546   if (result) {
547     return result;
548   }
549 
550   if (base::StartsWith(filename, kApkPrefix)) {
551     symbol_file =
552         root_str + "/" + dirname + "/" + filename.substr(sizeof(kApkPrefix));
553     result = IsCorrectFile(symbol_file, build_id);
554     if (result) {
555       return result;
556     }
557   }
558 
559   symbol_file = root_str + "/" + filename;
560   result = IsCorrectFile(symbol_file, build_id);
561   if (result) {
562     return result;
563   }
564 
565   if (base::StartsWith(filename, kApkPrefix)) {
566     symbol_file = root_str + "/" + filename.substr(sizeof(kApkPrefix));
567     result = IsCorrectFile(symbol_file, build_id);
568     if (result) {
569       return result;
570     }
571   }
572 
573   std::string hex_build_id = base::ToHex(build_id.c_str(), build_id.size());
574   std::string split_hex_build_id = SplitBuildID(hex_build_id);
575   if (!split_hex_build_id.empty()) {
576     symbol_file =
577         root_str + "/" + ".build-id" + "/" + split_hex_build_id + ".debug";
578     result = IsCorrectFile(symbol_file, build_id);
579     if (result) {
580       return result;
581     }
582   }
583 
584   return base::nullopt;
585 }
586 
587 LocalBinaryFinder::~LocalBinaryFinder() = default;
588 
LLVMSymbolizerProcess(const std::string & symbolizer_path)589 LLVMSymbolizerProcess::LLVMSymbolizerProcess(const std::string& symbolizer_path)
590     :
591 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
592       subprocess_(symbolizer_path, {}) {
593 }
594 #else
595       subprocess_(symbolizer_path, {"llvm-symbolizer"}) {
596 }
597 #endif
598 
Symbolize(const std::string & binary,uint64_t address)599 std::vector<SymbolizedFrame> LLVMSymbolizerProcess::Symbolize(
600     const std::string& binary,
601     uint64_t address) {
602   std::vector<SymbolizedFrame> result;
603   char buffer[1024];
604   int size = sprintf(buffer, "\"%s\" 0x%" PRIx64 "\n", binary.c_str(), address);
605   if (subprocess_.Write(buffer, static_cast<size_t>(size)) < 0) {
606     PERFETTO_ELOG("Failed to write to llvm-symbolizer.");
607     return result;
608   }
609   auto lines = GetLines([&](char* read_buffer, size_t buffer_size) {
610     return subprocess_.Read(read_buffer, buffer_size);
611   });
612   // llvm-symbolizer writes out records in the form of
613   // Foo(Bar*)
614   // foo.cc:123
615   // This is why we should always get a multiple of two number of lines.
616   PERFETTO_DCHECK(lines.size() % 2 == 0);
617   result.resize(lines.size() / 2);
618   for (size_t i = 0; i < lines.size(); ++i) {
619     SymbolizedFrame& cur = result[i / 2];
620     if (i % 2 == 0) {
621       cur.function_name = lines[i];
622     } else {
623       if (!ParseLlvmSymbolizerLine(lines[i], &cur.file_name, &cur.line)) {
624         PERFETTO_ELOG("Failed to parse llvm-symbolizer line: %s",
625                       lines[i].c_str());
626         cur.file_name = "";
627         cur.line = 0;
628       }
629     }
630   }
631 
632   for (auto it = result.begin(); it != result.end();) {
633     if (it->function_name == "??")
634       it = result.erase(it);
635     else
636       ++it;
637   }
638   return result;
639 }
Symbolize(const std::string & mapping_name,const std::string & build_id,uint64_t load_bias,const std::vector<uint64_t> & addresses)640 std::vector<std::vector<SymbolizedFrame>> LocalSymbolizer::Symbolize(
641     const std::string& mapping_name,
642     const std::string& build_id,
643     uint64_t load_bias,
644     const std::vector<uint64_t>& addresses) {
645   base::Optional<FoundBinary> binary =
646       finder_->FindBinary(mapping_name, build_id);
647   if (!binary)
648     return {};
649   uint64_t load_bias_correction = 0;
650   if (binary->load_bias > load_bias) {
651     // On Android 10, there was a bug in libunwindstack that would incorrectly
652     // calculate the load_bias, and thus the relative PC. This would end up in
653     // frames that made no sense. We can fix this up after the fact if we
654     // detect this situation.
655     load_bias_correction = binary->load_bias - load_bias;
656     PERFETTO_LOG("Correcting load bias by %" PRIu64 " for %s",
657                  load_bias_correction, mapping_name.c_str());
658   }
659   std::vector<std::vector<SymbolizedFrame>> result;
660   result.reserve(addresses.size());
661   for (uint64_t address : addresses)
662     result.emplace_back(llvm_symbolizer_.Symbolize(
663         binary->file_name, address + load_bias_correction));
664   return result;
665 }
666 
LocalSymbolizer(const std::string & symbolizer_path,std::unique_ptr<BinaryFinder> finder)667 LocalSymbolizer::LocalSymbolizer(const std::string& symbolizer_path,
668                                  std::unique_ptr<BinaryFinder> finder)
669     : llvm_symbolizer_(symbolizer_path), finder_(std::move(finder)) {}
670 
LocalSymbolizer(std::unique_ptr<BinaryFinder> finder)671 LocalSymbolizer::LocalSymbolizer(std::unique_ptr<BinaryFinder> finder)
672     : LocalSymbolizer(kDefaultSymbolizer, std::move(finder)) {}
673 
674 LocalSymbolizer::~LocalSymbolizer() = default;
675 
676 }  // namespace profiling
677 }  // namespace perfetto
678 
679 #endif  // PERFETTO_BUILDFLAG(PERFETTO_LOCAL_SYMBOLIZER)
680