Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2006-2009 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 "build/build_config.h"
      6 #include "base/debug_util.h"
      7 
      8 #include <errno.h>
      9 #include <fcntl.h>
     10 #include <stdio.h>
     11 #include <sys/stat.h>
     12 #include <sys/sysctl.h>
     13 #include <sys/types.h>
     14 #include <unistd.h>
     15 
     16 #if defined(__GLIBCXX__)
     17 #include <cxxabi.h>
     18 #endif
     19 
     20 #include <iostream>
     21 #include <string>
     22 
     23 #if defined(OS_MACOSX)
     24 #include <AvailabilityMacros.h>
     25 #endif
     26 
     27 #include "base/basictypes.h"
     28 #include "base/compat_execinfo.h"
     29 #include "base/eintr_wrapper.h"
     30 #include "base/logging.h"
     31 #include "base/safe_strerror_posix.h"
     32 #include "base/scoped_ptr.h"
     33 #include "base/string_piece.h"
     34 #include "base/string_util.h"
     35 
     36 #if defined(USE_SYMBOLIZE)
     37 #include "base/third_party/symbolize/symbolize.h"
     38 #endif
     39 
     40 namespace {
     41 // The prefix used for mangled symbols, per the Itanium C++ ABI:
     42 // http://www.codesourcery.com/cxx-abi/abi.html#mangling
     43 const char kMangledSymbolPrefix[] = "_Z";
     44 
     45 // Characters that can be used for symbols, generated by Ruby:
     46 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
     47 const char kSymbolCharacters[] =
     48     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
     49 
     50 // Demangles C++ symbols in the given text. Example:
     51 //
     52 // "sconsbuild/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
     53 // =>
     54 // "sconsbuild/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
     55 void DemangleSymbols(std::string* text) {
     56 #if defined(__GLIBCXX__)
     57 
     58   std::string::size_type search_from = 0;
     59   while (search_from < text->size()) {
     60     // Look for the start of a mangled symbol, from search_from.
     61     std::string::size_type mangled_start =
     62         text->find(kMangledSymbolPrefix, search_from);
     63     if (mangled_start == std::string::npos) {
     64       break;  // Mangled symbol not found.
     65     }
     66 
     67     // Look for the end of the mangled symbol.
     68     std::string::size_type mangled_end =
     69         text->find_first_not_of(kSymbolCharacters, mangled_start);
     70     if (mangled_end == std::string::npos) {
     71       mangled_end = text->size();
     72     }
     73     std::string mangled_symbol =
     74         text->substr(mangled_start, mangled_end - mangled_start);
     75 
     76     // Try to demangle the mangled symbol candidate.
     77     int status = 0;
     78     scoped_ptr_malloc<char> demangled_symbol(
     79         abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
     80     if (status == 0) {  // Demangling is successful.
     81       // Remove the mangled symbol.
     82       text->erase(mangled_start, mangled_end - mangled_start);
     83       // Insert the demangled symbol.
     84       text->insert(mangled_start, demangled_symbol.get());
     85       // Next time, we'll start right after the demangled symbol we inserted.
     86       search_from = mangled_start + strlen(demangled_symbol.get());
     87     } else {
     88       // Failed to demangle.  Retry after the "_Z" we just found.
     89       search_from = mangled_start + 2;
     90     }
     91   }
     92 
     93 #endif  // defined(__GLIBCXX__)
     94 }
     95 
     96 // Gets the backtrace as a vector of strings. If possible, resolve symbol
     97 // names and attach these. Otherwise just use raw addresses. Returns true
     98 // if any symbol name is resolved.
     99 bool GetBacktraceStrings(void **trace, int size,
    100                          std::vector<std::string>* trace_strings) {
    101   bool symbolized = false;
    102 
    103 #if defined(USE_SYMBOLIZE)
    104   for (int i = 0; i < size; ++i) {
    105     char symbol[1024];
    106     // Subtract by one as return address of function may be in the next
    107     // function when a function is annotated as noreturn.
    108     if (google::Symbolize(static_cast<char *>(trace[i]) - 1,
    109                           symbol, sizeof(symbol))) {
    110       // Don't call DemangleSymbols() here as the symbol is demangled by
    111       // google::Symbolize().
    112       trace_strings->push_back(StringPrintf("%s [%p]", symbol, trace[i]));
    113       symbolized = true;
    114     } else {
    115       trace_strings->push_back(StringPrintf("%p", trace[i]));
    116     }
    117   }
    118 #else
    119   scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
    120   if (trace_symbols.get()) {
    121     for (int i = 0; i < size; ++i) {
    122       std::string trace_symbol = trace_symbols.get()[i];
    123       DemangleSymbols(&trace_symbol);
    124       trace_strings->push_back(trace_symbol);
    125     }
    126     symbolized = true;
    127   } else {
    128     for (int i = 0; i < size; ++i) {
    129       trace_strings->push_back(StringPrintf("%p", trace[i]));
    130     }
    131   }
    132 #endif  // defined(USE_SYMBOLIZE)
    133 
    134   return symbolized;
    135 }
    136 
    137 }  // namespace
    138 
    139 // static
    140 bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
    141   NOTIMPLEMENTED();
    142   return false;
    143 }
    144 
    145 #if defined(OS_MACOSX)
    146 
    147 // Based on Apple's recommended method as described in
    148 // http://developer.apple.com/qa/qa2004/qa1361.html
    149 // static
    150 bool DebugUtil::BeingDebugged() {
    151   // If the process is sandboxed then we can't use the sysctl, so cache the
    152   // value.
    153   static bool is_set = false;
    154   static bool being_debugged = false;
    155 
    156   if (is_set) {
    157     return being_debugged;
    158   }
    159 
    160   // Initialize mib, which tells sysctl what info we want.  In this case,
    161   // we're looking for information about a specific process ID.
    162   int mib[] = {
    163     CTL_KERN,
    164     KERN_PROC,
    165     KERN_PROC_PID,
    166     getpid()
    167   };
    168 
    169   // Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE.  The source and
    170   // binary interfaces may change.
    171   struct kinfo_proc info;
    172   size_t info_size = sizeof(info);
    173 
    174   int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
    175   DCHECK(sysctl_result == 0);
    176   if (sysctl_result != 0) {
    177     is_set = true;
    178     being_debugged = false;
    179     return being_debugged;
    180   }
    181 
    182   // This process is being debugged if the P_TRACED flag is set.
    183   is_set = true;
    184   being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;
    185   return being_debugged;
    186 }
    187 
    188 #elif defined(OS_LINUX)
    189 
    190 // We can look in /proc/self/status for TracerPid.  We are likely used in crash
    191 // handling, so we are careful not to use the heap or have side effects.
    192 // Another option that is common is to try to ptrace yourself, but then we
    193 // can't detach without forking(), and that's not so great.
    194 // static
    195 bool DebugUtil::BeingDebugged() {
    196   int status_fd = open("/proc/self/status", O_RDONLY);
    197   if (status_fd == -1)
    198     return false;
    199 
    200   // We assume our line will be in the first 1024 characters and that we can
    201   // read this much all at once.  In practice this will generally be true.
    202   // This simplifies and speeds up things considerably.
    203   char buf[1024];
    204 
    205   ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
    206   if (HANDLE_EINTR(close(status_fd)) < 0)
    207     return false;
    208 
    209   if (num_read <= 0)
    210     return false;
    211 
    212   base::StringPiece status(buf, num_read);
    213   base::StringPiece tracer("TracerPid:\t");
    214 
    215   base::StringPiece::size_type pid_index = status.find(tracer);
    216   if (pid_index == base::StringPiece::npos)
    217     return false;
    218 
    219   // Our pid is 0 without a debugger, assume this for any pid starting with 0.
    220   pid_index += tracer.size();
    221   return pid_index < status.size() && status[pid_index] != '0';
    222 }
    223 
    224 #elif defined(OS_FREEBSD)
    225 
    226 bool DebugUtil::BeingDebugged() {
    227   // TODO(benl): can we determine this under FreeBSD?
    228   NOTIMPLEMENTED();
    229   return false;
    230 }
    231 
    232 #endif
    233 
    234 // static
    235 void DebugUtil::BreakDebugger() {
    236 #if defined(ARCH_CPU_ARM_FAMILY)
    237   asm("bkpt 0");
    238 #else
    239   asm("int3");
    240 #endif
    241 }
    242 
    243 StackTrace::StackTrace() {
    244 #if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
    245   if (backtrace == NULL) {
    246     count_ = 0;
    247     return;
    248   }
    249 #endif
    250   // Though the backtrace API man page does not list any possible negative
    251   // return values, we take no chance.
    252   count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
    253 }
    254 
    255 void StackTrace::PrintBacktrace() {
    256 #if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
    257   if (backtrace_symbols_fd == NULL)
    258     return;
    259 #endif
    260   fflush(stderr);
    261   std::vector<std::string> trace_strings;
    262   GetBacktraceStrings(trace_, count_, &trace_strings);
    263   for (size_t i = 0; i < trace_strings.size(); ++i) {
    264     std::cerr << "\t" << trace_strings[i] << "\n";
    265   }
    266 }
    267 
    268 void StackTrace::OutputToStream(std::ostream* os) {
    269 #if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
    270   if (backtrace_symbols == NULL)
    271     return;
    272 #endif
    273   std::vector<std::string> trace_strings;
    274   if (GetBacktraceStrings(trace_, count_, &trace_strings)) {
    275     (*os) << "Backtrace:\n";
    276   } else {
    277     (*os) << "Unable get symbols for backtrace (" << safe_strerror(errno)
    278           << "). Dumping raw addresses in trace:\n";
    279   }
    280 
    281   for (size_t i = 0; i < trace_strings.size(); ++i) {
    282     (*os) << "\t" << trace_strings[i] << "\n";
    283   }
    284 }
    285