Link to DbgHelp using pre-processor directive
[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 <limits>
60
61 #include "symbolize.h"
62 #include "demangle.h"
63
64 _START_GOOGLE_NAMESPACE_
65
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.
69
70 // A wrapper for abort() to make it callable in ? :.
71 static int AssertFail() {
72   abort();
73   return 0;  // Should not reach.
74 }
75
76 #define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail())
77
78 static SymbolizeCallback g_symbolize_callback = NULL;
79 void InstallSymbolizeCallback(SymbolizeCallback callback) {
80   g_symbolize_callback = callback;
81 }
82
83 static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback =
84     NULL;
85 void InstallSymbolizeOpenObjectFileCallback(
86     SymbolizeOpenObjectFileCallback callback) {
87   g_symbolize_open_object_file_callback = callback;
88 }
89
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
93 // get inlined.
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);
102     }
103   }
104 }
105
106 _END_GOOGLE_NAMESPACE_
107
108 #if defined(__ELF__)
109
110 #include <dlfcn.h>
111 #if defined(OS_OPENBSD)
112 #include <sys/exec_elf.h>
113 #else
114 #include <elf.h>
115 #endif
116 #include <errno.h>
117 #include <fcntl.h>
118 #include <limits.h>
119 #include <stdint.h>
120 #include <stdio.h>
121 #include <stdlib.h>
122 #include <stddef.h>
123 #include <string.h>
124 #include <sys/stat.h>
125 #include <sys/types.h>
126 #include <unistd.h>
127
128 #include "symbolize.h"
129 #include "config.h"
130 #include "glog/raw_logging.h"
131
132 // Re-runs fn until it doesn't cause EINTR.
133 #define NO_INTR(fn)   do {} while ((fn) < 0 && errno == EINTR)
134
135 _START_GOOGLE_NAMESPACE_
136
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) {
146     ssize_t len;
147     NO_INTR(len = read(fd, buf0 + num_bytes, count - num_bytes));
148     if (len < 0) {  // There was an error other than EINTR.
149       return -1;
150     }
151     if (len == 0) {  // Reached EOF.
152       break;
153     }
154     num_bytes += len;
155   }
156   SAFE_ASSERT(num_bytes <= count);
157   return num_bytes;
158 }
159
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) {
167     return -1;
168   }
169   return ReadPersistent(fd, buf, count);
170 }
171
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
175 // false.
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);
179   return len == count;
180 }
181
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)) {
186     return -1;
187   }
188   if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) {
189     return -1;
190   }
191   return elf_header.e_type;
192 }
193
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
198 // inlined.
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.
203   ElfW(Shdr) buf[16];
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) {
215         *out = buf[j];
216         return true;
217       }
218     }
219     i += num_headers_in_buf;
220   }
221   return false;
222 }
223
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;
227
228 // name_len should include terminating '\0'.
229 bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
230                             ElfW(Shdr) *out) {
231   ElfW(Ehdr) elf_header;
232   if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
233     return false;
234   }
235
236   ElfW(Shdr) shstrtab;
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)) {
240     return false;
241   }
242
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)) {
247       return false;
248     }
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.
254       return false;
255     }
256     off_t name_offset = shstrtab.sh_offset + out->sh_name;
257     ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
258     if (n_read == -1) {
259       return false;
260     } else if (n_read != name_len) {
261       // Short read -- name could be at end of file.
262       continue;
263     }
264     if (memcmp(header_name, name, name_len) == 0) {
265       return true;
266     }
267   }
268   return false;
269 }
270
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
276 // inlined.
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) {
282     return false;
283   }
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;
287
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.
291 #if __WORDSIZE == 64
292 #define NUM_SYMBOLS 32
293 #else
294 #define NUM_SYMBOLS 64
295 #endif
296
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) {
314           return false;
315         }
316         return true;  // Obtained the symbol name.
317       }
318     }
319     i += num_symbols_in_buf;
320   }
321   return false;
322 }
323
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
327 // false.
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)) {
334     return false;
335   }
336
337   uint64_t symbol_offset = 0;
338   if (elf_header.e_type == ET_DYN) {  // DSO needs offset adjustment.
339     ElfW(Phdr) phdr;
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)))
345         return false;
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
354         // address zero.
355         symbol_offset = map_base_address + phdr.p_offset - phdr.p_vaddr;
356         break;
357       }
358     }
359     if (symbol_offset == 0)
360       return false;
361   }
362
363   ElfW(Shdr) symtab, strtab;
364
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))) {
370       return false;
371     }
372     if (FindSymbol(pc, fd, out, out_size, symbol_offset,
373                    &strtab, &symtab)) {
374       return true;  // Found the symbol in a regular symbol table.
375     }
376   }
377
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))) {
383       return false;
384     }
385     if (FindSymbol(pc, fd, out, out_size, symbol_offset,
386                    &strtab, &symtab)) {
387       return true;  // Found the symbol in a dynamic symbol table.
388     }
389   }
390
391   return false;
392 }
393
394 namespace {
395 // Thin wrapper around a file descriptor so that the file descriptor
396 // gets closed for sure.
397 struct FileDescriptor {
398   const int fd_;
399   explicit FileDescriptor(int fd) : fd_(fd) {}
400   ~FileDescriptor() {
401     if (fd_ >= 0) {
402       NO_INTR(close(fd_));
403     }
404   }
405   int get() { return fd_; }
406
407  private:
408   explicit FileDescriptor(const FileDescriptor&);
409   void operator=(const FileDescriptor&);
410 };
411
412 // Helper class for reading lines from file.
413 //
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()
416 // and snprintf().
417 class LineReader {
418  public:
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) {
421   }
422
423   // Read '\n'-terminated line from file.  On success, modify "bol"
424   // and "eol", then return true.  Otherwise, return false.
425   //
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.
432         return false;
433       }
434       eod_ = buf_ + num_bytes;
435       bol_ = buf_;
436     } else {
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,
447                                                  capacity_left);
448         if (num_bytes <= 0) {  // EOF or error.
449           return false;
450         }
451         eod_ = append_pos + num_bytes;
452         bol_ = buf_;
453       }
454     }
455     eol_ = FindLineFeed();
456     if (eol_ == NULL) {  // '\n' not found.  Malformed line.
457       return false;
458     }
459     *eol_ = '\0';  // Replace '\n' with '\0'.
460
461     *bol = bol_;
462     *eol = eol_;
463     return true;
464   }
465
466   // Beginning of line.
467   const char *bol() {
468     return bol_;
469   }
470
471   // End of line.
472   const char *eol() {
473     return eol_;
474   }
475
476  private:
477   explicit LineReader(const LineReader&);
478   void operator=(const LineReader&);
479
480   char *FindLineFeed() {
481     return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_));
482   }
483
484   bool BufferIsEmpty() {
485     return buf_ == eod_;
486   }
487
488   bool HasCompleteLine() {
489     return !BufferIsEmpty() && FindLineFeed() != NULL;
490   }
491
492   const int fd_;
493   char * const buf_;
494   const int buf_len_;
495   char *bol_;
496   char *eol_;
497   const char *eod_;  // End of data in "buf_".
498 };
499 }  // namespace
500
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) {
504   *hex = 0;
505   const char *p;
506   for (p = start; p < end; ++p) {
507     int ch = *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.
512       break;
513     }
514   }
515   SAFE_ASSERT(p <= end);
516   return const_cast<char *>(p);
517 }
518
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,
531                                              char *out_file_name,
532                                              int out_file_name_size) {
533   int object_fd;
534
535   // Open /proc/self/maps.
536   int maps_fd;
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) {
540     return -1;
541   }
542
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
546   int num_maps = 0;
547   LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf));
548   while (true) {
549     num_maps++;
550     const char *cursor;
551     const char *eol;
552     if (!reader.ReadLine(&cursor, &eol)) {  // EOF or malformed line.
553       return -1;
554     }
555
556     // Start parsing line in /proc/self/maps.  Here is an example:
557     //
558     // 08048000-0804c000 r-xp 00000000 08:01 2142121    /bin/cat
559     //
560     // We want start address (08048000), end address (0804c000), flags
561     // (r-xp) and file name (/bin/cat).
562
563     // Read start address.
564     cursor = GetHex(cursor, eol, &start_address);
565     if (cursor == eol || *cursor != '-') {
566       return -1;  // Malformed line.
567     }
568     ++cursor;  // Skip '-'.
569
570     // Read end address.
571     uint64_t end_address;
572     cursor = GetHex(cursor, eol, &end_address);
573     if (cursor == eol || *cursor != ' ') {
574       return -1;  // Malformed line.
575     }
576     ++cursor;  // Skip ' '.
577
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.
581     }
582
583     // Read flags.  Skip flags until we encounter a space or eol.
584     const char * const flags_start = cursor;
585     while (cursor < eol && *cursor != ' ') {
586       ++cursor;
587     }
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.
591     }
592
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.
596     }
597     ++cursor;  // Skip ' '.
598
599     // Read file offset.
600     uint64_t file_offset;
601     cursor = GetHex(cursor, eol, &file_offset);
602     if (cursor == eol || *cursor != ' ') {
603       return -1;  // Malformed line.
604     }
605     ++cursor;  // Skip ' '.
606
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
617     //   first entry.
618     base_address = ((num_maps == 1) ? 0U : start_address) - file_offset;
619
620     // Skip to file name.  "cursor" now points to dev.  We need to
621     // skip at least two spaces for dev and inode.
622     int num_spaces = 0;
623     while (cursor < eol) {
624       if (*cursor == ' ') {
625         ++num_spaces;
626       } else if (num_spaces >= 2) {
627         // The first non-space character after skipping two spaces
628         // is the beginning of the file name.
629         break;
630       }
631       ++cursor;
632     }
633     if (cursor == eol) {
634       return -1;  // Malformed line.
635     }
636
637     // Finally, "cursor" now points to file name of our interest.
638     NO_INTR(object_fd = open(cursor, O_RDONLY));
639     if (object_fd < 0) {
640       // Failed to open object file.  Copy the object file name to
641       // |out_file_name|.
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';
645       return -1;
646     }
647     return object_fd;
648   }
649 }
650
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
656 // appended.
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.
660   size_t n = 1;
661   if (n > sz)
662     return NULL;
663
664   if (base < 2 || base > 16) {
665     buf[0] = '\000';
666     return NULL;
667   }
668
669   char *start = buf;
670
671   uintptr_t j = i;
672
673   // Handle negative numbers (only for base 10).
674   if (i < 0 && base == 10) {
675     j = -i;
676
677     // Make sure we can write the '-' character.
678     if (++n > sz) {
679       buf[0] = '\000';
680       return NULL;
681     }
682     *start++ = '-';
683   }
684
685   // Loop until we have converted the entire number. Output at least one
686   // character (i.e. '0').
687   char *ptr = start;
688   do {
689     // Make sure there is still enough space left in our output buffer.
690     if (++n > sz) {
691       buf[0] = '\000';
692       return NULL;
693     }
694
695     // Output the next digit.
696     *ptr++ = "0123456789abcdef"[j % base];
697     j /= base;
698
699     if (padding > 0)
700       padding--;
701   } while (j > 0 || padding > 0);
702
703   // Terminate the output with a NUL character.
704   *ptr = '\000';
705
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) {
711     char ch = *ptr;
712     *ptr = *start;
713     *start++ = ch;
714   }
715   return buf;
716 }
717
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';
728 }
729
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
732 // null-terminated.
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);
737 }
738
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
746 // get inlined.
747 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
748                                                     int out_size) {
749   uint64_t pc0 = reinterpret_cast<uintptr_t>(pc);
750   uint64_t start_address = 0;
751   uint64_t base_address = 0;
752   int object_fd = -1;
753
754   if (out_size < 1) {
755     return false;
756   }
757   out[0] = '\0';
758   SafeAppendString("(", out, out_size);
759
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,
763                                                       out_size - 1);
764   } else {
765     object_fd = OpenObjectFileContainingPcAndGetStartAddress(pc0, start_address,
766                                                              base_address,
767                                                              out + 1,
768                                                              out_size - 1);
769   }
770
771   // Check whether a file name was returned.
772   if (object_fd < 0) {
773     if (out[1]) {
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);
782       return true;
783     }
784     // Failed to determine the object file containing PC.  Bail out.
785     return false;
786   }
787   FileDescriptor wrapped_object_fd(object_fd);
788   int elf_type = FileGetElfType(wrapped_object_fd.get());
789   if (elf_type == -1) {
790     return false;
791   }
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(),
798                                                  pc, out, out_size,
799                                                  relocation);
800     if (num_bytes_written > 0) {
801       out += num_bytes_written;
802       out_size -= num_bytes_written;
803     }
804   }
805   if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0,
806                                out, out_size, base_address)) {
807     return false;
808   }
809
810   // Symbolization succeeded.  Now we try to demangle the symbol.
811   DemangleInplace(out, out_size);
812   return true;
813 }
814
815 _END_GOOGLE_NAMESPACE_
816
817 #elif defined(OS_MACOSX) && defined(HAVE_DLADDR)
818
819 #include <dlfcn.h>
820 #include <string.h>
821
822 _START_GOOGLE_NAMESPACE_
823
824 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
825                                                     int out_size) {
826   Dl_info info;
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);
832       return true;
833     }
834   }
835   return false;
836 }
837
838 _END_GOOGLE_NAMESPACE_
839
840 #elif defined(OS_WINDOWS)
841
842 #include <DbgHelp.h>
843 #pragma comment(lib, "DbgHelp")
844
845 _START_GOOGLE_NAMESPACE_
846
847 class SymInitializer {
848 public:
849   HANDLE process = NULL;
850   bool ready = false;
851   SymInitializer() {
852     // Initialize the symbol handler.
853     // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680344(v=vs.85).aspx
854     process = GetCurrentProcess();
855     // Defer symbol loading.
856     // We do not request undecorated symbols with SYMOPT_UNDNAME
857     // because the mangling library calls UnDecorateSymbolName.
858     SymSetOptions(SYMOPT_DEFERRED_LOADS);
859     if (SymInitialize(process, NULL, true)) {
860       ready = true;
861     }
862   }
863   ~SymInitializer() {
864     SymCleanup(process);
865     // We do not need to close `HANDLE process` because it's a "pseudo handle."
866   }
867 private:
868   SymInitializer(const SymInitializer&);
869   SymInitializer& operator=(const SymInitializer&);
870 };
871
872 static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
873                                                       int out_size) {
874   const static SymInitializer symInitializer;
875   if (!symInitializer.ready) {
876     return false;
877   }
878   // Resolve symbol information from address.
879   // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680578(v=vs.85).aspx
880   char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
881   SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(buf);
882   symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
883   symbol->MaxNameLen = MAX_SYM_NAME;
884   // We use the ANSI version to ensure the string type is always `char *`.
885   // This could break if a symbol has Unicode in it.
886   BOOL ret = SymFromAddr(symInitializer.process,
887                          reinterpret_cast<DWORD64>(pc), 0, symbol);
888   if (ret == 1 && static_cast<int>(symbol->NameLen) < out_size) {
889     // `NameLen` does not include the null terminating character.
890     strncpy(out, symbol->Name, static_cast<size_t>(symbol->NameLen) + 1);
891     out[static_cast<size_t>(symbol->NameLen)] = '\0';
892     // Symbolization succeeded.  Now we try to demangle the symbol.
893     DemangleInplace(out, out_size);
894     return true;
895   }
896   return false;
897 }
898
899 _END_GOOGLE_NAMESPACE_
900
901 #else
902 # error BUG: HAVE_SYMBOLIZE was wrongly set
903 #endif
904
905 _START_GOOGLE_NAMESPACE_
906
907 bool Symbolize(void *pc, char *out, int out_size) {
908   SAFE_ASSERT(out_size >= 0);
909   return SymbolizeAndDemangle(pc, out, out_size);
910 }
911
912 _END_GOOGLE_NAMESPACE_
913
914 #else  /* HAVE_SYMBOLIZE */
915
916 #include <assert.h>
917
918 #include "config.h"
919
920 _START_GOOGLE_NAMESPACE_
921
922 // TODO: Support other environments.
923 bool Symbolize(void *pc, char *out, int out_size) {
924   assert(0);
925   return false;
926 }
927
928 _END_GOOGLE_NAMESPACE_
929
930 #endif