symbolize_elf.inc (61273B)
1 // Copyright 2018 The Abseil Authors. 2 // 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 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 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. 14 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.). 19 // 20 // The algorithm used in Symbolize() is as follows. 21 // 22 // 1. Go through a list of maps in /proc/self/maps and find the map 23 // containing the program counter. 24 // 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. 31 // 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. 35 // 36 // Implementation note: 37 // 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. 40 // 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 46 // 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. 50 51 #include <dlfcn.h> 52 #include <elf.h> 53 #include <fcntl.h> 54 #include <link.h> // For ElfW() macro. 55 #include <sys/resource.h> 56 #include <sys/stat.h> 57 #include <sys/types.h> 58 #include <unistd.h> 59 60 #include <algorithm> 61 #include <array> 62 #include <atomic> 63 #include <cerrno> 64 #include <cinttypes> 65 #include <climits> 66 #include <cstdint> 67 #include <cstdio> 68 #include <cstdlib> 69 #include <cstring> 70 71 #include "absl/base/casts.h" 72 #include "absl/base/dynamic_annotations.h" 73 #include "absl/base/internal/low_level_alloc.h" 74 #include "absl/base/internal/raw_logging.h" 75 #include "absl/base/internal/spinlock.h" 76 #include "absl/base/port.h" 77 #include "absl/debugging/internal/demangle.h" 78 #include "absl/debugging/internal/vdso_support.h" 79 #include "absl/strings/string_view.h" 80 81 #if defined(__FreeBSD__) && !defined(ElfW) 82 #define ElfW(x) __ElfN(x) 83 #endif 84 85 namespace absl { 86 ABSL_NAMESPACE_BEGIN 87 88 // Value of argv[0]. Used by MaybeInitializeObjFile(). 89 static char *argv0_value = nullptr; 90 91 void InitializeSymbolizer(const char *argv0) { 92 #ifdef ABSL_HAVE_VDSO_SUPPORT 93 // We need to make sure VDSOSupport::Init() is called before any setuid or 94 // chroot calls, so InitializeSymbolizer() should be called very early in the 95 // life of a program. 96 absl::debugging_internal::VDSOSupport::Init(); 97 #endif 98 if (argv0_value != nullptr) { 99 free(argv0_value); 100 argv0_value = nullptr; 101 } 102 if (argv0 != nullptr && argv0[0] != '\0') { 103 argv0_value = strdup(argv0); 104 } 105 } 106 107 namespace debugging_internal { 108 namespace { 109 110 // Re-runs fn until it doesn't cause EINTR. 111 #define NO_INTR(fn) \ 112 do { \ 113 } while ((fn) < 0 && errno == EINTR) 114 115 // On Linux, ELF_ST_* are defined in <linux/elf.h>. To make this portable 116 // we define our own ELF_ST_BIND and ELF_ST_TYPE if not available. 117 #ifndef ELF_ST_BIND 118 #define ELF_ST_BIND(info) (((unsigned char)(info)) >> 4) 119 #endif 120 121 #ifndef ELF_ST_TYPE 122 #define ELF_ST_TYPE(info) (((unsigned char)(info)) & 0xF) 123 #endif 124 125 // Some platforms use a special .opd section to store function pointers. 126 const char kOpdSectionName[] = ".opd"; 127 128 #if (defined(__powerpc__) && !(_CALL_ELF > 1)) || defined(__ia64) 129 // Use opd section for function descriptors on these platforms, the function 130 // address is the first word of the descriptor. 131 enum { kPlatformUsesOPDSections = 1 }; 132 #else // not PPC or IA64 133 enum { kPlatformUsesOPDSections = 0 }; 134 #endif 135 136 // This works for PowerPC & IA64 only. A function descriptor consist of two 137 // pointers and the first one is the function's entry. 138 const size_t kFunctionDescriptorSize = sizeof(void *) * 2; 139 140 const int kMaxDecorators = 10; // Seems like a reasonable upper limit. 141 142 struct InstalledSymbolDecorator { 143 SymbolDecorator fn; 144 void *arg; 145 int ticket; 146 }; 147 148 int g_num_decorators; 149 InstalledSymbolDecorator g_decorators[kMaxDecorators]; 150 151 struct FileMappingHint { 152 const void *start; 153 const void *end; 154 uint64_t offset; 155 const char *filename; 156 }; 157 158 // Protects g_decorators. 159 // We are using SpinLock and not a Mutex here, because we may be called 160 // from inside Mutex::Lock itself, and it prohibits recursive calls. 161 // This happens in e.g. base/stacktrace_syscall_unittest. 162 // Moreover, we are using only TryLock(), if the decorator list 163 // is being modified (is busy), we skip all decorators, and possibly 164 // loose some info. Sorry, that's the best we could do. 165 ABSL_CONST_INIT absl::base_internal::SpinLock g_decorators_mu( 166 absl::kConstInit, absl::base_internal::SCHEDULE_KERNEL_ONLY); 167 168 const int kMaxFileMappingHints = 8; 169 int g_num_file_mapping_hints; 170 FileMappingHint g_file_mapping_hints[kMaxFileMappingHints]; 171 // Protects g_file_mapping_hints. 172 ABSL_CONST_INIT absl::base_internal::SpinLock g_file_mapping_mu( 173 absl::kConstInit, absl::base_internal::SCHEDULE_KERNEL_ONLY); 174 175 // Async-signal-safe function to zero a buffer. 176 // memset() is not guaranteed to be async-signal-safe. 177 static void SafeMemZero(void* p, size_t size) { 178 unsigned char *c = static_cast<unsigned char *>(p); 179 while (size--) { 180 *c++ = 0; 181 } 182 } 183 184 struct ObjFile { 185 ObjFile() 186 : filename(nullptr), 187 start_addr(nullptr), 188 end_addr(nullptr), 189 offset(0), 190 fd(-1), 191 elf_type(-1) { 192 SafeMemZero(&elf_header, sizeof(elf_header)); 193 SafeMemZero(&phdr[0], sizeof(phdr)); 194 } 195 196 char *filename; 197 const void *start_addr; 198 const void *end_addr; 199 uint64_t offset; 200 201 // The following fields are initialized on the first access to the 202 // object file. 203 int fd; 204 int elf_type; 205 ElfW(Ehdr) elf_header; 206 207 // PT_LOAD program header describing executable code. 208 // Normally we expect just one, but SWIFT binaries have two. 209 // CUDA binaries have 3 (see cr/473913254 description). 210 std::array<ElfW(Phdr), 4> phdr; 211 }; 212 213 // Build 4-way associative cache for symbols. Within each cache line, symbols 214 // are replaced in LRU order. 215 enum { 216 ASSOCIATIVITY = 4, 217 }; 218 struct SymbolCacheLine { 219 const void *pc[ASSOCIATIVITY]; 220 char *name[ASSOCIATIVITY]; 221 222 // age[i] is incremented when a line is accessed. it's reset to zero if the 223 // i'th entry is read. 224 uint32_t age[ASSOCIATIVITY]; 225 }; 226 227 // --------------------------------------------------------------- 228 // An async-signal-safe arena for LowLevelAlloc 229 static std::atomic<base_internal::LowLevelAlloc::Arena *> g_sig_safe_arena; 230 231 static base_internal::LowLevelAlloc::Arena *SigSafeArena() { 232 return g_sig_safe_arena.load(std::memory_order_acquire); 233 } 234 235 static void InitSigSafeArena() { 236 if (SigSafeArena() == nullptr) { 237 base_internal::LowLevelAlloc::Arena *new_arena = 238 base_internal::LowLevelAlloc::NewArena( 239 base_internal::LowLevelAlloc::kAsyncSignalSafe); 240 base_internal::LowLevelAlloc::Arena *old_value = nullptr; 241 if (!g_sig_safe_arena.compare_exchange_strong(old_value, new_arena, 242 std::memory_order_release, 243 std::memory_order_relaxed)) { 244 // We lost a race to allocate an arena; deallocate. 245 base_internal::LowLevelAlloc::DeleteArena(new_arena); 246 } 247 } 248 } 249 250 // --------------------------------------------------------------- 251 // An AddrMap is a vector of ObjFile, using SigSafeArena() for allocation. 252 253 class AddrMap { 254 public: 255 AddrMap() : size_(0), allocated_(0), obj_(nullptr) {} 256 ~AddrMap() { base_internal::LowLevelAlloc::Free(obj_); } 257 size_t Size() const { return size_; } 258 ObjFile *At(size_t i) { return &obj_[i]; } 259 ObjFile *Add(); 260 void Clear(); 261 262 private: 263 size_t size_; // count of valid elements (<= allocated_) 264 size_t allocated_; // count of allocated elements 265 ObjFile *obj_; // array of allocated_ elements 266 AddrMap(const AddrMap &) = delete; 267 AddrMap &operator=(const AddrMap &) = delete; 268 }; 269 270 void AddrMap::Clear() { 271 for (size_t i = 0; i != size_; i++) { 272 At(i)->~ObjFile(); 273 } 274 size_ = 0; 275 } 276 277 ObjFile *AddrMap::Add() { 278 if (size_ == allocated_) { 279 size_t new_allocated = allocated_ * 2 + 50; 280 ObjFile *new_obj_ = 281 static_cast<ObjFile *>(base_internal::LowLevelAlloc::AllocWithArena( 282 new_allocated * sizeof(*new_obj_), SigSafeArena())); 283 if (obj_) { 284 memcpy(new_obj_, obj_, allocated_ * sizeof(*new_obj_)); 285 base_internal::LowLevelAlloc::Free(obj_); 286 } 287 obj_ = new_obj_; 288 allocated_ = new_allocated; 289 } 290 return new (&obj_[size_++]) ObjFile; 291 } 292 293 class CachingFile { 294 public: 295 // Setup reader for fd that uses buf[0, buf_size-1] as a cache. 296 CachingFile(int fd, char *buf, size_t buf_size) 297 : fd_(fd), 298 cache_(buf), 299 cache_size_(buf_size), 300 cache_start_(0), 301 cache_limit_(0) {} 302 303 int fd() const { return fd_; } 304 ssize_t ReadFromOffset(void *buf, size_t count, off_t offset); 305 bool ReadFromOffsetExact(void *buf, size_t count, off_t offset); 306 307 private: 308 // Bytes [cache_start_, cache_limit_-1] from fd_ are stored in 309 // a prefix of cache_[0, cache_size_-1]. 310 int fd_; 311 char *cache_; 312 size_t cache_size_; 313 off_t cache_start_; 314 off_t cache_limit_; 315 }; 316 317 // --------------------------------------------------------------- 318 319 enum FindSymbolResult { SYMBOL_NOT_FOUND = 1, SYMBOL_TRUNCATED, SYMBOL_FOUND }; 320 321 class Symbolizer { 322 public: 323 Symbolizer(); 324 ~Symbolizer(); 325 const char *GetSymbol(const void *const pc); 326 327 private: 328 char *CopyString(const char *s) { 329 size_t len = strlen(s); 330 char *dst = static_cast<char *>( 331 base_internal::LowLevelAlloc::AllocWithArena(len + 1, SigSafeArena())); 332 ABSL_RAW_CHECK(dst != nullptr, "out of memory"); 333 memcpy(dst, s, len + 1); 334 return dst; 335 } 336 ObjFile *FindObjFile(const void *const start, 337 size_t size) ABSL_ATTRIBUTE_NOINLINE; 338 static bool RegisterObjFile(const char *filename, 339 const void *const start_addr, 340 const void *const end_addr, uint64_t offset, 341 void *arg); 342 SymbolCacheLine *GetCacheLine(const void *const pc); 343 const char *FindSymbolInCache(const void *const pc); 344 const char *InsertSymbolInCache(const void *const pc, const char *name); 345 void AgeSymbols(SymbolCacheLine *line); 346 void ClearAddrMap(); 347 FindSymbolResult GetSymbolFromObjectFile(const ObjFile &obj, 348 const void *const pc, 349 const ptrdiff_t relocation, 350 char *out, size_t out_size, 351 char *tmp_buf, size_t tmp_buf_size); 352 const char *GetUncachedSymbol(const void *pc); 353 354 enum { 355 SYMBOL_BUF_SIZE = 3072, 356 TMP_BUF_SIZE = 1024, 357 SYMBOL_CACHE_LINES = 128, 358 FILE_CACHE_SIZE = 8192, 359 }; 360 361 AddrMap addr_map_; 362 363 bool ok_; 364 bool addr_map_read_; 365 366 char symbol_buf_[SYMBOL_BUF_SIZE]; 367 char file_cache_[FILE_CACHE_SIZE]; 368 369 // tmp_buf_ will be used to store arrays of ElfW(Shdr) and ElfW(Sym) 370 // so we ensure that tmp_buf_ is properly aligned to store either. 371 alignas(16) char tmp_buf_[TMP_BUF_SIZE]; 372 static_assert(alignof(ElfW(Shdr)) <= 16, 373 "alignment of tmp buf too small for Shdr"); 374 static_assert(alignof(ElfW(Sym)) <= 16, 375 "alignment of tmp buf too small for Sym"); 376 377 SymbolCacheLine symbol_cache_[SYMBOL_CACHE_LINES]; 378 }; 379 380 // Protect against client code closing low-valued file descriptors it doesn't 381 // actually own. 382 int OpenReadOnlyWithHighFD(const char *fname) { 383 static int high_fd = [] { 384 struct rlimit rlim{}; 385 const int rc = getrlimit(RLIMIT_NOFILE, &rlim); 386 if (rc == 0 && rlim.rlim_cur >= 2000) { 387 const int max_fd = static_cast<int>(rlim.rlim_cur); 388 389 // This will return 2000 on reasonably-configured systems. 390 return std::min<int>(2000, max_fd - 1000); 391 } 392 ABSL_RAW_LOG(WARNING, "Unable to get high fd: rc=%d, limit=%ld", // 393 rc, static_cast<long>(rlim.rlim_cur)); 394 return -1; 395 }(); 396 constexpr int kOpenFlags = O_RDONLY | O_CLOEXEC; 397 if (high_fd >= 1000) { 398 const int fd = open(fname, kOpenFlags); 399 if (fd != -1 && fd < high_fd) { 400 // Try to relocate fd to high range. 401 static_assert(kOpenFlags & O_CLOEXEC, 402 "F_DUPFD_CLOEXEC assumes O_CLOEXEC"); 403 const int fd2 = fcntl(fd, F_DUPFD_CLOEXEC, high_fd); 404 if (fd2 != -1) { 405 // Successfully obtained high fd. Use it. 406 close(fd); 407 return fd2; 408 } else { 409 ABSL_RAW_LOG(WARNING, "Unable to dup fd=%d above %d, errno=%d", fd, 410 high_fd, errno); 411 } 412 } 413 // Either open failed and fd==-1, or fd is already above high_fd, or fcntl 414 // failed and fd is valid (but low). 415 return fd; 416 } 417 return open(fname, kOpenFlags); 418 } 419 420 static std::atomic<Symbolizer *> g_cached_symbolizer; 421 422 } // namespace 423 424 static size_t SymbolizerSize() { 425 #if defined(__wasm__) || defined(__asmjs__) 426 auto pagesize = static_cast<size_t>(getpagesize()); 427 #else 428 auto pagesize = static_cast<size_t>(sysconf(_SC_PAGESIZE)); 429 #endif 430 return ((sizeof(Symbolizer) - 1) / pagesize + 1) * pagesize; 431 } 432 433 // Return (and set null) g_cached_symbolized_state if it is not null. 434 // Otherwise return a new symbolizer. 435 static Symbolizer *AllocateSymbolizer() { 436 InitSigSafeArena(); 437 Symbolizer *symbolizer = 438 g_cached_symbolizer.exchange(nullptr, std::memory_order_acquire); 439 if (symbolizer != nullptr) { 440 return symbolizer; 441 } 442 return new (base_internal::LowLevelAlloc::AllocWithArena( 443 SymbolizerSize(), SigSafeArena())) Symbolizer(); 444 } 445 446 // Set g_cached_symbolize_state to s if it is null, otherwise 447 // delete s. 448 static void FreeSymbolizer(Symbolizer *s) { 449 Symbolizer *old_cached_symbolizer = nullptr; 450 if (!g_cached_symbolizer.compare_exchange_strong(old_cached_symbolizer, s, 451 std::memory_order_release, 452 std::memory_order_relaxed)) { 453 s->~Symbolizer(); 454 base_internal::LowLevelAlloc::Free(s); 455 } 456 } 457 458 Symbolizer::Symbolizer() : ok_(true), addr_map_read_(false) { 459 for (SymbolCacheLine &symbol_cache_line : symbol_cache_) { 460 for (size_t j = 0; j < ABSL_ARRAYSIZE(symbol_cache_line.name); ++j) { 461 symbol_cache_line.pc[j] = nullptr; 462 symbol_cache_line.name[j] = nullptr; 463 symbol_cache_line.age[j] = 0; 464 } 465 } 466 } 467 468 Symbolizer::~Symbolizer() { 469 for (SymbolCacheLine &symbol_cache_line : symbol_cache_) { 470 for (char *s : symbol_cache_line.name) { 471 base_internal::LowLevelAlloc::Free(s); 472 } 473 } 474 ClearAddrMap(); 475 } 476 477 // We don't use assert() since it's not guaranteed to be 478 // async-signal-safe. Instead we define a minimal assertion 479 // macro. So far, we don't need pretty printing for __FILE__, etc. 480 #define SAFE_ASSERT(expr) ((expr) ? static_cast<void>(0) : abort()) 481 482 // Read up to "count" bytes from file descriptor "fd" into the buffer 483 // starting at "buf" while handling short reads and EINTR. On 484 // success, return the number of bytes read. Otherwise, return -1. 485 static ssize_t ReadPersistent(int fd, void *buf, size_t count) { 486 SAFE_ASSERT(fd >= 0); 487 SAFE_ASSERT(count <= SSIZE_MAX); 488 char *buf0 = reinterpret_cast<char *>(buf); 489 size_t num_bytes = 0; 490 while (num_bytes < count) { 491 ssize_t len; 492 NO_INTR(len = read(fd, buf0 + num_bytes, count - num_bytes)); 493 if (len < 0) { // There was an error other than EINTR. 494 ABSL_RAW_LOG(WARNING, "read failed: errno=%d", errno); 495 return -1; 496 } 497 if (len == 0) { // Reached EOF. 498 break; 499 } 500 num_bytes += static_cast<size_t>(len); 501 } 502 SAFE_ASSERT(num_bytes <= count); 503 return static_cast<ssize_t>(num_bytes); 504 } 505 506 // Read up to "count" bytes from "offset" into the buffer starting at "buf", 507 // while handling short reads and EINTR. On success, return the number of bytes 508 // read. Otherwise, return -1. 509 ssize_t CachingFile::ReadFromOffset(void *buf, size_t count, off_t offset) { 510 char *dst = static_cast<char *>(buf); 511 size_t read = 0; 512 while (read < count) { 513 // Look in cache first. 514 if (offset >= cache_start_ && offset < cache_limit_) { 515 const char *hit_start = &cache_[offset - cache_start_]; 516 const size_t n = 517 std::min(count - read, static_cast<size_t>(cache_limit_ - offset)); 518 memcpy(dst, hit_start, n); 519 dst += n; 520 read += static_cast<size_t>(n); 521 offset += static_cast<off_t>(n); 522 continue; 523 } 524 525 cache_start_ = 0; 526 cache_limit_ = 0; 527 ssize_t n = pread(fd_, cache_, cache_size_, offset); 528 if (n < 0) { 529 if (errno == EINTR) { 530 continue; 531 } 532 ABSL_RAW_LOG(WARNING, "read failed: errno=%d", errno); 533 return -1; 534 } 535 if (n == 0) { // Reached EOF. 536 break; 537 } 538 539 cache_start_ = offset; 540 cache_limit_ = offset + static_cast<off_t>(n); 541 // Next iteration will copy from cache into dst. 542 } 543 return static_cast<ssize_t>(read); 544 } 545 546 // Try reading exactly "count" bytes from "offset" bytes into the buffer 547 // starting at "buf" while handling short reads and EINTR. On success, return 548 // true. Otherwise, return false. 549 bool CachingFile::ReadFromOffsetExact(void *buf, size_t count, off_t offset) { 550 ssize_t len = ReadFromOffset(buf, count, offset); 551 return len >= 0 && static_cast<size_t>(len) == count; 552 } 553 554 // Returns elf_header.e_type if the file pointed by fd is an ELF binary. 555 static int FileGetElfType(CachingFile *file) { 556 ElfW(Ehdr) elf_header; 557 if (!file->ReadFromOffsetExact(&elf_header, sizeof(elf_header), 0)) { 558 return -1; 559 } 560 if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) { 561 return -1; 562 } 563 return elf_header.e_type; 564 } 565 566 // Read the section headers in the given ELF binary, and if a section 567 // of the specified type is found, set the output to this section header 568 // and return true. Otherwise, return false. 569 // To keep stack consumption low, we would like this function to not get 570 // inlined. 571 static ABSL_ATTRIBUTE_NOINLINE bool GetSectionHeaderByType( 572 CachingFile *file, ElfW(Half) sh_num, const off_t sh_offset, 573 ElfW(Word) type, ElfW(Shdr) * out, char *tmp_buf, size_t tmp_buf_size) { 574 ElfW(Shdr) *buf = reinterpret_cast<ElfW(Shdr) *>(tmp_buf); 575 const size_t buf_entries = tmp_buf_size / sizeof(buf[0]); 576 const size_t buf_bytes = buf_entries * sizeof(buf[0]); 577 578 for (size_t i = 0; static_cast<int>(i) < sh_num;) { 579 const size_t num_bytes_left = 580 (static_cast<size_t>(sh_num) - i) * sizeof(buf[0]); 581 const size_t num_bytes_to_read = 582 (buf_bytes > num_bytes_left) ? num_bytes_left : buf_bytes; 583 const off_t offset = sh_offset + static_cast<off_t>(i * sizeof(buf[0])); 584 const ssize_t len = file->ReadFromOffset(buf, num_bytes_to_read, offset); 585 if (len <= 0) { 586 ABSL_RAW_LOG(WARNING, "Reading %zu bytes from offset %ju returned %zd.", 587 num_bytes_to_read, static_cast<intmax_t>(offset), len); 588 return false; 589 } 590 if (static_cast<size_t>(len) % sizeof(buf[0]) != 0) { 591 ABSL_RAW_LOG( 592 WARNING, 593 "Reading %zu bytes from offset %jd returned %zd which is not a " 594 "multiple of %zu.", 595 num_bytes_to_read, static_cast<intmax_t>(offset), len, 596 sizeof(buf[0])); 597 return false; 598 } 599 const size_t num_headers_in_buf = static_cast<size_t>(len) / sizeof(buf[0]); 600 SAFE_ASSERT(num_headers_in_buf <= buf_entries); 601 for (size_t j = 0; j < num_headers_in_buf; ++j) { 602 if (buf[j].sh_type == type) { 603 *out = buf[j]; 604 return true; 605 } 606 } 607 i += num_headers_in_buf; 608 } 609 return false; 610 } 611 612 // There is no particular reason to limit section name to 63 characters, 613 // but there has (as yet) been no need for anything longer either. 614 const int kMaxSectionNameLen = 64; 615 616 // Small cache to use for miscellaneous file reads. 617 const int kSmallFileCacheSize = 100; 618 619 bool ForEachSection(int fd, 620 const std::function<bool(absl::string_view name, 621 const ElfW(Shdr) &)> &callback) { 622 char buf[kSmallFileCacheSize]; 623 CachingFile file(fd, buf, sizeof(buf)); 624 625 ElfW(Ehdr) elf_header; 626 if (!file.ReadFromOffsetExact(&elf_header, sizeof(elf_header), 0)) { 627 return false; 628 } 629 630 // Technically it can be larger, but in practice this never happens. 631 if (elf_header.e_shentsize != sizeof(ElfW(Shdr))) { 632 return false; 633 } 634 635 ElfW(Shdr) shstrtab; 636 off_t shstrtab_offset = static_cast<off_t>(elf_header.e_shoff) + 637 elf_header.e_shentsize * elf_header.e_shstrndx; 638 if (!file.ReadFromOffsetExact(&shstrtab, sizeof(shstrtab), shstrtab_offset)) { 639 return false; 640 } 641 642 for (int i = 0; i < elf_header.e_shnum; ++i) { 643 ElfW(Shdr) out; 644 off_t section_header_offset = 645 static_cast<off_t>(elf_header.e_shoff) + elf_header.e_shentsize * i; 646 if (!file.ReadFromOffsetExact(&out, sizeof(out), section_header_offset)) { 647 return false; 648 } 649 off_t name_offset = static_cast<off_t>(shstrtab.sh_offset) + out.sh_name; 650 char header_name[kMaxSectionNameLen]; 651 ssize_t n_read = 652 file.ReadFromOffset(&header_name, kMaxSectionNameLen, name_offset); 653 if (n_read < 0) { 654 return false; 655 } else if (n_read > kMaxSectionNameLen) { 656 // Long read? 657 return false; 658 } 659 660 absl::string_view name(header_name, 661 strnlen(header_name, static_cast<size_t>(n_read))); 662 if (!callback(name, out)) { 663 break; 664 } 665 } 666 return true; 667 } 668 669 // name_len should include terminating '\0'. 670 bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, 671 ElfW(Shdr) * out) { 672 char header_name[kMaxSectionNameLen]; 673 if (sizeof(header_name) < name_len) { 674 ABSL_RAW_LOG(WARNING, 675 "Section name '%s' is too long (%zu); " 676 "section will not be found (even if present).", 677 name, name_len); 678 // No point in even trying. 679 return false; 680 } 681 682 char buf[kSmallFileCacheSize]; 683 CachingFile file(fd, buf, sizeof(buf)); 684 ElfW(Ehdr) elf_header; 685 if (!file.ReadFromOffsetExact(&elf_header, sizeof(elf_header), 0)) { 686 return false; 687 } 688 689 // Technically it can be larger, but in practice this never happens. 690 if (elf_header.e_shentsize != sizeof(ElfW(Shdr))) { 691 return false; 692 } 693 694 ElfW(Shdr) shstrtab; 695 off_t shstrtab_offset = static_cast<off_t>(elf_header.e_shoff) + 696 elf_header.e_shentsize * elf_header.e_shstrndx; 697 if (!file.ReadFromOffsetExact(&shstrtab, sizeof(shstrtab), shstrtab_offset)) { 698 return false; 699 } 700 701 for (int i = 0; i < elf_header.e_shnum; ++i) { 702 off_t section_header_offset = 703 static_cast<off_t>(elf_header.e_shoff) + elf_header.e_shentsize * i; 704 if (!file.ReadFromOffsetExact(out, sizeof(*out), section_header_offset)) { 705 return false; 706 } 707 off_t name_offset = static_cast<off_t>(shstrtab.sh_offset) + out->sh_name; 708 ssize_t n_read = file.ReadFromOffset(&header_name, name_len, name_offset); 709 if (n_read < 0) { 710 return false; 711 } else if (static_cast<size_t>(n_read) != name_len) { 712 // Short read -- name could be at end of file. 713 continue; 714 } 715 if (memcmp(header_name, name, name_len) == 0) { 716 return true; 717 } 718 } 719 return false; 720 } 721 722 // Compare symbols at in the same address. 723 // Return true if we should pick symbol1. 724 static bool ShouldPickFirstSymbol(const ElfW(Sym) & symbol1, 725 const ElfW(Sym) & symbol2) { 726 // If one of the symbols is weak and the other is not, pick the one 727 // this is not a weak symbol. 728 char bind1 = ELF_ST_BIND(symbol1.st_info); 729 char bind2 = ELF_ST_BIND(symbol1.st_info); 730 if (bind1 == STB_WEAK && bind2 != STB_WEAK) return false; 731 if (bind2 == STB_WEAK && bind1 != STB_WEAK) return true; 732 733 // If one of the symbols has zero size and the other is not, pick the 734 // one that has non-zero size. 735 if (symbol1.st_size != 0 && symbol2.st_size == 0) { 736 return true; 737 } 738 if (symbol1.st_size == 0 && symbol2.st_size != 0) { 739 return false; 740 } 741 742 // If one of the symbols has no type and the other is not, pick the 743 // one that has a type. 744 char type1 = ELF_ST_TYPE(symbol1.st_info); 745 char type2 = ELF_ST_TYPE(symbol1.st_info); 746 if (type1 != STT_NOTYPE && type2 == STT_NOTYPE) { 747 return true; 748 } 749 if (type1 == STT_NOTYPE && type2 != STT_NOTYPE) { 750 return false; 751 } 752 753 // Pick the first one, if we still cannot decide. 754 return true; 755 } 756 757 // Return true if an address is inside a section. 758 static bool InSection(const void *address, ptrdiff_t relocation, 759 const ElfW(Shdr) * section) { 760 const char *start = reinterpret_cast<const char *>( 761 section->sh_addr + static_cast<ElfW(Addr)>(relocation)); 762 size_t size = static_cast<size_t>(section->sh_size); 763 return start <= address && address < (start + size); 764 } 765 766 static const char *ComputeOffset(const char *base, ptrdiff_t offset) { 767 // Note: cast to intptr_t to avoid undefined behavior when base evaluates to 768 // zero and offset is non-zero. 769 return reinterpret_cast<const char *>(reinterpret_cast<intptr_t>(base) + 770 offset); 771 } 772 773 // Read a symbol table and look for the symbol containing the 774 // pc. Iterate over symbols in a symbol table and look for the symbol 775 // containing "pc". If the symbol is found, and its name fits in 776 // out_size, the name is written into out and SYMBOL_FOUND is returned. 777 // If the name does not fit, truncated name is written into out, 778 // and SYMBOL_TRUNCATED is returned. Out is NUL-terminated. 779 // If the symbol is not found, SYMBOL_NOT_FOUND is returned; 780 // To keep stack consumption low, we would like this function to not get 781 // inlined. 782 static ABSL_ATTRIBUTE_NOINLINE FindSymbolResult FindSymbol( 783 const void *const pc, CachingFile *file, char *out, size_t out_size, 784 ptrdiff_t relocation, const ElfW(Shdr) * strtab, const ElfW(Shdr) * symtab, 785 const ElfW(Shdr) * opd, char *tmp_buf, size_t tmp_buf_size) { 786 if (symtab == nullptr) { 787 return SYMBOL_NOT_FOUND; 788 } 789 790 // Read multiple symbols at once to save read() calls. 791 ElfW(Sym) *buf = reinterpret_cast<ElfW(Sym) *>(tmp_buf); 792 const size_t buf_entries = tmp_buf_size / sizeof(buf[0]); 793 794 const size_t num_symbols = symtab->sh_size / symtab->sh_entsize; 795 796 // On platforms using an .opd section (PowerPC & IA64), a function symbol 797 // has the address of a function descriptor, which contains the real 798 // starting address. However, we do not always want to use the real 799 // starting address because we sometimes want to symbolize a function 800 // pointer into the .opd section, e.g. FindSymbol(&foo,...). 801 const bool pc_in_opd = kPlatformUsesOPDSections && opd != nullptr && 802 InSection(pc, relocation, opd); 803 const bool deref_function_descriptor_pointer = 804 kPlatformUsesOPDSections && opd != nullptr && !pc_in_opd; 805 806 ElfW(Sym) best_match; 807 SafeMemZero(&best_match, sizeof(best_match)); 808 bool found_match = false; 809 for (size_t i = 0; i < num_symbols;) { 810 off_t offset = 811 static_cast<off_t>(symtab->sh_offset + i * symtab->sh_entsize); 812 const size_t num_remaining_symbols = num_symbols - i; 813 const size_t entries_in_chunk = 814 std::min(num_remaining_symbols, buf_entries); 815 const size_t bytes_in_chunk = entries_in_chunk * sizeof(buf[0]); 816 const ssize_t len = file->ReadFromOffset(buf, bytes_in_chunk, offset); 817 SAFE_ASSERT(len >= 0); 818 SAFE_ASSERT(static_cast<size_t>(len) % sizeof(buf[0]) == 0); 819 const size_t num_symbols_in_buf = static_cast<size_t>(len) / sizeof(buf[0]); 820 SAFE_ASSERT(num_symbols_in_buf <= entries_in_chunk); 821 for (size_t j = 0; j < num_symbols_in_buf; ++j) { 822 const ElfW(Sym) &symbol = buf[j]; 823 824 // For a DSO, a symbol address is relocated by the loading address. 825 // We keep the original address for opd redirection below. 826 const char *const original_start_address = 827 reinterpret_cast<const char *>(symbol.st_value); 828 const char *start_address = 829 ComputeOffset(original_start_address, relocation); 830 831 #ifdef __arm__ 832 // ARM functions are always aligned to multiples of two bytes; the 833 // lowest-order bit in start_address is ignored by the CPU and indicates 834 // whether the function contains ARM (0) or Thumb (1) code. We don't care 835 // about what encoding is being used; we just want the real start address 836 // of the function. 837 start_address = reinterpret_cast<const char *>( 838 reinterpret_cast<uintptr_t>(start_address) & ~1u); 839 #endif 840 841 if (deref_function_descriptor_pointer && 842 InSection(original_start_address, /*relocation=*/0, opd)) { 843 // The opd section is mapped into memory. Just dereference 844 // start_address to get the first double word, which points to the 845 // function entry. 846 start_address = *reinterpret_cast<const char *const *>(start_address); 847 } 848 849 // If pc is inside the .opd section, it points to a function descriptor. 850 const size_t size = pc_in_opd ? kFunctionDescriptorSize : symbol.st_size; 851 const void *const end_address = 852 ComputeOffset(start_address, static_cast<ptrdiff_t>(size)); 853 if (symbol.st_value != 0 && // Skip null value symbols. 854 symbol.st_shndx != 0 && // Skip undefined symbols. 855 #ifdef STT_TLS 856 ELF_ST_TYPE(symbol.st_info) != STT_TLS && // Skip thread-local data. 857 #endif // STT_TLS 858 ((start_address <= pc && pc < end_address) || 859 (start_address == pc && pc == end_address))) { 860 if (!found_match || ShouldPickFirstSymbol(symbol, best_match)) { 861 found_match = true; 862 best_match = symbol; 863 } 864 } 865 } 866 i += num_symbols_in_buf; 867 } 868 869 if (found_match) { 870 const off_t off = 871 static_cast<off_t>(strtab->sh_offset) + best_match.st_name; 872 const ssize_t n_read = file->ReadFromOffset(out, out_size, off); 873 if (n_read <= 0) { 874 // This should never happen. 875 ABSL_RAW_LOG(WARNING, 876 "Unable to read from fd %d at offset %lld: n_read = %zd", 877 file->fd(), static_cast<long long>(off), n_read); 878 return SYMBOL_NOT_FOUND; 879 } 880 ABSL_RAW_CHECK(static_cast<size_t>(n_read) <= out_size, 881 "ReadFromOffset read too much data."); 882 883 // strtab->sh_offset points into .strtab-like section that contains 884 // NUL-terminated strings: '\0foo\0barbaz\0...". 885 // 886 // sh_offset+st_name points to the start of symbol name, but we don't know 887 // how long the symbol is, so we try to read as much as we have space for, 888 // and usually over-read (i.e. there is a NUL somewhere before n_read). 889 if (memchr(out, '\0', static_cast<size_t>(n_read)) == nullptr) { 890 // Either out_size was too small (n_read == out_size and no NUL), or 891 // we tried to read past the EOF (n_read < out_size) and .strtab is 892 // corrupt (missing terminating NUL; should never happen for valid ELF). 893 out[n_read - 1] = '\0'; 894 return SYMBOL_TRUNCATED; 895 } 896 return SYMBOL_FOUND; 897 } 898 899 return SYMBOL_NOT_FOUND; 900 } 901 902 // Get the symbol name of "pc" from the file pointed by "fd". Process 903 // both regular and dynamic symbol tables if necessary. 904 // See FindSymbol() comment for description of return value. 905 FindSymbolResult Symbolizer::GetSymbolFromObjectFile( 906 const ObjFile &obj, const void *const pc, const ptrdiff_t relocation, 907 char *out, size_t out_size, char *tmp_buf, size_t tmp_buf_size) { 908 ElfW(Shdr) symtab; 909 ElfW(Shdr) strtab; 910 ElfW(Shdr) opd; 911 ElfW(Shdr) *opd_ptr = nullptr; 912 913 // On platforms using an .opd sections for function descriptor, read 914 // the section header. The .opd section is in data segment and should be 915 // loaded but we check that it is mapped just to be extra careful. 916 if (kPlatformUsesOPDSections) { 917 if (GetSectionHeaderByName(obj.fd, kOpdSectionName, 918 sizeof(kOpdSectionName) - 1, &opd) && 919 FindObjFile(reinterpret_cast<const char *>(opd.sh_addr) + relocation, 920 opd.sh_size) != nullptr) { 921 opd_ptr = &opd; 922 } else { 923 return SYMBOL_NOT_FOUND; 924 } 925 } 926 927 CachingFile file(obj.fd, file_cache_, sizeof(file_cache_)); 928 929 // Consult a regular symbol table, then fall back to the dynamic symbol table. 930 for (const auto symbol_table_type : {SHT_SYMTAB, SHT_DYNSYM}) { 931 if (!GetSectionHeaderByType(&file, obj.elf_header.e_shnum, 932 static_cast<off_t>(obj.elf_header.e_shoff), 933 static_cast<ElfW(Word)>(symbol_table_type), 934 &symtab, tmp_buf, tmp_buf_size)) { 935 continue; 936 } 937 if (!file.ReadFromOffsetExact( 938 &strtab, sizeof(strtab), 939 static_cast<off_t>(obj.elf_header.e_shoff + 940 symtab.sh_link * sizeof(symtab)))) { 941 continue; 942 } 943 const FindSymbolResult rc = 944 FindSymbol(pc, &file, out, out_size, relocation, &strtab, &symtab, 945 opd_ptr, tmp_buf, tmp_buf_size); 946 if (rc != SYMBOL_NOT_FOUND) { 947 return rc; 948 } 949 } 950 951 return SYMBOL_NOT_FOUND; 952 } 953 954 namespace { 955 // Thin wrapper around a file descriptor so that the file descriptor 956 // gets closed for sure. 957 class FileDescriptor { 958 public: 959 explicit FileDescriptor(int fd) : fd_(fd) {} 960 FileDescriptor(const FileDescriptor &) = delete; 961 FileDescriptor &operator=(const FileDescriptor &) = delete; 962 963 ~FileDescriptor() { 964 if (fd_ >= 0) { 965 close(fd_); 966 } 967 } 968 969 int get() const { return fd_; } 970 971 private: 972 const int fd_; 973 }; 974 975 // Helper class for reading lines from file. 976 // 977 // Note: we don't use ProcMapsIterator since the object is big (it has 978 // a 5k array member) and uses async-unsafe functions such as sscanf() 979 // and snprintf(). 980 class LineReader { 981 public: 982 explicit LineReader(int fd, char *buf, size_t buf_len) 983 : fd_(fd), 984 buf_len_(buf_len), 985 buf_(buf), 986 bol_(buf), 987 eol_(buf), 988 eod_(buf) {} 989 990 LineReader(const LineReader &) = delete; 991 LineReader &operator=(const LineReader &) = delete; 992 993 // Read '\n'-terminated line from file. On success, modify "bol" 994 // and "eol", then return true. Otherwise, return false. 995 // 996 // Note: if the last line doesn't end with '\n', the line will be 997 // dropped. It's an intentional behavior to make the code simple. 998 bool ReadLine(const char **bol, const char **eol) { 999 if (BufferIsEmpty()) { // First time. 1000 const ssize_t num_bytes = ReadPersistent(fd_, buf_, buf_len_); 1001 if (num_bytes <= 0) { // EOF or error. 1002 return false; 1003 } 1004 eod_ = buf_ + num_bytes; 1005 bol_ = buf_; 1006 } else { 1007 bol_ = eol_ + 1; // Advance to the next line in the buffer. 1008 SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_". 1009 if (!HasCompleteLine()) { 1010 const auto incomplete_line_length = static_cast<size_t>(eod_ - bol_); 1011 // Move the trailing incomplete line to the beginning. 1012 memmove(buf_, bol_, incomplete_line_length); 1013 // Read text from file and append it. 1014 char *const append_pos = buf_ + incomplete_line_length; 1015 const size_t capacity_left = buf_len_ - incomplete_line_length; 1016 const ssize_t num_bytes = 1017 ReadPersistent(fd_, append_pos, capacity_left); 1018 if (num_bytes <= 0) { // EOF or error. 1019 return false; 1020 } 1021 eod_ = append_pos + num_bytes; 1022 bol_ = buf_; 1023 } 1024 } 1025 eol_ = FindLineFeed(); 1026 if (eol_ == nullptr) { // '\n' not found. Malformed line. 1027 return false; 1028 } 1029 *eol_ = '\0'; // Replace '\n' with '\0'. 1030 1031 *bol = bol_; 1032 *eol = eol_; 1033 return true; 1034 } 1035 1036 private: 1037 char *FindLineFeed() const { 1038 return reinterpret_cast<char *>( 1039 memchr(bol_, '\n', static_cast<size_t>(eod_ - bol_))); 1040 } 1041 1042 bool BufferIsEmpty() const { return buf_ == eod_; } 1043 1044 bool HasCompleteLine() const { 1045 return !BufferIsEmpty() && FindLineFeed() != nullptr; 1046 } 1047 1048 const int fd_; 1049 const size_t buf_len_; 1050 char *const buf_; 1051 char *bol_; 1052 char *eol_; 1053 const char *eod_; // End of data in "buf_". 1054 }; 1055 } // namespace 1056 1057 // Place the hex number read from "start" into "*hex". The pointer to 1058 // the first non-hex character or "end" is returned. 1059 static const char *GetHex(const char *start, const char *end, 1060 uint64_t *const value) { 1061 uint64_t hex = 0; 1062 const char *p; 1063 for (p = start; p < end; ++p) { 1064 int ch = *p; 1065 if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || 1066 (ch >= 'a' && ch <= 'f')) { 1067 hex = (hex << 4) | 1068 static_cast<uint64_t>(ch < 'A' ? ch - '0' : (ch & 0xF) + 9); 1069 } else { // Encountered the first non-hex character. 1070 break; 1071 } 1072 } 1073 SAFE_ASSERT(p <= end); 1074 *value = hex; 1075 return p; 1076 } 1077 1078 static const char *GetHex(const char *start, const char *end, 1079 const void **const addr) { 1080 uint64_t hex = 0; 1081 const char *p = GetHex(start, end, &hex); 1082 *addr = reinterpret_cast<void *>(hex); 1083 return p; 1084 } 1085 1086 // Normally we are only interested in "r?x" maps. 1087 // On the PowerPC, function pointers point to descriptors in the .opd 1088 // section. The descriptors themselves are not executable code, so 1089 // we need to relax the check below to "r??". 1090 static bool ShouldUseMapping(const char *const flags) { 1091 return flags[0] == 'r' && (kPlatformUsesOPDSections || flags[2] == 'x'); 1092 } 1093 1094 // Read /proc/self/maps and run "callback" for each mmapped file found. If 1095 // "callback" returns false, stop scanning and return true. Else continue 1096 // scanning /proc/self/maps. Return true if no parse error is found. 1097 static ABSL_ATTRIBUTE_NOINLINE bool ReadAddrMap( 1098 bool (*callback)(const char *filename, const void *const start_addr, 1099 const void *const end_addr, uint64_t offset, void *arg), 1100 void *arg, void *tmp_buf, size_t tmp_buf_size) { 1101 // Use /proc/self/task/<pid>/maps instead of /proc/self/maps. The latter 1102 // requires kernel to stop all threads, and is significantly slower when there 1103 // are 1000s of threads. 1104 char maps_path[80]; 1105 snprintf(maps_path, sizeof(maps_path), "/proc/self/task/%d/maps", getpid()); 1106 1107 int maps_fd; 1108 NO_INTR(maps_fd = OpenReadOnlyWithHighFD(maps_path)); 1109 FileDescriptor wrapped_maps_fd(maps_fd); 1110 if (wrapped_maps_fd.get() < 0) { 1111 ABSL_RAW_LOG(WARNING, "%s: errno=%d", maps_path, errno); 1112 return false; 1113 } 1114 1115 // Iterate over maps and look for the map containing the pc. Then 1116 // look into the symbol tables inside. 1117 LineReader reader(wrapped_maps_fd.get(), static_cast<char *>(tmp_buf), 1118 tmp_buf_size); 1119 while (true) { 1120 const char *cursor; 1121 const char *eol; 1122 if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line. 1123 break; 1124 } 1125 1126 const char *line = cursor; 1127 const void *start_address; 1128 // Start parsing line in /proc/self/maps. Here is an example: 1129 // 1130 // 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat 1131 // 1132 // We want start address (08048000), end address (0804c000), flags 1133 // (r-xp) and file name (/bin/cat). 1134 1135 // Read start address. 1136 cursor = GetHex(cursor, eol, &start_address); 1137 if (cursor == eol || *cursor != '-') { 1138 ABSL_RAW_LOG(WARNING, "Corrupt /proc/self/maps line: %s", line); 1139 return false; 1140 } 1141 ++cursor; // Skip '-'. 1142 1143 // Read end address. 1144 const void *end_address; 1145 cursor = GetHex(cursor, eol, &end_address); 1146 if (cursor == eol || *cursor != ' ') { 1147 ABSL_RAW_LOG(WARNING, "Corrupt /proc/self/maps line: %s", line); 1148 return false; 1149 } 1150 ++cursor; // Skip ' '. 1151 1152 // Read flags. Skip flags until we encounter a space or eol. 1153 const char *const flags_start = cursor; 1154 while (cursor < eol && *cursor != ' ') { 1155 ++cursor; 1156 } 1157 // We expect at least four letters for flags (ex. "r-xp"). 1158 if (cursor == eol || cursor < flags_start + 4) { 1159 ABSL_RAW_LOG(WARNING, "Corrupt /proc/self/maps: %s", line); 1160 return false; 1161 } 1162 1163 // Check flags. 1164 if (!ShouldUseMapping(flags_start)) { 1165 continue; // We skip this map. 1166 } 1167 ++cursor; // Skip ' '. 1168 1169 // Read file offset. 1170 uint64_t offset; 1171 cursor = GetHex(cursor, eol, &offset); 1172 ++cursor; // Skip ' '. 1173 1174 // Skip to file name. "cursor" now points to dev. We need to skip at least 1175 // two spaces for dev and inode. 1176 int num_spaces = 0; 1177 while (cursor < eol) { 1178 if (*cursor == ' ') { 1179 ++num_spaces; 1180 } else if (num_spaces >= 2) { 1181 // The first non-space character after skipping two spaces 1182 // is the beginning of the file name. 1183 break; 1184 } 1185 ++cursor; 1186 } 1187 1188 // Check whether this entry corresponds to our hint table for the true 1189 // filename. 1190 bool hinted = 1191 GetFileMappingHint(&start_address, &end_address, &offset, &cursor); 1192 if (!hinted && (cursor == eol || cursor[0] == '[')) { 1193 // not an object file, typically [vdso] or [vsyscall] 1194 continue; 1195 } 1196 if (!callback(cursor, start_address, end_address, offset, arg)) break; 1197 } 1198 return true; 1199 } 1200 1201 // Find the objfile mapped in address region containing [addr, addr + len). 1202 ObjFile *Symbolizer::FindObjFile(const void *const addr, size_t len) { 1203 for (int i = 0; i < 2; ++i) { 1204 if (!ok_) return nullptr; 1205 1206 // Read /proc/self/maps if necessary 1207 if (!addr_map_read_) { 1208 addr_map_read_ = true; 1209 if (!ReadAddrMap(RegisterObjFile, this, tmp_buf_, TMP_BUF_SIZE)) { 1210 ok_ = false; 1211 return nullptr; 1212 } 1213 } 1214 1215 size_t lo = 0; 1216 size_t hi = addr_map_.Size(); 1217 while (lo < hi) { 1218 size_t mid = (lo + hi) / 2; 1219 if (addr < addr_map_.At(mid)->end_addr) { 1220 hi = mid; 1221 } else { 1222 lo = mid + 1; 1223 } 1224 } 1225 if (lo != addr_map_.Size()) { 1226 ObjFile *obj = addr_map_.At(lo); 1227 SAFE_ASSERT(obj->end_addr > addr); 1228 if (addr >= obj->start_addr && 1229 reinterpret_cast<const char *>(addr) + len <= obj->end_addr) 1230 return obj; 1231 } 1232 1233 // The address mapping may have changed since it was last read. Retry. 1234 ClearAddrMap(); 1235 } 1236 return nullptr; 1237 } 1238 1239 void Symbolizer::ClearAddrMap() { 1240 for (size_t i = 0; i != addr_map_.Size(); i++) { 1241 ObjFile *o = addr_map_.At(i); 1242 base_internal::LowLevelAlloc::Free(o->filename); 1243 if (o->fd >= 0) { 1244 close(o->fd); 1245 } 1246 } 1247 addr_map_.Clear(); 1248 addr_map_read_ = false; 1249 } 1250 1251 // Callback for ReadAddrMap to register objfiles in an in-memory table. 1252 bool Symbolizer::RegisterObjFile(const char *filename, 1253 const void *const start_addr, 1254 const void *const end_addr, uint64_t offset, 1255 void *arg) { 1256 Symbolizer *impl = static_cast<Symbolizer *>(arg); 1257 1258 // Files are supposed to be added in the increasing address order. Make 1259 // sure that's the case. 1260 size_t addr_map_size = impl->addr_map_.Size(); 1261 if (addr_map_size != 0) { 1262 ObjFile *old = impl->addr_map_.At(addr_map_size - 1); 1263 if (old->end_addr > end_addr) { 1264 ABSL_RAW_LOG(ERROR, 1265 "Unsorted addr map entry: 0x%" PRIxPTR ": %s <-> 0x%" PRIxPTR 1266 ": %s", 1267 reinterpret_cast<uintptr_t>(end_addr), filename, 1268 reinterpret_cast<uintptr_t>(old->end_addr), old->filename); 1269 return true; 1270 } else if (old->end_addr == end_addr) { 1271 // The same entry appears twice. This sometimes happens for [vdso]. 1272 if (old->start_addr != start_addr || 1273 strcmp(old->filename, filename) != 0) { 1274 ABSL_RAW_LOG(ERROR, 1275 "Duplicate addr 0x%" PRIxPTR ": %s <-> 0x%" PRIxPTR ": %s", 1276 reinterpret_cast<uintptr_t>(end_addr), filename, 1277 reinterpret_cast<uintptr_t>(old->end_addr), old->filename); 1278 } 1279 return true; 1280 } else if (old->end_addr == start_addr && 1281 reinterpret_cast<uintptr_t>(old->start_addr) - old->offset == 1282 reinterpret_cast<uintptr_t>(start_addr) - offset && 1283 strcmp(old->filename, filename) == 0) { 1284 // Two contiguous map entries that span a contiguous region of the file, 1285 // perhaps because some part of the file was mlock()ed. Combine them. 1286 old->end_addr = end_addr; 1287 return true; 1288 } 1289 } 1290 ObjFile *obj = impl->addr_map_.Add(); 1291 obj->filename = impl->CopyString(filename); 1292 obj->start_addr = start_addr; 1293 obj->end_addr = end_addr; 1294 obj->offset = offset; 1295 obj->elf_type = -1; // filled on demand 1296 obj->fd = -1; // opened on demand 1297 return true; 1298 } 1299 1300 // This function wraps the Demangle function to provide an interface 1301 // where the input symbol is demangled in-place. 1302 // To keep stack consumption low, we would like this function to not 1303 // get inlined. 1304 static ABSL_ATTRIBUTE_NOINLINE void DemangleInplace(char *out, size_t out_size, 1305 char *tmp_buf, 1306 size_t tmp_buf_size) { 1307 if (Demangle(out, tmp_buf, tmp_buf_size)) { 1308 // Demangling succeeded. Copy to out if the space allows. 1309 size_t len = strlen(tmp_buf); 1310 if (len + 1 <= out_size) { // +1 for '\0'. 1311 SAFE_ASSERT(len < tmp_buf_size); 1312 memmove(out, tmp_buf, len + 1); 1313 } 1314 } 1315 } 1316 1317 SymbolCacheLine *Symbolizer::GetCacheLine(const void *const pc) { 1318 uintptr_t pc0 = reinterpret_cast<uintptr_t>(pc); 1319 pc0 >>= 3; // drop the low 3 bits 1320 1321 // Shuffle bits. 1322 pc0 ^= (pc0 >> 6) ^ (pc0 >> 12) ^ (pc0 >> 18); 1323 return &symbol_cache_[pc0 % SYMBOL_CACHE_LINES]; 1324 } 1325 1326 void Symbolizer::AgeSymbols(SymbolCacheLine *line) { 1327 for (uint32_t &age : line->age) { 1328 ++age; 1329 } 1330 } 1331 1332 const char *Symbolizer::FindSymbolInCache(const void *const pc) { 1333 if (pc == nullptr) return nullptr; 1334 1335 SymbolCacheLine *line = GetCacheLine(pc); 1336 for (size_t i = 0; i < ABSL_ARRAYSIZE(line->pc); ++i) { 1337 if (line->pc[i] == pc) { 1338 AgeSymbols(line); 1339 line->age[i] = 0; 1340 return line->name[i]; 1341 } 1342 } 1343 return nullptr; 1344 } 1345 1346 const char *Symbolizer::InsertSymbolInCache(const void *const pc, 1347 const char *name) { 1348 SAFE_ASSERT(pc != nullptr); 1349 1350 SymbolCacheLine *line = GetCacheLine(pc); 1351 uint32_t max_age = 0; 1352 size_t oldest_index = 0; 1353 bool found_oldest_index = false; 1354 for (size_t i = 0; i < ABSL_ARRAYSIZE(line->pc); ++i) { 1355 if (line->pc[i] == nullptr) { 1356 AgeSymbols(line); 1357 line->pc[i] = pc; 1358 line->name[i] = CopyString(name); 1359 line->age[i] = 0; 1360 return line->name[i]; 1361 } 1362 if (line->age[i] >= max_age) { 1363 max_age = line->age[i]; 1364 oldest_index = i; 1365 found_oldest_index = true; 1366 } 1367 } 1368 1369 AgeSymbols(line); 1370 ABSL_RAW_CHECK(found_oldest_index, "Corrupt cache"); 1371 base_internal::LowLevelAlloc::Free(line->name[oldest_index]); 1372 line->pc[oldest_index] = pc; 1373 line->name[oldest_index] = CopyString(name); 1374 line->age[oldest_index] = 0; 1375 return line->name[oldest_index]; 1376 } 1377 1378 static void MaybeOpenFdFromSelfExe(ObjFile *obj) { 1379 if (memcmp(obj->start_addr, ELFMAG, SELFMAG) != 0) { 1380 return; 1381 } 1382 int fd = OpenReadOnlyWithHighFD("/proc/self/exe"); 1383 if (fd == -1) { 1384 return; 1385 } 1386 // Verify that contents of /proc/self/exe matches in-memory image of 1387 // the binary. This can fail if the "deleted" binary is in fact not 1388 // the main executable, or for binaries that have the first PT_LOAD 1389 // segment smaller than 4K. We do it in four steps so that the 1390 // buffer is smaller and we don't consume too much stack space. 1391 const char *mem = reinterpret_cast<const char *>(obj->start_addr); 1392 for (int i = 0; i < 4; ++i) { 1393 char buf[1024]; 1394 ssize_t n = read(fd, buf, sizeof(buf)); 1395 if (n != sizeof(buf) || memcmp(buf, mem, sizeof(buf)) != 0) { 1396 close(fd); 1397 return; 1398 } 1399 mem += sizeof(buf); 1400 } 1401 obj->fd = fd; 1402 } 1403 1404 static bool MaybeInitializeObjFile(ObjFile *obj) { 1405 if (obj->fd < 0) { 1406 obj->fd = OpenReadOnlyWithHighFD(obj->filename); 1407 1408 if (obj->fd < 0) { 1409 // Getting /proc/self/exe here means that we were hinted. 1410 if (strcmp(obj->filename, "/proc/self/exe") == 0) { 1411 // /proc/self/exe may be inaccessible (due to setuid, etc.), so try 1412 // accessing the binary via argv0. 1413 if (argv0_value != nullptr) { 1414 obj->fd = OpenReadOnlyWithHighFD(argv0_value); 1415 } 1416 } else { 1417 MaybeOpenFdFromSelfExe(obj); 1418 } 1419 } 1420 1421 if (obj->fd < 0) { 1422 ABSL_RAW_LOG(WARNING, "%s: open failed: errno=%d", obj->filename, errno); 1423 return false; 1424 } 1425 1426 char buf[kSmallFileCacheSize]; 1427 CachingFile file(obj->fd, buf, sizeof(buf)); 1428 1429 obj->elf_type = FileGetElfType(&file); 1430 if (obj->elf_type < 0) { 1431 ABSL_RAW_LOG(WARNING, "%s: wrong elf type: %d", obj->filename, 1432 obj->elf_type); 1433 return false; 1434 } 1435 1436 if (!file.ReadFromOffsetExact(&obj->elf_header, sizeof(obj->elf_header), 1437 0)) { 1438 ABSL_RAW_LOG(WARNING, "%s: failed to read elf header", obj->filename); 1439 return false; 1440 } 1441 const int phnum = obj->elf_header.e_phnum; 1442 const int phentsize = obj->elf_header.e_phentsize; 1443 auto phoff = static_cast<off_t>(obj->elf_header.e_phoff); 1444 size_t num_interesting_load_segments = 0; 1445 for (int j = 0; j < phnum; j++) { 1446 ElfW(Phdr) phdr; 1447 if (!file.ReadFromOffsetExact(&phdr, sizeof(phdr), phoff)) { 1448 ABSL_RAW_LOG(WARNING, "%s: failed to read program header %d", 1449 obj->filename, j); 1450 return false; 1451 } 1452 phoff += phentsize; 1453 1454 #if defined(__powerpc__) && !(_CALL_ELF > 1) 1455 // On the PowerPC ELF v1 ABI, function pointers actually point to function 1456 // descriptors. These descriptors are stored in an .opd section, which is 1457 // mapped read-only. We thus need to look at all readable segments, not 1458 // just the executable ones. 1459 constexpr int interesting = PF_R; 1460 #else 1461 constexpr int interesting = PF_X | PF_R; 1462 #endif 1463 1464 if (phdr.p_type != PT_LOAD 1465 || (phdr.p_flags & interesting) != interesting) { 1466 // Not a LOAD segment, not executable code, and not a function 1467 // descriptor. 1468 continue; 1469 } 1470 if (num_interesting_load_segments < obj->phdr.size()) { 1471 memcpy(&obj->phdr[num_interesting_load_segments++], &phdr, sizeof(phdr)); 1472 } else { 1473 ABSL_RAW_LOG( 1474 WARNING, "%s: too many interesting LOAD segments: %zu >= %zu", 1475 obj->filename, num_interesting_load_segments, obj->phdr.size()); 1476 break; 1477 } 1478 } 1479 if (num_interesting_load_segments == 0) { 1480 // This object has no interesting LOAD segments. That's unexpected. 1481 ABSL_RAW_LOG(WARNING, "%s: no interesting LOAD segments", obj->filename); 1482 return false; 1483 } 1484 } 1485 return true; 1486 } 1487 1488 // The implementation of our symbolization routine. If it 1489 // successfully finds the symbol containing "pc" and obtains the 1490 // symbol name, returns pointer to that symbol. Otherwise, returns nullptr. 1491 // If any symbol decorators have been installed via InstallSymbolDecorator(), 1492 // they are called here as well. 1493 // To keep stack consumption low, we would like this function to not 1494 // get inlined. 1495 const char *Symbolizer::GetUncachedSymbol(const void *pc) { 1496 ObjFile *const obj = FindObjFile(pc, 1); 1497 ptrdiff_t relocation = 0; 1498 int fd = -1; 1499 if (obj != nullptr) { 1500 if (MaybeInitializeObjFile(obj)) { 1501 const size_t start_addr = reinterpret_cast<size_t>(obj->start_addr); 1502 if (obj->elf_type == ET_DYN && start_addr >= obj->offset) { 1503 // This object was relocated. 1504 // 1505 // For obj->offset > 0, adjust the relocation since a mapping at offset 1506 // X in the file will have a start address of [true relocation]+X. 1507 relocation = static_cast<ptrdiff_t>(start_addr - obj->offset); 1508 1509 // Note: some binaries have multiple LOAD segments that can contain 1510 // function pointers. We must find the right one. 1511 ElfW(Phdr) *phdr = nullptr; 1512 for (size_t j = 0; j < obj->phdr.size(); j++) { 1513 ElfW(Phdr) &p = obj->phdr[j]; 1514 if (p.p_type != PT_LOAD) { 1515 // We only expect PT_LOADs. This must be PT_NULL that we didn't 1516 // write over (i.e. we exhausted all interesting PT_LOADs). 1517 ABSL_RAW_CHECK(p.p_type == PT_NULL, "unexpected p_type"); 1518 break; 1519 } 1520 if (pc < reinterpret_cast<void *>(start_addr + p.p_vaddr + p.p_memsz)) { 1521 phdr = &p; 1522 break; 1523 } 1524 } 1525 if (phdr == nullptr) { 1526 // That's unexpected. Hope for the best. 1527 ABSL_RAW_LOG( 1528 WARNING, 1529 "%s: unable to find LOAD segment for pc: %p, start_addr: %zx", 1530 obj->filename, pc, start_addr); 1531 } else { 1532 // Adjust relocation in case phdr.p_vaddr != 0. 1533 // This happens for binaries linked with `lld --rosegment`, and for 1534 // binaries linked with BFD `ld -z separate-code`. 1535 relocation -= phdr->p_vaddr - phdr->p_offset; 1536 } 1537 } 1538 1539 fd = obj->fd; 1540 if (GetSymbolFromObjectFile(*obj, pc, relocation, symbol_buf_, 1541 sizeof(symbol_buf_), tmp_buf_, 1542 sizeof(tmp_buf_)) == SYMBOL_FOUND) { 1543 // Only try to demangle the symbol name if it fit into symbol_buf_. 1544 DemangleInplace(symbol_buf_, sizeof(symbol_buf_), tmp_buf_, 1545 sizeof(tmp_buf_)); 1546 } 1547 } 1548 } else { 1549 #if ABSL_HAVE_VDSO_SUPPORT 1550 VDSOSupport vdso; 1551 if (vdso.IsPresent()) { 1552 VDSOSupport::SymbolInfo symbol_info; 1553 if (vdso.LookupSymbolByAddress(pc, &symbol_info)) { 1554 // All VDSO symbols are known to be short. 1555 size_t len = strlen(symbol_info.name); 1556 ABSL_RAW_CHECK(len + 1 < sizeof(symbol_buf_), 1557 "VDSO symbol unexpectedly long"); 1558 memcpy(symbol_buf_, symbol_info.name, len + 1); 1559 } 1560 } 1561 #endif 1562 } 1563 1564 if (g_decorators_mu.TryLock()) { 1565 if (g_num_decorators > 0) { 1566 SymbolDecoratorArgs decorator_args = { 1567 pc, relocation, fd, symbol_buf_, sizeof(symbol_buf_), 1568 tmp_buf_, sizeof(tmp_buf_), nullptr}; 1569 for (int i = 0; i < g_num_decorators; ++i) { 1570 decorator_args.arg = g_decorators[i].arg; 1571 g_decorators[i].fn(&decorator_args); 1572 } 1573 } 1574 g_decorators_mu.Unlock(); 1575 } 1576 if (symbol_buf_[0] == '\0') { 1577 return nullptr; 1578 } 1579 symbol_buf_[sizeof(symbol_buf_) - 1] = '\0'; // Paranoia. 1580 return InsertSymbolInCache(pc, symbol_buf_); 1581 } 1582 1583 const char *Symbolizer::GetSymbol(const void *pc) { 1584 const char *entry = FindSymbolInCache(pc); 1585 if (entry != nullptr) { 1586 return entry; 1587 } 1588 symbol_buf_[0] = '\0'; 1589 1590 #ifdef __hppa__ 1591 { 1592 // In some contexts (e.g., return addresses), PA-RISC uses the lowest two 1593 // bits of the address to indicate the privilege level. Clear those bits 1594 // before trying to symbolize. 1595 const auto pc_bits = reinterpret_cast<uintptr_t>(pc); 1596 const auto address = pc_bits & ~0x3; 1597 entry = GetUncachedSymbol(reinterpret_cast<const void *>(address)); 1598 if (entry != nullptr) { 1599 return entry; 1600 } 1601 1602 // In some contexts, PA-RISC also uses bit 1 of the address to indicate that 1603 // this is a cross-DSO function pointer. Such function pointers actually 1604 // point to a procedure label, a struct whose first 32-bit (pointer) element 1605 // actually points to the function text. With no symbol found for this 1606 // address so far, try interpreting it as a cross-DSO function pointer and 1607 // see how that goes. 1608 if (pc_bits & 0x2) { 1609 return GetUncachedSymbol(*reinterpret_cast<const void *const *>(address)); 1610 } 1611 1612 return nullptr; 1613 } 1614 #else 1615 return GetUncachedSymbol(pc); 1616 #endif 1617 } 1618 1619 bool RemoveAllSymbolDecorators(void) { 1620 if (!g_decorators_mu.TryLock()) { 1621 // Someone else is using decorators. Get out. 1622 return false; 1623 } 1624 g_num_decorators = 0; 1625 g_decorators_mu.Unlock(); 1626 return true; 1627 } 1628 1629 bool RemoveSymbolDecorator(int ticket) { 1630 if (!g_decorators_mu.TryLock()) { 1631 // Someone else is using decorators. Get out. 1632 return false; 1633 } 1634 for (int i = 0; i < g_num_decorators; ++i) { 1635 if (g_decorators[i].ticket == ticket) { 1636 while (i < g_num_decorators - 1) { 1637 g_decorators[i] = g_decorators[i + 1]; 1638 ++i; 1639 } 1640 g_num_decorators = i; 1641 break; 1642 } 1643 } 1644 g_decorators_mu.Unlock(); 1645 return true; // Decorator is known to be removed. 1646 } 1647 1648 int InstallSymbolDecorator(SymbolDecorator decorator, void *arg) { 1649 static int ticket = 0; 1650 1651 if (!g_decorators_mu.TryLock()) { 1652 // Someone else is using decorators. Get out. 1653 return -2; 1654 } 1655 int ret = ticket; 1656 if (g_num_decorators >= kMaxDecorators) { 1657 ret = -1; 1658 } else { 1659 g_decorators[g_num_decorators] = {decorator, arg, ticket++}; 1660 ++g_num_decorators; 1661 } 1662 g_decorators_mu.Unlock(); 1663 return ret; 1664 } 1665 1666 bool RegisterFileMappingHint(const void *start, const void *end, uint64_t offset, 1667 const char *filename) { 1668 SAFE_ASSERT(start <= end); 1669 SAFE_ASSERT(filename != nullptr); 1670 1671 InitSigSafeArena(); 1672 1673 if (!g_file_mapping_mu.TryLock()) { 1674 return false; 1675 } 1676 1677 bool ret = true; 1678 if (g_num_file_mapping_hints >= kMaxFileMappingHints) { 1679 ret = false; 1680 } else { 1681 // TODO(ckennelly): Move this into a string copy routine. 1682 size_t len = strlen(filename); 1683 char *dst = static_cast<char *>( 1684 base_internal::LowLevelAlloc::AllocWithArena(len + 1, SigSafeArena())); 1685 ABSL_RAW_CHECK(dst != nullptr, "out of memory"); 1686 memcpy(dst, filename, len + 1); 1687 1688 auto &hint = g_file_mapping_hints[g_num_file_mapping_hints++]; 1689 hint.start = start; 1690 hint.end = end; 1691 hint.offset = offset; 1692 hint.filename = dst; 1693 } 1694 1695 g_file_mapping_mu.Unlock(); 1696 return ret; 1697 } 1698 1699 bool GetFileMappingHint(const void **start, const void **end, uint64_t *offset, 1700 const char **filename) { 1701 if (!g_file_mapping_mu.TryLock()) { 1702 return false; 1703 } 1704 bool found = false; 1705 for (int i = 0; i < g_num_file_mapping_hints; i++) { 1706 if (g_file_mapping_hints[i].start <= *start && 1707 *end <= g_file_mapping_hints[i].end) { 1708 // We assume that the start_address for the mapping is the base 1709 // address of the ELF section, but when [start_address,end_address) is 1710 // not strictly equal to [hint.start, hint.end), that assumption is 1711 // invalid. 1712 // 1713 // This uses the hint's start address (even though hint.start is not 1714 // necessarily equal to start_address) to ensure the correct 1715 // relocation is computed later. 1716 *start = g_file_mapping_hints[i].start; 1717 *end = g_file_mapping_hints[i].end; 1718 *offset = g_file_mapping_hints[i].offset; 1719 *filename = g_file_mapping_hints[i].filename; 1720 found = true; 1721 break; 1722 } 1723 } 1724 g_file_mapping_mu.Unlock(); 1725 return found; 1726 } 1727 1728 } // namespace debugging_internal 1729 1730 bool Symbolize(const void *pc, char *out, int out_size) { 1731 // Symbolization is very slow under tsan. 1732 ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN(); 1733 SAFE_ASSERT(out_size >= 0); 1734 debugging_internal::Symbolizer *s = debugging_internal::AllocateSymbolizer(); 1735 const char *name = s->GetSymbol(pc); 1736 bool ok = false; 1737 if (name != nullptr && out_size > 0) { 1738 strncpy(out, name, static_cast<size_t>(out_size)); 1739 ok = true; 1740 if (out[static_cast<size_t>(out_size) - 1] != '\0') { 1741 // strncpy() does not '\0' terminate when it truncates. Do so, with 1742 // trailing ellipsis. 1743 static constexpr char kEllipsis[] = "..."; 1744 size_t ellipsis_size = 1745 std::min(strlen(kEllipsis), static_cast<size_t>(out_size) - 1); 1746 memcpy(out + static_cast<size_t>(out_size) - ellipsis_size - 1, kEllipsis, 1747 ellipsis_size); 1748 out[static_cast<size_t>(out_size) - 1] = '\0'; 1749 } 1750 } 1751 debugging_internal::FreeSymbolizer(s); 1752 ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_END(); 1753 return ok; 1754 } 1755 1756 ABSL_NAMESPACE_END 1757 } // namespace absl 1758 1759 extern "C" bool AbslInternalGetFileMappingHint(const void **start, 1760 const void **end, uint64_t *offset, 1761 const char **filename) { 1762 return absl::debugging_internal::GetFileMappingHint(start, end, offset, 1763 filename); 1764 }