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 "partition_alloc/partition_alloc_base/debug/stack_trace.h"
6
7 #include <cstdint>
8
9 #include "build/build_config.h"
10 #include "partition_alloc/partition_alloc_base/check.h"
11 #include "partition_alloc/partition_alloc_base/compiler_specific.h"
12 #include "partition_alloc/partition_alloc_base/process/process_handle.h"
13 #include "partition_alloc/partition_alloc_base/threading/platform_thread.h"
14
15 #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
16 extern "C" void* __libc_stack_end;
17 #endif
18
19 namespace partition_alloc::internal::base::debug {
20 namespace {
21
22 #if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS)
23
24 #if defined(__arm__) && defined(__GNUC__) && !defined(__clang__)
25 // GCC and LLVM generate slightly different frames on ARM, see
26 // https://llvm.org/bugs/show_bug.cgi?id=18505 - LLVM generates
27 // x86-compatible frame, while GCC needs adjustment.
28 constexpr size_t kStackFrameAdjustment = sizeof(uintptr_t);
29 #else
30 constexpr size_t kStackFrameAdjustment = 0;
31 #endif
32
33 // On Arm-v8.3+ systems with pointer authentication codes (PAC), signature bits
34 // are set in the top bits of the pointer, which confuses test assertions.
35 // Because the signature size can vary based on the system configuration, use
36 // the xpaclri instruction to remove the signature.
StripPointerAuthenticationBits(uintptr_t ptr)37 static uintptr_t StripPointerAuthenticationBits(uintptr_t ptr) {
38 #if defined(ARCH_CPU_ARM64)
39 // A single Chromium binary currently spans all Arm systems (including those
40 // with and without pointer authentication). xpaclri is used here because it's
41 // in the HINT space and treated as a no-op on older Arm cores (unlike the
42 // more generic xpaci which has a new encoding). The downside is that ptr has
43 // to be moved to x30 to use this instruction. TODO([email protected]):
44 // replace with an intrinsic once that is available.
45 register uintptr_t x30 __asm("x30") = ptr;
46 asm("xpaclri" : "+r"(x30));
47 return x30;
48 #else
49 // No-op on other platforms.
50 return ptr;
51 #endif
52 }
53
GetNextStackFrame(uintptr_t fp)54 uintptr_t GetNextStackFrame(uintptr_t fp) {
55 const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
56 PA_MSAN_UNPOISON(fp_addr, sizeof(uintptr_t));
57 return fp_addr[0] - kStackFrameAdjustment;
58 }
59
GetStackFramePC(uintptr_t fp)60 uintptr_t GetStackFramePC(uintptr_t fp) {
61 const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
62 PA_MSAN_UNPOISON(&fp_addr[1], sizeof(uintptr_t));
63 return StripPointerAuthenticationBits(fp_addr[1]);
64 }
65
IsStackFrameValid(uintptr_t fp,uintptr_t prev_fp,uintptr_t stack_end)66 bool IsStackFrameValid(uintptr_t fp, uintptr_t prev_fp, uintptr_t stack_end) {
67 // With the stack growing downwards, older stack frame must be
68 // at a greater address that the current one.
69 if (fp <= prev_fp) {
70 return false;
71 }
72
73 // Assume huge stack frames are bogus.
74 if (fp - prev_fp > 100000) {
75 return false;
76 }
77
78 // Check alignment.
79 if (fp & (sizeof(uintptr_t) - 1)) {
80 return false;
81 }
82
83 if (stack_end) {
84 // Both fp[0] and fp[1] must be within the stack.
85 if (fp > stack_end - 2 * sizeof(uintptr_t)) {
86 return false;
87 }
88
89 // Additional check to filter out false positives.
90 if (GetStackFramePC(fp) < 32768) {
91 return false;
92 }
93 }
94
95 return true;
96 }
97
98 // ScanStackForNextFrame() scans the stack for a valid frame to allow unwinding
99 // past system libraries. Only supported on Linux where system libraries are
100 // usually in the middle of the trace:
101 //
102 // TraceStackFramePointers
103 // <more frames from Chrome>
104 // base::WorkSourceDispatch <-- unwinding stops (next frame is invalid),
105 // g_main_context_dispatch ScanStackForNextFrame() is called
106 // <more frames from glib>
107 // g_main_context_iteration
108 // base::MessagePumpGlib::Run <-- ScanStackForNextFrame() finds valid frame,
109 // base::RunLoop::Run unwinding resumes
110 // <more frames from Chrome>
111 // __libc_start_main
112 //
113 // ScanStackForNextFrame() returns 0 if it couldn't find a valid frame
114 // (or if stack scanning is not supported on the current platform).
ScanStackForNextFrame(uintptr_t fp,uintptr_t stack_end)115 uintptr_t ScanStackForNextFrame(uintptr_t fp, uintptr_t stack_end) {
116 // Enough to resume almost all prematurely terminated traces.
117 constexpr size_t kMaxStackScanArea = 8192;
118
119 if (!stack_end) {
120 // Too dangerous to scan without knowing where the stack ends.
121 return 0;
122 }
123
124 fp += sizeof(uintptr_t); // current frame is known to be invalid
125 uintptr_t last_fp_to_scan =
126 std::min(fp + kMaxStackScanArea, stack_end) - sizeof(uintptr_t);
127 for (; fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
128 uintptr_t next_fp = GetNextStackFrame(fp);
129 if (IsStackFrameValid(next_fp, fp, stack_end)) {
130 // Check two frames deep. Since stack frame is just a pointer to
131 // a higher address on the stack, it's relatively easy to find
132 // something that looks like one. However two linked frames are
133 // far less likely to be bogus.
134 uintptr_t next2_fp = GetNextStackFrame(next_fp);
135 if (IsStackFrameValid(next2_fp, next_fp, stack_end)) {
136 return fp;
137 }
138 }
139 }
140
141 return 0;
142 }
143
144 #endif // BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS)
145
146 } // namespace
147
148 #if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS)
149
150 // We force this function to be inlined into its callers (e.g.
151 // TraceStackFramePointers()) in all build modes so we don't have to worry about
152 // 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)153 __attribute__((always_inline)) size_t TraceStackFramePointersInternal(
154 uintptr_t fp,
155 uintptr_t stack_end,
156 size_t max_depth,
157 size_t skip_initial,
158 bool enable_scanning,
159 const void** out_trace) {
160 size_t depth = 0;
161 while (depth < max_depth) {
162 uintptr_t pc = GetStackFramePC(fp);
163 if (skip_initial != 0) {
164 skip_initial--;
165 } else {
166 out_trace[depth++] = reinterpret_cast<const void*>(pc);
167 }
168
169 uintptr_t next_fp = GetNextStackFrame(fp);
170 if (IsStackFrameValid(next_fp, fp, stack_end)) {
171 fp = next_fp;
172 continue;
173 }
174
175 if (!enable_scanning) {
176 break;
177 }
178
179 next_fp = ScanStackForNextFrame(fp, stack_end);
180 if (next_fp) {
181 fp = next_fp;
182 } else {
183 break;
184 }
185 }
186
187 return depth;
188 }
189
TraceStackFramePointers(const void ** out_trace,size_t max_depth,size_t skip_initial,bool enable_scanning)190 PA_NOINLINE size_t TraceStackFramePointers(const void** out_trace,
191 size_t max_depth,
192 size_t skip_initial,
193 bool enable_scanning) {
194 return TraceStackFramePointersInternal(
195 reinterpret_cast<uintptr_t>(__builtin_frame_address(0)) -
196 kStackFrameAdjustment,
197 GetStackEnd(), max_depth, skip_initial, enable_scanning, out_trace);
198 }
199
200 #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
201
202 #if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS)
GetStackEnd()203 uintptr_t GetStackEnd() {
204 #if BUILDFLAG(IS_ANDROID)
205 // Bionic reads proc/maps on every call to pthread_getattr_np() when called
206 // from the main thread. So we need to cache end of stack in that case to get
207 // acceptable performance.
208 // For all other threads pthread_getattr_np() is fast enough as it just reads
209 // values from its pthread_t argument.
210 static uintptr_t main_stack_end = 0;
211
212 bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId();
213 if (is_main_thread && main_stack_end) {
214 return main_stack_end;
215 }
216
217 uintptr_t stack_begin = 0;
218 size_t stack_size = 0;
219 pthread_attr_t attributes;
220 int error = pthread_getattr_np(pthread_self(), &attributes);
221 if (!error) {
222 error = pthread_attr_getstack(
223 &attributes, reinterpret_cast<void**>(&stack_begin), &stack_size);
224 pthread_attr_destroy(&attributes);
225 }
226 PA_BASE_DCHECK(!error);
227
228 uintptr_t stack_end = stack_begin + stack_size;
229 if (is_main_thread) {
230 main_stack_end = stack_end;
231 }
232 return stack_end; // 0 in case of error
233 #elif BUILDFLAG(IS_APPLE)
234 // No easy way to get end of the stack for non-main threads,
235 // see crbug.com/617730.
236 return reinterpret_cast<uintptr_t>(pthread_get_stackaddr_np(pthread_self()));
237 #else
238
239 #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
240 if (GetCurrentProcId() == PlatformThread::CurrentId()) {
241 // For the main thread we have a shortcut.
242 return reinterpret_cast<uintptr_t>(__libc_stack_end);
243 }
244 #endif
245
246 // Don't know how to get end of the stack.
247 return 0;
248 #endif
249 }
250 #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
251
252 } // namespace partition_alloc::internal::base::debug
253