symbolize_elf.inc 60 KB

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