cmake: remove config.h from public headers (closes #238)
[platform/upstream/glog.git] / src / symbolize.cc
1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
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
13 // distribution.
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.
17 //
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.
29 //
30 // Author: Satoru Takabayashi
31 // Stack-footprint reduction work done by Raksit Ashok
32 //
33 // Implementation note:
34 //
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.
37 //
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
43 //
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.
47 //
48 // Additional header can be specified by the GLOG_BUILD_CONFIG_INCLUDE
49 // macro to add platform specific defines (e.g. OS_OPENBSD).
50
51 #ifdef GLOG_BUILD_CONFIG_INCLUDE
52 #include GLOG_BUILD_CONFIG_INCLUDE
53 #endif  // GLOG_BUILD_CONFIG_INCLUDE
54
55 #include "utilities.h"
56
57 #if defined(HAVE_SYMBOLIZE)
58
59 #include <string.h>
60
61 #include <limits>
62
63 #include "symbolize.h"
64 #include "demangle.h"
65
66 _START_GOOGLE_NAMESPACE_
67
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.
71
72 // A wrapper for abort() to make it callable in ? :.
73 static int AssertFail() {
74   abort();
75   return 0;  // Should not reach.
76 }
77
78 #define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail())
79
80 static SymbolizeCallback g_symbolize_callback = NULL;
81 void InstallSymbolizeCallback(SymbolizeCallback callback) {
82   g_symbolize_callback = callback;
83 }
84
85 static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback =
86     NULL;
87 void InstallSymbolizeOpenObjectFileCallback(
88     SymbolizeOpenObjectFileCallback callback) {
89   g_symbolize_open_object_file_callback = callback;
90 }
91
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
95 // get inlined.
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);
104     }
105   }
106 }
107
108 _END_GOOGLE_NAMESPACE_
109
110 #if defined(__ELF__)
111
112 #include <dlfcn.h>
113 #if defined(OS_OPENBSD)
114 #include <sys/exec_elf.h>
115 #else
116 #include <elf.h>
117 #endif
118 #include <errno.h>
119 #include <fcntl.h>
120 #include <limits.h>
121 #include <stdint.h>
122 #include <stdio.h>
123 #include <stdlib.h>
124 #include <stddef.h>
125 #include <string.h>
126 #include <sys/stat.h>
127 #include <sys/types.h>
128 #include <unistd.h>
129
130 #include "symbolize.h"
131 #include "config.h"
132 #include "glog/raw_logging.h"
133
134 // Re-runs fn until it doesn't cause EINTR.
135 #define NO_INTR(fn)   do {} while ((fn) < 0 && errno == EINTR)
136
137 _START_GOOGLE_NAMESPACE_
138
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) {
148     ssize_t len;
149     NO_INTR(len = read(fd, buf0 + num_bytes, count - num_bytes));
150     if (len < 0) {  // There was an error other than EINTR.
151       return -1;
152     }
153     if (len == 0) {  // Reached EOF.
154       break;
155     }
156     num_bytes += len;
157   }
158   SAFE_ASSERT(num_bytes <= count);
159   return num_bytes;
160 }
161
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) {
169     return -1;
170   }
171   return ReadPersistent(fd, buf, count);
172 }
173
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
177 // false.
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);
181   return len == count;
182 }
183
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)) {
188     return -1;
189   }
190   if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) {
191     return -1;
192   }
193   return elf_header.e_type;
194 }
195
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
200 // inlined.
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.
205   ElfW(Shdr) buf[16];
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) {
217         *out = buf[j];
218         return true;
219       }
220     }
221     i += num_headers_in_buf;
222   }
223   return false;
224 }
225
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;
229
230 // name_len should include terminating '\0'.
231 bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
232                             ElfW(Shdr) *out) {
233   ElfW(Ehdr) elf_header;
234   if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
235     return false;
236   }
237
238   ElfW(Shdr) shstrtab;
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)) {
242     return false;
243   }
244
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)) {
249       return false;
250     }
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.
256       return false;
257     }
258     off_t name_offset = shstrtab.sh_offset + out->sh_name;
259     ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
260     if (n_read == -1) {
261       return false;
262     } else if (n_read != name_len) {
263       // Short read -- name could be at end of file.
264       continue;
265     }
266     if (memcmp(header_name, name, name_len) == 0) {
267       return true;
268     }
269   }
270   return false;
271 }
272
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
278 // inlined.
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) {
284     return false;
285   }
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;
289
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.
293 #if __WORDSIZE == 64
294 #define NUM_SYMBOLS 32
295 #else
296 #define NUM_SYMBOLS 64
297 #endif
298
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) {
316           return false;
317         }
318         return true;  // Obtained the symbol name.
319       }
320     }
321     i += num_symbols_in_buf;
322   }
323   return false;
324 }
325
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
329 // false.
330 static bool GetSymbolFromObjectFile(const int fd,
331                                     uint64_t pc,
332                                     char* out,
333                                     int out_size,
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)) {
338     return false;
339   }
340
341   ElfW(Shdr) symtab, strtab;
342
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))) {
348       return false;
349     }
350     if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
351       return true;  // Found the symbol in a regular symbol table.
352     }
353   }
354
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))) {
360       return false;
361     }
362     if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
363       return true;  // Found the symbol in a dynamic symbol table.
364     }
365   }
366
367   return false;
368 }
369
370 namespace {
371 // Thin wrapper around a file descriptor so that the file descriptor
372 // gets closed for sure.
373 struct FileDescriptor {
374   const int fd_;
375   explicit FileDescriptor(int fd) : fd_(fd) {}
376   ~FileDescriptor() {
377     if (fd_ >= 0) {
378       NO_INTR(close(fd_));
379     }
380   }
381   int get() { return fd_; }
382
383  private:
384   explicit FileDescriptor(const FileDescriptor&);
385   void operator=(const FileDescriptor&);
386 };
387
388 // Helper class for reading lines from file.
389 //
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()
392 // and snprintf().
393 class LineReader {
394  public:
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) {
397   }
398
399   // Read '\n'-terminated line from file.  On success, modify "bol"
400   // and "eol", then return true.  Otherwise, return false.
401   //
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.
408         return false;
409       }
410       eod_ = buf_ + num_bytes;
411       bol_ = buf_;
412     } else {
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,
423                                                  capacity_left);
424         if (num_bytes <= 0) {  // EOF or error.
425           return false;
426         }
427         eod_ = append_pos + num_bytes;
428         bol_ = buf_;
429       }
430     }
431     eol_ = FindLineFeed();
432     if (eol_ == NULL) {  // '\n' not found.  Malformed line.
433       return false;
434     }
435     *eol_ = '\0';  // Replace '\n' with '\0'.
436
437     *bol = bol_;
438     *eol = eol_;
439     return true;
440   }
441
442   // Beginning of line.
443   const char *bol() {
444     return bol_;
445   }
446
447   // End of line.
448   const char *eol() {
449     return eol_;
450   }
451
452  private:
453   explicit LineReader(const LineReader&);
454   void operator=(const LineReader&);
455
456   char *FindLineFeed() {
457     return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_));
458   }
459
460   bool BufferIsEmpty() {
461     return buf_ == eod_;
462   }
463
464   bool HasCompleteLine() {
465     return !BufferIsEmpty() && FindLineFeed() != NULL;
466   }
467
468   const int fd_;
469   char * const buf_;
470   const int buf_len_;
471   char *bol_;
472   char *eol_;
473   const char *eod_;  // End of data in "buf_".
474 };
475 }  // namespace
476
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) {
480   *hex = 0;
481   const char *p;
482   for (p = start; p < end; ++p) {
483     int ch = *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.
488       break;
489     }
490   }
491   SAFE_ASSERT(p <= end);
492   return const_cast<char *>(p);
493 }
494
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,
507                                              char *out_file_name,
508                                              int out_file_name_size) {
509   int object_fd;
510
511   int maps_fd;
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) {
515     return -1;
516   }
517
518   int mem_fd;
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) {
522     return -1;
523   }
524
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
528   int num_maps = 0;
529   LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf));
530   while (true) {
531     num_maps++;
532     const char *cursor;
533     const char *eol;
534     if (!reader.ReadLine(&cursor, &eol)) {  // EOF or malformed line.
535       return -1;
536     }
537
538     // Start parsing line in /proc/self/maps.  Here is an example:
539     //
540     // 08048000-0804c000 r-xp 00000000 08:01 2142121    /bin/cat
541     //
542     // We want start address (08048000), end address (0804c000), flags
543     // (r-xp) and file name (/bin/cat).
544
545     // Read start address.
546     cursor = GetHex(cursor, eol, &start_address);
547     if (cursor == eol || *cursor != '-') {
548       return -1;  // Malformed line.
549     }
550     ++cursor;  // Skip '-'.
551
552     // Read end address.
553     uint64_t end_address;
554     cursor = GetHex(cursor, eol, &end_address);
555     if (cursor == eol || *cursor != ' ') {
556       return -1;  // Malformed line.
557     }
558     ++cursor;  // Skip ' '.
559
560     // Read flags.  Skip flags until we encounter a space or eol.
561     const char * const flags_start = cursor;
562     while (cursor < eol && *cursor != ' ') {
563       ++cursor;
564     }
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.
568     }
569
570     // Determine the base address by reading ELF headers in process memory.
571     ElfW(Ehdr) ehdr;
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) {
577         case ET_EXEC:
578           base_address = 0;
579           break;
580         case ET_DYN:
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.
586           //
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) {
591             ElfW(Phdr) phdr;
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;
597               break;
598             }
599           }
600           break;
601         default:
602           // ET_REL or ET_CORE. These aren't directly executable, so they don't
603           // affect the base address.
604           break;
605       }
606     }
607
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.
611     }
612
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.
616     }
617     ++cursor;  // Skip ' '.
618
619     // Read file offset.
620     uint64_t file_offset;
621     cursor = GetHex(cursor, eol, &file_offset);
622     if (cursor == eol || *cursor != ' ') {
623       return -1;  // Malformed line.
624     }
625     ++cursor;  // Skip ' '.
626
627     // Skip to file name.  "cursor" now points to dev.  We need to
628     // skip at least two spaces for dev and inode.
629     int num_spaces = 0;
630     while (cursor < eol) {
631       if (*cursor == ' ') {
632         ++num_spaces;
633       } else if (num_spaces >= 2) {
634         // The first non-space character after skipping two spaces
635         // is the beginning of the file name.
636         break;
637       }
638       ++cursor;
639     }
640     if (cursor == eol) {
641       return -1;  // Malformed line.
642     }
643
644     // Finally, "cursor" now points to file name of our interest.
645     NO_INTR(object_fd = open(cursor, O_RDONLY));
646     if (object_fd < 0) {
647       // Failed to open object file.  Copy the object file name to
648       // |out_file_name|.
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';
652       return -1;
653     }
654     return object_fd;
655   }
656 }
657
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
663 // appended.
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.
667   size_t n = 1;
668   if (n > sz)
669     return NULL;
670
671   if (base < 2 || base > 16) {
672     buf[0] = '\000';
673     return NULL;
674   }
675
676   char *start = buf;
677
678   uintptr_t j = i;
679
680   // Handle negative numbers (only for base 10).
681   if (i < 0 && base == 10) {
682     j = -i;
683
684     // Make sure we can write the '-' character.
685     if (++n > sz) {
686       buf[0] = '\000';
687       return NULL;
688     }
689     *start++ = '-';
690   }
691
692   // Loop until we have converted the entire number. Output at least one
693   // character (i.e. '0').
694   char *ptr = start;
695   do {
696     // Make sure there is still enough space left in our output buffer.
697     if (++n > sz) {
698       buf[0] = '\000';
699       return NULL;
700     }
701
702     // Output the next digit.
703     *ptr++ = "0123456789abcdef"[j % base];
704     j /= base;
705
706     if (padding > 0)
707       padding--;
708   } while (j > 0 || padding > 0);
709
710   // Terminate the output with a NUL character.
711   *ptr = '\000';
712
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) {
718     char ch = *ptr;
719     *ptr = *start;
720     *start++ = ch;
721   }
722   return buf;
723 }
724
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';
735 }
736
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
739 // null-terminated.
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);
744 }
745
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
753 // get inlined.
754 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
755                                                     int out_size) {
756   uint64_t pc0 = reinterpret_cast<uintptr_t>(pc);
757   uint64_t start_address = 0;
758   uint64_t base_address = 0;
759   int object_fd = -1;
760
761   if (out_size < 1) {
762     return false;
763   }
764   out[0] = '\0';
765   SafeAppendString("(", out, out_size);
766
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,
770                                                       out_size - 1);
771   } else {
772     object_fd = OpenObjectFileContainingPcAndGetStartAddress(pc0, start_address,
773                                                              base_address,
774                                                              out + 1,
775                                                              out_size - 1);
776   }
777
778   // Check whether a file name was returned.
779   if (object_fd < 0) {
780     if (out[1]) {
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);
789       return true;
790     }
791     // Failed to determine the object file containing PC.  Bail out.
792     return false;
793   }
794   FileDescriptor wrapped_object_fd(object_fd);
795   int elf_type = FileGetElfType(wrapped_object_fd.get());
796   if (elf_type == -1) {
797     return false;
798   }
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(),
805                                                  pc, out, out_size,
806                                                  relocation);
807     if (num_bytes_written > 0) {
808       out += num_bytes_written;
809       out_size -= num_bytes_written;
810     }
811   }
812   if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0,
813                                out, out_size, base_address)) {
814     return false;
815   }
816
817   // Symbolization succeeded.  Now we try to demangle the symbol.
818   DemangleInplace(out, out_size);
819   return true;
820 }
821
822 _END_GOOGLE_NAMESPACE_
823
824 #elif defined(OS_MACOSX) && defined(HAVE_DLADDR)
825
826 #include <dlfcn.h>
827 #include <string.h>
828
829 _START_GOOGLE_NAMESPACE_
830
831 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
832                                                     int out_size) {
833   Dl_info info;
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);
839       return true;
840     }
841   }
842   return false;
843 }
844
845 _END_GOOGLE_NAMESPACE_
846
847 #elif defined(OS_WINDOWS)
848
849 #include <DbgHelp.h>
850 #pragma comment(lib, "DbgHelp")
851
852 _START_GOOGLE_NAMESPACE_
853
854 class SymInitializer {
855 public:
856   HANDLE process = NULL;
857   bool ready = false;
858   SymInitializer() {
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)) {
867       ready = true;
868     }
869   }
870   ~SymInitializer() {
871     SymCleanup(process);
872     // We do not need to close `HANDLE process` because it's a "pseudo handle."
873   }
874 private:
875   SymInitializer(const SymInitializer&);
876   SymInitializer& operator=(const SymInitializer&);
877 };
878
879 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
880                                                       int out_size) {
881   const static SymInitializer symInitializer;
882   if (!symInitializer.ready) {
883     return false;
884   }
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);
901     return true;
902   }
903   return false;
904 }
905
906 _END_GOOGLE_NAMESPACE_
907
908 #else
909 # error BUG: HAVE_SYMBOLIZE was wrongly set
910 #endif
911
912 _START_GOOGLE_NAMESPACE_
913
914 bool Symbolize(void *pc, char *out, int out_size) {
915   SAFE_ASSERT(out_size >= 0);
916   return SymbolizeAndDemangle(pc, out, out_size);
917 }
918
919 _END_GOOGLE_NAMESPACE_
920
921 #else  /* HAVE_SYMBOLIZE */
922
923 #include <assert.h>
924
925 #include "config.h"
926
927 _START_GOOGLE_NAMESPACE_
928
929 // TODO: Support other environments.
930 bool Symbolize(void *pc, char *out, int out_size) {
931   assert(0);
932   return false;
933 }
934
935 _END_GOOGLE_NAMESPACE_
936
937 #endif