Coverage Report

Created: 2025-06-16 06:26

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