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