blob: 8b4ca96b9e0f99e2d9a26cf11974a90d521653db [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
[email protected]58580352010-10-26 04:07:502// 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_
[email protected]58580352010-10-26 04:07:507
aviebe805c2015-12-24 08:20:288#include <stddef.h>
9
Lei Zhang4493f552025-06-14 06:11:3110#include <array>
[email protected]58580352010-10-26 04:07:5011#include <iosfwd>
[email protected]d4114ba2011-10-12 16:13:4012#include <string>
[email protected]58580352010-10-26 04:07:5013
[email protected]0bea7252011-08-05 15:34:0014#include "base/base_export.h"
Daniel Chenga0e290d2023-10-16 18:47:2415#include "base/containers/span.h"
Scott Violet44165792018-02-22 02:08:0816#include "base/debug/debugging_buildflags.h"
Keishi Hattorif28f4f82022-06-21 11:32:1517#include "base/memory/raw_ptr.h"
Greg Thompsonc82cbc92024-04-10 07:36:0618#include "base/strings/cstring_view.h"
[email protected]58580352010-10-26 04:07:5019#include "build/build_config.h"
20
Xiaohan Wang131aa4d2022-01-15 19:39:4121#if BUILDFLAG(IS_POSIX)
Andreas Haas54c0c022019-06-14 17:33:5322#include <signal.h>
[email protected]47c45562012-11-17 14:33:2523#include <unistd.h>
24#endif
25
Xiaohan Wang131aa4d2022-01-15 19:39:4126#if BUILDFLAG(IS_WIN)
[email protected]58580352010-10-26 04:07:5027struct _EXCEPTION_POINTERS;
wittman7808da72015-02-03 17:46:5128struct _CONTEXT;
[email protected]58580352010-10-26 04:07:5029#endif
30
Jan Keitel4161bcb2024-08-01 12:44:2431namespace base::debug {
[email protected]58580352010-10-26 04:07:5032
[email protected]11b93faa2012-11-01 21:58:3033// Enables stack dump to console output on exception and signals.
34// When enabled, the process will quit immediately. This is meant to be used in
35// unit_tests only! This is not thread-safe: only call from main thread.
jam79dc59a2015-08-17 03:38:1636// In sandboxed processes, this has to be called before the sandbox is turned
37// on.
[email protected]ad9a0122014-03-22 00:34:5238// Calling this function on Linux opens /proc/self/maps and caches its
jam79dc59a2015-08-17 03:38:1639// contents. In non-official builds, this function also opens the object files
40// that are loaded in memory and caches their file descriptors (this cannot be
[email protected]ad9a0122014-03-22 00:34:5241// done in official builds because it has security implications).
jam79dc59a2015-08-17 03:38:1642BASE_EXPORT bool EnableInProcessStackDumping();
[email protected]ad9a0122014-03-22 00:34:5243
Alex Goughd007d622025-09-11 17:55:4944#if BUILDFLAG(IS_WIN)
45// Returns `true` if EnableInProcessStackDumping() was called and succeeded.
46// Only supported on Windows.
47BASE_EXPORT bool InProcessStackDumpingEnabled();
Alex Gough0bbe87d2025-09-12 21:12:1148
49// Allows tests to exercise code that runs when symbolization is not available.
50BASE_EXPORT bool DisableInProcessStackDumpingForTesting();
Alex Goughd007d622025-09-11 17:55:4951#endif // BUILDFLAG(IS_WIN)
52
Nico Weber6f2d26d2025-06-27 07:32:0853#if BUILDFLAG(IS_POSIX)
Andreas Haasef19d592019-04-30 18:16:5154// Sets a first-chance callback for the stack dump signal handler. This callback
55// is called at the beginning of the signal handler to handle special kinds of
56// signals, like out-of-bounds memory accesses in WebAssembly (WebAssembly Trap
57// Handler).
58// {SetStackDumpFirstChanceCallback} returns {true} if the callback
59// has been set correctly. It returns {false} if the stack dump signal handler
60// has not been registered with the OS, e.g. because of ASAN.
61BASE_EXPORT bool SetStackDumpFirstChanceCallback(bool (*handler)(int,
Andreas Haas54c0c022019-06-14 17:33:5362 siginfo_t*,
Eric Holkdc499db2017-07-17 17:57:3563 void*));
64#endif
65
erikchend6b2b822017-02-22 21:10:3166// Returns end of the stack, or 0 if we couldn't get it.
erikchenf7c8a0d2017-04-06 21:15:2767#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
erikchend6b2b822017-02-22 21:10:3168BASE_EXPORT uintptr_t GetStackEnd();
69#endif
70
[email protected]58580352010-10-26 04:07:5071// A stacktrace can be helpful in debugging. For example, you can include a
72// stacktrace member in a object (probably around #ifndef NDEBUG) so that you
73// can later see where the given object was created from.
[email protected]0bea7252011-08-05 15:34:0074class BASE_EXPORT StackTrace {
[email protected]58580352010-10-26 04:07:5075 public:
Daniel Cheng42dd8442024-03-05 22:14:1176 // LINT.IfChange(max_stack_frames)
Daniel Cheng1e96ff32023-06-26 20:01:0177#if BUILDFLAG(IS_ANDROID)
Alison Galed94ce4f2024-04-22 15:20:3978 // TODO(crbug.com/41437515): Testing indicates that Android has issues
Daniel Cheng1e96ff32023-06-26 20:01:0179 // with a larger value here, so leave Android at 62.
80 static constexpr size_t kMaxTraces = 62;
81#else
82 // For other platforms, use 250. This seems reasonable without
83 // being huge.
84 static constexpr size_t kMaxTraces = 250;
85#endif
Daniel Cheng42dd8442024-03-05 22:14:1186 // LINT.ThenChange(dwarf_line_no.cc:max_stack_frames)
Daniel Cheng1e96ff32023-06-26 20:01:0187
[email protected]58580352010-10-26 04:07:5088 // Creates a stacktrace from the current location.
89 StackTrace();
90
wez73f8d7e2017-01-29 06:18:1391 // Creates a stacktrace from the current location, of up to |count| entries.
92 // |count| will be limited to at most |kMaxTraces|.
93 explicit StackTrace(size_t count);
94
danakje75c6c812024-07-26 20:37:4795 // Creates a stacktrace from an existing array of instruction pointers (such
96 // as returned by Addresses()). Only the first `kMaxTraces` of the span will
97 // be used.
98 explicit StackTrace(span<const void* const> trace);
[email protected]f01ae9812011-08-30 19:33:0499
Xiaohan Wang131aa4d2022-01-15 19:39:41100#if BUILDFLAG(IS_WIN)
[email protected]58580352010-10-26 04:07:50101 // Creates a stacktrace for an exception.
102 // Note: this function will throw an import not found (StackWalk64) exception
103 // on system without dbghelp 5.1.
jam79dc59a2015-08-17 03:38:16104 StackTrace(_EXCEPTION_POINTERS* exception_pointers);
rnk0565cdd62015-10-06 16:48:30105 StackTrace(const _CONTEXT* context);
[email protected]58580352010-10-26 04:07:50106#endif
107
Gabriel Charetteae1bb012021-05-06 19:31:21108 // Returns true if this current test environment is expected to have
109 // symbolized frames when printing a stack trace.
110 static bool WillSymbolizeToStreamForTesting();
111
Xiyuan Xiae9dc9d42025-09-25 16:14:13112 // Initialize features.
113 static void InitializeFeatures();
114
[email protected]58580352010-10-26 04:07:50115 // Copying and assignment are allowed with the default functions.
116
[email protected]58580352010-10-26 04:07:50117 // Gets an array of instruction pointer values. |*count| will be set to the
Bruce Dawson19e29bb2020-01-06 21:20:14118 // number of elements in the returned array. Addresses()[0] will contain an
119 // address from the leaf function, and Addresses()[count-1] will contain an
120 // address from the root function (i.e.; the thread's entry point).
Daniel Chenga0e290d2023-10-16 18:47:24121 span<const void* const> addresses() const {
Jan Keitel4161bcb2024-08-01 12:44:24122 return span(trace_).first(count_);
Daniel Chenga0e290d2023-10-16 18:47:24123 }
[email protected]58580352010-10-26 04:07:50124
[email protected]5ddbf1c2013-08-29 01:59:38125 // Prints the stack trace to stderr.
126 void Print() const;
[email protected]58580352010-10-26 04:07:50127
Mason Freedb9ef2b62018-09-10 17:17:27128 // Prints the stack trace to stderr, prepending the given string before
129 // each output line.
Greg Thompson8b1b295b2024-04-10 07:44:14130 void PrintWithPrefix(cstring_view prefix_string) const;
Mason Freedb9ef2b62018-09-10 17:17:27131
Gabriel Charetteae1bb012021-05-06 19:31:21132#if !defined(__UCLIBC__) && !defined(_AIX)
[email protected]58580352010-10-26 04:07:50133 // Resolves backtrace to symbols and write to stream.
[email protected]501dfc42011-04-14 16:34:00134 void OutputToStream(std::ostream* os) const;
Mason Freedb9ef2b62018-09-10 17:17:27135 // Resolves backtrace to symbols and write to stream, with the provided
136 // prefix string prepended to each line.
137 void OutputToStreamWithPrefix(std::ostream* os,
Greg Thompson8b1b295b2024-04-10 07:44:14138 cstring_view prefix_string) const;
[email protected]816e50452014-04-09 22:29:38139#endif
[email protected]58580352010-10-26 04:07:50140
[email protected]d4114ba2011-10-12 16:13:40141 // Resolves backtrace to symbols and returns as string.
142 std::string ToString() const;
143
Mason Freedb9ef2b62018-09-10 17:17:27144 // Resolves backtrace to symbols and returns as string, prepending the
145 // provided prefix string to each line.
Greg Thompson8b1b295b2024-04-10 07:44:14146 std::string ToStringWithPrefix(cstring_view prefix_string) const;
Mason Freedb9ef2b62018-09-10 17:17:27147
Greg Thompsonc82cbc92024-04-10 07:36:06148 // Sets a message to be emitted in place of symbolized stack traces. When
149 // such a message is provided, collection and symbolization of stack traces
150 // is suppressed. Suppression is cancelled if `message` is empty.
151 static void SuppressStackTracesWithMessageForTesting(std::string message);
152
[email protected]58580352010-10-26 04:07:50153 private:
Greg Thompsonc82cbc92024-04-10 07:36:06154 // Prints `message` with an optional prefix.
Greg Thompson8b1b295b2024-04-10 07:44:14155 static void PrintMessageWithPrefix(cstring_view prefix_string,
Greg Thompsonc82cbc92024-04-10 07:36:06156 cstring_view message);
157
Greg Thompson8b1b295b2024-04-10 07:44:14158 void PrintWithPrefixImpl(cstring_view prefix_string) const;
Greg Thompsonc82cbc92024-04-10 07:36:06159#if !defined(__UCLIBC__) && !defined(_AIX)
160 void OutputToStreamWithPrefixImpl(std::ostream* os,
Greg Thompson8b1b295b2024-04-10 07:44:14161 cstring_view prefix_string) const;
Greg Thompsonc82cbc92024-04-10 07:36:06162#endif
163
Greg Thompson75724f92024-03-21 08:31:27164 // Returns true if generation of symbolized stack traces is to be suppressed.
165 static bool ShouldSuppressOutput();
166
Xiaohan Wang131aa4d2022-01-15 19:39:41167#if BUILDFLAG(IS_WIN)
rnk0565cdd62015-10-06 16:48:30168 void InitTrace(const _CONTEXT* context_record);
wittman7808da72015-02-03 17:46:51169#endif
170
Jan Keitel4161bcb2024-08-01 12:44:24171 std::array<const void*, kMaxTraces> trace_;
[email protected]e645c7a2012-07-25 21:43:44172
Greg Thompson75724f92024-03-21 08:31:27173 // The number of valid frames in |trace_|, or 0 if collection was suppressed.
174 size_t count_ = 0;
[email protected]58580352010-10-26 04:07:50175};
176
Gabriel Charettec41da4512019-02-22 02:07:10177// Forwards to StackTrace::OutputToStream().
178BASE_EXPORT std::ostream& operator<<(std::ostream& os, const StackTrace& s);
179
Vlad Tsyrklevich2788d59962019-01-23 03:32:45180// Record a stack trace with up to |count| frames into |trace|. Returns the
181// number of frames read.
danakje75c6c812024-07-26 20:37:47182BASE_EXPORT size_t CollectStackTrace(span<const void*> trace);
Vlad Tsyrklevich2788d59962019-01-23 03:32:45183
Greg Thompson75724f92024-03-21 08:31:27184// A helper for tests that must either override the default suppression of
185// symbolized stack traces in death tests, or the default generation of them in
186// normal tests.
187class BASE_EXPORT OverrideStackTraceOutputForTesting {
Greg Thompsona6e88c12024-03-13 16:37:13188 public:
Greg Thompson75724f92024-03-21 08:31:27189 enum class Mode {
190 kUnset,
191 kForceOutput,
192 kSuppressOutput,
193 };
194 explicit OverrideStackTraceOutputForTesting(Mode mode);
195 OverrideStackTraceOutputForTesting(
196 const OverrideStackTraceOutputForTesting&) = delete;
197 OverrideStackTraceOutputForTesting& operator=(
198 const OverrideStackTraceOutputForTesting&) = delete;
199 ~OverrideStackTraceOutputForTesting();
Greg Thompsona6e88c12024-03-13 16:37:13200};
201
erikchenf7c8a0d2017-04-06 21:15:27202#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
ssidc1d5a3d2020-09-11 05:20:30203
204// For stack scanning to be efficient it's very important for the thread to
205// be started by Chrome. In that case we naturally terminate unwinding once
206// we reach the origin of the stack (i.e. GetStackEnd()). If the thread is
207// not started by Chrome (e.g. Android's main thread), then we end up always
208// scanning area at the origin of the stack, wasting time and not finding any
209// frames (since Android libraries don't have frame pointers). Scanning is not
210// enabled on other posix platforms due to legacy reasons.
Xiaohan Wang131aa4d2022-01-15 19:39:41211#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
ssidc1d5a3d2020-09-11 05:20:30212constexpr bool kEnableScanningByDefault = true;
213#else
214constexpr bool kEnableScanningByDefault = false;
215#endif
216
dskiba79080da02016-04-23 00:10:27217// Traces the stack by using frame pointers. This function is faster but less
218// reliable than StackTrace. It should work for debug and profiling builds,
219// but not for release builds (although there are some exceptions).
220//
221// Writes at most |max_depth| frames (instruction pointers) into |out_trace|
222// after skipping |skip_initial| frames. Note that the function itself is not
223// added to the trace so |skip_initial| should be 0 in most cases.
ssidc1d5a3d2020-09-11 05:20:30224// Returns number of frames written. |enable_scanning| enables scanning on
225// platforms that do not enable scanning by default.
226BASE_EXPORT size_t
danakje75c6c812024-07-26 20:37:47227TraceStackFramePointers(span<const void*> out_trace,
ssidc1d5a3d2020-09-11 05:20:30228 size_t skip_initial,
229 bool enable_scanning = kEnableScanningByDefault);
230
dskibaa8c951e2016-10-25 23:39:11231// Links stack frame |fp| to |parent_fp|, so that during stack unwinding
232// TraceStackFramePointers() visits |parent_fp| after visiting |fp|.
233// Both frame pointers must come from __builtin_frame_address().
234// Destructor restores original linkage of |fp| to avoid corrupting caller's
235// frame register on return.
236//
237// This class can be used to repair broken stack frame chain in cases
238// when execution flow goes into code built without frame pointers:
239//
240// void DoWork() {
241// Call_SomeLibrary();
242// }
243// static __thread void* g_saved_fp;
244// void Call_SomeLibrary() {
245// g_saved_fp = __builtin_frame_address(0);
246// some_library_call(...); // indirectly calls SomeLibrary_Callback()
247// }
248// void SomeLibrary_Callback() {
249// ScopedStackFrameLinker linker(__builtin_frame_address(0), g_saved_fp);
250// ...
251// TraceStackFramePointers(...);
252// }
253//
254// This produces the following trace:
255//
256// #0 SomeLibrary_Callback()
257// #1 <address of the code inside SomeLibrary that called #0>
258// #2 DoWork()
259// ...rest of the trace...
260//
261// SomeLibrary doesn't use frame pointers, so when SomeLibrary_Callback()
262// is called, stack frame register contains bogus value that becomes callback'
263// parent frame address. Without ScopedStackFrameLinker unwinding would've
264// stopped at that bogus frame address yielding just two first frames (#0, #1).
265// ScopedStackFrameLinker overwrites callback's parent frame address with
266// Call_SomeLibrary's frame, so unwinder produces full trace without even
267// noticing that stack frame chain was broken.
268class BASE_EXPORT ScopedStackFrameLinker {
269 public:
270 ScopedStackFrameLinker(void* fp, void* parent_fp);
Peter Boström7319bbd2021-09-15 22:59:38271
272 ScopedStackFrameLinker(const ScopedStackFrameLinker&) = delete;
273 ScopedStackFrameLinker& operator=(const ScopedStackFrameLinker&) = delete;
274
dskibaa8c951e2016-10-25 23:39:11275 ~ScopedStackFrameLinker();
276
277 private:
Keishi Hattorif28f4f82022-06-21 11:32:15278 raw_ptr<void> fp_;
279 raw_ptr<void> parent_fp_;
280 raw_ptr<void> original_parent_fp_;
dskibaa8c951e2016-10-25 23:39:11281};
282
erikchenf7c8a0d2017-04-06 21:15:27283#endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
dskiba79080da02016-04-23 00:10:27284
[email protected]1e218b72012-11-14 19:32:23285namespace internal {
286
Xiaohan Wang131aa4d2022-01-15 19:39:41287#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
[email protected]1e218b72012-11-14 19:32:23288// POSIX doesn't define any async-signal safe function for converting
289// an integer to ASCII. We'll have to define our own version.
290// itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
291// conversion was successful or NULL otherwise. It never writes more than "sz"
292// bytes. Output will be truncated as needed, and a NUL character is always
293// appended.
danakjd53babfe2024-10-09 14:04:16294BASE_EXPORT void itoa_r(intptr_t i,
295 int base,
296 size_t padding,
297 base::span<char> buf);
Xiaohan Wang131aa4d2022-01-15 19:39:41298#endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
[email protected]1e218b72012-11-14 19:32:23299
300} // namespace internal
301
Jan Keitel4161bcb2024-08-01 12:44:24302} // namespace base::debug
[email protected]58580352010-10-26 04:07:50303
304#endif // BASE_DEBUG_STACK_TRACE_H_