You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

symbolize_elf.inc 56 kB

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