Coverage Report

Created: 2023-09-25 06:27

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