Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(81)

Side by Side Diff: base/debug/stack_trace.cc

Issue 2276813002: Unwind stack past system libraries on Linux. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@get-stack-end-linux
Patch Set: Introduce ScanStackForNextFrame Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/debug/stack_trace.h" 5 #include "base/debug/stack_trace.h"
6 6
7 #include <string.h> 7 #include <string.h>
8 8
9 #include <algorithm> 9 #include <algorithm>
10 #include <limits>
11 #include <sstream> 10 #include <sstream>
12 11
13 #include "base/macros.h" 12 #include "base/macros.h"
14 13
15 #if HAVE_TRACE_STACK_FRAME_POINTERS 14 #if HAVE_TRACE_STACK_FRAME_POINTERS
16 15
17 #if defined(OS_LINUX) || defined(OS_ANDROID) 16 #if defined(OS_LINUX) || defined(OS_ANDROID)
18 #include <pthread.h> 17 #include <pthread.h>
19 #include "base/process/process_handle.h" 18 #include "base/process/process_handle.h"
20 #include "base/threading/platform_thread.h" 19 #include "base/threading/platform_thread.h"
21 #endif 20 #endif
22 21
23 #if defined(OS_LINUX) && defined(__GLIBC__) 22 #if defined(OS_LINUX) && defined(__GLIBC__)
24 extern "C" void* __libc_stack_end; 23 extern "C" void* __libc_stack_end;
25 #endif 24 #endif
26 25
27 #endif // HAVE_TRACE_STACK_FRAME_POINTERS 26 #endif // HAVE_TRACE_STACK_FRAME_POINTERS
28 27
29 namespace base { 28 namespace base {
30 namespace debug { 29 namespace debug {
31 30
32 StackTrace::StackTrace(const void* const* trace, size_t count) { 31 namespace {
33 count = std::min(count, arraysize(trace_));
34 if (count)
35 memcpy(trace_, trace, count * sizeof(trace_[0]));
36 count_ = count;
37 }
38
39 StackTrace::~StackTrace() {
40 }
41
42 const void *const *StackTrace::Addresses(size_t* count) const {
43 *count = count_;
44 if (count_)
45 return trace_;
46 return NULL;
47 }
48
49 std::string StackTrace::ToString() const {
50 std::stringstream stream;
51 #if !defined(__UCLIBC__)
52 OutputToStream(&stream);
53 #endif
54 return stream.str();
55 }
56 32
57 #if HAVE_TRACE_STACK_FRAME_POINTERS 33 #if HAVE_TRACE_STACK_FRAME_POINTERS
58 34
59 static uintptr_t GetStackEnd() { 35 #if defined(OS_LINUX)
36 // TraceStackFramePointers() will try to scan stack for frame pointers to
37 // continue unwinding past system libraries. Only supported on Linux where
38 // system libraries are usually in the middle of the trace, for example:
39 //
40 // TraceStackFramePointers
41 // <more frames from Chrome>
42 // g_main_context_dispatch <--- unwinding stops here
43 // g_main_context_iteration
44 // base::MessagePumpGlib::Run
45 // base::RunLoop::Run <--- resumes from here
46 // <more frames from Chrome>
47 // __libc_start_main
48 //
49 // Note that base::MessagePumpGlib::Run() is lost, because its frame was
50 // not saved by g_main_context_iteration().
51 //
52 // For stack scanning to be efficient it's very important for the thread to
53 // be started by Chrome. In that case we naturally terminate unwinding once
54 // we reach the origin of the stack (i.e. GetStackEnd()). If the thread was
55 // not started by Chrome (e.g. Android's main thread), then we end up always
56 // scanning area at the origin of the stack, wasting time and not finding any
57 // frames (since e.g. Android libraries don't have frame pointers).
58 #define SCAN_STACK_FOR_FRAMES
59
60 // Allows to resume ~95% of all prematurely terminated traces on Linux.
61 constexpr size_t kMaxStackScanArea = 512;
62 #endif
63
64 #if defined(__arm__) && defined(__GNUC__) && !defined(__clang__)
65 // GCC and LLVM generate slightly different frames on ARM, see
66 // https://llvm.org/bugs/show_bug.cgi?id=18505 - LLVM generates
67 // x86-compatible frame, while GCC needs adjustment.
68 constexpr size_t kStackFrameAdjustment = sizeof(uintptr_t);
69 #else
70 constexpr size_t kStackFrameAdjustment = 0;
71 #endif
72
73 // Returns end of the stack, or 0 if we couldn't get it.
74 uintptr_t GetStackEnd() {
60 #if defined(OS_ANDROID) 75 #if defined(OS_ANDROID)
61 // Bionic reads proc/maps on every call to pthread_getattr_np() when called 76 // Bionic reads proc/maps on every call to pthread_getattr_np() when called
62 // from the main thread. So we need to cache end of stack in that case to get 77 // from the main thread. So we need to cache end of stack in that case to get
63 // acceptable performance. 78 // acceptable performance.
64 // For all other threads pthread_getattr_np() is fast enough as it just reads 79 // For all other threads pthread_getattr_np() is fast enough as it just reads
65 // values from its pthread_t argument. 80 // values from its pthread_t argument.
66 static uintptr_t main_stack_end = 0; 81 static uintptr_t main_stack_end = 0;
67 82
68 bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId(); 83 bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId();
69 if (is_main_thread && main_stack_end) { 84 if (is_main_thread && main_stack_end) {
(...skipping 10 matching lines...) Expand all
80 reinterpret_cast<void**>(&stack_begin), 95 reinterpret_cast<void**>(&stack_begin),
81 &stack_size); 96 &stack_size);
82 pthread_attr_destroy(&attributes); 97 pthread_attr_destroy(&attributes);
83 } 98 }
84 DCHECK(!error); 99 DCHECK(!error);
85 100
86 uintptr_t stack_end = stack_begin + stack_size; 101 uintptr_t stack_end = stack_begin + stack_size;
87 if (is_main_thread) { 102 if (is_main_thread) {
88 main_stack_end = stack_end; 103 main_stack_end = stack_end;
89 } 104 }
90 return stack_end; 105 return stack_end; // 0 in case of error
91 106
92 #elif defined(OS_LINUX) && defined(__GLIBC__) 107 #elif defined(OS_LINUX) && defined(__GLIBC__)
93 108
94 if (GetCurrentProcId() == PlatformThread::CurrentId()) { 109 if (GetCurrentProcId() == PlatformThread::CurrentId()) {
95 // For the main thread we have a shortcut. 110 // For the main thread we have a shortcut.
96 return reinterpret_cast<uintptr_t>(__libc_stack_end); 111 return reinterpret_cast<uintptr_t>(__libc_stack_end);
97 } 112 }
98 113
99 // No easy way to get stack end for non-main threads, see crbug.com/617730. 114 // No easy way to get end of the stack for non-main threads,
100 115 // see crbug.com/617730.
101 #else
102
103 // TODO(dskiba): support Windows, macOS
104 116
105 #endif 117 #endif
106 118
107 // Couldn't get end of stack address. 119 // Don't know how to get end of the stack.
108 return std::numeric_limits<uintptr_t>::max(); 120 return 0;
109 } 121 }
110 122
123 uintptr_t GetNextStackFrame(uintptr_t fp) {
124 return reinterpret_cast<const uintptr_t*>(fp)[0] - kStackFrameAdjustment;
125 }
126
127 uintptr_t GetStackFramePC(uintptr_t fp) {
128 return reinterpret_cast<const uintptr_t*>(fp)[1];
129 }
130
131 bool IsStackFrameValid(uintptr_t fp, uintptr_t prev_fp, uintptr_t stack_end) {
132 // With the stack growing downwards, older stack frame must be
133 // at a greater address that the current one.
134 if (fp <= prev_fp) return false;
135
136 // Assume huge stack frames are bogus.
137 if (fp - prev_fp > 100000) return false;
138
139 // Check alignment.
140 if (fp & (sizeof(uintptr_t) - 1)) return false;
141
142 if (stack_end) {
143 // Both fp[0] and fp[1] must be within the stack.
144 if (fp > stack_end - 2 * sizeof(uintptr_t)) return false;
145
146 #if defined(SCAN_STACK_FOR_FRAMES)
Primiano Tucci (use gerrit) 2016/08/31 13:48:50 why this extra check is if-defed? makes sense in a
147 // Additional check to filter out false positives.
148 if (GetStackFramePC(fp) < 32768) return false;
149 #endif
150 }
151
152 return true;
153 };
154
155 #if defined(SCAN_STACK_FOR_FRAMES)
156
157 // Returns 0 on failure.
158 uintptr_t ScanStackForNextFrame(uintptr_t fp, uintptr_t stack_end) {
159 if (!stack_end) {
160 // Too dangerous to scan without knowing where the stack ends.
161 return 0;
162 }
163
164 fp += sizeof(uintptr_t); // current frame is known to be invalid
165 uintptr_t last_fp_to_scan = std::min(fp + kMaxStackScanArea, stack_end) -
166 sizeof(uintptr_t);
167 for (;fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
168 uintptr_t next_fp = GetNextStackFrame(fp);
169 if (IsStackFrameValid(next_fp, fp, stack_end)) {
Primiano Tucci (use gerrit) 2016/08/31 13:48:50 Ahhh now I understand what this really does. For a
170 // Check two frames deep. Since stack frame is just a pointer to
171 // a higher address on the stack, it's relatively easy to find
172 // something that looks like one. However two linked frames are
173 // far less likely to be bogus.
174 uintptr_t next2_fp = GetNextStackFrame(next_fp);
175 if (IsStackFrameValid(next2_fp, next_fp, stack_end)) {
176 return fp;
177 }
178 }
179 }
180
181 return 0;
182 }
183
184 #endif // defined(SCAN_STACK_FOR_FRAMES)
185
186 #endif // HAVE_TRACE_STACK_FRAME_POINTERS
187
188 } // namespace
189
190 StackTrace::StackTrace(const void* const* trace, size_t count) {
191 count = std::min(count, arraysize(trace_));
192 if (count)
193 memcpy(trace_, trace, count * sizeof(trace_[0]));
194 count_ = count;
195 }
196
197 StackTrace::~StackTrace() {
Primiano Tucci (use gerrit) 2016/08/31 13:48:50 nit: I think this should be {} (without the newlin
198 }
199
200 const void *const *StackTrace::Addresses(size_t* count) const {
201 *count = count_;
202 if (count_)
203 return trace_;
204 return NULL;
205 }
206
207 std::string StackTrace::ToString() const {
208 std::stringstream stream;
209 #if !defined(__UCLIBC__)
210 OutputToStream(&stream);
211 #endif
212 return stream.str();
213 }
214
215 #if HAVE_TRACE_STACK_FRAME_POINTERS
216
111 size_t TraceStackFramePointers(const void** out_trace, 217 size_t TraceStackFramePointers(const void** out_trace,
112 size_t max_depth, 218 size_t max_depth,
113 size_t skip_initial) { 219 size_t skip_initial) {
114 // Usage of __builtin_frame_address() enables frame pointers in this 220 // Usage of __builtin_frame_address() enables frame pointers in this
115 // function even if they are not enabled globally. So 'sp' will always 221 // function even if they are not enabled globally. So 'fp' will always
116 // be valid. 222 // be valid.
117 uintptr_t sp = reinterpret_cast<uintptr_t>(__builtin_frame_address(0)); 223 uintptr_t fp = reinterpret_cast<uintptr_t>(__builtin_frame_address(0)) -
224 kStackFrameAdjustment;
118 225
119 uintptr_t stack_end = GetStackEnd(); 226 uintptr_t stack_end = GetStackEnd();
120 227
121 size_t depth = 0; 228 size_t depth = 0;
122 while (depth < max_depth) { 229 while (depth < max_depth) {
123 #if defined(__arm__) && defined(__GNUC__) && !defined(__clang__)
124 // GCC and LLVM generate slightly different frames on ARM, see
125 // https://llvm.org/bugs/show_bug.cgi?id=18505 - LLVM generates
126 // x86-compatible frame, while GCC needs adjustment.
127 sp -= sizeof(uintptr_t);
128 #endif
129
130 // Both sp[0] and s[1] must be valid.
131 if (sp + 2 * sizeof(uintptr_t) > stack_end) {
132 break;
133 }
134
135 if (skip_initial != 0) { 230 if (skip_initial != 0) {
136 skip_initial--; 231 skip_initial--;
137 } else { 232 } else {
138 out_trace[depth++] = reinterpret_cast<const void**>(sp)[1]; 233 out_trace[depth++] = reinterpret_cast<const void*>(GetStackFramePC(fp));
Primiano Tucci (use gerrit) 2016/08/31 13:48:50 I think you just lost the protection for the first
Dmitry Skiba 2016/09/07 22:33:24 Actually, __builtin_frame_address() will force fra
139 } 234 }
140 235
141 // Find out next frame pointer 236 uintptr_t next_fp = GetNextStackFrame(fp);
142 // (heuristics are from TCMalloc's stacktrace functions) 237 if (IsStackFrameValid(next_fp, fp, stack_end)) {
143 { 238 fp = next_fp;
144 uintptr_t next_sp = reinterpret_cast<const uintptr_t*>(sp)[0]; 239 continue;
240 }
241 #if defined(SCAN_STACK_FOR_FRAMES)
242 next_fp = ScanStackForNextFrame(fp, stack_end);
243 if (next_fp) {
244 fp = next_fp;
245 continue;
246 }
247 #endif
145 248
146 // With the stack growing downwards, older stack frame must be 249 // Failed to find next frame.
147 // at a greater address that the current one. 250 break;
148 if (next_sp <= sp) break;
149
150 // Assume stack frames larger than 100,000 bytes are bogus.
151 if (next_sp - sp > 100000) break;
152
153 // Check alignment.
154 if (sp & (sizeof(void*) - 1)) break;
155
156 sp = next_sp;
157 }
158 } 251 }
159 252
160 return depth; 253 return depth;
161 } 254 }
162 255
163 #endif // HAVE_TRACE_STACK_FRAME_POINTERS 256 #endif // HAVE_TRACE_STACK_FRAME_POINTERS
164 257
165 } // namespace debug 258 } // namespace debug
166 } // namespace base 259 } // namespace base
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698