1 // Copyright 2018 The Abseil Authors.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 // This library provides Symbolize() function that symbolizes program
16 // counters to their corresponding symbol names on linux platforms.
17 // This library has a minimal implementation of an ELF symbol table
18 // reader (i.e. it doesn't depend on libelf, etc.).
20 // The algorithm used in Symbolize() is as follows.
22 // 1. Go through a list of maps in /proc/self/maps and find the map
23 // containing the program counter.
25 // 2. Open the mapped file and find a regular symbol table inside.
26 // Iterate over symbols in the symbol table and look for the symbol
27 // containing the program counter. If such a symbol is found,
28 // obtain the symbol name, and demangle the symbol if possible.
29 // If the symbol isn't found in the regular symbol table (binary is
30 // stripped), try the same thing with a dynamic symbol table.
32 // Note that Symbolize() is originally implemented to be used in
33 // signal handlers, hence it doesn't use malloc() and other unsafe
34 // operations. It should be both thread-safe and async-signal-safe.
36 // Implementation note:
38 // We don't use heaps but only use stacks. We want to reduce the
39 // stack consumption so that the symbolizer can run on small stacks.
41 // Here are some numbers collected with GCC 4.1.0 on x86:
42 // - sizeof(Elf32_Sym) = 16
43 // - sizeof(Elf32_Shdr) = 40
44 // - sizeof(Elf64_Sym) = 24
45 // - sizeof(Elf64_Shdr) = 64
47 // This implementation is intended to be async-signal-safe but uses some
48 // functions which are not guaranteed to be so, such as memchr() and
49 // memmove(). We assume they are async-signal-safe.
54 #include <link.h> // For ElfW() macro.
56 #include <sys/types.h>
69 #include "absl/base/casts.h"
70 #include "absl/base/dynamic_annotations.h"
71 #include "absl/base/internal/low_level_alloc.h"
72 #include "absl/base/internal/raw_logging.h"
73 #include "absl/base/internal/spinlock.h"
74 #include "absl/base/port.h"
75 #include "absl/debugging/internal/demangle.h"
76 #include "absl/debugging/internal/vdso_support.h"
80 // Value of argv[0]. Used by MaybeInitializeObjFile().
81 static char *argv0_value = nullptr;
83 void InitializeSymbolizer(const char *argv0) {
84 if (argv0_value != nullptr) {
86 argv0_value = nullptr;
88 if (argv0 != nullptr && argv0[0] != '\0') {
89 argv0_value = strdup(argv0);
93 namespace debugging_internal {
96 // Re-runs fn until it doesn't cause EINTR.
99 } while ((fn) < 0 && errno == EINTR)
101 // On Linux, ELF_ST_* are defined in <linux/elf.h>. To make this portable
102 // we define our own ELF_ST_BIND and ELF_ST_TYPE if not available.
104 #define ELF_ST_BIND(info) (((unsigned char)(info)) >> 4)
108 #define ELF_ST_TYPE(info) (((unsigned char)(info)) & 0xF)
111 // Some platforms use a special .opd section to store function pointers.
112 const char kOpdSectionName[] = ".opd";
114 #if (defined(__powerpc__) && !(_CALL_ELF > 1)) || defined(__ia64)
115 // Use opd section for function descriptors on these platforms, the function
116 // address is the first word of the descriptor.
117 enum { kPlatformUsesOPDSections = 1 };
118 #else // not PPC or IA64
119 enum { kPlatformUsesOPDSections = 0 };
122 // This works for PowerPC & IA64 only. A function descriptor consist of two
123 // pointers and the first one is the function's entry.
124 const size_t kFunctionDescriptorSize = sizeof(void *) * 2;
126 const int kMaxDecorators = 10; // Seems like a reasonable upper limit.
128 struct InstalledSymbolDecorator {
134 int g_num_decorators;
135 InstalledSymbolDecorator g_decorators[kMaxDecorators];
137 struct FileMappingHint {
141 const char *filename;
144 // Protects g_decorators.
145 // We are using SpinLock and not a Mutex here, because we may be called
146 // from inside Mutex::Lock itself, and it prohibits recursive calls.
147 // This happens in e.g. base/stacktrace_syscall_unittest.
148 // Moreover, we are using only TryLock(), if the decorator list
149 // is being modified (is busy), we skip all decorators, and possibly
150 // loose some info. Sorry, that's the best we could do.
151 base_internal::SpinLock g_decorators_mu(base_internal::kLinkerInitialized);
153 const int kMaxFileMappingHints = 8;
154 int g_num_file_mapping_hints;
155 FileMappingHint g_file_mapping_hints[kMaxFileMappingHints];
156 // Protects g_file_mapping_hints.
157 base_internal::SpinLock g_file_mapping_mu(base_internal::kLinkerInitialized);
159 // Async-signal-safe function to zero a buffer.
160 // memset() is not guaranteed to be async-signal-safe.
161 static void SafeMemZero(void* p, size_t size) {
162 unsigned char *c = static_cast<unsigned char *>(p);
176 SafeMemZero(&elf_header, sizeof(elf_header));
180 const void *start_addr;
181 const void *end_addr;
184 // The following fields are initialized on the first access to the
188 ElfW(Ehdr) elf_header;
191 // Build 4-way associative cache for symbols. Within each cache line, symbols
192 // are replaced in LRU order.
196 struct SymbolCacheLine {
197 const void *pc[ASSOCIATIVITY];
198 char *name[ASSOCIATIVITY];
200 // age[i] is incremented when a line is accessed. it's reset to zero if the
201 // i'th entry is read.
202 uint32_t age[ASSOCIATIVITY];
205 // ---------------------------------------------------------------
206 // An async-signal-safe arena for LowLevelAlloc
207 static std::atomic<base_internal::LowLevelAlloc::Arena *> g_sig_safe_arena;
209 static base_internal::LowLevelAlloc::Arena *SigSafeArena() {
210 return g_sig_safe_arena.load(std::memory_order_acquire);
213 static void InitSigSafeArena() {
214 if (SigSafeArena() == nullptr) {
215 base_internal::LowLevelAlloc::Arena *new_arena =
216 base_internal::LowLevelAlloc::NewArena(
217 base_internal::LowLevelAlloc::kAsyncSignalSafe);
218 base_internal::LowLevelAlloc::Arena *old_value = nullptr;
219 if (!g_sig_safe_arena.compare_exchange_strong(old_value, new_arena,
220 std::memory_order_release,
221 std::memory_order_relaxed)) {
222 // We lost a race to allocate an arena; deallocate.
223 base_internal::LowLevelAlloc::DeleteArena(new_arena);
228 // ---------------------------------------------------------------
229 // An AddrMap is a vector of ObjFile, using SigSafeArena() for allocation.
233 AddrMap() : size_(0), allocated_(0), obj_(nullptr) {}
234 ~AddrMap() { base_internal::LowLevelAlloc::Free(obj_); }
235 int Size() const { return size_; }
236 ObjFile *At(int i) { return &obj_[i]; }
241 int size_; // count of valid elements (<= allocated_)
242 int allocated_; // count of allocated elements
243 ObjFile *obj_; // array of allocated_ elements
244 AddrMap(const AddrMap &) = delete;
245 AddrMap &operator=(const AddrMap &) = delete;
248 void AddrMap::Clear() {
249 for (int i = 0; i != size_; i++) {
255 ObjFile *AddrMap::Add() {
256 if (size_ == allocated_) {
257 int new_allocated = allocated_ * 2 + 50;
259 static_cast<ObjFile *>(base_internal::LowLevelAlloc::AllocWithArena(
260 new_allocated * sizeof(*new_obj_), SigSafeArena()));
262 memcpy(new_obj_, obj_, allocated_ * sizeof(*new_obj_));
263 base_internal::LowLevelAlloc::Free(obj_);
266 allocated_ = new_allocated;
268 return new (&obj_[size_++]) ObjFile;
271 // ---------------------------------------------------------------
273 enum FindSymbolResult { SYMBOL_NOT_FOUND = 1, SYMBOL_TRUNCATED, SYMBOL_FOUND };
279 const char *GetSymbol(const void *const pc);
282 char *CopyString(const char *s) {
284 char *dst = static_cast<char *>(
285 base_internal::LowLevelAlloc::AllocWithArena(len + 1, SigSafeArena()));
286 ABSL_RAW_CHECK(dst != nullptr, "out of memory");
287 memcpy(dst, s, len + 1);
290 ObjFile *FindObjFile(const void *const start,
291 size_t size) ABSL_ATTRIBUTE_NOINLINE;
292 static bool RegisterObjFile(const char *filename,
293 const void *const start_addr,
294 const void *const end_addr, uint64_t offset,
296 SymbolCacheLine *GetCacheLine(const void *const pc);
297 const char *FindSymbolInCache(const void *const pc);
298 const char *InsertSymbolInCache(const void *const pc, const char *name);
299 void AgeSymbols(SymbolCacheLine *line);
301 FindSymbolResult GetSymbolFromObjectFile(const ObjFile &obj,
302 const void *const pc,
303 const ptrdiff_t relocation,
304 char *out, int out_size,
305 char *tmp_buf, int tmp_buf_size);
308 SYMBOL_BUF_SIZE = 3072,
310 SYMBOL_CACHE_LINES = 128,
318 char symbol_buf_[SYMBOL_BUF_SIZE];
320 // tmp_buf_ will be used to store arrays of ElfW(Shdr) and ElfW(Sym)
321 // so we ensure that tmp_buf_ is properly aligned to store either.
322 alignas(16) char tmp_buf_[TMP_BUF_SIZE];
323 static_assert(alignof(ElfW(Shdr)) <= 16,
324 "alignment of tmp buf too small for Shdr");
325 static_assert(alignof(ElfW(Sym)) <= 16,
326 "alignment of tmp buf too small for Sym");
328 SymbolCacheLine symbol_cache_[SYMBOL_CACHE_LINES];
331 static std::atomic<Symbolizer *> g_cached_symbolizer;
335 static int SymbolizerSize() {
336 #if defined(__wasm__) || defined(__asmjs__)
337 int pagesize = getpagesize();
339 int pagesize = sysconf(_SC_PAGESIZE);
341 return ((sizeof(Symbolizer) - 1) / pagesize + 1) * pagesize;
344 // Return (and set null) g_cached_symbolized_state if it is not null.
345 // Otherwise return a new symbolizer.
346 static Symbolizer *AllocateSymbolizer() {
348 Symbolizer *symbolizer =
349 g_cached_symbolizer.exchange(nullptr, std::memory_order_acquire);
350 if (symbolizer != nullptr) {
353 return new (base_internal::LowLevelAlloc::AllocWithArena(
354 SymbolizerSize(), SigSafeArena())) Symbolizer();
357 // Set g_cached_symbolize_state to s if it is null, otherwise
359 static void FreeSymbolizer(Symbolizer *s) {
360 Symbolizer *old_cached_symbolizer = nullptr;
361 if (!g_cached_symbolizer.compare_exchange_strong(old_cached_symbolizer, s,
362 std::memory_order_release,
363 std::memory_order_relaxed)) {
365 base_internal::LowLevelAlloc::Free(s);
369 Symbolizer::Symbolizer() : ok_(true), addr_map_read_(false) {
370 for (SymbolCacheLine &symbol_cache_line : symbol_cache_) {
371 for (size_t j = 0; j < ABSL_ARRAYSIZE(symbol_cache_line.name); ++j) {
372 symbol_cache_line.pc[j] = nullptr;
373 symbol_cache_line.name[j] = nullptr;
374 symbol_cache_line.age[j] = 0;
379 Symbolizer::~Symbolizer() {
380 for (SymbolCacheLine &symbol_cache_line : symbol_cache_) {
381 for (char *s : symbol_cache_line.name) {
382 base_internal::LowLevelAlloc::Free(s);
388 // We don't use assert() since it's not guaranteed to be
389 // async-signal-safe. Instead we define a minimal assertion
390 // macro. So far, we don't need pretty printing for __FILE__, etc.
391 #define SAFE_ASSERT(expr) ((expr) ? static_cast<void>(0) : abort())
393 // Read up to "count" bytes from file descriptor "fd" into the buffer
394 // starting at "buf" while handling short reads and EINTR. On
395 // success, return the number of bytes read. Otherwise, return -1.
396 static ssize_t ReadPersistent(int fd, void *buf, size_t count) {
397 SAFE_ASSERT(fd >= 0);
398 SAFE_ASSERT(count <= SSIZE_MAX);
399 char *buf0 = reinterpret_cast<char *>(buf);
400 size_t num_bytes = 0;
401 while (num_bytes < count) {
403 NO_INTR(len = read(fd, buf0 + num_bytes, count - num_bytes));
404 if (len < 0) { // There was an error other than EINTR.
405 ABSL_RAW_LOG(WARNING, "read failed: errno=%d", errno);
408 if (len == 0) { // Reached EOF.
413 SAFE_ASSERT(num_bytes <= count);
414 return static_cast<ssize_t>(num_bytes);
417 // Read up to "count" bytes from "offset" in the file pointed by file
418 // descriptor "fd" into the buffer starting at "buf". On success,
419 // return the number of bytes read. Otherwise, return -1.
420 static ssize_t ReadFromOffset(const int fd, void *buf, const size_t count,
421 const off_t offset) {
422 off_t off = lseek(fd, offset, SEEK_SET);
423 if (off == (off_t)-1) {
424 ABSL_RAW_LOG(WARNING, "lseek(%d, %ju, SEEK_SET) failed: errno=%d", fd,
425 static_cast<uintmax_t>(offset), errno);
428 return ReadPersistent(fd, buf, count);
431 // Try reading exactly "count" bytes from "offset" bytes in a file
432 // pointed by "fd" into the buffer starting at "buf" while handling
433 // short reads and EINTR. On success, return true. Otherwise, return
435 static bool ReadFromOffsetExact(const int fd, void *buf, const size_t count,
436 const off_t offset) {
437 ssize_t len = ReadFromOffset(fd, buf, count, offset);
438 return len >= 0 && static_cast<size_t>(len) == count;
441 // Returns elf_header.e_type if the file pointed by fd is an ELF binary.
442 static int FileGetElfType(const int fd) {
443 ElfW(Ehdr) elf_header;
444 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
447 if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) {
450 return elf_header.e_type;
453 // Read the section headers in the given ELF binary, and if a section
454 // of the specified type is found, set the output to this section header
455 // and return true. Otherwise, return false.
456 // To keep stack consumption low, we would like this function to not get
458 static ABSL_ATTRIBUTE_NOINLINE bool GetSectionHeaderByType(
459 const int fd, ElfW(Half) sh_num, const off_t sh_offset, ElfW(Word) type,
460 ElfW(Shdr) * out, char *tmp_buf, int tmp_buf_size) {
461 ElfW(Shdr) *buf = reinterpret_cast<ElfW(Shdr) *>(tmp_buf);
462 const int buf_entries = tmp_buf_size / sizeof(buf[0]);
463 const int buf_bytes = buf_entries * sizeof(buf[0]);
465 for (int i = 0; i < sh_num;) {
466 const ssize_t num_bytes_left = (sh_num - i) * sizeof(buf[0]);
467 const ssize_t num_bytes_to_read =
468 (buf_bytes > num_bytes_left) ? num_bytes_left : buf_bytes;
469 const off_t offset = sh_offset + i * sizeof(buf[0]);
470 const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read, offset);
471 if (len % sizeof(buf[0]) != 0) {
474 "Reading %zd bytes from offset %ju returned %zd which is not a "
476 num_bytes_to_read, static_cast<uintmax_t>(offset), len,
480 const ssize_t num_headers_in_buf = len / sizeof(buf[0]);
481 SAFE_ASSERT(num_headers_in_buf <= buf_entries);
482 for (int j = 0; j < num_headers_in_buf; ++j) {
483 if (buf[j].sh_type == type) {
488 i += num_headers_in_buf;
493 // There is no particular reason to limit section name to 63 characters,
494 // but there has (as yet) been no need for anything longer either.
495 const int kMaxSectionNameLen = 64;
497 bool ForEachSection(int fd,
498 const std::function<bool(const std::string &name,
499 const ElfW(Shdr) &)> &callback) {
500 ElfW(Ehdr) elf_header;
501 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
506 off_t shstrtab_offset =
507 (elf_header.e_shoff + elf_header.e_shentsize * elf_header.e_shstrndx);
508 if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) {
512 for (int i = 0; i < elf_header.e_shnum; ++i) {
514 off_t section_header_offset =
515 (elf_header.e_shoff + elf_header.e_shentsize * i);
516 if (!ReadFromOffsetExact(fd, &out, sizeof(out), section_header_offset)) {
519 off_t name_offset = shstrtab.sh_offset + out.sh_name;
520 char header_name[kMaxSectionNameLen + 1];
522 ReadFromOffset(fd, &header_name, kMaxSectionNameLen, name_offset);
525 } else if (n_read > kMaxSectionNameLen) {
529 header_name[n_read] = '\0';
531 std::string name(header_name);
532 if (!callback(name, out)) {
539 // name_len should include terminating '\0'.
540 bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
542 char header_name[kMaxSectionNameLen];
543 if (sizeof(header_name) < name_len) {
544 ABSL_RAW_LOG(WARNING,
545 "Section name '%s' is too long (%zu); "
546 "section will not be found (even if present).",
548 // No point in even trying.
552 ElfW(Ehdr) elf_header;
553 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
558 off_t shstrtab_offset =
559 (elf_header.e_shoff + elf_header.e_shentsize * elf_header.e_shstrndx);
560 if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) {
564 for (int i = 0; i < elf_header.e_shnum; ++i) {
565 off_t section_header_offset =
566 (elf_header.e_shoff + elf_header.e_shentsize * i);
567 if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) {
570 off_t name_offset = shstrtab.sh_offset + out->sh_name;
571 ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
574 } else if (static_cast<size_t>(n_read) != name_len) {
575 // Short read -- name could be at end of file.
578 if (memcmp(header_name, name, name_len) == 0) {
585 // Compare symbols at in the same address.
586 // Return true if we should pick symbol1.
587 static bool ShouldPickFirstSymbol(const ElfW(Sym) & symbol1,
588 const ElfW(Sym) & symbol2) {
589 // If one of the symbols is weak and the other is not, pick the one
590 // this is not a weak symbol.
591 char bind1 = ELF_ST_BIND(symbol1.st_info);
592 char bind2 = ELF_ST_BIND(symbol1.st_info);
593 if (bind1 == STB_WEAK && bind2 != STB_WEAK) return false;
594 if (bind2 == STB_WEAK && bind1 != STB_WEAK) return true;
596 // If one of the symbols has zero size and the other is not, pick the
597 // one that has non-zero size.
598 if (symbol1.st_size != 0 && symbol2.st_size == 0) {
601 if (symbol1.st_size == 0 && symbol2.st_size != 0) {
605 // If one of the symbols has no type and the other is not, pick the
606 // one that has a type.
607 char type1 = ELF_ST_TYPE(symbol1.st_info);
608 char type2 = ELF_ST_TYPE(symbol1.st_info);
609 if (type1 != STT_NOTYPE && type2 == STT_NOTYPE) {
612 if (type1 == STT_NOTYPE && type2 != STT_NOTYPE) {
616 // Pick the first one, if we still cannot decide.
620 // Return true if an address is inside a section.
621 static bool InSection(const void *address, const ElfW(Shdr) * section) {
622 const char *start = reinterpret_cast<const char *>(section->sh_addr);
623 size_t size = static_cast<size_t>(section->sh_size);
624 return start <= address && address < (start + size);
627 // Read a symbol table and look for the symbol containing the
628 // pc. Iterate over symbols in a symbol table and look for the symbol
629 // containing "pc". If the symbol is found, and its name fits in
630 // out_size, the name is written into out and SYMBOL_FOUND is returned.
631 // If the name does not fit, truncated name is written into out,
632 // and SYMBOL_TRUNCATED is returned. Out is NUL-terminated.
633 // If the symbol is not found, SYMBOL_NOT_FOUND is returned;
634 // To keep stack consumption low, we would like this function to not get
636 static ABSL_ATTRIBUTE_NOINLINE FindSymbolResult FindSymbol(
637 const void *const pc, const int fd, char *out, int out_size,
638 ptrdiff_t relocation, const ElfW(Shdr) * strtab, const ElfW(Shdr) * symtab,
639 const ElfW(Shdr) * opd, char *tmp_buf, int tmp_buf_size) {
640 if (symtab == nullptr) {
641 return SYMBOL_NOT_FOUND;
644 // Read multiple symbols at once to save read() calls.
645 ElfW(Sym) *buf = reinterpret_cast<ElfW(Sym) *>(tmp_buf);
646 const int buf_entries = tmp_buf_size / sizeof(buf[0]);
648 const int num_symbols = symtab->sh_size / symtab->sh_entsize;
650 // On platforms using an .opd section (PowerPC & IA64), a function symbol
651 // has the address of a function descriptor, which contains the real
652 // starting address. However, we do not always want to use the real
653 // starting address because we sometimes want to symbolize a function
654 // pointer into the .opd section, e.g. FindSymbol(&foo,...).
655 const bool pc_in_opd =
656 kPlatformUsesOPDSections && opd != nullptr && InSection(pc, opd);
657 const bool deref_function_descriptor_pointer =
658 kPlatformUsesOPDSections && opd != nullptr && !pc_in_opd;
660 ElfW(Sym) best_match;
661 SafeMemZero(&best_match, sizeof(best_match));
662 bool found_match = false;
663 for (int i = 0; i < num_symbols;) {
664 off_t offset = symtab->sh_offset + i * symtab->sh_entsize;
665 const int num_remaining_symbols = num_symbols - i;
666 const int entries_in_chunk = std::min(num_remaining_symbols, buf_entries);
667 const int bytes_in_chunk = entries_in_chunk * sizeof(buf[0]);
668 const ssize_t len = ReadFromOffset(fd, buf, bytes_in_chunk, offset);
669 SAFE_ASSERT(len % sizeof(buf[0]) == 0);
670 const ssize_t num_symbols_in_buf = len / sizeof(buf[0]);
671 SAFE_ASSERT(num_symbols_in_buf <= entries_in_chunk);
672 for (int j = 0; j < num_symbols_in_buf; ++j) {
673 const ElfW(Sym) &symbol = buf[j];
675 // For a DSO, a symbol address is relocated by the loading address.
676 // We keep the original address for opd redirection below.
677 const char *const original_start_address =
678 reinterpret_cast<const char *>(symbol.st_value);
679 const char *start_address = original_start_address + relocation;
681 if (deref_function_descriptor_pointer &&
682 InSection(original_start_address, opd)) {
683 // The opd section is mapped into memory. Just dereference
684 // start_address to get the first double word, which points to the
686 start_address = *reinterpret_cast<const char *const *>(start_address);
689 // If pc is inside the .opd section, it points to a function descriptor.
690 const size_t size = pc_in_opd ? kFunctionDescriptorSize : symbol.st_size;
691 const void *const end_address =
692 reinterpret_cast<const char *>(start_address) + size;
693 if (symbol.st_value != 0 && // Skip null value symbols.
694 symbol.st_shndx != 0 && // Skip undefined symbols.
696 ELF_ST_TYPE(symbol.st_info) != STT_TLS && // Skip thread-local data.
698 ((start_address <= pc && pc < end_address) ||
699 (start_address == pc && pc == end_address))) {
700 if (!found_match || ShouldPickFirstSymbol(symbol, best_match)) {
706 i += num_symbols_in_buf;
710 const size_t off = strtab->sh_offset + best_match.st_name;
711 const ssize_t n_read = ReadFromOffset(fd, out, out_size, off);
713 // This should never happen.
714 ABSL_RAW_LOG(WARNING,
715 "Unable to read from fd %d at offset %zu: n_read = %zd", fd,
717 return SYMBOL_NOT_FOUND;
719 ABSL_RAW_CHECK(n_read <= out_size, "ReadFromOffset read too much data.");
721 // strtab->sh_offset points into .strtab-like section that contains
722 // NUL-terminated strings: '\0foo\0barbaz\0...".
724 // sh_offset+st_name points to the start of symbol name, but we don't know
725 // how long the symbol is, so we try to read as much as we have space for,
726 // and usually over-read (i.e. there is a NUL somewhere before n_read).
727 if (memchr(out, '\0', n_read) == nullptr) {
728 // Either out_size was too small (n_read == out_size and no NUL), or
729 // we tried to read past the EOF (n_read < out_size) and .strtab is
730 // corrupt (missing terminating NUL; should never happen for valid ELF).
731 out[n_read - 1] = '\0';
732 return SYMBOL_TRUNCATED;
737 return SYMBOL_NOT_FOUND;
740 // Get the symbol name of "pc" from the file pointed by "fd". Process
741 // both regular and dynamic symbol tables if necessary.
742 // See FindSymbol() comment for description of return value.
743 FindSymbolResult Symbolizer::GetSymbolFromObjectFile(
744 const ObjFile &obj, const void *const pc, const ptrdiff_t relocation,
745 char *out, int out_size, char *tmp_buf, int tmp_buf_size) {
749 ElfW(Shdr) *opd_ptr = nullptr;
751 // On platforms using an .opd sections for function descriptor, read
752 // the section header. The .opd section is in data segment and should be
753 // loaded but we check that it is mapped just to be extra careful.
754 if (kPlatformUsesOPDSections) {
755 if (GetSectionHeaderByName(obj.fd, kOpdSectionName,
756 sizeof(kOpdSectionName) - 1, &opd) &&
757 FindObjFile(reinterpret_cast<const char *>(opd.sh_addr) + relocation,
758 opd.sh_size) != nullptr) {
761 return SYMBOL_NOT_FOUND;
765 // Consult a regular symbol table, then fall back to the dynamic symbol table.
766 for (const auto symbol_table_type : {SHT_SYMTAB, SHT_DYNSYM}) {
767 if (!GetSectionHeaderByType(obj.fd, obj.elf_header.e_shnum,
768 obj.elf_header.e_shoff, symbol_table_type,
769 &symtab, tmp_buf, tmp_buf_size)) {
772 if (!ReadFromOffsetExact(
773 obj.fd, &strtab, sizeof(strtab),
774 obj.elf_header.e_shoff + symtab.sh_link * sizeof(symtab))) {
777 const FindSymbolResult rc =
778 FindSymbol(pc, obj.fd, out, out_size, relocation, &strtab, &symtab,
779 opd_ptr, tmp_buf, tmp_buf_size);
780 if (rc != SYMBOL_NOT_FOUND) {
785 return SYMBOL_NOT_FOUND;
789 // Thin wrapper around a file descriptor so that the file descriptor
790 // gets closed for sure.
791 class FileDescriptor {
793 explicit FileDescriptor(int fd) : fd_(fd) {}
794 FileDescriptor(const FileDescriptor &) = delete;
795 FileDescriptor &operator=(const FileDescriptor &) = delete;
803 int get() const { return fd_; }
809 // Helper class for reading lines from file.
811 // Note: we don't use ProcMapsIterator since the object is big (it has
812 // a 5k array member) and uses async-unsafe functions such as sscanf()
816 explicit LineReader(int fd, char *buf, int buf_len)
824 LineReader(const LineReader &) = delete;
825 LineReader &operator=(const LineReader &) = delete;
827 // Read '\n'-terminated line from file. On success, modify "bol"
828 // and "eol", then return true. Otherwise, return false.
830 // Note: if the last line doesn't end with '\n', the line will be
831 // dropped. It's an intentional behavior to make the code simple.
832 bool ReadLine(const char **bol, const char **eol) {
833 if (BufferIsEmpty()) { // First time.
834 const ssize_t num_bytes = ReadPersistent(fd_, buf_, buf_len_);
835 if (num_bytes <= 0) { // EOF or error.
838 eod_ = buf_ + num_bytes;
841 bol_ = eol_ + 1; // Advance to the next line in the buffer.
842 SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_".
843 if (!HasCompleteLine()) {
844 const int incomplete_line_length = eod_ - bol_;
845 // Move the trailing incomplete line to the beginning.
846 memmove(buf_, bol_, incomplete_line_length);
847 // Read text from file and append it.
848 char *const append_pos = buf_ + incomplete_line_length;
849 const int capacity_left = buf_len_ - incomplete_line_length;
850 const ssize_t num_bytes =
851 ReadPersistent(fd_, append_pos, capacity_left);
852 if (num_bytes <= 0) { // EOF or error.
855 eod_ = append_pos + num_bytes;
859 eol_ = FindLineFeed();
860 if (eol_ == nullptr) { // '\n' not found. Malformed line.
863 *eol_ = '\0'; // Replace '\n' with '\0'.
871 char *FindLineFeed() const {
872 return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_));
875 bool BufferIsEmpty() const { return buf_ == eod_; }
877 bool HasCompleteLine() const {
878 return !BufferIsEmpty() && FindLineFeed() != nullptr;
886 const char *eod_; // End of data in "buf_".
890 // Place the hex number read from "start" into "*hex". The pointer to
891 // the first non-hex character or "end" is returned.
892 static const char *GetHex(const char *start, const char *end,
893 uint64_t *const value) {
896 for (p = start; p < end; ++p) {
898 if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') ||
899 (ch >= 'a' && ch <= 'f')) {
900 hex = (hex << 4) | (ch < 'A' ? ch - '0' : (ch & 0xF) + 9);
901 } else { // Encountered the first non-hex character.
905 SAFE_ASSERT(p <= end);
910 static const char *GetHex(const char *start, const char *end,
911 const void **const addr) {
913 const char *p = GetHex(start, end, &hex);
914 *addr = reinterpret_cast<void *>(hex);
918 // Normally we are only interested in "r?x" maps.
919 // On the PowerPC, function pointers point to descriptors in the .opd
920 // section. The descriptors themselves are not executable code, so
921 // we need to relax the check below to "r??".
922 static bool ShouldUseMapping(const char *const flags) {
923 return flags[0] == 'r' && (kPlatformUsesOPDSections || flags[2] == 'x');
926 // Read /proc/self/maps and run "callback" for each mmapped file found. If
927 // "callback" returns false, stop scanning and return true. Else continue
928 // scanning /proc/self/maps. Return true if no parse error is found.
929 static ABSL_ATTRIBUTE_NOINLINE bool ReadAddrMap(
930 bool (*callback)(const char *filename, const void *const start_addr,
931 const void *const end_addr, uint64_t offset, void *arg),
932 void *arg, void *tmp_buf, int tmp_buf_size) {
933 // Use /proc/self/task/<pid>/maps instead of /proc/self/maps. The latter
934 // requires kernel to stop all threads, and is significantly slower when there
935 // are 1000s of threads.
937 snprintf(maps_path, sizeof(maps_path), "/proc/self/task/%d/maps", getpid());
940 NO_INTR(maps_fd = open(maps_path, O_RDONLY));
941 FileDescriptor wrapped_maps_fd(maps_fd);
942 if (wrapped_maps_fd.get() < 0) {
943 ABSL_RAW_LOG(WARNING, "%s: errno=%d", maps_path, errno);
947 // Iterate over maps and look for the map containing the pc. Then
948 // look into the symbol tables inside.
949 LineReader reader(wrapped_maps_fd.get(), static_cast<char *>(tmp_buf),
954 if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line.
958 const char *line = cursor;
959 const void *start_address;
960 // Start parsing line in /proc/self/maps. Here is an example:
962 // 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat
964 // We want start address (08048000), end address (0804c000), flags
965 // (r-xp) and file name (/bin/cat).
967 // Read start address.
968 cursor = GetHex(cursor, eol, &start_address);
969 if (cursor == eol || *cursor != '-') {
970 ABSL_RAW_LOG(WARNING, "Corrupt /proc/self/maps line: %s", line);
973 ++cursor; // Skip '-'.
976 const void *end_address;
977 cursor = GetHex(cursor, eol, &end_address);
978 if (cursor == eol || *cursor != ' ') {
979 ABSL_RAW_LOG(WARNING, "Corrupt /proc/self/maps line: %s", line);
982 ++cursor; // Skip ' '.
984 // Read flags. Skip flags until we encounter a space or eol.
985 const char *const flags_start = cursor;
986 while (cursor < eol && *cursor != ' ') {
989 // We expect at least four letters for flags (ex. "r-xp").
990 if (cursor == eol || cursor < flags_start + 4) {
991 ABSL_RAW_LOG(WARNING, "Corrupt /proc/self/maps: %s", line);
996 if (!ShouldUseMapping(flags_start)) {
997 continue; // We skip this map.
999 ++cursor; // Skip ' '.
1001 // Read file offset.
1003 cursor = GetHex(cursor, eol, &offset);
1004 ++cursor; // Skip ' '.
1006 // Skip to file name. "cursor" now points to dev. We need to skip at least
1007 // two spaces for dev and inode.
1009 while (cursor < eol) {
1010 if (*cursor == ' ') {
1012 } else if (num_spaces >= 2) {
1013 // The first non-space character after skipping two spaces
1014 // is the beginning of the file name.
1020 // Check whether this entry corresponds to our hint table for the true
1023 GetFileMappingHint(&start_address, &end_address, &offset, &cursor);
1024 if (!hinted && (cursor == eol || cursor[0] == '[')) {
1025 // not an object file, typically [vdso] or [vsyscall]
1028 if (!callback(cursor, start_address, end_address, offset, arg)) break;
1033 // Find the objfile mapped in address region containing [addr, addr + len).
1034 ObjFile *Symbolizer::FindObjFile(const void *const addr, size_t len) {
1035 for (int i = 0; i < 2; ++i) {
1036 if (!ok_) return nullptr;
1038 // Read /proc/self/maps if necessary
1039 if (!addr_map_read_) {
1040 addr_map_read_ = true;
1041 if (!ReadAddrMap(RegisterObjFile, this, tmp_buf_, TMP_BUF_SIZE)) {
1048 int hi = addr_map_.Size();
1050 int mid = (lo + hi) / 2;
1051 if (addr < addr_map_.At(mid)->end_addr) {
1057 if (lo != addr_map_.Size()) {
1058 ObjFile *obj = addr_map_.At(lo);
1059 SAFE_ASSERT(obj->end_addr > addr);
1060 if (addr >= obj->start_addr &&
1061 reinterpret_cast<const char *>(addr) + len <= obj->end_addr)
1065 // The address mapping may have changed since it was last read. Retry.
1071 void Symbolizer::ClearAddrMap() {
1072 for (int i = 0; i != addr_map_.Size(); i++) {
1073 ObjFile *o = addr_map_.At(i);
1074 base_internal::LowLevelAlloc::Free(o->filename);
1076 NO_INTR(close(o->fd));
1080 addr_map_read_ = false;
1083 // Callback for ReadAddrMap to register objfiles in an in-memory table.
1084 bool Symbolizer::RegisterObjFile(const char *filename,
1085 const void *const start_addr,
1086 const void *const end_addr, uint64_t offset,
1088 Symbolizer *impl = static_cast<Symbolizer *>(arg);
1090 // Files are supposed to be added in the increasing address order. Make
1091 // sure that's the case.
1092 int addr_map_size = impl->addr_map_.Size();
1093 if (addr_map_size != 0) {
1094 ObjFile *old = impl->addr_map_.At(addr_map_size - 1);
1095 if (old->end_addr > end_addr) {
1097 "Unsorted addr map entry: 0x%" PRIxPTR ": %s <-> 0x%" PRIxPTR
1099 reinterpret_cast<uintptr_t>(end_addr), filename,
1100 reinterpret_cast<uintptr_t>(old->end_addr), old->filename);
1102 } else if (old->end_addr == end_addr) {
1103 // The same entry appears twice. This sometimes happens for [vdso].
1104 if (old->start_addr != start_addr ||
1105 strcmp(old->filename, filename) != 0) {
1107 "Duplicate addr 0x%" PRIxPTR ": %s <-> 0x%" PRIxPTR ": %s",
1108 reinterpret_cast<uintptr_t>(end_addr), filename,
1109 reinterpret_cast<uintptr_t>(old->end_addr), old->filename);
1114 ObjFile *obj = impl->addr_map_.Add();
1115 obj->filename = impl->CopyString(filename);
1116 obj->start_addr = start_addr;
1117 obj->end_addr = end_addr;
1118 obj->offset = offset;
1119 obj->elf_type = -1; // filled on demand
1120 obj->fd = -1; // opened on demand
1124 // This function wraps the Demangle function to provide an interface
1125 // where the input symbol is demangled in-place.
1126 // To keep stack consumption low, we would like this function to not
1128 static ABSL_ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size,
1131 if (Demangle(out, tmp_buf, tmp_buf_size)) {
1132 // Demangling succeeded. Copy to out if the space allows.
1133 int len = strlen(tmp_buf);
1134 if (len + 1 <= out_size) { // +1 for '\0'.
1135 SAFE_ASSERT(len < tmp_buf_size);
1136 memmove(out, tmp_buf, len + 1);
1141 SymbolCacheLine *Symbolizer::GetCacheLine(const void *const pc) {
1142 uintptr_t pc0 = reinterpret_cast<uintptr_t>(pc);
1143 pc0 >>= 3; // drop the low 3 bits
1146 pc0 ^= (pc0 >> 6) ^ (pc0 >> 12) ^ (pc0 >> 18);
1147 return &symbol_cache_[pc0 % SYMBOL_CACHE_LINES];
1150 void Symbolizer::AgeSymbols(SymbolCacheLine *line) {
1151 for (uint32_t &age : line->age) {
1156 const char *Symbolizer::FindSymbolInCache(const void *const pc) {
1157 if (pc == nullptr) return nullptr;
1159 SymbolCacheLine *line = GetCacheLine(pc);
1160 for (size_t i = 0; i < ABSL_ARRAYSIZE(line->pc); ++i) {
1161 if (line->pc[i] == pc) {
1164 return line->name[i];
1170 const char *Symbolizer::InsertSymbolInCache(const void *const pc,
1172 SAFE_ASSERT(pc != nullptr);
1174 SymbolCacheLine *line = GetCacheLine(pc);
1175 uint32_t max_age = 0;
1176 int oldest_index = -1;
1177 for (size_t i = 0; i < ABSL_ARRAYSIZE(line->pc); ++i) {
1178 if (line->pc[i] == nullptr) {
1181 line->name[i] = CopyString(name);
1183 return line->name[i];
1185 if (line->age[i] >= max_age) {
1186 max_age = line->age[i];
1192 ABSL_RAW_CHECK(oldest_index >= 0, "Corrupt cache");
1193 base_internal::LowLevelAlloc::Free(line->name[oldest_index]);
1194 line->pc[oldest_index] = pc;
1195 line->name[oldest_index] = CopyString(name);
1196 line->age[oldest_index] = 0;
1197 return line->name[oldest_index];
1200 static void MaybeOpenFdFromSelfExe(ObjFile *obj) {
1201 if (memcmp(obj->start_addr, ELFMAG, SELFMAG) != 0) {
1204 int fd = open("/proc/self/exe", O_RDONLY);
1208 // Verify that contents of /proc/self/exe matches in-memory image of
1209 // the binary. This can fail if the "deleted" binary is in fact not
1210 // the main executable, or for binaries that have the first PT_LOAD
1211 // segment smaller than 4K. We do it in four steps so that the
1212 // buffer is smaller and we don't consume too much stack space.
1213 const char *mem = reinterpret_cast<const char *>(obj->start_addr);
1214 for (int i = 0; i < 4; ++i) {
1216 ssize_t n = read(fd, buf, sizeof(buf));
1217 if (n != sizeof(buf) || memcmp(buf, mem, sizeof(buf)) != 0) {
1226 static bool MaybeInitializeObjFile(ObjFile *obj) {
1228 obj->fd = open(obj->filename, O_RDONLY);
1231 // Getting /proc/self/exe here means that we were hinted.
1232 if (strcmp(obj->filename, "/proc/self/exe") == 0) {
1233 // /proc/self/exe may be inaccessible (due to setuid, etc.), so try
1234 // accessing the binary via argv0.
1235 if (argv0_value != nullptr) {
1236 obj->fd = open(argv0_value, O_RDONLY);
1239 MaybeOpenFdFromSelfExe(obj);
1244 ABSL_RAW_LOG(WARNING, "%s: open failed: errno=%d", obj->filename, errno);
1247 obj->elf_type = FileGetElfType(obj->fd);
1248 if (obj->elf_type < 0) {
1249 ABSL_RAW_LOG(WARNING, "%s: wrong elf type: %d", obj->filename,
1254 if (!ReadFromOffsetExact(obj->fd, &obj->elf_header, sizeof(obj->elf_header),
1256 ABSL_RAW_LOG(WARNING, "%s: failed to read elf header", obj->filename);
1263 // The implementation of our symbolization routine. If it
1264 // successfully finds the symbol containing "pc" and obtains the
1265 // symbol name, returns pointer to that symbol. Otherwise, returns nullptr.
1266 // If any symbol decorators have been installed via InstallSymbolDecorator(),
1267 // they are called here as well.
1268 // To keep stack consumption low, we would like this function to not
1270 const char *Symbolizer::GetSymbol(const void *const pc) {
1271 const char *entry = FindSymbolInCache(pc);
1272 if (entry != nullptr) {
1275 symbol_buf_[0] = '\0';
1277 ObjFile *const obj = FindObjFile(pc, 1);
1278 ptrdiff_t relocation = 0;
1280 if (obj != nullptr) {
1281 if (MaybeInitializeObjFile(obj)) {
1282 if (obj->elf_type == ET_DYN &&
1283 reinterpret_cast<uint64_t>(obj->start_addr) >= obj->offset) {
1284 // This object was relocated.
1286 // For obj->offset > 0, adjust the relocation since a mapping at offset
1287 // X in the file will have a start address of [true relocation]+X.
1288 relocation = reinterpret_cast<ptrdiff_t>(obj->start_addr) - obj->offset;
1293 if (GetSymbolFromObjectFile(*obj, pc, relocation, symbol_buf_,
1294 sizeof(symbol_buf_), tmp_buf_,
1295 sizeof(tmp_buf_)) == SYMBOL_FOUND) {
1296 // Only try to demangle the symbol name if it fit into symbol_buf_.
1297 DemangleInplace(symbol_buf_, sizeof(symbol_buf_), tmp_buf_,
1301 #if ABSL_HAVE_VDSO_SUPPORT
1303 if (vdso.IsPresent()) {
1304 VDSOSupport::SymbolInfo symbol_info;
1305 if (vdso.LookupSymbolByAddress(pc, &symbol_info)) {
1306 // All VDSO symbols are known to be short.
1307 size_t len = strlen(symbol_info.name);
1308 ABSL_RAW_CHECK(len + 1 < sizeof(symbol_buf_),
1309 "VDSO symbol unexpectedly long");
1310 memcpy(symbol_buf_, symbol_info.name, len + 1);
1316 if (g_decorators_mu.TryLock()) {
1317 if (g_num_decorators > 0) {
1318 SymbolDecoratorArgs decorator_args = {
1319 pc, relocation, fd, symbol_buf_, sizeof(symbol_buf_),
1320 tmp_buf_, sizeof(tmp_buf_), nullptr};
1321 for (int i = 0; i < g_num_decorators; ++i) {
1322 decorator_args.arg = g_decorators[i].arg;
1323 g_decorators[i].fn(&decorator_args);
1326 g_decorators_mu.Unlock();
1328 if (symbol_buf_[0] == '\0') {
1331 symbol_buf_[sizeof(symbol_buf_) - 1] = '\0'; // Paranoia.
1332 return InsertSymbolInCache(pc, symbol_buf_);
1335 bool RemoveAllSymbolDecorators(void) {
1336 if (!g_decorators_mu.TryLock()) {
1337 // Someone else is using decorators. Get out.
1340 g_num_decorators = 0;
1341 g_decorators_mu.Unlock();
1345 bool RemoveSymbolDecorator(int ticket) {
1346 if (!g_decorators_mu.TryLock()) {
1347 // Someone else is using decorators. Get out.
1350 for (int i = 0; i < g_num_decorators; ++i) {
1351 if (g_decorators[i].ticket == ticket) {
1352 while (i < g_num_decorators - 1) {
1353 g_decorators[i] = g_decorators[i + 1];
1356 g_num_decorators = i;
1360 g_decorators_mu.Unlock();
1361 return true; // Decorator is known to be removed.
1364 int InstallSymbolDecorator(SymbolDecorator decorator, void *arg) {
1365 static int ticket = 0;
1367 if (!g_decorators_mu.TryLock()) {
1368 // Someone else is using decorators. Get out.
1372 if (g_num_decorators >= kMaxDecorators) {
1375 g_decorators[g_num_decorators] = {decorator, arg, ticket++};
1378 g_decorators_mu.Unlock();
1382 bool RegisterFileMappingHint(const void *start, const void *end, uint64_t offset,
1383 const char *filename) {
1384 SAFE_ASSERT(start <= end);
1385 SAFE_ASSERT(filename != nullptr);
1389 if (!g_file_mapping_mu.TryLock()) {
1394 if (g_num_file_mapping_hints >= kMaxFileMappingHints) {
1397 // TODO(ckennelly): Move this into a std::string copy routine.
1398 int len = strlen(filename);
1399 char *dst = static_cast<char *>(
1400 base_internal::LowLevelAlloc::AllocWithArena(len + 1, SigSafeArena()));
1401 ABSL_RAW_CHECK(dst != nullptr, "out of memory");
1402 memcpy(dst, filename, len + 1);
1404 auto &hint = g_file_mapping_hints[g_num_file_mapping_hints++];
1407 hint.offset = offset;
1408 hint.filename = dst;
1411 g_file_mapping_mu.Unlock();
1415 bool GetFileMappingHint(const void **start, const void **end, uint64_t *offset,
1416 const char **filename) {
1417 if (!g_file_mapping_mu.TryLock()) {
1421 for (int i = 0; i < g_num_file_mapping_hints; i++) {
1422 if (g_file_mapping_hints[i].start <= *start &&
1423 *end <= g_file_mapping_hints[i].end) {
1424 // We assume that the start_address for the mapping is the base
1425 // address of the ELF section, but when [start_address,end_address) is
1426 // not strictly equal to [hint.start, hint.end), that assumption is
1429 // This uses the hint's start address (even though hint.start is not
1430 // necessarily equal to start_address) to ensure the correct
1431 // relocation is computed later.
1432 *start = g_file_mapping_hints[i].start;
1433 *end = g_file_mapping_hints[i].end;
1434 *offset = g_file_mapping_hints[i].offset;
1435 *filename = g_file_mapping_hints[i].filename;
1440 g_file_mapping_mu.Unlock();
1444 } // namespace debugging_internal
1446 bool Symbolize(const void *pc, char *out, int out_size) {
1447 // Symbolization is very slow under tsan.
1448 ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN();
1449 SAFE_ASSERT(out_size >= 0);
1450 debugging_internal::Symbolizer *s = debugging_internal::AllocateSymbolizer();
1451 const char *name = s->GetSymbol(pc);
1453 if (name != nullptr && out_size > 0) {
1454 strncpy(out, name, out_size);
1456 if (out[out_size - 1] != '\0') {
1457 // strncpy() does not '\0' terminate when it truncates. Do so, with
1458 // trailing ellipsis.
1459 static constexpr char kEllipsis[] = "...";
1461 std::min(implicit_cast<int>(strlen(kEllipsis)), out_size - 1);
1462 memcpy(out + out_size - ellipsis_size - 1, kEllipsis, ellipsis_size);
1463 out[out_size - 1] = '\0';
1466 debugging_internal::FreeSymbolizer(s);
1467 ANNOTATE_IGNORE_READS_AND_WRITES_END();