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 #ifndef BASE_DEBUG_STACK_TRACE_H_
      6 #define BASE_DEBUG_STACK_TRACE_H_
      7 
      8 #include <stddef.h>
      9 
     10 #include <iosfwd>
     11 #include <string>
     12 
     13 #include "base/base_export.h"
     14 #include "base/debug/debugging_buildflags.h"
     15 #include "base/macros.h"
     16 #include "build/build_config.h"
     17 
     18 #if defined(OS_POSIX)
     19 #include <unistd.h>
     20 #endif
     21 
     22 #if defined(OS_WIN)
     23 struct _EXCEPTION_POINTERS;
     24 struct _CONTEXT;
     25 #endif
     26 
     27 namespace base {
     28 namespace debug {
     29 
     30 // Enables stack dump to console output on exception and signals.
     31 // When enabled, the process will quit immediately. This is meant to be used in
     32 // unit_tests only! This is not thread-safe: only call from main thread.
     33 // In sandboxed processes, this has to be called before the sandbox is turned
     34 // on.
     35 // Calling this function on Linux opens /proc/self/maps and caches its
     36 // contents. In non-official builds, this function also opens the object files
     37 // that are loaded in memory and caches their file descriptors (this cannot be
     38 // done in official builds because it has security implications).
     39 BASE_EXPORT bool EnableInProcessStackDumping();
     40 
     41 #if defined(OS_POSIX)
     42 BASE_EXPORT void SetStackDumpFirstChanceCallback(bool (*handler)(int,
     43                                                                  void*,
     44                                                                  void*));
     45 #endif
     46 
     47 // Returns end of the stack, or 0 if we couldn't get it.
     48 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
     49 BASE_EXPORT uintptr_t GetStackEnd();
     50 #endif
     51 
     52 // A stacktrace can be helpful in debugging. For example, you can include a
     53 // stacktrace member in a object (probably around #ifndef NDEBUG) so that you
     54 // can later see where the given object was created from.
     55 class BASE_EXPORT StackTrace {
     56  public:
     57   // Creates a stacktrace from the current location.
     58   StackTrace();
     59 
     60   // Creates a stacktrace from the current location, of up to |count| entries.
     61   // |count| will be limited to at most |kMaxTraces|.
     62   explicit StackTrace(size_t count);
     63 
     64   // Creates a stacktrace from an existing array of instruction
     65   // pointers (such as returned by Addresses()).  |count| will be
     66   // limited to at most |kMaxTraces|.
     67   StackTrace(const void* const* trace, size_t count);
     68 
     69 #if defined(OS_WIN)
     70   // Creates a stacktrace for an exception.
     71   // Note: this function will throw an import not found (StackWalk64) exception
     72   // on system without dbghelp 5.1.
     73   StackTrace(_EXCEPTION_POINTERS* exception_pointers);
     74   StackTrace(const _CONTEXT* context);
     75 #endif
     76 
     77   // Copying and assignment are allowed with the default functions.
     78 
     79   // Gets an array of instruction pointer values. |*count| will be set to the
     80   // number of elements in the returned array.
     81   const void* const* Addresses(size_t* count) const;
     82 
     83   // Prints the stack trace to stderr.
     84   void Print() const;
     85 
     86 #if !defined(__UCLIBC__) & !defined(_AIX)
     87   // Resolves backtrace to symbols and write to stream.
     88   void OutputToStream(std::ostream* os) const;
     89 #endif
     90 
     91   // Resolves backtrace to symbols and returns as string.
     92   std::string ToString() const;
     93 
     94  private:
     95 #if defined(OS_WIN)
     96   void InitTrace(const _CONTEXT* context_record);
     97 #endif
     98 
     99   // From http://msdn.microsoft.com/en-us/library/bb204633.aspx,
    100   // the sum of FramesToSkip and FramesToCapture must be less than 63,
    101   // so set it to 62. Even if on POSIX it could be a larger value, it usually
    102   // doesn't give much more information.
    103   static const int kMaxTraces = 62;
    104 
    105   void* trace_[kMaxTraces];
    106 
    107   // The number of valid frames in |trace_|.
    108   size_t count_;
    109 };
    110 
    111 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
    112 // Traces the stack by using frame pointers. This function is faster but less
    113 // reliable than StackTrace. It should work for debug and profiling builds,
    114 // but not for release builds (although there are some exceptions).
    115 //
    116 // Writes at most |max_depth| frames (instruction pointers) into |out_trace|
    117 // after skipping |skip_initial| frames. Note that the function itself is not
    118 // added to the trace so |skip_initial| should be 0 in most cases.
    119 // Returns number of frames written.
    120 BASE_EXPORT size_t TraceStackFramePointers(const void** out_trace,
    121                                            size_t max_depth,
    122                                            size_t skip_initial);
    123 
    124 // Links stack frame |fp| to |parent_fp|, so that during stack unwinding
    125 // TraceStackFramePointers() visits |parent_fp| after visiting |fp|.
    126 // Both frame pointers must come from __builtin_frame_address().
    127 // Destructor restores original linkage of |fp| to avoid corrupting caller's
    128 // frame register on return.
    129 //
    130 // This class can be used to repair broken stack frame chain in cases
    131 // when execution flow goes into code built without frame pointers:
    132 //
    133 // void DoWork() {
    134 //   Call_SomeLibrary();
    135 // }
    136 // static __thread void*  g_saved_fp;
    137 // void Call_SomeLibrary() {
    138 //   g_saved_fp = __builtin_frame_address(0);
    139 //   some_library_call(...); // indirectly calls SomeLibrary_Callback()
    140 // }
    141 // void SomeLibrary_Callback() {
    142 //   ScopedStackFrameLinker linker(__builtin_frame_address(0), g_saved_fp);
    143 //   ...
    144 //   TraceStackFramePointers(...);
    145 // }
    146 //
    147 // This produces the following trace:
    148 //
    149 // #0 SomeLibrary_Callback()
    150 // #1 <address of the code inside SomeLibrary that called #0>
    151 // #2 DoWork()
    152 // ...rest of the trace...
    153 //
    154 // SomeLibrary doesn't use frame pointers, so when SomeLibrary_Callback()
    155 // is called, stack frame register contains bogus value that becomes callback'
    156 // parent frame address. Without ScopedStackFrameLinker unwinding would've
    157 // stopped at that bogus frame address yielding just two first frames (#0, #1).
    158 // ScopedStackFrameLinker overwrites callback's parent frame address with
    159 // Call_SomeLibrary's frame, so unwinder produces full trace without even
    160 // noticing that stack frame chain was broken.
    161 class BASE_EXPORT ScopedStackFrameLinker {
    162  public:
    163   ScopedStackFrameLinker(void* fp, void* parent_fp);
    164   ~ScopedStackFrameLinker();
    165 
    166  private:
    167   void* fp_;
    168   void* parent_fp_;
    169   void* original_parent_fp_;
    170 
    171   DISALLOW_COPY_AND_ASSIGN(ScopedStackFrameLinker);
    172 };
    173 
    174 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
    175 
    176 namespace internal {
    177 
    178 #if defined(OS_POSIX) && !defined(OS_ANDROID)
    179 // POSIX doesn't define any async-signal safe function for converting
    180 // an integer to ASCII. We'll have to define our own version.
    181 // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
    182 // conversion was successful or NULL otherwise. It never writes more than "sz"
    183 // bytes. Output will be truncated as needed, and a NUL character is always
    184 // appended.
    185 BASE_EXPORT char *itoa_r(intptr_t i,
    186                          char *buf,
    187                          size_t sz,
    188                          int base,
    189                          size_t padding);
    190 #endif  // defined(OS_POSIX) && !defined(OS_ANDROID)
    191 
    192 }  // namespace internal
    193 
    194 }  // namespace debug
    195 }  // namespace base
    196 
    197 #endif  // BASE_DEBUG_STACK_TRACE_H_
    198