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 "base/strings/cstring_view.h" 18 #include "build/build_config.h" 19 20 #if BUILDFLAG(IS_POSIX) 21 #if !BUILDFLAG(IS_NACL) 22 #include <signal.h> 23 #endif 24 #include <unistd.h> 25 #endif 26 27 #if BUILDFLAG(IS_WIN) 28 struct _EXCEPTION_POINTERS; 29 struct _CONTEXT; 30 #endif 31 32 namespace base::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 // LINT.IfChange(max_stack_frames) 69 #if BUILDFLAG(IS_ANDROID) 70 // TODO(crbug.com/41437515): Testing indicates that Android has issues 71 // with a larger value here, so leave Android at 62. 72 static constexpr size_t kMaxTraces = 62; 73 #else 74 // For other platforms, use 250. This seems reasonable without 75 // being huge. 76 static constexpr size_t kMaxTraces = 250; 77 #endif 78 // LINT.ThenChange(dwarf_line_no.cc:max_stack_frames) 79 80 // Creates a stacktrace from the current location. 81 StackTrace(); 82 83 // Creates a stacktrace from the current location, of up to |count| entries. 84 // |count| will be limited to at most |kMaxTraces|. 85 explicit StackTrace(size_t count); 86 87 // Creates a stacktrace from an existing array of instruction pointers (such 88 // as returned by Addresses()). Only the first `kMaxTraces` of the span will 89 // be used. 90 explicit StackTrace(span<const void* const> trace); 91 92 #if BUILDFLAG(IS_WIN) 93 // Creates a stacktrace for an exception. 94 // Note: this function will throw an import not found (StackWalk64) exception 95 // on system without dbghelp 5.1. 96 StackTrace(_EXCEPTION_POINTERS* exception_pointers); 97 StackTrace(const _CONTEXT* context); 98 #endif 99 100 // Returns true if this current test environment is expected to have 101 // symbolized frames when printing a stack trace. 102 static bool WillSymbolizeToStreamForTesting(); 103 104 // Copying and assignment are allowed with the default functions. 105 106 // Gets an array of instruction pointer values. |*count| will be set to the 107 // number of elements in the returned array. Addresses()[0] will contain an 108 // address from the leaf function, and Addresses()[count-1] will contain an 109 // address from the root function (i.e.; the thread's entry point). addresses()110 span<const void* const> addresses() const { 111 return span(trace_).first(count_); 112 } 113 114 // Prints the stack trace to stderr. 115 void Print() const; 116 117 // Prints the stack trace to stderr, prepending the given string before 118 // each output line. 119 void PrintWithPrefix(cstring_view prefix_string) const; 120 121 #if !defined(__UCLIBC__) && !defined(_AIX) 122 // Resolves backtrace to symbols and write to stream. 123 void OutputToStream(std::ostream* os) const; 124 // Resolves backtrace to symbols and write to stream, with the provided 125 // prefix string prepended to each line. 126 void OutputToStreamWithPrefix(std::ostream* os, 127 cstring_view prefix_string) const; 128 #endif 129 130 // Resolves backtrace to symbols and returns as string. 131 std::string ToString() const; 132 133 // Resolves backtrace to symbols and returns as string, prepending the 134 // provided prefix string to each line. 135 std::string ToStringWithPrefix(cstring_view prefix_string) const; 136 137 // Sets a message to be emitted in place of symbolized stack traces. When 138 // such a message is provided, collection and symbolization of stack traces 139 // is suppressed. Suppression is cancelled if `message` is empty. 140 static void SuppressStackTracesWithMessageForTesting(std::string message); 141 142 private: 143 // Prints `message` with an optional prefix. 144 static void PrintMessageWithPrefix(cstring_view prefix_string, 145 cstring_view message); 146 147 void PrintWithPrefixImpl(cstring_view prefix_string) const; 148 #if !defined(__UCLIBC__) && !defined(_AIX) 149 void OutputToStreamWithPrefixImpl(std::ostream* os, 150 cstring_view prefix_string) const; 151 #endif 152 153 // Returns true if generation of symbolized stack traces is to be suppressed. 154 static bool ShouldSuppressOutput(); 155 156 #if BUILDFLAG(IS_WIN) 157 void InitTrace(const _CONTEXT* context_record); 158 #endif 159 160 std::array<const void*, kMaxTraces> trace_; 161 162 // The number of valid frames in |trace_|, or 0 if collection was suppressed. 163 size_t count_ = 0; 164 }; 165 166 // Forwards to StackTrace::OutputToStream(). 167 BASE_EXPORT std::ostream& operator<<(std::ostream& os, const StackTrace& s); 168 169 // Record a stack trace with up to |count| frames into |trace|. Returns the 170 // number of frames read. 171 BASE_EXPORT size_t CollectStackTrace(span<const void*> trace); 172 173 // A helper for tests that must either override the default suppression of 174 // symbolized stack traces in death tests, or the default generation of them in 175 // normal tests. 176 class BASE_EXPORT OverrideStackTraceOutputForTesting { 177 public: 178 enum class Mode { 179 kUnset, 180 kForceOutput, 181 kSuppressOutput, 182 }; 183 explicit OverrideStackTraceOutputForTesting(Mode mode); 184 OverrideStackTraceOutputForTesting( 185 const OverrideStackTraceOutputForTesting&) = delete; 186 OverrideStackTraceOutputForTesting& operator=( 187 const OverrideStackTraceOutputForTesting&) = delete; 188 ~OverrideStackTraceOutputForTesting(); 189 }; 190 191 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) 192 193 // For stack scanning to be efficient it's very important for the thread to 194 // be started by Chrome. In that case we naturally terminate unwinding once 195 // we reach the origin of the stack (i.e. GetStackEnd()). If the thread is 196 // not started by Chrome (e.g. Android's main thread), then we end up always 197 // scanning area at the origin of the stack, wasting time and not finding any 198 // frames (since Android libraries don't have frame pointers). Scanning is not 199 // enabled on other posix platforms due to legacy reasons. 200 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) 201 constexpr bool kEnableScanningByDefault = true; 202 #else 203 constexpr bool kEnableScanningByDefault = false; 204 #endif 205 206 // Traces the stack by using frame pointers. This function is faster but less 207 // reliable than StackTrace. It should work for debug and profiling builds, 208 // but not for release builds (although there are some exceptions). 209 // 210 // Writes at most |max_depth| frames (instruction pointers) into |out_trace| 211 // after skipping |skip_initial| frames. Note that the function itself is not 212 // added to the trace so |skip_initial| should be 0 in most cases. 213 // Returns number of frames written. |enable_scanning| enables scanning on 214 // platforms that do not enable scanning by default. 215 BASE_EXPORT size_t 216 TraceStackFramePointers(span<const void*> out_trace, 217 size_t skip_initial, 218 bool enable_scanning = kEnableScanningByDefault); 219 220 // Links stack frame |fp| to |parent_fp|, so that during stack unwinding 221 // TraceStackFramePointers() visits |parent_fp| after visiting |fp|. 222 // Both frame pointers must come from __builtin_frame_address(). 223 // Destructor restores original linkage of |fp| to avoid corrupting caller's 224 // frame register on return. 225 // 226 // This class can be used to repair broken stack frame chain in cases 227 // when execution flow goes into code built without frame pointers: 228 // 229 // void DoWork() { 230 // Call_SomeLibrary(); 231 // } 232 // static __thread void* g_saved_fp; 233 // void Call_SomeLibrary() { 234 // g_saved_fp = __builtin_frame_address(0); 235 // some_library_call(...); // indirectly calls SomeLibrary_Callback() 236 // } 237 // void SomeLibrary_Callback() { 238 // ScopedStackFrameLinker linker(__builtin_frame_address(0), g_saved_fp); 239 // ... 240 // TraceStackFramePointers(...); 241 // } 242 // 243 // This produces the following trace: 244 // 245 // #0 SomeLibrary_Callback() 246 // #1 <address of the code inside SomeLibrary that called #0> 247 // #2 DoWork() 248 // ...rest of the trace... 249 // 250 // SomeLibrary doesn't use frame pointers, so when SomeLibrary_Callback() 251 // is called, stack frame register contains bogus value that becomes callback' 252 // parent frame address. Without ScopedStackFrameLinker unwinding would've 253 // stopped at that bogus frame address yielding just two first frames (#0, #1). 254 // ScopedStackFrameLinker overwrites callback's parent frame address with 255 // Call_SomeLibrary's frame, so unwinder produces full trace without even 256 // noticing that stack frame chain was broken. 257 class BASE_EXPORT ScopedStackFrameLinker { 258 public: 259 ScopedStackFrameLinker(void* fp, void* parent_fp); 260 261 ScopedStackFrameLinker(const ScopedStackFrameLinker&) = delete; 262 ScopedStackFrameLinker& operator=(const ScopedStackFrameLinker&) = delete; 263 264 ~ScopedStackFrameLinker(); 265 266 private: 267 raw_ptr<void> fp_; 268 raw_ptr<void> parent_fp_; 269 raw_ptr<void> original_parent_fp_; 270 }; 271 272 #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) 273 274 namespace internal { 275 276 #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) 277 // POSIX doesn't define any async-signal safe function for converting 278 // an integer to ASCII. We'll have to define our own version. 279 // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the 280 // conversion was successful or NULL otherwise. It never writes more than "sz" 281 // bytes. Output will be truncated as needed, and a NUL character is always 282 // appended. 283 BASE_EXPORT void itoa_r(intptr_t i, 284 int base, 285 size_t padding, 286 base::span<char> buf); 287 #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) 288 289 } // namespace internal 290 291 } // namespace base::debug 292 293 #endif // BASE_DEBUG_STACK_TRACE_H_ 294