xref: /aosp_15_r20/external/cronet/base/debug/stack_trace.cc (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 #include "base/debug/stack_trace.h"
6 
7 #include <string.h>
8 
9 #include <algorithm>
10 #include <sstream>
11 #include <utility>
12 
13 #include "base/check_op.h"
14 #include "build/build_config.h"
15 #include "build/config/compiler/compiler_buildflags.h"
16 
17 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
18 #include <optional>
19 
20 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
21 #include <pthread.h>
22 
23 #include "base/process/process_handle.h"
24 #include "base/threading/platform_thread.h"
25 #endif
26 
27 #if BUILDFLAG(IS_APPLE)
28 #include <pthread.h>
29 #endif
30 
31 #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
32 extern "C" void* __libc_stack_end;
33 #endif
34 
35 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
36 
37 namespace base {
38 namespace debug {
39 
40 namespace {
41 
42 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
43 
44 #if defined(__arm__) && defined(__GNUC__) && !defined(__clang__)
45 // GCC and LLVM generate slightly different frames on ARM, see
46 // https://llvm.org/bugs/show_bug.cgi?id=18505 - LLVM generates
47 // x86-compatible frame, while GCC needs adjustment.
48 constexpr size_t kStackFrameAdjustment = sizeof(uintptr_t);
49 #else
50 constexpr size_t kStackFrameAdjustment = 0;
51 #endif
52 
53 // On Arm-v8.3+ systems with pointer authentication codes (PAC), signature bits
54 // are set in the top bits of the pointer, which confuses test assertions.
55 // Because the signature size can vary based on the system configuration, use
56 // the xpaclri instruction to remove the signature.
StripPointerAuthenticationBits(uintptr_t ptr)57 static uintptr_t StripPointerAuthenticationBits(uintptr_t ptr) {
58 #if defined(ARCH_CPU_ARM64)
59   // A single Chromium binary currently spans all Arm systems (including those
60   // with and without pointer authentication). xpaclri is used here because it's
61   // in the HINT space and treated as a no-op on older Arm cores (unlike the
62   // more generic xpaci which has a new encoding). The downside is that ptr has
63   // to be moved to x30 to use this instruction. TODO([email protected]):
64   // replace with an intrinsic once that is available.
65   register uintptr_t x30 __asm("x30") = ptr;
66   asm("xpaclri" : "+r"(x30));
67   return x30;
68 #else
69   // No-op on other platforms.
70   return ptr;
71 #endif
72 }
73 
GetNextStackFrame(uintptr_t fp)74 uintptr_t GetNextStackFrame(uintptr_t fp) {
75   const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
76   MSAN_UNPOISON(fp_addr, sizeof(uintptr_t));
77   return fp_addr[0] - kStackFrameAdjustment;
78 }
79 
GetStackFramePC(uintptr_t fp)80 uintptr_t GetStackFramePC(uintptr_t fp) {
81   const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
82   MSAN_UNPOISON(&fp_addr[1], sizeof(uintptr_t));
83   return StripPointerAuthenticationBits(fp_addr[1]);
84 }
85 
IsStackFrameValid(uintptr_t fp,uintptr_t prev_fp,uintptr_t stack_end)86 bool IsStackFrameValid(uintptr_t fp, uintptr_t prev_fp, uintptr_t stack_end) {
87   // With the stack growing downwards, older stack frame must be
88   // at a greater address that the current one.
89   if (fp <= prev_fp) return false;
90 
91   // Assume huge stack frames are bogus.
92   if (fp - prev_fp > 100000) return false;
93 
94   // Check alignment.
95   if (fp & (sizeof(uintptr_t) - 1)) return false;
96 
97   if (stack_end) {
98     // Both fp[0] and fp[1] must be within the stack.
99     if (fp > stack_end - 2 * sizeof(uintptr_t)) return false;
100 
101     // Additional check to filter out false positives.
102     if (GetStackFramePC(fp) < 32768) return false;
103   }
104 
105   return true;
106 }
107 
108 // ScanStackForNextFrame() scans the stack for a valid frame to allow unwinding
109 // past system libraries. Only supported on Linux where system libraries are
110 // usually in the middle of the trace:
111 //
112 //   TraceStackFramePointers
113 //   <more frames from Chrome>
114 //   base::WorkSourceDispatch   <-- unwinding stops (next frame is invalid),
115 //   g_main_context_dispatch        ScanStackForNextFrame() is called
116 //   <more frames from glib>
117 //   g_main_context_iteration
118 //   base::MessagePumpGlib::Run <-- ScanStackForNextFrame() finds valid frame,
119 //   base::RunLoop::Run             unwinding resumes
120 //   <more frames from Chrome>
121 //   __libc_start_main
122 //
123 // ScanStackForNextFrame() returns 0 if it couldn't find a valid frame
124 // (or if stack scanning is not supported on the current platform).
ScanStackForNextFrame(uintptr_t fp,uintptr_t stack_end)125 uintptr_t ScanStackForNextFrame(uintptr_t fp, uintptr_t stack_end) {
126   // Enough to resume almost all prematurely terminated traces.
127   constexpr size_t kMaxStackScanArea = 8192;
128 
129   if (!stack_end) {
130     // Too dangerous to scan without knowing where the stack ends.
131     return 0;
132   }
133 
134   fp += sizeof(uintptr_t);  // current frame is known to be invalid
135   uintptr_t last_fp_to_scan = std::min(fp + kMaxStackScanArea, stack_end) -
136                                   sizeof(uintptr_t);
137   for (;fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
138     uintptr_t next_fp = GetNextStackFrame(fp);
139     if (IsStackFrameValid(next_fp, fp, stack_end)) {
140       // Check two frames deep. Since stack frame is just a pointer to
141       // a higher address on the stack, it's relatively easy to find
142       // something that looks like one. However two linked frames are
143       // far less likely to be bogus.
144       uintptr_t next2_fp = GetNextStackFrame(next_fp);
145       if (IsStackFrameValid(next2_fp, next_fp, stack_end)) {
146         return fp;
147       }
148     }
149   }
150 
151   return 0;
152 }
153 
154 // Links stack frame |fp| to |parent_fp|, so that during stack unwinding
155 // TraceStackFramePointers() visits |parent_fp| after visiting |fp|.
156 // Both frame pointers must come from __builtin_frame_address().
157 // Returns previous stack frame |fp| was linked to.
LinkStackFrames(void * fpp,void * parent_fp)158 void* LinkStackFrames(void* fpp, void* parent_fp) {
159   uintptr_t fp = reinterpret_cast<uintptr_t>(fpp) - kStackFrameAdjustment;
160   void* prev_parent_fp = reinterpret_cast<void**>(fp)[0];
161   reinterpret_cast<void**>(fp)[0] = parent_fp;
162   return prev_parent_fp;
163 }
164 
165 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
166 
167 // A message to be emitted in place of a symbolized stack trace. Ordinarily used
168 // in death test child processes to inform a developer that they may rerun a
169 // failing test with a switch to prevent the test launcher from suppressing
170 // stacks in such processes.
171 std::string* g_stack_trace_message = nullptr;
172 
173 // True if an OverrideStackTraceOutputForTesting instance is alive to force
174 // or prevent generation of symbolized stack traces despite a suppression
175 // message having been set (or not).
176 OverrideStackTraceOutputForTesting::Mode g_override_suppression =
177     OverrideStackTraceOutputForTesting::Mode::kUnset;
178 
179 }  // namespace
180 
181 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
GetStackEnd()182 uintptr_t GetStackEnd() {
183 #if BUILDFLAG(IS_ANDROID)
184   // Bionic reads proc/maps on every call to pthread_getattr_np() when called
185   // from the main thread. So we need to cache end of stack in that case to get
186   // acceptable performance.
187   // For all other threads pthread_getattr_np() is fast enough as it just reads
188   // values from its pthread_t argument.
189   static uintptr_t main_stack_end = 0;
190 
191   bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId();
192   if (is_main_thread && main_stack_end) {
193     return main_stack_end;
194   }
195 
196   uintptr_t stack_begin = 0;
197   size_t stack_size = 0;
198   pthread_attr_t attributes;
199   int error = pthread_getattr_np(pthread_self(), &attributes);
200   if (!error) {
201     error = pthread_attr_getstack(
202         &attributes, reinterpret_cast<void**>(&stack_begin), &stack_size);
203     pthread_attr_destroy(&attributes);
204   }
205   DCHECK(!error);
206 
207   uintptr_t stack_end = stack_begin + stack_size;
208   if (is_main_thread) {
209     main_stack_end = stack_end;
210   }
211   return stack_end;  // 0 in case of error
212 #elif BUILDFLAG(IS_APPLE)
213   // No easy way to get end of the stack for non-main threads,
214   // see crbug.com/617730.
215   return reinterpret_cast<uintptr_t>(pthread_get_stackaddr_np(pthread_self()));
216 #else
217 
218 #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
219   if (GetCurrentProcId() == PlatformThread::CurrentId()) {
220     // For the main thread we have a shortcut.
221     return reinterpret_cast<uintptr_t>(__libc_stack_end);
222   }
223 #endif
224 
225   // Don't know how to get end of the stack.
226   return 0;
227 #endif
228 }
229 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
230 
StackTrace()231 StackTrace::StackTrace() : StackTrace(std::size(trace_)) {}
232 
StackTrace(size_t count)233 StackTrace::StackTrace(size_t count)
234     : count_(ShouldSuppressOutput()
235                  ? 0
236                  : CollectStackTrace(trace_,
237                                      std::min(count, std::size(trace_)))) {}
238 
StackTrace(const void * const * trace,size_t count)239 StackTrace::StackTrace(const void* const* trace, size_t count)
240     : count_(std::min(count, std::size(trace_))) {
241   if (count_) {
242     memcpy(trace_, trace, count_ * sizeof(trace_[0]));
243   }
244 }
245 
246 // static
WillSymbolizeToStreamForTesting()247 bool StackTrace::WillSymbolizeToStreamForTesting() {
248 #if BUILDFLAG(SYMBOL_LEVEL) == 0
249   // Symbols are not expected to be reliable when gn args specifies
250   // symbol_level=0.
251   return false;
252 #elif defined(__UCLIBC__) || defined(_AIX)
253   // StackTrace::OutputToStream() is not implemented under uclibc, nor AIX.
254   // See https://crbug.com/706728
255   return false;
256 #elif defined(OFFICIAL_BUILD) && \
257     ((BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)) || BUILDFLAG(IS_FUCHSIA))
258   // On some platforms stack traces require an extra data table that bloats our
259   // binaries, so they're turned off for official builds.
260   return false;
261 #elif defined(OFFICIAL_BUILD) && BUILDFLAG(IS_APPLE)
262   // Official Mac OS X builds contain enough information to unwind the stack,
263   // but not enough to symbolize the output.
264   return false;
265 #elif BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_ANDROID)
266   // Under Fuchsia and Android, StackTrace emits executable build-Ids and
267   // address offsets which are symbolized on the test host system, rather than
268   // being symbolized in-process.
269   return false;
270 #elif defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
271     defined(MEMORY_SANITIZER)
272   // Sanitizer configurations (ASan, TSan, MSan) emit unsymbolized stacks.
273   return false;
274 #else
275   return true;
276 #endif
277 }
278 
Print() const279 void StackTrace::Print() const {
280   PrintWithPrefix({});
281 }
282 
PrintWithPrefix(cstring_view prefix_string) const283 void StackTrace::PrintWithPrefix(cstring_view prefix_string) const {
284   if (!count_ || ShouldSuppressOutput()) {
285     if (g_stack_trace_message) {
286       PrintMessageWithPrefix(prefix_string, *g_stack_trace_message);
287     }
288     return;
289   }
290   PrintWithPrefixImpl(prefix_string);
291 }
292 
OutputToStream(std::ostream * os) const293 void StackTrace::OutputToStream(std::ostream* os) const {
294   OutputToStreamWithPrefix(os, {});
295 }
296 
OutputToStreamWithPrefix(std::ostream * os,cstring_view prefix_string) const297 void StackTrace::OutputToStreamWithPrefix(std::ostream* os,
298                                           cstring_view prefix_string) const {
299   if (!count_ || ShouldSuppressOutput()) {
300     if (g_stack_trace_message) {
301       (*os) << prefix_string << *g_stack_trace_message;
302     }
303     return;
304   }
305   OutputToStreamWithPrefixImpl(os, prefix_string);
306 }
307 
ToString() const308 std::string StackTrace::ToString() const {
309   return ToStringWithPrefix({});
310 }
311 
ToStringWithPrefix(cstring_view prefix_string) const312 std::string StackTrace::ToStringWithPrefix(cstring_view prefix_string) const {
313   std::stringstream stream;
314 #if !defined(__UCLIBC__) && !defined(_AIX)
315   OutputToStreamWithPrefix(&stream, prefix_string);
316 #endif
317   return stream.str();
318 }
319 
320 // static
SuppressStackTracesWithMessageForTesting(std::string message)321 void StackTrace::SuppressStackTracesWithMessageForTesting(std::string message) {
322   delete std::exchange(
323       g_stack_trace_message,
324       (message.empty() ? nullptr : new std::string(std::move(message))));
325 }
326 
327 // static
ShouldSuppressOutput()328 bool StackTrace::ShouldSuppressOutput() {
329   using Mode = OverrideStackTraceOutputForTesting::Mode;
330   // Do not generate stack traces if a suppression message has been provided,
331   // unless an OverrideStackTraceOutputForTesting instance is alive.
332   return g_override_suppression != Mode::kUnset
333              ? (g_override_suppression == Mode::kSuppressOutput)
334              : (g_stack_trace_message != nullptr);
335 }
336 
operator <<(std::ostream & os,const StackTrace & s)337 std::ostream& operator<<(std::ostream& os, const StackTrace& s) {
338 #if !defined(__UCLIBC__) && !defined(_AIX)
339   s.OutputToStream(&os);
340 #else
341   os << "StackTrace::OutputToStream not implemented.";
342 #endif
343   return os;
344 }
345 
OverrideStackTraceOutputForTesting(Mode mode)346 OverrideStackTraceOutputForTesting::OverrideStackTraceOutputForTesting(
347     Mode mode) {
348   CHECK_NE(mode, Mode::kUnset);
349   CHECK_EQ(g_override_suppression, Mode::kUnset);  // Nesting not supported.
350   g_override_suppression = mode;
351 }
352 
~OverrideStackTraceOutputForTesting()353 OverrideStackTraceOutputForTesting::~OverrideStackTraceOutputForTesting() {
354   CHECK_NE(g_override_suppression, Mode::kUnset);  // Nesting not supported.
355   g_override_suppression = Mode::kUnset;
356 }
357 
358 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
359 
360 struct AddressRange {
361   uintptr_t start;
362   uintptr_t end;
363 };
364 
IsWithinRange(uintptr_t address,const AddressRange & range)365 bool IsWithinRange(uintptr_t address, const AddressRange& range) {
366   return address >= range.start && address <= range.end;
367 }
368 
369 // We force this function to be inlined into its callers (e.g.
370 // TraceStackFramePointers()) in all build modes so we don't have to worry about
371 // conditionally skipping a frame based on potential inlining or tail calls.
TraceStackFramePointersInternal(uintptr_t fp,uintptr_t stack_end,size_t max_depth,size_t skip_initial,bool enable_scanning,const void ** out_trace)372 __attribute__((always_inline)) size_t TraceStackFramePointersInternal(
373     uintptr_t fp,
374     uintptr_t stack_end,
375     size_t max_depth,
376     size_t skip_initial,
377     bool enable_scanning,
378     const void** out_trace) {
379   size_t depth = 0;
380   while (depth < max_depth) {
381     uintptr_t pc = GetStackFramePC(fp);
382     if (skip_initial != 0) {
383       skip_initial--;
384     } else {
385       out_trace[depth++] = reinterpret_cast<const void*>(pc);
386     }
387 
388     uintptr_t next_fp = GetNextStackFrame(fp);
389     if (IsStackFrameValid(next_fp, fp, stack_end)) {
390       fp = next_fp;
391       continue;
392     }
393 
394     if (!enable_scanning)
395       break;
396 
397     next_fp = ScanStackForNextFrame(fp, stack_end);
398     if (next_fp) {
399       fp = next_fp;
400     } else {
401       break;
402     }
403   }
404 
405   return depth;
406 }
407 
TraceStackFramePointers(const void ** out_trace,size_t max_depth,size_t skip_initial,bool enable_scanning)408 NOINLINE size_t TraceStackFramePointers(const void** out_trace,
409                                         size_t max_depth,
410                                         size_t skip_initial,
411                                         bool enable_scanning) {
412   return TraceStackFramePointersInternal(
413       reinterpret_cast<uintptr_t>(__builtin_frame_address(0)) -
414           kStackFrameAdjustment,
415       GetStackEnd(), max_depth, skip_initial, enable_scanning, out_trace);
416 }
417 
TraceStackFramePointersFromBuffer(uintptr_t fp,uintptr_t stack_end,const void ** out_trace,size_t max_depth,size_t skip_initial,bool enable_scanning)418 NOINLINE size_t TraceStackFramePointersFromBuffer(uintptr_t fp,
419                                                   uintptr_t stack_end,
420                                                   const void** out_trace,
421                                                   size_t max_depth,
422                                                   size_t skip_initial,
423                                                   bool enable_scanning) {
424   return TraceStackFramePointersInternal(fp, stack_end, max_depth, skip_initial,
425                                          enable_scanning, out_trace);
426 }
427 
ScopedStackFrameLinker(void * fp,void * parent_fp)428 ScopedStackFrameLinker::ScopedStackFrameLinker(void* fp, void* parent_fp)
429     : fp_(fp),
430       parent_fp_(parent_fp),
431       original_parent_fp_(LinkStackFrames(fp, parent_fp)) {}
432 
~ScopedStackFrameLinker()433 ScopedStackFrameLinker::~ScopedStackFrameLinker() {
434   void* previous_parent_fp = LinkStackFrames(fp_, original_parent_fp_);
435   CHECK_EQ(parent_fp_, previous_parent_fp)
436       << "Stack frame's parent pointer has changed!";
437 }
438 
439 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
440 
441 }  // namespace debug
442 }  // namespace base
443