symbolize_elf.inc 58 KB

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