symbolize_elf.inc 53 KB

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