symbolize_elf.inc 57 KB

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