1 // Copyright 2012 The Chromium Authors 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/containers/span.h" 15 #include "base/debug/debugging_buildflags.h" 16 #include "base/memory/raw_ptr.h" 17 #include "build/build_config.h" 18 19 #if BUILDFLAG(IS_POSIX) 20 #if !BUILDFLAG(IS_NACL) 21 #include <signal.h> 22 #endif 23 #include <unistd.h> 24 #endif 25 26 #if BUILDFLAG(IS_WIN) 27 struct _EXCEPTION_POINTERS; 28 struct _CONTEXT; 29 #endif 30 31 namespace base { 32 namespace debug { 33 34 // Enables stack dump to console output on exception and signals. 35 // When enabled, the process will quit immediately. This is meant to be used in 36 // unit_tests only! This is not thread-safe: only call from main thread. 37 // In sandboxed processes, this has to be called before the sandbox is turned 38 // on. 39 // Calling this function on Linux opens /proc/self/maps and caches its 40 // contents. In non-official builds, this function also opens the object files 41 // that are loaded in memory and caches their file descriptors (this cannot be 42 // done in official builds because it has security implications). 43 BASE_EXPORT bool EnableInProcessStackDumping(); 44 45 #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_NACL) 46 // Sets a first-chance callback for the stack dump signal handler. This callback 47 // is called at the beginning of the signal handler to handle special kinds of 48 // signals, like out-of-bounds memory accesses in WebAssembly (WebAssembly Trap 49 // Handler). 50 // {SetStackDumpFirstChanceCallback} returns {true} if the callback 51 // has been set correctly. It returns {false} if the stack dump signal handler 52 // has not been registered with the OS, e.g. because of ASAN. 53 BASE_EXPORT bool SetStackDumpFirstChanceCallback(bool (*handler)(int, 54 siginfo_t*, 55 void*)); 56 #endif 57 58 // Returns end of the stack, or 0 if we couldn't get it. 59 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) 60 BASE_EXPORT uintptr_t GetStackEnd(); 61 #endif 62 63 // A stacktrace can be helpful in debugging. For example, you can include a 64 // stacktrace member in a object (probably around #ifndef NDEBUG) so that you 65 // can later see where the given object was created from. 66 class BASE_EXPORT StackTrace { 67 public: 68 #if BUILDFLAG(IS_ANDROID) 69 // TODO(https://crbug.com/925525): Testing indicates that Android has issues 70 // with a larger value here, so leave Android at 62. 71 static constexpr size_t kMaxTraces = 62; 72 #else 73 // For other platforms, use 250. This seems reasonable without 74 // being huge. 75 static constexpr size_t kMaxTraces = 250; 76 #endif 77 78 // Creates a stacktrace from the current location. 79 StackTrace(); 80 81 // Creates a stacktrace from the current location, of up to |count| entries. 82 // |count| will be limited to at most |kMaxTraces|. 83 explicit StackTrace(size_t count); 84 85 // Creates a stacktrace from an existing array of instruction 86 // pointers (such as returned by Addresses()). |count| will be 87 // limited to at most |kMaxTraces|. 88 StackTrace(const void* const* trace, size_t count); 89 90 #if BUILDFLAG(IS_WIN) 91 // Creates a stacktrace for an exception. 92 // Note: this function will throw an import not found (StackWalk64) exception 93 // on system without dbghelp 5.1. 94 StackTrace(_EXCEPTION_POINTERS* exception_pointers); 95 StackTrace(const _CONTEXT* context); 96 #endif 97 98 // Returns true if this current test environment is expected to have 99 // symbolized frames when printing a stack trace. 100 static bool WillSymbolizeToStreamForTesting(); 101 102 // Copying and assignment are allowed with the default functions. 103 104 // Gets an array of instruction pointer values. |*count| will be set to the 105 // number of elements in the returned array. Addresses()[0] will contain an 106 // address from the leaf function, and Addresses()[count-1] will contain an 107 // address from the root function (i.e.; the thread's entry point). addresses()108 span<const void* const> addresses() const { 109 return make_span(trace_, count_); 110 } 111 112 // Prints the stack trace to stderr. 113 void Print() const; 114 115 // Prints the stack trace to stderr, prepending the given string before 116 // each output line. 117 void PrintWithPrefix(const char* prefix_string) const; 118 119 #if !defined(__UCLIBC__) && !defined(_AIX) 120 // Resolves backtrace to symbols and write to stream. 121 void OutputToStream(std::ostream* os) const; 122 // Resolves backtrace to symbols and write to stream, with the provided 123 // prefix string prepended to each line. 124 void OutputToStreamWithPrefix(std::ostream* os, 125 const char* prefix_string) const; 126 #endif 127 128 // Resolves backtrace to symbols and returns as string. 129 std::string ToString() const; 130 131 // Resolves backtrace to symbols and returns as string, prepending the 132 // provided prefix string to each line. 133 std::string ToStringWithPrefix(const char* prefix_string) const; 134 135 private: 136 #if BUILDFLAG(IS_WIN) 137 void InitTrace(const _CONTEXT* context_record); 138 #endif 139 140 const void* trace_[kMaxTraces]; 141 142 // The number of valid frames in |trace_|. 143 size_t count_; 144 }; 145 146 // Forwards to StackTrace::OutputToStream(). 147 BASE_EXPORT std::ostream& operator<<(std::ostream& os, const StackTrace& s); 148 149 // Record a stack trace with up to |count| frames into |trace|. Returns the 150 // number of frames read. 151 BASE_EXPORT size_t CollectStackTrace(const void** trace, size_t count); 152 153 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) 154 155 // For stack scanning to be efficient it's very important for the thread to 156 // be started by Chrome. In that case we naturally terminate unwinding once 157 // we reach the origin of the stack (i.e. GetStackEnd()). If the thread is 158 // not started by Chrome (e.g. Android's main thread), then we end up always 159 // scanning area at the origin of the stack, wasting time and not finding any 160 // frames (since Android libraries don't have frame pointers). Scanning is not 161 // enabled on other posix platforms due to legacy reasons. 162 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) 163 constexpr bool kEnableScanningByDefault = true; 164 #else 165 constexpr bool kEnableScanningByDefault = false; 166 #endif 167 168 // Traces the stack by using frame pointers. This function is faster but less 169 // reliable than StackTrace. It should work for debug and profiling builds, 170 // but not for release builds (although there are some exceptions). 171 // 172 // Writes at most |max_depth| frames (instruction pointers) into |out_trace| 173 // after skipping |skip_initial| frames. Note that the function itself is not 174 // added to the trace so |skip_initial| should be 0 in most cases. 175 // Returns number of frames written. |enable_scanning| enables scanning on 176 // platforms that do not enable scanning by default. 177 BASE_EXPORT size_t 178 TraceStackFramePointers(const void** out_trace, 179 size_t max_depth, 180 size_t skip_initial, 181 bool enable_scanning = kEnableScanningByDefault); 182 183 // Same as above function, but allows to pass in frame pointer and stack end 184 // address for unwinding. This is useful when unwinding based on a copied stack 185 // segment. Note that the client has to take care of rewriting all the pointers 186 // in the stack pointing within the stack to point to the copied addresses. 187 BASE_EXPORT size_t TraceStackFramePointersFromBuffer( 188 uintptr_t fp, 189 uintptr_t stack_end, 190 const void** out_trace, 191 size_t max_depth, 192 size_t skip_initial, 193 bool enable_scanning = kEnableScanningByDefault); 194 195 // Links stack frame |fp| to |parent_fp|, so that during stack unwinding 196 // TraceStackFramePointers() visits |parent_fp| after visiting |fp|. 197 // Both frame pointers must come from __builtin_frame_address(). 198 // Destructor restores original linkage of |fp| to avoid corrupting caller's 199 // frame register on return. 200 // 201 // This class can be used to repair broken stack frame chain in cases 202 // when execution flow goes into code built without frame pointers: 203 // 204 // void DoWork() { 205 // Call_SomeLibrary(); 206 // } 207 // static __thread void* g_saved_fp; 208 // void Call_SomeLibrary() { 209 // g_saved_fp = __builtin_frame_address(0); 210 // some_library_call(...); // indirectly calls SomeLibrary_Callback() 211 // } 212 // void SomeLibrary_Callback() { 213 // ScopedStackFrameLinker linker(__builtin_frame_address(0), g_saved_fp); 214 // ... 215 // TraceStackFramePointers(...); 216 // } 217 // 218 // This produces the following trace: 219 // 220 // #0 SomeLibrary_Callback() 221 // #1 <address of the code inside SomeLibrary that called #0> 222 // #2 DoWork() 223 // ...rest of the trace... 224 // 225 // SomeLibrary doesn't use frame pointers, so when SomeLibrary_Callback() 226 // is called, stack frame register contains bogus value that becomes callback' 227 // parent frame address. Without ScopedStackFrameLinker unwinding would've 228 // stopped at that bogus frame address yielding just two first frames (#0, #1). 229 // ScopedStackFrameLinker overwrites callback's parent frame address with 230 // Call_SomeLibrary's frame, so unwinder produces full trace without even 231 // noticing that stack frame chain was broken. 232 class BASE_EXPORT ScopedStackFrameLinker { 233 public: 234 ScopedStackFrameLinker(void* fp, void* parent_fp); 235 236 ScopedStackFrameLinker(const ScopedStackFrameLinker&) = delete; 237 ScopedStackFrameLinker& operator=(const ScopedStackFrameLinker&) = delete; 238 239 ~ScopedStackFrameLinker(); 240 241 private: 242 raw_ptr<void> fp_; 243 raw_ptr<void> parent_fp_; 244 raw_ptr<void> original_parent_fp_; 245 }; 246 247 #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) 248 249 namespace internal { 250 251 #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) 252 // POSIX doesn't define any async-signal safe function for converting 253 // an integer to ASCII. We'll have to define our own version. 254 // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the 255 // conversion was successful or NULL otherwise. It never writes more than "sz" 256 // bytes. Output will be truncated as needed, and a NUL character is always 257 // appended. 258 BASE_EXPORT char *itoa_r(intptr_t i, 259 char *buf, 260 size_t sz, 261 int base, 262 size_t padding); 263 #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) 264 265 } // namespace internal 266 267 } // namespace debug 268 } // namespace base 269 270 #endif // BASE_DEBUG_STACK_TRACE_H_ 271