blob: a9129db48aba894863351f7bc3abe26aebf08039 [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
Nico Weber6f2d26d2025-06-27 07:32:0844#if BUILDFLAG(IS_POSIX)
Andreas Haasef19d592019-04-30 18:16:5145// Sets a first-chance callback for the stack dump signal handler. This callback
46// is called at the beginning of the signal handler to handle special kinds of
47// signals, like out-of-bounds memory accesses in WebAssembly (WebAssembly Trap
48// Handler).
49// {SetStackDumpFirstChanceCallback} returns {true} if the callback
50// has been set correctly. It returns {false} if the stack dump signal handler
51// has not been registered with the OS, e.g. because of ASAN.
52BASE_EXPORT bool SetStackDumpFirstChanceCallback(bool (*handler)(int,
Andreas Haas54c0c022019-06-14 17:33:5353 siginfo_t*,
Eric Holkdc499db2017-07-17 17:57:3554 void*));
55#endif
56
erikchend6b2b822017-02-22 21:10:3157// Returns end of the stack, or 0 if we couldn't get it.
erikchenf7c8a0d2017-04-06 21:15:2758#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
erikchend6b2b822017-02-22 21:10:3159BASE_EXPORT uintptr_t GetStackEnd();
60#endif
61
[email protected]58580352010-10-26 04:07:5062// A stacktrace can be helpful in debugging. For example, you can include a
63// stacktrace member in a object (probably around #ifndef NDEBUG) so that you
64// can later see where the given object was created from.
[email protected]0bea7252011-08-05 15:34:0065class BASE_EXPORT StackTrace {
[email protected]58580352010-10-26 04:07:5066 public:
Daniel Cheng42dd8442024-03-05 22:14:1167 // LINT.IfChange(max_stack_frames)
Daniel Cheng1e96ff32023-06-26 20:01:0168#if BUILDFLAG(IS_ANDROID)
Alison Galed94ce4f2024-04-22 15:20:3969 // TODO(crbug.com/41437515): Testing indicates that Android has issues
Daniel Cheng1e96ff32023-06-26 20:01:0170 // 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
Daniel Cheng42dd8442024-03-05 22:14:1177 // LINT.ThenChange(dwarf_line_no.cc:max_stack_frames)
Daniel Cheng1e96ff32023-06-26 20:01:0178
[email protected]58580352010-10-26 04:07:5079 // Creates a stacktrace from the current location.
80 StackTrace();
81
wez73f8d7e2017-01-29 06:18:1382 // Creates a stacktrace from the current location, of up to |count| entries.
83 // |count| will be limited to at most |kMaxTraces|.
84 explicit StackTrace(size_t count);
85
danakje75c6c812024-07-26 20:37:4786 // Creates a stacktrace from an existing array of instruction pointers (such
87 // as returned by Addresses()). Only the first `kMaxTraces` of the span will
88 // be used.
89 explicit StackTrace(span<const void* const> trace);
[email protected]f01ae9812011-08-30 19:33:0490
Xiaohan Wang131aa4d2022-01-15 19:39:4191#if BUILDFLAG(IS_WIN)
[email protected]58580352010-10-26 04:07:5092 // Creates a stacktrace for an exception.
93 // Note: this function will throw an import not found (StackWalk64) exception
94 // on system without dbghelp 5.1.
jam79dc59a2015-08-17 03:38:1695 StackTrace(_EXCEPTION_POINTERS* exception_pointers);
rnk0565cdd62015-10-06 16:48:3096 StackTrace(const _CONTEXT* context);
[email protected]58580352010-10-26 04:07:5097#endif
98
Gabriel Charetteae1bb012021-05-06 19:31:2199 // Returns true if this current test environment is expected to have
100 // symbolized frames when printing a stack trace.
101 static bool WillSymbolizeToStreamForTesting();
102
[email protected]58580352010-10-26 04:07:50103 // Copying and assignment are allowed with the default functions.
104
[email protected]58580352010-10-26 04:07:50105 // Gets an array of instruction pointer values. |*count| will be set to the
Bruce Dawson19e29bb2020-01-06 21:20:14106 // number of elements in the returned array. Addresses()[0] will contain an
107 // address from the leaf function, and Addresses()[count-1] will contain an
108 // address from the root function (i.e.; the thread's entry point).
Daniel Chenga0e290d2023-10-16 18:47:24109 span<const void* const> addresses() const {
Jan Keitel4161bcb2024-08-01 12:44:24110 return span(trace_).first(count_);
Daniel Chenga0e290d2023-10-16 18:47:24111 }
[email protected]58580352010-10-26 04:07:50112
[email protected]5ddbf1c2013-08-29 01:59:38113 // Prints the stack trace to stderr.
114 void Print() const;
[email protected]58580352010-10-26 04:07:50115
Mason Freedb9ef2b62018-09-10 17:17:27116 // Prints the stack trace to stderr, prepending the given string before
117 // each output line.
Greg Thompson8b1b295b2024-04-10 07:44:14118 void PrintWithPrefix(cstring_view prefix_string) const;
Mason Freedb9ef2b62018-09-10 17:17:27119
Gabriel Charetteae1bb012021-05-06 19:31:21120#if !defined(__UCLIBC__) && !defined(_AIX)
[email protected]58580352010-10-26 04:07:50121 // Resolves backtrace to symbols and write to stream.
[email protected]501dfc42011-04-14 16:34:00122 void OutputToStream(std::ostream* os) const;
Mason Freedb9ef2b62018-09-10 17:17:27123 // Resolves backtrace to symbols and write to stream, with the provided
124 // prefix string prepended to each line.
125 void OutputToStreamWithPrefix(std::ostream* os,
Greg Thompson8b1b295b2024-04-10 07:44:14126 cstring_view prefix_string) const;
[email protected]816e50452014-04-09 22:29:38127#endif
[email protected]58580352010-10-26 04:07:50128
[email protected]d4114ba2011-10-12 16:13:40129 // Resolves backtrace to symbols and returns as string.
130 std::string ToString() const;
131
Mason Freedb9ef2b62018-09-10 17:17:27132 // Resolves backtrace to symbols and returns as string, prepending the
133 // provided prefix string to each line.
Greg Thompson8b1b295b2024-04-10 07:44:14134 std::string ToStringWithPrefix(cstring_view prefix_string) const;
Mason Freedb9ef2b62018-09-10 17:17:27135
Greg Thompsonc82cbc92024-04-10 07:36:06136 // Sets a message to be emitted in place of symbolized stack traces. When
137 // such a message is provided, collection and symbolization of stack traces
138 // is suppressed. Suppression is cancelled if `message` is empty.
139 static void SuppressStackTracesWithMessageForTesting(std::string message);
140
[email protected]58580352010-10-26 04:07:50141 private:
Greg Thompsonc82cbc92024-04-10 07:36:06142 // Prints `message` with an optional prefix.
Greg Thompson8b1b295b2024-04-10 07:44:14143 static void PrintMessageWithPrefix(cstring_view prefix_string,
Greg Thompsonc82cbc92024-04-10 07:36:06144 cstring_view message);
145
Greg Thompson8b1b295b2024-04-10 07:44:14146 void PrintWithPrefixImpl(cstring_view prefix_string) const;
Greg Thompsonc82cbc92024-04-10 07:36:06147#if !defined(__UCLIBC__) && !defined(_AIX)
148 void OutputToStreamWithPrefixImpl(std::ostream* os,
Greg Thompson8b1b295b2024-04-10 07:44:14149 cstring_view prefix_string) const;
Greg Thompsonc82cbc92024-04-10 07:36:06150#endif
151
Greg Thompson75724f92024-03-21 08:31:27152 // Returns true if generation of symbolized stack traces is to be suppressed.
153 static bool ShouldSuppressOutput();
154
Xiaohan Wang131aa4d2022-01-15 19:39:41155#if BUILDFLAG(IS_WIN)
rnk0565cdd62015-10-06 16:48:30156 void InitTrace(const _CONTEXT* context_record);
wittman7808da72015-02-03 17:46:51157#endif
158
Jan Keitel4161bcb2024-08-01 12:44:24159 std::array<const void*, kMaxTraces> trace_;
[email protected]e645c7a2012-07-25 21:43:44160
Greg Thompson75724f92024-03-21 08:31:27161 // The number of valid frames in |trace_|, or 0 if collection was suppressed.
162 size_t count_ = 0;
[email protected]58580352010-10-26 04:07:50163};
164
Gabriel Charettec41da4512019-02-22 02:07:10165// Forwards to StackTrace::OutputToStream().
166BASE_EXPORT std::ostream& operator<<(std::ostream& os, const StackTrace& s);
167
Vlad Tsyrklevich2788d59962019-01-23 03:32:45168// Record a stack trace with up to |count| frames into |trace|. Returns the
169// number of frames read.
danakje75c6c812024-07-26 20:37:47170BASE_EXPORT size_t CollectStackTrace(span<const void*> trace);
Vlad Tsyrklevich2788d59962019-01-23 03:32:45171
Greg Thompson75724f92024-03-21 08:31:27172// A helper for tests that must either override the default suppression of
173// symbolized stack traces in death tests, or the default generation of them in
174// normal tests.
175class BASE_EXPORT OverrideStackTraceOutputForTesting {
Greg Thompsona6e88c12024-03-13 16:37:13176 public:
Greg Thompson75724f92024-03-21 08:31:27177 enum class Mode {
178 kUnset,
179 kForceOutput,
180 kSuppressOutput,
181 };
182 explicit OverrideStackTraceOutputForTesting(Mode mode);
183 OverrideStackTraceOutputForTesting(
184 const OverrideStackTraceOutputForTesting&) = delete;
185 OverrideStackTraceOutputForTesting& operator=(
186 const OverrideStackTraceOutputForTesting&) = delete;
187 ~OverrideStackTraceOutputForTesting();
Greg Thompsona6e88c12024-03-13 16:37:13188};
189
erikchenf7c8a0d2017-04-06 21:15:27190#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
ssidc1d5a3d2020-09-11 05:20:30191
192// For stack scanning to be efficient it's very important for the thread to
193// be started by Chrome. In that case we naturally terminate unwinding once
194// we reach the origin of the stack (i.e. GetStackEnd()). If the thread is
195// not started by Chrome (e.g. Android's main thread), then we end up always
196// scanning area at the origin of the stack, wasting time and not finding any
197// frames (since Android libraries don't have frame pointers). Scanning is not
198// enabled on other posix platforms due to legacy reasons.
Xiaohan Wang131aa4d2022-01-15 19:39:41199#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
ssidc1d5a3d2020-09-11 05:20:30200constexpr bool kEnableScanningByDefault = true;
201#else
202constexpr bool kEnableScanningByDefault = false;
203#endif
204
dskiba79080da02016-04-23 00:10:27205// Traces the stack by using frame pointers. This function is faster but less
206// reliable than StackTrace. It should work for debug and profiling builds,
207// but not for release builds (although there are some exceptions).
208//
209// Writes at most |max_depth| frames (instruction pointers) into |out_trace|
210// after skipping |skip_initial| frames. Note that the function itself is not
211// added to the trace so |skip_initial| should be 0 in most cases.
ssidc1d5a3d2020-09-11 05:20:30212// Returns number of frames written. |enable_scanning| enables scanning on
213// platforms that do not enable scanning by default.
214BASE_EXPORT size_t
danakje75c6c812024-07-26 20:37:47215TraceStackFramePointers(span<const void*> out_trace,
ssidc1d5a3d2020-09-11 05:20:30216 size_t skip_initial,
217 bool enable_scanning = kEnableScanningByDefault);
218
dskibaa8c951e2016-10-25 23:39:11219// Links stack frame |fp| to |parent_fp|, so that during stack unwinding
220// TraceStackFramePointers() visits |parent_fp| after visiting |fp|.
221// Both frame pointers must come from __builtin_frame_address().
222// Destructor restores original linkage of |fp| to avoid corrupting caller's
223// frame register on return.
224//
225// This class can be used to repair broken stack frame chain in cases
226// when execution flow goes into code built without frame pointers:
227//
228// void DoWork() {
229// Call_SomeLibrary();
230// }
231// static __thread void* g_saved_fp;
232// void Call_SomeLibrary() {
233// g_saved_fp = __builtin_frame_address(0);
234// some_library_call(...); // indirectly calls SomeLibrary_Callback()
235// }
236// void SomeLibrary_Callback() {
237// ScopedStackFrameLinker linker(__builtin_frame_address(0), g_saved_fp);
238// ...
239// TraceStackFramePointers(...);
240// }
241//
242// This produces the following trace:
243//
244// #0 SomeLibrary_Callback()
245// #1 <address of the code inside SomeLibrary that called #0>
246// #2 DoWork()
247// ...rest of the trace...
248//
249// SomeLibrary doesn't use frame pointers, so when SomeLibrary_Callback()
250// is called, stack frame register contains bogus value that becomes callback'
251// parent frame address. Without ScopedStackFrameLinker unwinding would've
252// stopped at that bogus frame address yielding just two first frames (#0, #1).
253// ScopedStackFrameLinker overwrites callback's parent frame address with
254// Call_SomeLibrary's frame, so unwinder produces full trace without even
255// noticing that stack frame chain was broken.
256class BASE_EXPORT ScopedStackFrameLinker {
257 public:
258 ScopedStackFrameLinker(void* fp, void* parent_fp);
Peter Boström7319bbd2021-09-15 22:59:38259
260 ScopedStackFrameLinker(const ScopedStackFrameLinker&) = delete;
261 ScopedStackFrameLinker& operator=(const ScopedStackFrameLinker&) = delete;
262
dskibaa8c951e2016-10-25 23:39:11263 ~ScopedStackFrameLinker();
264
265 private:
Keishi Hattorif28f4f82022-06-21 11:32:15266 raw_ptr<void> fp_;
267 raw_ptr<void> parent_fp_;
268 raw_ptr<void> original_parent_fp_;
dskibaa8c951e2016-10-25 23:39:11269};
270
erikchenf7c8a0d2017-04-06 21:15:27271#endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
dskiba79080da02016-04-23 00:10:27272
[email protected]1e218b72012-11-14 19:32:23273namespace internal {
274
Xiaohan Wang131aa4d2022-01-15 19:39:41275#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
[email protected]1e218b72012-11-14 19:32:23276// POSIX doesn't define any async-signal safe function for converting
277// an integer to ASCII. We'll have to define our own version.
278// itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
279// conversion was successful or NULL otherwise. It never writes more than "sz"
280// bytes. Output will be truncated as needed, and a NUL character is always
281// appended.
danakjd53babfe2024-10-09 14:04:16282BASE_EXPORT void itoa_r(intptr_t i,
283 int base,
284 size_t padding,
285 base::span<char> buf);
Xiaohan Wang131aa4d2022-01-15 19:39:41286#endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
[email protected]1e218b72012-11-14 19:32:23287
288} // namespace internal
289
Jan Keitel4161bcb2024-08-01 12:44:24290} // namespace base::debug
[email protected]58580352010-10-26 04:07:50291
292#endif // BASE_DEBUG_STACK_TRACE_H_