• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 
12 #include "base/logging.h"
13 #include "base/macros.h"
14 
15 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
16 
17 #if defined(OS_LINUX) || defined(OS_ANDROID)
18 #include <pthread.h>
19 #include "base/process/process_handle.h"
20 #include "base/threading/platform_thread.h"
21 #endif
22 
23 #if defined(OS_MACOSX)
24 #include <pthread.h>
25 #endif
26 
27 #if defined(OS_LINUX) && defined(__GLIBC__)
28 extern "C" void* __libc_stack_end;
29 #endif
30 
31 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
32 
33 namespace base {
34 namespace debug {
35 
36 namespace {
37 
38 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
39 
40 #if defined(__arm__) && defined(__GNUC__) && !defined(__clang__)
41 // GCC and LLVM generate slightly different frames on ARM, see
42 // https://llvm.org/bugs/show_bug.cgi?id=18505 - LLVM generates
43 // x86-compatible frame, while GCC needs adjustment.
44 constexpr size_t kStackFrameAdjustment = sizeof(uintptr_t);
45 #else
46 constexpr size_t kStackFrameAdjustment = 0;
47 #endif
48 
GetNextStackFrame(uintptr_t fp)49 uintptr_t GetNextStackFrame(uintptr_t fp) {
50   return reinterpret_cast<const uintptr_t*>(fp)[0] - kStackFrameAdjustment;
51 }
52 
GetStackFramePC(uintptr_t fp)53 uintptr_t GetStackFramePC(uintptr_t fp) {
54   return reinterpret_cast<const uintptr_t*>(fp)[1];
55 }
56 
IsStackFrameValid(uintptr_t fp,uintptr_t prev_fp,uintptr_t stack_end)57 bool IsStackFrameValid(uintptr_t fp, uintptr_t prev_fp, uintptr_t stack_end) {
58   // With the stack growing downwards, older stack frame must be
59   // at a greater address that the current one.
60   if (fp <= prev_fp) return false;
61 
62   // Assume huge stack frames are bogus.
63   if (fp - prev_fp > 100000) return false;
64 
65   // Check alignment.
66   if (fp & (sizeof(uintptr_t) - 1)) return false;
67 
68   if (stack_end) {
69     // Both fp[0] and fp[1] must be within the stack.
70     if (fp > stack_end - 2 * sizeof(uintptr_t)) return false;
71 
72     // Additional check to filter out false positives.
73     if (GetStackFramePC(fp) < 32768) return false;
74   }
75 
76   return true;
77 };
78 
79 // ScanStackForNextFrame() scans the stack for a valid frame to allow unwinding
80 // past system libraries. Only supported on Linux where system libraries are
81 // usually in the middle of the trace:
82 //
83 //   TraceStackFramePointers
84 //   <more frames from Chrome>
85 //   base::WorkSourceDispatch   <-- unwinding stops (next frame is invalid),
86 //   g_main_context_dispatch        ScanStackForNextFrame() is called
87 //   <more frames from glib>
88 //   g_main_context_iteration
89 //   base::MessagePumpGlib::Run <-- ScanStackForNextFrame() finds valid frame,
90 //   base::RunLoop::Run             unwinding resumes
91 //   <more frames from Chrome>
92 //   __libc_start_main
93 //
94 // For stack scanning to be efficient it's very important for the thread to
95 // be started by Chrome. In that case we naturally terminate unwinding once
96 // we reach the origin of the stack (i.e. GetStackEnd()). If the thread is
97 // not started by Chrome (e.g. Android's main thread), then we end up always
98 // scanning area at the origin of the stack, wasting time and not finding any
99 // frames (since Android libraries don't have frame pointers).
100 //
101 // ScanStackForNextFrame() returns 0 if it couldn't find a valid frame
102 // (or if stack scanning is not supported on the current platform).
ScanStackForNextFrame(uintptr_t fp,uintptr_t stack_end)103 uintptr_t ScanStackForNextFrame(uintptr_t fp, uintptr_t stack_end) {
104 #if defined(OS_LINUX)
105   // Enough to resume almost all prematurely terminated traces.
106   constexpr size_t kMaxStackScanArea = 8192;
107 
108   if (!stack_end) {
109     // Too dangerous to scan without knowing where the stack ends.
110     return 0;
111   }
112 
113   fp += sizeof(uintptr_t);  // current frame is known to be invalid
114   uintptr_t last_fp_to_scan = std::min(fp + kMaxStackScanArea, stack_end) -
115                                   sizeof(uintptr_t);
116   for (;fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
117     uintptr_t next_fp = GetNextStackFrame(fp);
118     if (IsStackFrameValid(next_fp, fp, stack_end)) {
119       // Check two frames deep. Since stack frame is just a pointer to
120       // a higher address on the stack, it's relatively easy to find
121       // something that looks like one. However two linked frames are
122       // far less likely to be bogus.
123       uintptr_t next2_fp = GetNextStackFrame(next_fp);
124       if (IsStackFrameValid(next2_fp, next_fp, stack_end)) {
125         return fp;
126       }
127     }
128   }
129 #endif  // defined(OS_LINUX)
130 
131   return 0;
132 }
133 
134 // Links stack frame |fp| to |parent_fp|, so that during stack unwinding
135 // TraceStackFramePointers() visits |parent_fp| after visiting |fp|.
136 // Both frame pointers must come from __builtin_frame_address().
137 // Returns previous stack frame |fp| was linked to.
LinkStackFrames(void * fpp,void * parent_fp)138 void* LinkStackFrames(void* fpp, void* parent_fp) {
139   uintptr_t fp = reinterpret_cast<uintptr_t>(fpp) - kStackFrameAdjustment;
140   void* prev_parent_fp = reinterpret_cast<void**>(fp)[0];
141   reinterpret_cast<void**>(fp)[0] = parent_fp;
142   return prev_parent_fp;
143 }
144 
145 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
146 
147 }  // namespace
148 
149 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
GetStackEnd()150 uintptr_t GetStackEnd() {
151 #if defined(OS_ANDROID)
152   // Bionic reads proc/maps on every call to pthread_getattr_np() when called
153   // from the main thread. So we need to cache end of stack in that case to get
154   // acceptable performance.
155   // For all other threads pthread_getattr_np() is fast enough as it just reads
156   // values from its pthread_t argument.
157   static uintptr_t main_stack_end = 0;
158 
159   bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId();
160   if (is_main_thread && main_stack_end) {
161     return main_stack_end;
162   }
163 
164   uintptr_t stack_begin = 0;
165   size_t stack_size = 0;
166   pthread_attr_t attributes;
167   int error = pthread_getattr_np(pthread_self(), &attributes);
168   if (!error) {
169     error = pthread_attr_getstack(
170         &attributes, reinterpret_cast<void**>(&stack_begin), &stack_size);
171     pthread_attr_destroy(&attributes);
172   }
173   DCHECK(!error);
174 
175   uintptr_t stack_end = stack_begin + stack_size;
176   if (is_main_thread) {
177     main_stack_end = stack_end;
178   }
179   return stack_end;  // 0 in case of error
180 
181 #elif defined(OS_LINUX) && defined(__GLIBC__)
182 
183   if (GetCurrentProcId() == PlatformThread::CurrentId()) {
184     // For the main thread we have a shortcut.
185     return reinterpret_cast<uintptr_t>(__libc_stack_end);
186   }
187 
188 // No easy way to get end of the stack for non-main threads,
189 // see crbug.com/617730.
190 #elif defined(OS_MACOSX)
191   return reinterpret_cast<uintptr_t>(pthread_get_stackaddr_np(pthread_self()));
192 #endif
193 
194   // Don't know how to get end of the stack.
195   return 0;
196 }
197 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
198 
StackTrace()199 StackTrace::StackTrace() : StackTrace(arraysize(trace_)) {}
200 
StackTrace(const void * const * trace,size_t count)201 StackTrace::StackTrace(const void* const* trace, size_t count) {
202   count = std::min(count, arraysize(trace_));
203   if (count)
204     memcpy(trace_, trace, count * sizeof(trace_[0]));
205   count_ = count;
206 }
207 
Addresses(size_t * count) const208 const void *const *StackTrace::Addresses(size_t* count) const {
209   *count = count_;
210   if (count_)
211     return trace_;
212   return nullptr;
213 }
214 
ToString() const215 std::string StackTrace::ToString() const {
216   std::stringstream stream;
217 #if !defined(__UCLIBC__) && !defined(_AIX)
218   OutputToStream(&stream);
219 #endif
220   return stream.str();
221 }
222 
223 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
224 
TraceStackFramePointers(const void ** out_trace,size_t max_depth,size_t skip_initial)225 size_t TraceStackFramePointers(const void** out_trace,
226                                size_t max_depth,
227                                size_t skip_initial) {
228   // Usage of __builtin_frame_address() enables frame pointers in this
229   // function even if they are not enabled globally. So 'fp' will always
230   // be valid.
231   uintptr_t fp = reinterpret_cast<uintptr_t>(__builtin_frame_address(0)) -
232                     kStackFrameAdjustment;
233 
234   uintptr_t stack_end = GetStackEnd();
235 
236   size_t depth = 0;
237   while (depth < max_depth) {
238     if (skip_initial != 0) {
239       skip_initial--;
240     } else {
241       out_trace[depth++] = reinterpret_cast<const void*>(GetStackFramePC(fp));
242     }
243 
244     uintptr_t next_fp = GetNextStackFrame(fp);
245     if (IsStackFrameValid(next_fp, fp, stack_end)) {
246       fp = next_fp;
247       continue;
248     }
249 
250     next_fp = ScanStackForNextFrame(fp, stack_end);
251     if (next_fp) {
252       fp = next_fp;
253       continue;
254     }
255 
256     // Failed to find next frame.
257     break;
258   }
259 
260   return depth;
261 }
262 
ScopedStackFrameLinker(void * fp,void * parent_fp)263 ScopedStackFrameLinker::ScopedStackFrameLinker(void* fp, void* parent_fp)
264     : fp_(fp),
265       parent_fp_(parent_fp),
266       original_parent_fp_(LinkStackFrames(fp, parent_fp)) {}
267 
~ScopedStackFrameLinker()268 ScopedStackFrameLinker::~ScopedStackFrameLinker() {
269   void* previous_parent_fp = LinkStackFrames(fp_, original_parent_fp_);
270   CHECK_EQ(parent_fp_, previous_parent_fp)
271       << "Stack frame's parent pointer has changed!";
272 }
273 
274 #endif  // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
275 
276 }  // namespace debug
277 }  // namespace base
278