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)
63 #include "symbolize.h"
66 _START_GOOGLE_NAMESPACE_
68 // We don't use assert() since it's not guaranteed to be
69 // async-signal-safe. Instead we define a minimal assertion
70 // macro. So far, we don't need pretty printing for __FILE__, etc.
72 // A wrapper for abort() to make it callable in ? :.
73 static int AssertFail() {
75 return 0; // Should not reach.
78 #define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail())
80 static SymbolizeCallback g_symbolize_callback = NULL;
81 void InstallSymbolizeCallback(SymbolizeCallback callback) {
82 g_symbolize_callback = callback;
85 static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback =
87 void InstallSymbolizeOpenObjectFileCallback(
88 SymbolizeOpenObjectFileCallback callback) {
89 g_symbolize_open_object_file_callback = callback;
92 // This function wraps the Demangle function to provide an interface
93 // where the input symbol is demangled in-place.
94 // To keep stack consumption low, we would like this function to not
96 static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size) {
97 char demangled[256]; // Big enough for sane demangled symbols.
98 if (Demangle(out, demangled, sizeof(demangled))) {
99 // Demangling succeeded. Copy to out if the space allows.
100 size_t len = strlen(demangled);
101 if (len + 1 <= (size_t)out_size) { // +1 for '\0'.
102 SAFE_ASSERT(len < sizeof(demangled));
103 memmove(out, demangled, len + 1);
108 _END_GOOGLE_NAMESPACE_
113 #if defined(OS_OPENBSD)
114 #include <sys/exec_elf.h>
126 #include <sys/stat.h>
127 #include <sys/types.h>
130 #include "symbolize.h"
132 #include "glog/raw_logging.h"
134 // Re-runs fn until it doesn't cause EINTR.
135 #define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR)
137 _START_GOOGLE_NAMESPACE_
139 // Read up to "count" bytes from file descriptor "fd" into the buffer
140 // starting at "buf" while handling short reads and EINTR. On
141 // success, return the number of bytes read. Otherwise, return -1.
142 static ssize_t ReadPersistent(const int fd, void *buf, const size_t count) {
143 SAFE_ASSERT(fd >= 0);
144 SAFE_ASSERT(count <= std::numeric_limits<ssize_t>::max());
145 char *buf0 = reinterpret_cast<char *>(buf);
146 ssize_t num_bytes = 0;
147 while (num_bytes < count) {
149 NO_INTR(len = read(fd, buf0 + num_bytes, count - num_bytes));
150 if (len < 0) { // There was an error other than EINTR.
153 if (len == 0) { // Reached EOF.
158 SAFE_ASSERT(num_bytes <= count);
162 // Read up to "count" bytes from "offset" in the file pointed by file
163 // descriptor "fd" into the buffer starting at "buf". On success,
164 // return the number of bytes read. Otherwise, return -1.
165 static ssize_t ReadFromOffset(const int fd, void *buf,
166 const size_t count, const off_t offset) {
167 off_t off = lseek(fd, offset, SEEK_SET);
168 if (off == (off_t)-1) {
171 return ReadPersistent(fd, buf, count);
174 // Try reading exactly "count" bytes from "offset" bytes in a file
175 // pointed by "fd" into the buffer starting at "buf" while handling
176 // short reads and EINTR. On success, return true. Otherwise, return
178 static bool ReadFromOffsetExact(const int fd, void *buf,
179 const size_t count, const off_t offset) {
180 ssize_t len = ReadFromOffset(fd, buf, count, offset);
184 // Returns elf_header.e_type if the file pointed by fd is an ELF binary.
185 static int FileGetElfType(const int fd) {
186 ElfW(Ehdr) elf_header;
187 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
190 if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) {
193 return elf_header.e_type;
196 // Read the section headers in the given ELF binary, and if a section
197 // of the specified type is found, set the output to this section header
198 // and return true. Otherwise, return false.
199 // To keep stack consumption low, we would like this function to not get
201 static ATTRIBUTE_NOINLINE bool
202 GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const off_t sh_offset,
203 ElfW(Word) type, ElfW(Shdr) *out) {
204 // Read at most 16 section headers at a time to save read calls.
206 for (int i = 0; i < sh_num;) {
207 const ssize_t num_bytes_left = (sh_num - i) * sizeof(buf[0]);
208 const ssize_t num_bytes_to_read =
209 (sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf);
210 const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read,
211 sh_offset + i * sizeof(buf[0]));
212 SAFE_ASSERT(len % sizeof(buf[0]) == 0);
213 const ssize_t num_headers_in_buf = len / sizeof(buf[0]);
214 SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0]));
215 for (int j = 0; j < num_headers_in_buf; ++j) {
216 if (buf[j].sh_type == type) {
221 i += num_headers_in_buf;
226 // There is no particular reason to limit section name to 63 characters,
227 // but there has (as yet) been no need for anything longer either.
228 const int kMaxSectionNameLen = 64;
230 // name_len should include terminating '\0'.
231 bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
233 ElfW(Ehdr) elf_header;
234 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
239 off_t shstrtab_offset = (elf_header.e_shoff +
240 elf_header.e_shentsize * elf_header.e_shstrndx);
241 if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) {
245 for (int i = 0; i < elf_header.e_shnum; ++i) {
246 off_t section_header_offset = (elf_header.e_shoff +
247 elf_header.e_shentsize * i);
248 if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) {
251 char header_name[kMaxSectionNameLen];
252 if (sizeof(header_name) < name_len) {
253 RAW_LOG(WARNING, "Section name '%s' is too long (%" PRIuS "); "
254 "section will not be found (even if present).", name, name_len);
255 // No point in even trying.
258 off_t name_offset = shstrtab.sh_offset + out->sh_name;
259 ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
262 } else if (n_read != name_len) {
263 // Short read -- name could be at end of file.
266 if (memcmp(header_name, name, name_len) == 0) {
273 // Read a symbol table and look for the symbol containing the
274 // pc. Iterate over symbols in a symbol table and look for the symbol
275 // containing "pc". On success, return true and write the symbol name
276 // to out. Otherwise, return false.
277 // To keep stack consumption low, we would like this function to not get
279 static ATTRIBUTE_NOINLINE bool
280 FindSymbol(uint64_t pc, const int fd, char *out, int out_size,
281 uint64_t symbol_offset, const ElfW(Shdr) *strtab,
282 const ElfW(Shdr) *symtab) {
283 if (symtab == NULL) {
286 const int num_symbols = symtab->sh_size / symtab->sh_entsize;
287 for (int i = 0; i < num_symbols;) {
288 off_t offset = symtab->sh_offset + i * symtab->sh_entsize;
290 // If we are reading Elf64_Sym's, we want to limit this array to
291 // 32 elements (to keep stack consumption low), otherwise we can
292 // have a 64 element Elf32_Sym array.
294 #define NUM_SYMBOLS 32
296 #define NUM_SYMBOLS 64
299 // Read at most NUM_SYMBOLS symbols at once to save read() calls.
300 ElfW(Sym) buf[NUM_SYMBOLS];
301 const ssize_t len = ReadFromOffset(fd, &buf, sizeof(buf), offset);
302 SAFE_ASSERT(len % sizeof(buf[0]) == 0);
303 const ssize_t num_symbols_in_buf = len / sizeof(buf[0]);
304 SAFE_ASSERT(num_symbols_in_buf <= sizeof(buf)/sizeof(buf[0]));
305 for (int j = 0; j < num_symbols_in_buf; ++j) {
306 const ElfW(Sym)& symbol = buf[j];
307 uint64_t start_address = symbol.st_value;
308 start_address += symbol_offset;
309 uint64_t end_address = start_address + symbol.st_size;
310 if (symbol.st_value != 0 && // Skip null value symbols.
311 symbol.st_shndx != 0 && // Skip undefined symbols.
312 start_address <= pc && pc < end_address) {
313 ssize_t len1 = ReadFromOffset(fd, out, out_size,
314 strtab->sh_offset + symbol.st_name);
315 if (len1 <= 0 || memchr(out, '\0', out_size) == NULL) {
318 return true; // Obtained the symbol name.
321 i += num_symbols_in_buf;
326 // Get the symbol name of "pc" from the file pointed by "fd". Process
327 // both regular and dynamic symbol tables if necessary. On success,
328 // write the symbol name to "out" and return true. Otherwise, return
330 static bool GetSymbolFromObjectFile(const int fd,
334 uint64_t base_address) {
335 // Read the ELF header.
336 ElfW(Ehdr) elf_header;
337 if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
341 ElfW(Shdr) symtab, strtab;
343 // Consult a regular symbol table first.
344 if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
345 SHT_SYMTAB, &symtab)) {
346 if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
347 symtab.sh_link * sizeof(symtab))) {
350 if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
351 return true; // Found the symbol in a regular symbol table.
355 // If the symbol is not found, then consult a dynamic symbol table.
356 if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
357 SHT_DYNSYM, &symtab)) {
358 if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
359 symtab.sh_link * sizeof(symtab))) {
362 if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
363 return true; // Found the symbol in a dynamic symbol table.
371 // Thin wrapper around a file descriptor so that the file descriptor
372 // gets closed for sure.
373 struct FileDescriptor {
375 explicit FileDescriptor(int fd) : fd_(fd) {}
381 int get() { return fd_; }
384 explicit FileDescriptor(const FileDescriptor&);
385 void operator=(const FileDescriptor&);
388 // Helper class for reading lines from file.
390 // Note: we don't use ProcMapsIterator since the object is big (it has
391 // a 5k array member) and uses async-unsafe functions such as sscanf()
395 explicit LineReader(int fd, char *buf, int buf_len) : fd_(fd),
396 buf_(buf), buf_len_(buf_len), bol_(buf), eol_(buf), eod_(buf) {
399 // Read '\n'-terminated line from file. On success, modify "bol"
400 // and "eol", then return true. Otherwise, return false.
402 // Note: if the last line doesn't end with '\n', the line will be
403 // dropped. It's an intentional behavior to make the code simple.
404 bool ReadLine(const char **bol, const char **eol) {
405 if (BufferIsEmpty()) { // First time.
406 const ssize_t num_bytes = ReadPersistent(fd_, buf_, buf_len_);
407 if (num_bytes <= 0) { // EOF or error.
410 eod_ = buf_ + num_bytes;
413 bol_ = eol_ + 1; // Advance to the next line in the buffer.
414 SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_".
415 if (!HasCompleteLine()) {
416 const int incomplete_line_length = eod_ - bol_;
417 // Move the trailing incomplete line to the beginning.
418 memmove(buf_, bol_, incomplete_line_length);
419 // Read text from file and append it.
420 char * const append_pos = buf_ + incomplete_line_length;
421 const int capacity_left = buf_len_ - incomplete_line_length;
422 const ssize_t num_bytes = ReadPersistent(fd_, append_pos,
424 if (num_bytes <= 0) { // EOF or error.
427 eod_ = append_pos + num_bytes;
431 eol_ = FindLineFeed();
432 if (eol_ == NULL) { // '\n' not found. Malformed line.
435 *eol_ = '\0'; // Replace '\n' with '\0'.
442 // Beginning of line.
453 explicit LineReader(const LineReader&);
454 void operator=(const LineReader&);
456 char *FindLineFeed() {
457 return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_));
460 bool BufferIsEmpty() {
464 bool HasCompleteLine() {
465 return !BufferIsEmpty() && FindLineFeed() != NULL;
473 const char *eod_; // End of data in "buf_".
477 // Place the hex number read from "start" into "*hex". The pointer to
478 // the first non-hex character or "end" is returned.
479 static char *GetHex(const char *start, const char *end, uint64_t *hex) {
482 for (p = start; p < end; ++p) {
484 if ((ch >= '0' && ch <= '9') ||
485 (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) {
486 *hex = (*hex << 4) | (ch < 'A' ? ch - '0' : (ch & 0xF) + 9);
487 } else { // Encountered the first non-hex character.
491 SAFE_ASSERT(p <= end);
492 return const_cast<char *>(p);
495 // Searches for the object file (from /proc/self/maps) that contains
496 // the specified pc. If found, sets |start_address| to the start address
497 // of where this object file is mapped in memory, sets the module base
498 // address into |base_address|, copies the object file name into
499 // |out_file_name|, and attempts to open the object file. If the object
500 // file is opened successfully, returns the file descriptor. Otherwise,
501 // returns -1. |out_file_name_size| is the size of the file name buffer
502 // (including the null-terminator).
503 static ATTRIBUTE_NOINLINE int
504 OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc,
505 uint64_t &start_address,
506 uint64_t &base_address,
508 int out_file_name_size) {
512 NO_INTR(maps_fd = open("/proc/self/maps", O_RDONLY));
513 FileDescriptor wrapped_maps_fd(maps_fd);
514 if (wrapped_maps_fd.get() < 0) {
519 NO_INTR(mem_fd = open("/proc/self/mem", O_RDONLY));
520 FileDescriptor wrapped_mem_fd(mem_fd);
521 if (wrapped_mem_fd.get() < 0) {
525 // Iterate over maps and look for the map containing the pc. Then
526 // look into the symbol tables inside.
527 char buf[1024]; // Big enough for line of sane /proc/self/maps
529 LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf));
534 if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line.
538 // Start parsing line in /proc/self/maps. Here is an example:
540 // 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat
542 // We want start address (08048000), end address (0804c000), flags
543 // (r-xp) and file name (/bin/cat).
545 // Read start address.
546 cursor = GetHex(cursor, eol, &start_address);
547 if (cursor == eol || *cursor != '-') {
548 return -1; // Malformed line.
550 ++cursor; // Skip '-'.
553 uint64_t end_address;
554 cursor = GetHex(cursor, eol, &end_address);
555 if (cursor == eol || *cursor != ' ') {
556 return -1; // Malformed line.
558 ++cursor; // Skip ' '.
560 // Read flags. Skip flags until we encounter a space or eol.
561 const char * const flags_start = cursor;
562 while (cursor < eol && *cursor != ' ') {
565 // We expect at least four letters for flags (ex. "r-xp").
566 if (cursor == eol || cursor < flags_start + 4) {
567 return -1; // Malformed line.
570 // Determine the base address by reading ELF headers in process memory.
572 // Skip non-readable maps.
573 if (flags_start[0] == 'r' &&
574 ReadFromOffsetExact(mem_fd, &ehdr, sizeof(ElfW(Ehdr)), start_address) &&
575 memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
576 switch (ehdr.e_type) {
581 // Find the segment containing file offset 0. This will correspond
582 // to the ELF header that we just read. Normally this will have
583 // virtual address 0, but this is not guaranteed. We must subtract
584 // the virtual address from the address where the ELF header was
585 // mapped to get the base address.
587 // If we fail to find a segment for file offset 0, use the address
588 // of the ELF header as the base address.
589 base_address = start_address;
590 for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
592 if (ReadFromOffsetExact(
593 mem_fd, &phdr, sizeof(phdr),
594 start_address + ehdr.e_phoff + i * sizeof(phdr)) &&
595 phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
596 base_address = start_address - phdr.p_vaddr;
602 // ET_REL or ET_CORE. These aren't directly executable, so they don't
603 // affect the base address.
608 // Check start and end addresses.
609 if (!(start_address <= pc && pc < end_address)) {
610 continue; // We skip this map. PC isn't in this map.
613 // Check flags. We are only interested in "r*x" maps.
614 if (flags_start[0] != 'r' || flags_start[2] != 'x') {
615 continue; // We skip this map.
617 ++cursor; // Skip ' '.
620 uint64_t file_offset;
621 cursor = GetHex(cursor, eol, &file_offset);
622 if (cursor == eol || *cursor != ' ') {
623 return -1; // Malformed line.
625 ++cursor; // Skip ' '.
627 // Skip to file name. "cursor" now points to dev. We need to
628 // skip at least two spaces for dev and inode.
630 while (cursor < eol) {
631 if (*cursor == ' ') {
633 } else if (num_spaces >= 2) {
634 // The first non-space character after skipping two spaces
635 // is the beginning of the file name.
641 return -1; // Malformed line.
644 // Finally, "cursor" now points to file name of our interest.
645 NO_INTR(object_fd = open(cursor, O_RDONLY));
647 // Failed to open object file. Copy the object file name to
649 strncpy(out_file_name, cursor, out_file_name_size);
650 // Making sure |out_file_name| is always null-terminated.
651 out_file_name[out_file_name_size - 1] = '\0';
658 // POSIX doesn't define any async-signal safe function for converting
659 // an integer to ASCII. We'll have to define our own version.
660 // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
661 // conversion was successful or NULL otherwise. It never writes more than "sz"
662 // bytes. Output will be truncated as needed, and a NUL character is always
664 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
665 char *itoa_r(intptr_t i, char *buf, size_t sz, int base, size_t padding) {
666 // Make sure we can write at least one NUL byte.
671 if (base < 2 || base > 16) {
680 // Handle negative numbers (only for base 10).
681 if (i < 0 && base == 10) {
684 // Make sure we can write the '-' character.
692 // Loop until we have converted the entire number. Output at least one
693 // character (i.e. '0').
696 // Make sure there is still enough space left in our output buffer.
702 // Output the next digit.
703 *ptr++ = "0123456789abcdef"[j % base];
708 } while (j > 0 || padding > 0);
710 // Terminate the output with a NUL character.
713 // Conversion to ASCII actually resulted in the digits being in reverse
714 // order. We can't easily generate them in forward order, as we can't tell
715 // the number of characters needed until we are done converting.
716 // So, now, we reverse the string (except for the possible "-" sign).
717 while (--ptr > start) {
725 // Safely appends string |source| to string |dest|. Never writes past the
726 // buffer size |dest_size| and guarantees that |dest| is null-terminated.
727 void SafeAppendString(const char* source, char* dest, int dest_size) {
728 int dest_string_length = strlen(dest);
729 SAFE_ASSERT(dest_string_length < dest_size);
730 dest += dest_string_length;
731 dest_size -= dest_string_length;
732 strncpy(dest, source, dest_size);
733 // Making sure |dest| is always null-terminated.
734 dest[dest_size - 1] = '\0';
737 // Converts a 64-bit value into a hex string, and safely appends it to |dest|.
738 // Never writes past the buffer size |dest_size| and guarantees that |dest| is
740 void SafeAppendHexNumber(uint64_t value, char* dest, int dest_size) {
741 // 64-bit numbers in hex can have up to 16 digits.
742 char buf[17] = {'\0'};
743 SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size);
746 // The implementation of our symbolization routine. If it
747 // successfully finds the symbol containing "pc" and obtains the
748 // symbol name, returns true and write the symbol name to "out".
749 // Otherwise, returns false. If Callback function is installed via
750 // InstallSymbolizeCallback(), the function is also called in this function,
751 // and "out" is used as its output.
752 // To keep stack consumption low, we would like this function to not
754 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
756 uint64_t pc0 = reinterpret_cast<uintptr_t>(pc);
757 uint64_t start_address = 0;
758 uint64_t base_address = 0;
765 SafeAppendString("(", out, out_size);
767 if (g_symbolize_open_object_file_callback) {
768 object_fd = g_symbolize_open_object_file_callback(pc0, start_address,
769 base_address, out + 1,
772 object_fd = OpenObjectFileContainingPcAndGetStartAddress(pc0, start_address,
778 // Check whether a file name was returned.
781 // The object file containing PC was determined successfully however the
782 // object file was not opened successfully. This is still considered
783 // success because the object file name and offset are known and tools
784 // like asan_symbolize.py can be used for the symbolization.
785 out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated.
786 SafeAppendString("+0x", out, out_size);
787 SafeAppendHexNumber(pc0 - base_address, out, out_size);
788 SafeAppendString(")", out, out_size);
791 // Failed to determine the object file containing PC. Bail out.
794 FileDescriptor wrapped_object_fd(object_fd);
795 int elf_type = FileGetElfType(wrapped_object_fd.get());
796 if (elf_type == -1) {
799 if (g_symbolize_callback) {
800 // Run the call back if it's installed.
801 // Note: relocation (and much of the rest of this code) will be
802 // wrong for prelinked shared libraries and PIE executables.
803 uint64 relocation = (elf_type == ET_DYN) ? start_address : 0;
804 int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(),
807 if (num_bytes_written > 0) {
808 out += num_bytes_written;
809 out_size -= num_bytes_written;
812 if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0,
813 out, out_size, base_address)) {
817 // Symbolization succeeded. Now we try to demangle the symbol.
818 DemangleInplace(out, out_size);
822 _END_GOOGLE_NAMESPACE_
824 #elif defined(OS_MACOSX) && defined(HAVE_DLADDR)
829 _START_GOOGLE_NAMESPACE_
831 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
834 if (dladdr(pc, &info)) {
835 if ((int)strlen(info.dli_sname) < out_size) {
836 strcpy(out, info.dli_sname);
837 // Symbolization succeeded. Now we try to demangle the symbol.
838 DemangleInplace(out, out_size);
845 _END_GOOGLE_NAMESPACE_
847 #elif defined(OS_WINDOWS)
850 #pragma comment(lib, "DbgHelp")
852 _START_GOOGLE_NAMESPACE_
854 class SymInitializer {
856 HANDLE process = NULL;
859 // Initialize the symbol handler.
860 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680344(v=vs.85).aspx
861 process = GetCurrentProcess();
862 // Defer symbol loading.
863 // We do not request undecorated symbols with SYMOPT_UNDNAME
864 // because the mangling library calls UnDecorateSymbolName.
865 SymSetOptions(SYMOPT_DEFERRED_LOADS);
866 if (SymInitialize(process, NULL, true)) {
872 // We do not need to close `HANDLE process` because it's a "pseudo handle."
875 SymInitializer(const SymInitializer&);
876 SymInitializer& operator=(const SymInitializer&);
879 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
881 const static SymInitializer symInitializer;
882 if (!symInitializer.ready) {
885 // Resolve symbol information from address.
886 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680578(v=vs.85).aspx
887 char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
888 SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(buf);
889 symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
890 symbol->MaxNameLen = MAX_SYM_NAME;
891 // We use the ANSI version to ensure the string type is always `char *`.
892 // This could break if a symbol has Unicode in it.
893 BOOL ret = SymFromAddr(symInitializer.process,
894 reinterpret_cast<DWORD64>(pc), 0, symbol);
895 if (ret == 1 && static_cast<int>(symbol->NameLen) < out_size) {
896 // `NameLen` does not include the null terminating character.
897 strncpy(out, symbol->Name, static_cast<size_t>(symbol->NameLen) + 1);
898 out[static_cast<size_t>(symbol->NameLen)] = '\0';
899 // Symbolization succeeded. Now we try to demangle the symbol.
900 DemangleInplace(out, out_size);
906 _END_GOOGLE_NAMESPACE_
909 # error BUG: HAVE_SYMBOLIZE was wrongly set
912 _START_GOOGLE_NAMESPACE_
914 bool Symbolize(void *pc, char *out, int out_size) {
915 SAFE_ASSERT(out_size >= 0);
916 return SymbolizeAndDemangle(pc, out, out_size);
919 _END_GOOGLE_NAMESPACE_
921 #else /* HAVE_SYMBOLIZE */
927 _START_GOOGLE_NAMESPACE_
929 // TODO: Support other environments.
930 bool Symbolize(void *pc, char *out, int out_size) {
935 _END_GOOGLE_NAMESPACE_