Home | History | Annotate | Download | only in debug
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "base/debug/stack_trace.h"
      6 
      7 #include <errno.h>
      8 #include <fcntl.h>
      9 #include <signal.h>
     10 #include <stddef.h>
     11 #include <stdint.h>
     12 #include <stdio.h>
     13 #include <stdlib.h>
     14 #include <sys/param.h>
     15 #include <sys/stat.h>
     16 #include <sys/types.h>
     17 #include <unistd.h>
     18 
     19 #include <map>
     20 #include <memory>
     21 #include <ostream>
     22 #include <string>
     23 #include <vector>
     24 
     25 #if defined(__GLIBCXX__)
     26 #include <cxxabi.h>
     27 #endif
     28 #if !defined(__UCLIBC__)
     29 #include <execinfo.h>
     30 #endif
     31 
     32 #if defined(OS_MACOSX)
     33 #include <AvailabilityMacros.h>
     34 #endif
     35 
     36 #include "base/debug/debugger.h"
     37 #include "base/debug/proc_maps_linux.h"
     38 #include "base/logging.h"
     39 #include "base/macros.h"
     40 #include "base/memory/free_deleter.h"
     41 #include "base/memory/singleton.h"
     42 #include "base/numerics/safe_conversions.h"
     43 #include "base/posix/eintr_wrapper.h"
     44 #include "base/strings/string_number_conversions.h"
     45 #include "build/build_config.h"
     46 
     47 #if defined(USE_SYMBOLIZE)
     48 #error "symbolize support was removed from libchrome"
     49 #endif
     50 
     51 namespace base {
     52 namespace debug {
     53 
     54 namespace {
     55 
     56 volatile sig_atomic_t in_signal_handler = 0;
     57 
     58 #if !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
     59 // The prefix used for mangled symbols, per the Itanium C++ ABI:
     60 // http://www.codesourcery.com/cxx-abi/abi.html#mangling
     61 const char kMangledSymbolPrefix[] = "_Z";
     62 
     63 // Characters that can be used for symbols, generated by Ruby:
     64 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
     65 const char kSymbolCharacters[] =
     66     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
     67 #endif  // !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
     68 
     69 #if !defined(USE_SYMBOLIZE)
     70 // Demangles C++ symbols in the given text. Example:
     71 //
     72 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
     73 // =>
     74 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
     75 #if defined(__GLIBCXX__) && !defined(__UCLIBC__)
     76 void DemangleSymbols(std::string* text) {
     77   // Note: code in this function is NOT async-signal safe (std::string uses
     78   // malloc internally).
     79   std::string::size_type search_from = 0;
     80   while (search_from < text->size()) {
     81     // Look for the start of a mangled symbol, from search_from.
     82     std::string::size_type mangled_start =
     83         text->find(kMangledSymbolPrefix, search_from);
     84     if (mangled_start == std::string::npos) {
     85       break;  // Mangled symbol not found.
     86     }
     87 
     88     // Look for the end of the mangled symbol.
     89     std::string::size_type mangled_end =
     90         text->find_first_not_of(kSymbolCharacters, mangled_start);
     91     if (mangled_end == std::string::npos) {
     92       mangled_end = text->size();
     93     }
     94     std::string mangled_symbol =
     95         text->substr(mangled_start, mangled_end - mangled_start);
     96 
     97     // Try to demangle the mangled symbol candidate.
     98     int status = 0;
     99     std::unique_ptr<char, base::FreeDeleter> demangled_symbol(
    100         abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
    101     if (status == 0) {  // Demangling is successful.
    102       // Remove the mangled symbol.
    103       text->erase(mangled_start, mangled_end - mangled_start);
    104       // Insert the demangled symbol.
    105       text->insert(mangled_start, demangled_symbol.get());
    106       // Next time, we'll start right after the demangled symbol we inserted.
    107       search_from = mangled_start + strlen(demangled_symbol.get());
    108     } else {
    109       // Failed to demangle.  Retry after the "_Z" we just found.
    110       search_from = mangled_start + 2;
    111     }
    112   }
    113 }
    114 #elif !defined(__UCLIBC__)
    115 void DemangleSymbols(std::string* /* text */) {}
    116 #endif  // defined(__GLIBCXX__) && !defined(__UCLIBC__)
    117 
    118 #endif  // !defined(USE_SYMBOLIZE)
    119 
    120 class BacktraceOutputHandler {
    121  public:
    122   virtual void HandleOutput(const char* output) = 0;
    123 
    124  protected:
    125   virtual ~BacktraceOutputHandler() {}
    126 };
    127 
    128 #if defined(USE_SYMBOLIZE) || !defined(__UCLIBC__)
    129 void OutputPointer(void* pointer, BacktraceOutputHandler* handler) {
    130   // This should be more than enough to store a 64-bit number in hex:
    131   // 16 hex digits + 1 for null-terminator.
    132   char buf[17] = { '\0' };
    133   handler->HandleOutput("0x");
    134   internal::itoa_r(reinterpret_cast<intptr_t>(pointer),
    135                    buf, sizeof(buf), 16, 12);
    136   handler->HandleOutput(buf);
    137 }
    138 #endif  // defined(USE_SYMBOLIZE) ||  !defined(__UCLIBC__)
    139 
    140 #if defined(USE_SYMBOLIZE)
    141 void OutputFrameId(intptr_t frame_id, BacktraceOutputHandler* handler) {
    142   // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615).
    143   // Hence, 30 digits should be more than enough to represent it in decimal
    144   // (including the null-terminator).
    145   char buf[30] = { '\0' };
    146   handler->HandleOutput("#");
    147   internal::itoa_r(frame_id, buf, sizeof(buf), 10, 1);
    148   handler->HandleOutput(buf);
    149 }
    150 #endif  // defined(USE_SYMBOLIZE)
    151 
    152 #if !defined(__UCLIBC__)
    153 void ProcessBacktrace(void *const * trace,
    154                       size_t size,
    155                       BacktraceOutputHandler* handler) {
    156   (void)trace;  // unused based on build context below.
    157   (void)size;  // unusud based on build context below.
    158   (void)handler;  // unused based on build context below.
    159   // NOTE: This code MUST be async-signal safe (it's used by in-process
    160   // stack dumping signal handler). NO malloc or stdio is allowed here.
    161 
    162 #if defined(USE_SYMBOLIZE)
    163   for (size_t i = 0; i < size; ++i) {
    164     OutputFrameId(i, handler);
    165     handler->HandleOutput(" ");
    166     OutputPointer(trace[i], handler);
    167     handler->HandleOutput(" ");
    168 
    169     char buf[1024] = { '\0' };
    170 
    171     // Subtract by one as return address of function may be in the next
    172     // function when a function is annotated as noreturn.
    173     void* address = static_cast<char*>(trace[i]) - 1;
    174     if (google::Symbolize(address, buf, sizeof(buf)))
    175       handler->HandleOutput(buf);
    176     else
    177       handler->HandleOutput("<unknown>");
    178 
    179     handler->HandleOutput("\n");
    180   }
    181 #else
    182   bool printed = false;
    183 
    184   // Below part is async-signal unsafe (uses malloc), so execute it only
    185   // when we are not executing the signal handler.
    186   if (in_signal_handler == 0) {
    187     std::unique_ptr<char*, FreeDeleter> trace_symbols(
    188         backtrace_symbols(trace, size));
    189     if (trace_symbols.get()) {
    190       for (size_t i = 0; i < size; ++i) {
    191         std::string trace_symbol = trace_symbols.get()[i];
    192         DemangleSymbols(&trace_symbol);
    193         handler->HandleOutput(trace_symbol.c_str());
    194         handler->HandleOutput("\n");
    195       }
    196 
    197       printed = true;
    198     }
    199   }
    200 
    201   if (!printed) {
    202     for (size_t i = 0; i < size; ++i) {
    203       handler->HandleOutput(" [");
    204       OutputPointer(trace[i], handler);
    205       handler->HandleOutput("]\n");
    206     }
    207   }
    208 #endif  // defined(USE_SYMBOLIZE)
    209 }
    210 #endif  // !defined(__UCLIBC__)
    211 
    212 void PrintToStderr(const char* output) {
    213   // NOTE: This code MUST be async-signal safe (it's used by in-process
    214   // stack dumping signal handler). NO malloc or stdio is allowed here.
    215   ignore_result(HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output))));
    216 }
    217 
    218 void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
    219   (void)void_context;  // unused depending on build context
    220   // NOTE: This code MUST be async-signal safe.
    221   // NO malloc or stdio is allowed here.
    222 
    223   // Record the fact that we are in the signal handler now, so that the rest
    224   // of StackTrace can behave in an async-signal-safe manner.
    225   in_signal_handler = 1;
    226 
    227   if (BeingDebugged())
    228     BreakDebugger();
    229 
    230   PrintToStderr("Received signal ");
    231   char buf[1024] = { 0 };
    232   internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
    233   PrintToStderr(buf);
    234   if (signal == SIGBUS) {
    235     if (info->si_code == BUS_ADRALN)
    236       PrintToStderr(" BUS_ADRALN ");
    237     else if (info->si_code == BUS_ADRERR)
    238       PrintToStderr(" BUS_ADRERR ");
    239     else if (info->si_code == BUS_OBJERR)
    240       PrintToStderr(" BUS_OBJERR ");
    241     else
    242       PrintToStderr(" <unknown> ");
    243   } else if (signal == SIGFPE) {
    244     if (info->si_code == FPE_FLTDIV)
    245       PrintToStderr(" FPE_FLTDIV ");
    246     else if (info->si_code == FPE_FLTINV)
    247       PrintToStderr(" FPE_FLTINV ");
    248     else if (info->si_code == FPE_FLTOVF)
    249       PrintToStderr(" FPE_FLTOVF ");
    250     else if (info->si_code == FPE_FLTRES)
    251       PrintToStderr(" FPE_FLTRES ");
    252     else if (info->si_code == FPE_FLTSUB)
    253       PrintToStderr(" FPE_FLTSUB ");
    254     else if (info->si_code == FPE_FLTUND)
    255       PrintToStderr(" FPE_FLTUND ");
    256     else if (info->si_code == FPE_INTDIV)
    257       PrintToStderr(" FPE_INTDIV ");
    258     else if (info->si_code == FPE_INTOVF)
    259       PrintToStderr(" FPE_INTOVF ");
    260     else
    261       PrintToStderr(" <unknown> ");
    262   } else if (signal == SIGILL) {
    263     if (info->si_code == ILL_BADSTK)
    264       PrintToStderr(" ILL_BADSTK ");
    265     else if (info->si_code == ILL_COPROC)
    266       PrintToStderr(" ILL_COPROC ");
    267     else if (info->si_code == ILL_ILLOPN)
    268       PrintToStderr(" ILL_ILLOPN ");
    269     else if (info->si_code == ILL_ILLADR)
    270       PrintToStderr(" ILL_ILLADR ");
    271     else if (info->si_code == ILL_ILLTRP)
    272       PrintToStderr(" ILL_ILLTRP ");
    273     else if (info->si_code == ILL_PRVOPC)
    274       PrintToStderr(" ILL_PRVOPC ");
    275     else if (info->si_code == ILL_PRVREG)
    276       PrintToStderr(" ILL_PRVREG ");
    277     else
    278       PrintToStderr(" <unknown> ");
    279   } else if (signal == SIGSEGV) {
    280     if (info->si_code == SEGV_MAPERR)
    281       PrintToStderr(" SEGV_MAPERR ");
    282     else if (info->si_code == SEGV_ACCERR)
    283       PrintToStderr(" SEGV_ACCERR ");
    284     else
    285       PrintToStderr(" <unknown> ");
    286   }
    287   if (signal == SIGBUS || signal == SIGFPE ||
    288       signal == SIGILL || signal == SIGSEGV) {
    289     internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
    290                      buf, sizeof(buf), 16, 12);
    291     PrintToStderr(buf);
    292   }
    293   PrintToStderr("\n");
    294 
    295 #if defined(CFI_ENFORCEMENT)
    296   if (signal == SIGILL && info->si_code == ILL_ILLOPN) {
    297     PrintToStderr(
    298         "CFI: Most likely a control flow integrity violation; for more "
    299         "information see:\n");
    300     PrintToStderr(
    301         "https://www.chromium.org/developers/testing/control-flow-integrity\n");
    302   }
    303 #endif
    304 
    305   debug::StackTrace().Print();
    306 
    307 #if defined(OS_LINUX)
    308 #if ARCH_CPU_X86_FAMILY
    309   ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
    310   const struct {
    311     const char* label;
    312     greg_t value;
    313   } registers[] = {
    314 #if ARCH_CPU_32_BITS
    315     { "  gs: ", context->uc_mcontext.gregs[REG_GS] },
    316     { "  fs: ", context->uc_mcontext.gregs[REG_FS] },
    317     { "  es: ", context->uc_mcontext.gregs[REG_ES] },
    318     { "  ds: ", context->uc_mcontext.gregs[REG_DS] },
    319     { " edi: ", context->uc_mcontext.gregs[REG_EDI] },
    320     { " esi: ", context->uc_mcontext.gregs[REG_ESI] },
    321     { " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
    322     { " esp: ", context->uc_mcontext.gregs[REG_ESP] },
    323     { " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
    324     { " edx: ", context->uc_mcontext.gregs[REG_EDX] },
    325     { " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
    326     { " eax: ", context->uc_mcontext.gregs[REG_EAX] },
    327     { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
    328     { " err: ", context->uc_mcontext.gregs[REG_ERR] },
    329     { "  ip: ", context->uc_mcontext.gregs[REG_EIP] },
    330     { "  cs: ", context->uc_mcontext.gregs[REG_CS] },
    331     { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
    332     { " usp: ", context->uc_mcontext.gregs[REG_UESP] },
    333     { "  ss: ", context->uc_mcontext.gregs[REG_SS] },
    334 #elif ARCH_CPU_64_BITS
    335     { "  r8: ", context->uc_mcontext.gregs[REG_R8] },
    336     { "  r9: ", context->uc_mcontext.gregs[REG_R9] },
    337     { " r10: ", context->uc_mcontext.gregs[REG_R10] },
    338     { " r11: ", context->uc_mcontext.gregs[REG_R11] },
    339     { " r12: ", context->uc_mcontext.gregs[REG_R12] },
    340     { " r13: ", context->uc_mcontext.gregs[REG_R13] },
    341     { " r14: ", context->uc_mcontext.gregs[REG_R14] },
    342     { " r15: ", context->uc_mcontext.gregs[REG_R15] },
    343     { "  di: ", context->uc_mcontext.gregs[REG_RDI] },
    344     { "  si: ", context->uc_mcontext.gregs[REG_RSI] },
    345     { "  bp: ", context->uc_mcontext.gregs[REG_RBP] },
    346     { "  bx: ", context->uc_mcontext.gregs[REG_RBX] },
    347     { "  dx: ", context->uc_mcontext.gregs[REG_RDX] },
    348     { "  ax: ", context->uc_mcontext.gregs[REG_RAX] },
    349     { "  cx: ", context->uc_mcontext.gregs[REG_RCX] },
    350     { "  sp: ", context->uc_mcontext.gregs[REG_RSP] },
    351     { "  ip: ", context->uc_mcontext.gregs[REG_RIP] },
    352     { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
    353     { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
    354     { " erf: ", context->uc_mcontext.gregs[REG_ERR] },
    355     { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
    356     { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
    357     { " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
    358 #endif  // ARCH_CPU_32_BITS
    359   };
    360 
    361 #if ARCH_CPU_32_BITS
    362   const int kRegisterPadding = 8;
    363 #elif ARCH_CPU_64_BITS
    364   const int kRegisterPadding = 16;
    365 #endif
    366 
    367   for (size_t i = 0; i < arraysize(registers); i++) {
    368     PrintToStderr(registers[i].label);
    369     internal::itoa_r(registers[i].value, buf, sizeof(buf),
    370                      16, kRegisterPadding);
    371     PrintToStderr(buf);
    372 
    373     if ((i + 1) % 4 == 0)
    374       PrintToStderr("\n");
    375   }
    376   PrintToStderr("\n");
    377 #endif  // ARCH_CPU_X86_FAMILY
    378 #endif  // defined(OS_LINUX)
    379 
    380   PrintToStderr("[end of stack trace]\n");
    381 
    382 #if defined(OS_MACOSX) && !defined(OS_IOS)
    383   if (::signal(signal, SIG_DFL) == SIG_ERR)
    384     _exit(1);
    385 #else
    386   // Non-Mac OSes should probably reraise the signal as well, but the Linux
    387   // sandbox tests break on CrOS devices.
    388   // https://code.google.com/p/chromium/issues/detail?id=551681
    389   _exit(1);
    390 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
    391 }
    392 
    393 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
    394  public:
    395   PrintBacktraceOutputHandler() {}
    396 
    397   void HandleOutput(const char* output) override {
    398     // NOTE: This code MUST be async-signal safe (it's used by in-process
    399     // stack dumping signal handler). NO malloc or stdio is allowed here.
    400     PrintToStderr(output);
    401   }
    402 
    403  private:
    404   DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
    405 };
    406 
    407 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
    408  public:
    409   explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
    410   }
    411 
    412   void HandleOutput(const char* output) override { (*os_) << output; }
    413 
    414  private:
    415   std::ostream* os_;
    416 
    417   DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
    418 };
    419 
    420 void WarmUpBacktrace() {
    421   // Warm up stack trace infrastructure. It turns out that on the first
    422   // call glibc initializes some internal data structures using pthread_once,
    423   // and even backtrace() can call malloc(), leading to hangs.
    424   //
    425   // Example stack trace snippet (with tcmalloc):
    426   //
    427   // #8  0x0000000000a173b5 in tc_malloc
    428   //             at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
    429   // #9  0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
    430   // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
    431   // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
    432   // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
    433   //             at dl-open.c:639
    434   // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
    435   // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
    436   // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
    437   // #16 __GI___libc_dlopen_mode at dl-libc.c:165
    438   // #17 0x00007ffff61ef8f5 in init
    439   //             at ../sysdeps/x86_64/../ia64/backtrace.c:53
    440   // #18 0x00007ffff6aad400 in pthread_once
    441   //             at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
    442   // #19 0x00007ffff61efa14 in __GI___backtrace
    443   //             at ../sysdeps/x86_64/../ia64/backtrace.c:104
    444   // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
    445   //             at base/debug/stack_trace_posix.cc:175
    446   // #21 0x00000000007a4ae5 in
    447   //             base::(anonymous namespace)::StackDumpSignalHandler
    448   //             at base/process_util_posix.cc:172
    449   // #22 <signal handler called>
    450   StackTrace stack_trace;
    451 }
    452 
    453 }  // namespace
    454 
    455 #if defined(USE_SYMBOLIZE)
    456 
    457 // class SandboxSymbolizeHelper.
    458 //
    459 // The purpose of this class is to prepare and install a "file open" callback
    460 // needed by the stack trace symbolization code
    461 // (base/third_party/symbolize/symbolize.h) so that it can function properly
    462 // in a sandboxed process.  The caveat is that this class must be instantiated
    463 // before the sandboxing is enabled so that it can get the chance to open all
    464 // the object files that are loaded in the virtual address space of the current
    465 // process.
    466 class SandboxSymbolizeHelper {
    467  public:
    468   // Returns the singleton instance.
    469   static SandboxSymbolizeHelper* GetInstance() {
    470     return Singleton<SandboxSymbolizeHelper>::get();
    471   }
    472 
    473  private:
    474   friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
    475 
    476   SandboxSymbolizeHelper()
    477       : is_initialized_(false) {
    478     Init();
    479   }
    480 
    481   ~SandboxSymbolizeHelper() {
    482     UnregisterCallback();
    483     CloseObjectFiles();
    484   }
    485 
    486   // Returns a O_RDONLY file descriptor for |file_path| if it was opened
    487   // successfully during the initialization.  The file is repositioned at
    488   // offset 0.
    489   // IMPORTANT: This function must be async-signal-safe because it can be
    490   // called from a signal handler (symbolizing stack frames for a crash).
    491   int GetFileDescriptor(const char* file_path) {
    492     int fd = -1;
    493 
    494 #if !defined(OFFICIAL_BUILD)
    495     if (file_path) {
    496       // The assumption here is that iterating over std::map<std::string, int>
    497       // using a const_iterator does not allocate dynamic memory, hense it is
    498       // async-signal-safe.
    499       std::map<std::string, int>::const_iterator it;
    500       for (it = modules_.begin(); it != modules_.end(); ++it) {
    501         if (strcmp((it->first).c_str(), file_path) == 0) {
    502           // POSIX.1-2004 requires an implementation to guarantee that dup()
    503           // is async-signal-safe.
    504           fd = dup(it->second);
    505           break;
    506         }
    507       }
    508       // POSIX.1-2004 requires an implementation to guarantee that lseek()
    509       // is async-signal-safe.
    510       if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
    511         // Failed to seek.
    512         fd = -1;
    513       }
    514     }
    515 #endif  // !defined(OFFICIAL_BUILD)
    516 
    517     return fd;
    518   }
    519 
    520   // Searches for the object file (from /proc/self/maps) that contains
    521   // the specified pc.  If found, sets |start_address| to the start address
    522   // of where this object file is mapped in memory, sets the module base
    523   // address into |base_address|, copies the object file name into
    524   // |out_file_name|, and attempts to open the object file.  If the object
    525   // file is opened successfully, returns the file descriptor.  Otherwise,
    526   // returns -1.  |out_file_name_size| is the size of the file name buffer
    527   // (including the null terminator).
    528   // IMPORTANT: This function must be async-signal-safe because it can be
    529   // called from a signal handler (symbolizing stack frames for a crash).
    530   static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address,
    531                                         uint64_t& base_address, char* file_path,
    532                                         int file_path_size) {
    533     // This method can only be called after the singleton is instantiated.
    534     // This is ensured by the following facts:
    535     // * This is the only static method in this class, it is private, and
    536     //   the class has no friends (except for the DefaultSingletonTraits).
    537     //   The compiler guarantees that it can only be called after the
    538     //   singleton is instantiated.
    539     // * This method is used as a callback for the stack tracing code and
    540     //   the callback registration is done in the constructor, so logically
    541     //   it cannot be called before the singleton is created.
    542     SandboxSymbolizeHelper* instance = GetInstance();
    543 
    544     // The assumption here is that iterating over
    545     // std::vector<MappedMemoryRegion> using a const_iterator does not allocate
    546     // dynamic memory, hence it is async-signal-safe.
    547     std::vector<MappedMemoryRegion>::const_iterator it;
    548     bool is_first = true;
    549     for (it = instance->regions_.begin(); it != instance->regions_.end();
    550          ++it, is_first = false) {
    551       const MappedMemoryRegion& region = *it;
    552       if (region.start <= pc && pc < region.end) {
    553         start_address = region.start;
    554         // Don't subtract 'start_address' from the first entry:
    555         // * If a binary is compiled w/o -pie, then the first entry in
    556         //   process maps is likely the binary itself (all dynamic libs
    557         //   are mapped higher in address space). For such a binary,
    558         //   instruction offset in binary coincides with the actual
    559         //   instruction address in virtual memory (as code section
    560         //   is mapped to a fixed memory range).
    561         // * If a binary is compiled with -pie, all the modules are
    562         //   mapped high at address space (in particular, higher than
    563         //   shadow memory of the tool), so the module can't be the
    564         //   first entry.
    565         base_address = (is_first ? 0U : start_address) - region.offset;
    566         if (file_path && file_path_size > 0) {
    567           strncpy(file_path, region.path.c_str(), file_path_size);
    568           // Ensure null termination.
    569           file_path[file_path_size - 1] = '\0';
    570         }
    571         return instance->GetFileDescriptor(region.path.c_str());
    572       }
    573     }
    574     return -1;
    575   }
    576 
    577   // Parses /proc/self/maps in order to compile a list of all object file names
    578   // for the modules that are loaded in the current process.
    579   // Returns true on success.
    580   bool CacheMemoryRegions() {
    581     // Reads /proc/self/maps.
    582     std::string contents;
    583     if (!ReadProcMaps(&contents)) {
    584       LOG(ERROR) << "Failed to read /proc/self/maps";
    585       return false;
    586     }
    587 
    588     // Parses /proc/self/maps.
    589     if (!ParseProcMaps(contents, &regions_)) {
    590       LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
    591       return false;
    592     }
    593 
    594     is_initialized_ = true;
    595     return true;
    596   }
    597 
    598   // Opens all object files and caches their file descriptors.
    599   void OpenSymbolFiles() {
    600     // Pre-opening and caching the file descriptors of all loaded modules is
    601     // not safe for production builds.  Hence it is only done in non-official
    602     // builds.  For more details, take a look at: http://crbug.com/341966.
    603 #if !defined(OFFICIAL_BUILD)
    604     // Open the object files for all read-only executable regions and cache
    605     // their file descriptors.
    606     std::vector<MappedMemoryRegion>::const_iterator it;
    607     for (it = regions_.begin(); it != regions_.end(); ++it) {
    608       const MappedMemoryRegion& region = *it;
    609       // Only interesed in read-only executable regions.
    610       if ((region.permissions & MappedMemoryRegion::READ) ==
    611               MappedMemoryRegion::READ &&
    612           (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
    613           (region.permissions & MappedMemoryRegion::EXECUTE) ==
    614               MappedMemoryRegion::EXECUTE) {
    615         if (region.path.empty()) {
    616           // Skip regions with empty file names.
    617           continue;
    618         }
    619         if (region.path[0] == '[') {
    620           // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
    621           continue;
    622         }
    623         // Avoid duplicates.
    624         if (modules_.find(region.path) == modules_.end()) {
    625           int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
    626           if (fd >= 0) {
    627             modules_.insert(std::make_pair(region.path, fd));
    628           } else {
    629             LOG(WARNING) << "Failed to open file: " << region.path
    630                          << "\n  Error: " << strerror(errno);
    631           }
    632         }
    633       }
    634     }
    635 #endif  // !defined(OFFICIAL_BUILD)
    636   }
    637 
    638   // Initializes and installs the symbolization callback.
    639   void Init() {
    640     if (CacheMemoryRegions()) {
    641       OpenSymbolFiles();
    642       google::InstallSymbolizeOpenObjectFileCallback(
    643           &OpenObjectFileContainingPc);
    644     }
    645   }
    646 
    647   // Unregister symbolization callback.
    648   void UnregisterCallback() {
    649     if (is_initialized_) {
    650       google::InstallSymbolizeOpenObjectFileCallback(NULL);
    651       is_initialized_ = false;
    652     }
    653   }
    654 
    655   // Closes all file descriptors owned by this instance.
    656   void CloseObjectFiles() {
    657 #if !defined(OFFICIAL_BUILD)
    658     std::map<std::string, int>::iterator it;
    659     for (it = modules_.begin(); it != modules_.end(); ++it) {
    660       int ret = IGNORE_EINTR(close(it->second));
    661       DCHECK(!ret);
    662       it->second = -1;
    663     }
    664     modules_.clear();
    665 #endif  // !defined(OFFICIAL_BUILD)
    666   }
    667 
    668   // Set to true upon successful initialization.
    669   bool is_initialized_;
    670 
    671 #if !defined(OFFICIAL_BUILD)
    672   // Mapping from file name to file descriptor.  Includes file descriptors
    673   // for all successfully opened object files and the file descriptor for
    674   // /proc/self/maps.  This code is not safe for production builds.
    675   std::map<std::string, int> modules_;
    676 #endif  // !defined(OFFICIAL_BUILD)
    677 
    678   // Cache for the process memory regions.  Produced by parsing the contents
    679   // of /proc/self/maps cache.
    680   std::vector<MappedMemoryRegion> regions_;
    681 
    682   DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper);
    683 };
    684 #endif  // USE_SYMBOLIZE
    685 
    686 bool EnableInProcessStackDumping() {
    687 #if defined(USE_SYMBOLIZE)
    688   SandboxSymbolizeHelper::GetInstance();
    689 #endif  // USE_SYMBOLIZE
    690 
    691   // When running in an application, our code typically expects SIGPIPE
    692   // to be ignored.  Therefore, when testing that same code, it should run
    693   // with SIGPIPE ignored as well.
    694   struct sigaction sigpipe_action;
    695   memset(&sigpipe_action, 0, sizeof(sigpipe_action));
    696   sigpipe_action.sa_handler = SIG_IGN;
    697   sigemptyset(&sigpipe_action.sa_mask);
    698   bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
    699 
    700   // Avoid hangs during backtrace initialization, see above.
    701   WarmUpBacktrace();
    702 
    703   struct sigaction action;
    704   memset(&action, 0, sizeof(action));
    705   action.sa_flags = SA_RESETHAND | SA_SIGINFO;
    706   action.sa_sigaction = &StackDumpSignalHandler;
    707   sigemptyset(&action.sa_mask);
    708 
    709   success &= (sigaction(SIGILL, &action, NULL) == 0);
    710   success &= (sigaction(SIGABRT, &action, NULL) == 0);
    711   success &= (sigaction(SIGFPE, &action, NULL) == 0);
    712   success &= (sigaction(SIGBUS, &action, NULL) == 0);
    713   success &= (sigaction(SIGSEGV, &action, NULL) == 0);
    714 // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
    715 #if !defined(OS_LINUX)
    716   success &= (sigaction(SIGSYS, &action, NULL) == 0);
    717 #endif  // !defined(OS_LINUX)
    718 
    719   return success;
    720 }
    721 
    722 StackTrace::StackTrace() {
    723   // NOTE: This code MUST be async-signal safe (it's used by in-process
    724   // stack dumping signal handler). NO malloc or stdio is allowed here.
    725 
    726 #if !defined(__UCLIBC__)
    727   // Though the backtrace API man page does not list any possible negative
    728   // return values, we take no chance.
    729   count_ = base::saturated_cast<size_t>(backtrace(trace_, arraysize(trace_)));
    730 #else
    731   count_ = 0;
    732 #endif
    733 }
    734 
    735 void StackTrace::Print() const {
    736   // NOTE: This code MUST be async-signal safe (it's used by in-process
    737   // stack dumping signal handler). NO malloc or stdio is allowed here.
    738 
    739 #if !defined(__UCLIBC__)
    740   PrintBacktraceOutputHandler handler;
    741   ProcessBacktrace(trace_, count_, &handler);
    742 #endif
    743 }
    744 
    745 #if !defined(__UCLIBC__)
    746 void StackTrace::OutputToStream(std::ostream* os) const {
    747   StreamBacktraceOutputHandler handler(os);
    748   ProcessBacktrace(trace_, count_, &handler);
    749 }
    750 #endif
    751 
    752 namespace internal {
    753 
    754 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
    755 char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
    756   // Make sure we can write at least one NUL byte.
    757   size_t n = 1;
    758   if (n > sz)
    759     return NULL;
    760 
    761   if (base < 2 || base > 16) {
    762     buf[0] = '\000';
    763     return NULL;
    764   }
    765 
    766   char* start = buf;
    767 
    768   uintptr_t j = i;
    769 
    770   // Handle negative numbers (only for base 10).
    771   if (i < 0 && base == 10) {
    772     // This does "j = -i" while avoiding integer overflow.
    773     j = static_cast<uintptr_t>(-(i + 1)) + 1;
    774 
    775     // Make sure we can write the '-' character.
    776     if (++n > sz) {
    777       buf[0] = '\000';
    778       return NULL;
    779     }
    780     *start++ = '-';
    781   }
    782 
    783   // Loop until we have converted the entire number. Output at least one
    784   // character (i.e. '0').
    785   char* ptr = start;
    786   do {
    787     // Make sure there is still enough space left in our output buffer.
    788     if (++n > sz) {
    789       buf[0] = '\000';
    790       return NULL;
    791     }
    792 
    793     // Output the next digit.
    794     *ptr++ = "0123456789abcdef"[j % base];
    795     j /= base;
    796 
    797     if (padding > 0)
    798       padding--;
    799   } while (j > 0 || padding > 0);
    800 
    801   // Terminate the output with a NUL character.
    802   *ptr = '\000';
    803 
    804   // Conversion to ASCII actually resulted in the digits being in reverse
    805   // order. We can't easily generate them in forward order, as we can't tell
    806   // the number of characters needed until we are done converting.
    807   // So, now, we reverse the string (except for the possible "-" sign).
    808   while (--ptr > start) {
    809     char ch = *ptr;
    810     *ptr = *start;
    811     *start++ = ch;
    812   }
    813   return buf;
    814 }
    815 
    816 }  // namespace internal
    817 
    818 }  // namespace debug
    819 }  // namespace base
    820