Coverage Report

Created: 2025-08-25 06:55

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