1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: Satoru Takabayashi
31 // Stack-footprint reduction work done by Raksit Ashok
33 // Implementation note:
35 // We don't use heaps but only use stacks. We want to reduce the
36 // stack consumption so that the symbolizer can run on small stacks.
38 // Here are some numbers collected with GCC 4.1.0 on x86:
39 // - sizeof(Elf32_Sym) = 16
40 // - sizeof(Elf32_Shdr) = 40
41 // - sizeof(Elf64_Sym) = 24
42 // - sizeof(Elf64_Shdr) = 64
44 // This implementation is intended to be async-signal-safe but uses
45 // some functions which are not guaranteed to be so, such as memchr()
46 // and memmove(). We assume they are async-signal-safe.
48 // Additional header can be specified by the GLOG_BUILD_CONFIG_INCLUDE
49 // macro to add platform specific defines (e.g. OS_OPENBSD).
51 #ifdef GLOG_BUILD_CONFIG_INCLUDE
52 #include GLOG_BUILD_CONFIG_INCLUDE
53 #endif // GLOG_BUILD_CONFIG_INCLUDE
55 #include "utilities.h"
57 #if defined(HAVE_SYMBOLIZE)
61 #include "symbolize.h"
64 _START_GOOGLE_NAMESPACE_
66 // We don't use assert() since it's not guaranteed to be
67 // async-signal-safe. Instead we define a minimal assertion
68 // macro. So far, we don't need pretty printing for __FILE__, etc.
70 // A wrapper for abort() to make it callable in ? :.
71 static int AssertFail() {
73 return 0; // Should not reach.
76 #define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail())
78 static SymbolizeCallback g_symbolize_callback = NULL;
79 void InstallSymbolizeCallback(SymbolizeCallback callback) {
80 g_symbolize_callback = callback;
83 static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback =
85 void InstallSymbolizeOpenObjectFileCallback(
86 SymbolizeOpenObjectFileCallback callback) {
87 g_symbolize_open_object_file_callback = callback;
90 // This function wraps the Demangle function to provide an interface
91 // where the input symbol is demangled in-place.
92 // To keep stack consumption low, we would like this function to not
94 static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size) {
95 char demangled[256]; // Big enough for sane demangled symbols.
96 if (Demangle(out, demangled, sizeof(demangled))) {
97 // Demangling succeeded. Copy to out if the space allows.
98 size_t len = strlen(demangled);
99 if (len + 1 <= (size_t)out_size) { // +1 for '\0'.
100 SAFE_ASSERT(len < sizeof(demangled));
101 memmove(out, demangled, len + 1);
106 _END_GOOGLE_NAMESPACE_
111 #if defined(OS_OPENBSD)
112 #include <sys/exec_elf.h>
124 #include <sys/stat.h>
125 #include <sys/types.h>
128 #include "symbolize.h"
130 #include "glog/raw_logging.h"
132 // Re-runs fn until it doesn't cause EINTR.
133 #define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR)
135 _START_GOOGLE_NAMESPACE_
137 // Read up to "count" bytes from file descriptor "fd" into the buffer
138 // starting at "buf" while handling short reads and EINTR. On
139 // success, return the number of bytes read. Otherwise, return -1.
140 static ssize_t ReadPersistent(const int fd, void *buf, const size_t count) {
141 SAFE_ASSERT(fd >= 0);
142 SAFE_ASSERT(count <= std::numeric_limits<ssize_t>::max());
143 char *buf0 = reinterpret_cast<char *>(buf);
144 ssize_t num_bytes = 0;
145 while (num_bytes < count) {
147 NO_INTR(len = read(fd, buf0 + num_bytes, count - num_bytes));
148 if (len < 0) { // There was an error other than EINTR.
151 if (len == 0) { // Reached EOF.
156 SAFE_ASSERT(num_bytes <= count);
160 // Read up to "count" bytes from "offset" in the file pointed by file
161 // descriptor "fd" into the buffer starting at "buf". On success,
162 // return the number of bytes read. Otherwise, return -1.
163 static ssize_t ReadFromOffset(const int fd, void *buf,
164 const size_t count, const off_t offset) {
165 off_t off = lseek(fd, offset, SEEK_SET);
166 if (off == (off_t)-1) {
169 return ReadPersistent(fd, buf, count);
172 // Try reading exactly "count" bytes from "offset" bytes in a file
173 // pointed by "fd" into the buffer starting at "buf" while handling
174 // short reads and EINTR. On success, return true. Otherwise, return
176 static bool ReadFromOffsetExact(const int fd, void *buf,
177 const size_t count, const off_t offset) {
178 ssize_t len = ReadFromOffset(fd, buf, count, offset);
182 // Returns elf_header.e_type if the file pointed by fd is an ELF binary.
183 static int FileGetElfType(const int fd) {
184 ElfW(Ehdr) elf_header;
185 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
188 if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) {
191 return elf_header.e_type;
194 // Read the section headers in the given ELF binary, and if a section
195 // of the specified type is found, set the output to this section header
196 // and return true. Otherwise, return false.
197 // To keep stack consumption low, we would like this function to not get
199 static ATTRIBUTE_NOINLINE bool
200 GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const off_t sh_offset,
201 ElfW(Word) type, ElfW(Shdr) *out) {
202 // Read at most 16 section headers at a time to save read calls.
204 for (int i = 0; i < sh_num;) {
205 const ssize_t num_bytes_left = (sh_num - i) * sizeof(buf[0]);
206 const ssize_t num_bytes_to_read =
207 (sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf);
208 const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read,
209 sh_offset + i * sizeof(buf[0]));
210 SAFE_ASSERT(len % sizeof(buf[0]) == 0);
211 const ssize_t num_headers_in_buf = len / sizeof(buf[0]);
212 SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0]));
213 for (int j = 0; j < num_headers_in_buf; ++j) {
214 if (buf[j].sh_type == type) {
219 i += num_headers_in_buf;
224 // There is no particular reason to limit section name to 63 characters,
225 // but there has (as yet) been no need for anything longer either.
226 const int kMaxSectionNameLen = 64;
228 // name_len should include terminating '\0'.
229 bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
231 ElfW(Ehdr) elf_header;
232 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
237 off_t shstrtab_offset = (elf_header.e_shoff +
238 elf_header.e_shentsize * elf_header.e_shstrndx);
239 if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) {
243 for (int i = 0; i < elf_header.e_shnum; ++i) {
244 off_t section_header_offset = (elf_header.e_shoff +
245 elf_header.e_shentsize * i);
246 if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) {
249 char header_name[kMaxSectionNameLen];
250 if (sizeof(header_name) < name_len) {
251 RAW_LOG(WARNING, "Section name '%s' is too long (%" PRIuS "); "
252 "section will not be found (even if present).", name, name_len);
253 // No point in even trying.
256 off_t name_offset = shstrtab.sh_offset + out->sh_name;
257 ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
260 } else if (n_read != name_len) {
261 // Short read -- name could be at end of file.
264 if (memcmp(header_name, name, name_len) == 0) {
271 // Read a symbol table and look for the symbol containing the
272 // pc. Iterate over symbols in a symbol table and look for the symbol
273 // containing "pc". On success, return true and write the symbol name
274 // to out. Otherwise, return false.
275 // To keep stack consumption low, we would like this function to not get
277 static ATTRIBUTE_NOINLINE bool
278 FindSymbol(uint64_t pc, const int fd, char *out, int out_size,
279 uint64_t symbol_offset, const ElfW(Shdr) *strtab,
280 const ElfW(Shdr) *symtab) {
281 if (symtab == NULL) {
284 const int num_symbols = symtab->sh_size / symtab->sh_entsize;
285 for (int i = 0; i < num_symbols;) {
286 off_t offset = symtab->sh_offset + i * symtab->sh_entsize;
288 // If we are reading Elf64_Sym's, we want to limit this array to
289 // 32 elements (to keep stack consumption low), otherwise we can
290 // have a 64 element Elf32_Sym array.
292 #define NUM_SYMBOLS 32
294 #define NUM_SYMBOLS 64
297 // Read at most NUM_SYMBOLS symbols at once to save read() calls.
298 ElfW(Sym) buf[NUM_SYMBOLS];
299 const ssize_t len = ReadFromOffset(fd, &buf, sizeof(buf), offset);
300 SAFE_ASSERT(len % sizeof(buf[0]) == 0);
301 const ssize_t num_symbols_in_buf = len / sizeof(buf[0]);
302 SAFE_ASSERT(num_symbols_in_buf <= sizeof(buf)/sizeof(buf[0]));
303 for (int j = 0; j < num_symbols_in_buf; ++j) {
304 const ElfW(Sym)& symbol = buf[j];
305 uint64_t start_address = symbol.st_value;
306 start_address += symbol_offset;
307 uint64_t end_address = start_address + symbol.st_size;
308 if (symbol.st_value != 0 && // Skip null value symbols.
309 symbol.st_shndx != 0 && // Skip undefined symbols.
310 start_address <= pc && pc < end_address) {
311 ssize_t len1 = ReadFromOffset(fd, out, out_size,
312 strtab->sh_offset + symbol.st_name);
313 if (len1 <= 0 || memchr(out, '\0', out_size) == NULL) {
316 return true; // Obtained the symbol name.
319 i += num_symbols_in_buf;
324 // Get the symbol name of "pc" from the file pointed by "fd". Process
325 // both regular and dynamic symbol tables if necessary. On success,
326 // write the symbol name to "out" and return true. Otherwise, return
328 static bool GetSymbolFromObjectFile(const int fd, uint64_t pc,
329 char *out, int out_size,
330 uint64_t map_base_address) {
331 // Read the ELF header.
332 ElfW(Ehdr) elf_header;
333 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
337 uint64_t symbol_offset = 0;
338 if (elf_header.e_type == ET_DYN) { // DSO needs offset adjustment.
340 // We need to find the PT_LOAD segment corresponding to the read-execute
341 // file mapping in order to correctly perform the offset adjustment.
342 for (unsigned i = 0; i != elf_header.e_phnum; ++i) {
343 if (!ReadFromOffsetExact(fd, &phdr, sizeof(phdr),
344 elf_header.e_phoff + i * sizeof(phdr)))
346 if (phdr.p_type == PT_LOAD &&
347 (phdr.p_flags & (PF_R | PF_X)) == (PF_R | PF_X)) {
348 // Find the mapped address corresponding to virtual address zero. We do
349 // this by first adding p_offset. This gives us the mapped address of
350 // the start of the segment, or in other words the mapped address
351 // corresponding to the virtual address of the segment. (Note that this
352 // is distinct from the start address, as p_offset is not guaranteed to
353 // be page aligned.) We then subtract p_vaddr, which takes us to virtual
355 symbol_offset = map_base_address + phdr.p_offset - phdr.p_vaddr;
359 if (symbol_offset == 0)
363 ElfW(Shdr) symtab, strtab;
365 // Consult a regular symbol table first.
366 if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
367 SHT_SYMTAB, &symtab)) {
368 if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
369 symtab.sh_link * sizeof(symtab))) {
372 if (FindSymbol(pc, fd, out, out_size, symbol_offset,
374 return true; // Found the symbol in a regular symbol table.
378 // If the symbol is not found, then consult a dynamic symbol table.
379 if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
380 SHT_DYNSYM, &symtab)) {
381 if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
382 symtab.sh_link * sizeof(symtab))) {
385 if (FindSymbol(pc, fd, out, out_size, symbol_offset,
387 return true; // Found the symbol in a dynamic symbol table.
395 // Thin wrapper around a file descriptor so that the file descriptor
396 // gets closed for sure.
397 struct FileDescriptor {
399 explicit FileDescriptor(int fd) : fd_(fd) {}
405 int get() { return fd_; }
408 explicit FileDescriptor(const FileDescriptor&);
409 void operator=(const FileDescriptor&);
412 // Helper class for reading lines from file.
414 // Note: we don't use ProcMapsIterator since the object is big (it has
415 // a 5k array member) and uses async-unsafe functions such as sscanf()
419 explicit LineReader(int fd, char *buf, int buf_len) : fd_(fd),
420 buf_(buf), buf_len_(buf_len), bol_(buf), eol_(buf), eod_(buf) {
423 // Read '\n'-terminated line from file. On success, modify "bol"
424 // and "eol", then return true. Otherwise, return false.
426 // Note: if the last line doesn't end with '\n', the line will be
427 // dropped. It's an intentional behavior to make the code simple.
428 bool ReadLine(const char **bol, const char **eol) {
429 if (BufferIsEmpty()) { // First time.
430 const ssize_t num_bytes = ReadPersistent(fd_, buf_, buf_len_);
431 if (num_bytes <= 0) { // EOF or error.
434 eod_ = buf_ + num_bytes;
437 bol_ = eol_ + 1; // Advance to the next line in the buffer.
438 SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_".
439 if (!HasCompleteLine()) {
440 const int incomplete_line_length = eod_ - bol_;
441 // Move the trailing incomplete line to the beginning.
442 memmove(buf_, bol_, incomplete_line_length);
443 // Read text from file and append it.
444 char * const append_pos = buf_ + incomplete_line_length;
445 const int capacity_left = buf_len_ - incomplete_line_length;
446 const ssize_t num_bytes = ReadPersistent(fd_, append_pos,
448 if (num_bytes <= 0) { // EOF or error.
451 eod_ = append_pos + num_bytes;
455 eol_ = FindLineFeed();
456 if (eol_ == NULL) { // '\n' not found. Malformed line.
459 *eol_ = '\0'; // Replace '\n' with '\0'.
466 // Beginning of line.
477 explicit LineReader(const LineReader&);
478 void operator=(const LineReader&);
480 char *FindLineFeed() {
481 return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_));
484 bool BufferIsEmpty() {
488 bool HasCompleteLine() {
489 return !BufferIsEmpty() && FindLineFeed() != NULL;
497 const char *eod_; // End of data in "buf_".
501 // Place the hex number read from "start" into "*hex". The pointer to
502 // the first non-hex character or "end" is returned.
503 static char *GetHex(const char *start, const char *end, uint64_t *hex) {
506 for (p = start; p < end; ++p) {
508 if ((ch >= '0' && ch <= '9') ||
509 (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) {
510 *hex = (*hex << 4) | (ch < 'A' ? ch - '0' : (ch & 0xF) + 9);
511 } else { // Encountered the first non-hex character.
515 SAFE_ASSERT(p <= end);
516 return const_cast<char *>(p);
519 // Searches for the object file (from /proc/self/maps) that contains
520 // the specified pc. If found, sets |start_address| to the start address
521 // of where this object file is mapped in memory, sets the module base
522 // address into |base_address|, copies the object file name into
523 // |out_file_name|, and attempts to open the object file. If the object
524 // file is opened successfully, returns the file descriptor. Otherwise,
525 // returns -1. |out_file_name_size| is the size of the file name buffer
526 // (including the null-terminator).
527 static ATTRIBUTE_NOINLINE int
528 OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc,
529 uint64_t &start_address,
530 uint64_t &base_address,
532 int out_file_name_size) {
535 // Open /proc/self/maps.
537 NO_INTR(maps_fd = open("/proc/self/maps", O_RDONLY));
538 FileDescriptor wrapped_maps_fd(maps_fd);
539 if (wrapped_maps_fd.get() < 0) {
543 // Iterate over maps and look for the map containing the pc. Then
544 // look into the symbol tables inside.
545 char buf[1024]; // Big enough for line of sane /proc/self/maps
547 LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf));
552 if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line.
556 // Start parsing line in /proc/self/maps. Here is an example:
558 // 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat
560 // We want start address (08048000), end address (0804c000), flags
561 // (r-xp) and file name (/bin/cat).
563 // Read start address.
564 cursor = GetHex(cursor, eol, &start_address);
565 if (cursor == eol || *cursor != '-') {
566 return -1; // Malformed line.
568 ++cursor; // Skip '-'.
571 uint64_t end_address;
572 cursor = GetHex(cursor, eol, &end_address);
573 if (cursor == eol || *cursor != ' ') {
574 return -1; // Malformed line.
576 ++cursor; // Skip ' '.
578 // Check start and end addresses.
579 if (!(start_address <= pc && pc < end_address)) {
580 continue; // We skip this map. PC isn't in this map.
583 // Read flags. Skip flags until we encounter a space or eol.
584 const char * const flags_start = cursor;
585 while (cursor < eol && *cursor != ' ') {
588 // We expect at least four letters for flags (ex. "r-xp").
589 if (cursor == eol || cursor < flags_start + 4) {
590 return -1; // Malformed line.
593 // Check flags. We are only interested in "r*x" maps.
594 if (flags_start[0] != 'r' || flags_start[2] != 'x') {
595 continue; // We skip this map.
597 ++cursor; // Skip ' '.
600 uint64_t file_offset;
601 cursor = GetHex(cursor, eol, &file_offset);
602 if (cursor == eol || *cursor != ' ') {
603 return -1; // Malformed line.
605 ++cursor; // Skip ' '.
607 // Don't subtract 'start_address' from the first entry:
608 // * If a binary is compiled w/o -pie, then the first entry in
609 // process maps is likely the binary itself (all dynamic libs
610 // are mapped higher in address space). For such a binary,
611 // instruction offset in binary coincides with the actual
612 // instruction address in virtual memory (as code section
613 // is mapped to a fixed memory range).
614 // * If a binary is compiled with -pie, all the modules are
615 // mapped high at address space (in particular, higher than
616 // shadow memory of the tool), so the module can't be the
618 base_address = ((num_maps == 1) ? 0U : start_address) - file_offset;
620 // Skip to file name. "cursor" now points to dev. We need to
621 // skip at least two spaces for dev and inode.
623 while (cursor < eol) {
624 if (*cursor == ' ') {
626 } else if (num_spaces >= 2) {
627 // The first non-space character after skipping two spaces
628 // is the beginning of the file name.
634 return -1; // Malformed line.
637 // Finally, "cursor" now points to file name of our interest.
638 NO_INTR(object_fd = open(cursor, O_RDONLY));
640 // Failed to open object file. Copy the object file name to
642 strncpy(out_file_name, cursor, out_file_name_size);
643 // Making sure |out_file_name| is always null-terminated.
644 out_file_name[out_file_name_size - 1] = '\0';
651 // POSIX doesn't define any async-signal safe function for converting
652 // an integer to ASCII. We'll have to define our own version.
653 // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
654 // conversion was successful or NULL otherwise. It never writes more than "sz"
655 // bytes. Output will be truncated as needed, and a NUL character is always
657 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
658 char *itoa_r(intptr_t i, char *buf, size_t sz, int base, size_t padding) {
659 // Make sure we can write at least one NUL byte.
664 if (base < 2 || base > 16) {
673 // Handle negative numbers (only for base 10).
674 if (i < 0 && base == 10) {
677 // Make sure we can write the '-' character.
685 // Loop until we have converted the entire number. Output at least one
686 // character (i.e. '0').
689 // Make sure there is still enough space left in our output buffer.
695 // Output the next digit.
696 *ptr++ = "0123456789abcdef"[j % base];
701 } while (j > 0 || padding > 0);
703 // Terminate the output with a NUL character.
706 // Conversion to ASCII actually resulted in the digits being in reverse
707 // order. We can't easily generate them in forward order, as we can't tell
708 // the number of characters needed until we are done converting.
709 // So, now, we reverse the string (except for the possible "-" sign).
710 while (--ptr > start) {
718 // Safely appends string |source| to string |dest|. Never writes past the
719 // buffer size |dest_size| and guarantees that |dest| is null-terminated.
720 void SafeAppendString(const char* source, char* dest, int dest_size) {
721 int dest_string_length = strlen(dest);
722 SAFE_ASSERT(dest_string_length < dest_size);
723 dest += dest_string_length;
724 dest_size -= dest_string_length;
725 strncpy(dest, source, dest_size);
726 // Making sure |dest| is always null-terminated.
727 dest[dest_size - 1] = '\0';
730 // Converts a 64-bit value into a hex string, and safely appends it to |dest|.
731 // Never writes past the buffer size |dest_size| and guarantees that |dest| is
733 void SafeAppendHexNumber(uint64_t value, char* dest, int dest_size) {
734 // 64-bit numbers in hex can have up to 16 digits.
735 char buf[17] = {'\0'};
736 SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size);
739 // The implementation of our symbolization routine. If it
740 // successfully finds the symbol containing "pc" and obtains the
741 // symbol name, returns true and write the symbol name to "out".
742 // Otherwise, returns false. If Callback function is installed via
743 // InstallSymbolizeCallback(), the function is also called in this function,
744 // and "out" is used as its output.
745 // To keep stack consumption low, we would like this function to not
747 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
749 uint64_t pc0 = reinterpret_cast<uintptr_t>(pc);
750 uint64_t start_address = 0;
751 uint64_t base_address = 0;
758 SafeAppendString("(", out, out_size);
760 if (g_symbolize_open_object_file_callback) {
761 object_fd = g_symbolize_open_object_file_callback(pc0, start_address,
762 base_address, out + 1,
765 object_fd = OpenObjectFileContainingPcAndGetStartAddress(pc0, start_address,
771 // Check whether a file name was returned.
774 // The object file containing PC was determined successfully however the
775 // object file was not opened successfully. This is still considered
776 // success because the object file name and offset are known and tools
777 // like asan_symbolize.py can be used for the symbolization.
778 out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated.
779 SafeAppendString("+0x", out, out_size);
780 SafeAppendHexNumber(pc0 - base_address, out, out_size);
781 SafeAppendString(")", out, out_size);
784 // Failed to determine the object file containing PC. Bail out.
787 FileDescriptor wrapped_object_fd(object_fd);
788 int elf_type = FileGetElfType(wrapped_object_fd.get());
789 if (elf_type == -1) {
792 if (g_symbolize_callback) {
793 // Run the call back if it's installed.
794 // Note: relocation (and much of the rest of this code) will be
795 // wrong for prelinked shared libraries and PIE executables.
796 uint64 relocation = (elf_type == ET_DYN) ? start_address : 0;
797 int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(),
800 if (num_bytes_written > 0) {
801 out += num_bytes_written;
802 out_size -= num_bytes_written;
805 if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0,
806 out, out_size, base_address)) {
810 // Symbolization succeeded. Now we try to demangle the symbol.
811 DemangleInplace(out, out_size);
815 _END_GOOGLE_NAMESPACE_
817 #elif defined(OS_MACOSX) && defined(HAVE_DLADDR)
822 _START_GOOGLE_NAMESPACE_
824 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
827 if (dladdr(pc, &info)) {
828 if ((int)strlen(info.dli_sname) < out_size) {
829 strcpy(out, info.dli_sname);
830 // Symbolization succeeded. Now we try to demangle the symbol.
831 DemangleInplace(out, out_size);
838 _END_GOOGLE_NAMESPACE_
841 # error BUG: HAVE_SYMBOLIZE was wrongly set
844 _START_GOOGLE_NAMESPACE_
846 bool Symbolize(void *pc, char *out, int out_size) {
847 SAFE_ASSERT(out_size >= 0);
848 return SymbolizeAndDemangle(pc, out, out_size);
851 _END_GOOGLE_NAMESPACE_
853 #else /* HAVE_SYMBOLIZE */
859 _START_GOOGLE_NAMESPACE_
861 // TODO: Support other environments.
862 bool Symbolize(void *pc, char *out, int out_size) {
867 _END_GOOGLE_NAMESPACE_