Chromium Code Reviews

Side by Side Diff: src/base/debug/stack_trace_posix.cc

Issue 2248393002: Replace DumpBacktrace with Chromium's StackTrace implementation. (Closed) Base URL: https://chromium.googlesource.com/v8/v8.git@master
Patch Set: Fix mac Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff |
OLDNEW
(Empty)
1 // Copyright 2016 the V8 project 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 "src/base/debug/stack_trace.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <signal.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <sys/param.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18
19 #include <map>
20 #include <memory>
21 #include <ostream>
22 #include <string>
23 #include <vector>
24
25 #if V8_LIBC_GLIBC || V8_OS_BSD
26 #include <cxxabi.h>
27 #include <execinfo.h>
28 #endif
29 #if V8_OS_MACOSX
30 #include <AvailabilityMacros.h>
31 #endif
32
33 #include "src/base/build_config.h"
34 #include "src/base/free_deleter.h"
35 #include "src/base/logging.h"
36 #include "src/base/macros.h"
37
38 namespace v8 {
39 namespace base {
40 namespace debug {
41
42 namespace internal {
43
44 // POSIX doesn't define any async-signal safe function for converting
45 // an integer to ASCII. We'll have to define our own version.
46 // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
47 // conversion was successful or NULL otherwise. It never writes more than "sz"
48 // bytes. Output will be truncated as needed, and a NUL character is always
49 // appended.
50 char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding);
51
52 } // namespace internal
53
54 namespace {
55
56 volatile sig_atomic_t in_signal_handler = 0;
57 bool dump_stack_in_signal_handler = 1;
58
59 // The prefix used for mangled symbols, per the Itanium C++ ABI:
60 // http://www.codesourcery.com/cxx-abi/abi.html#mangling
61 const char kMangledSymbolPrefix[] = "_Z";
62
63 // Characters that can be used for symbols, generated by Ruby:
64 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
65 const char kSymbolCharacters[] =
66 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
67
68 // Demangles C++ symbols in the given text. Example:
69 //
70 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
71 // =>
72 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
73 void DemangleSymbols(std::string* text) {
74 // Note: code in this function is NOT async-signal safe (std::string uses
75 // malloc internally).
76
77 #if V8_LIBC_GLIBC || V8_OS_BSD
78
79 std::string::size_type search_from = 0;
80 while (search_from < text->size()) {
81 // Look for the start of a mangled symbol, from search_from.
82 std::string::size_type mangled_start =
83 text->find(kMangledSymbolPrefix, search_from);
84 if (mangled_start == std::string::npos) {
85 break; // Mangled symbol not found.
86 }
87
88 // Look for the end of the mangled symbol.
89 std::string::size_type mangled_end =
90 text->find_first_not_of(kSymbolCharacters, mangled_start);
91 if (mangled_end == std::string::npos) {
92 mangled_end = text->size();
93 }
94 std::string mangled_symbol =
95 text->substr(mangled_start, mangled_end - mangled_start);
96
97 // Try to demangle the mangled symbol candidate.
98 int status = 0;
99 std::unique_ptr<char, FreeDeleter> demangled_symbol(
100 abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
101 if (status == 0) { // Demangling is successful.
102 // Remove the mangled symbol.
103 text->erase(mangled_start, mangled_end - mangled_start);
104 // Insert the demangled symbol.
105 text->insert(mangled_start, demangled_symbol.get());
106 // Next time, we'll start right after the demangled symbol we inserted.
107 search_from = mangled_start + strlen(demangled_symbol.get());
108 } else {
109 // Failed to demangle. Retry after the "_Z" we just found.
110 search_from = mangled_start + 2;
111 }
112 }
113
114 #endif // V8_LIBC_GLIBC || V8_OS_BSD
115 }
116
117 class BacktraceOutputHandler {
118 public:
119 virtual void HandleOutput(const char* output) = 0;
120
121 protected:
122 virtual ~BacktraceOutputHandler() {}
123 };
124
125 void OutputPointer(void* pointer, BacktraceOutputHandler* handler) {
126 // This should be more than enough to store a 64-bit number in hex:
127 // 16 hex digits + 1 for null-terminator.
128 char buf[17] = {'\0'};
129 handler->HandleOutput("0x");
130 internal::itoa_r(reinterpret_cast<intptr_t>(pointer), buf, sizeof(buf), 16,
131 12);
132 handler->HandleOutput(buf);
133 }
134
135 void ProcessBacktrace(void* const* trace, size_t size,
136 BacktraceOutputHandler* handler) {
137 // NOTE: This code MUST be async-signal safe (it's used by in-process
138 // stack dumping signal handler). NO malloc or stdio is allowed here.
139 handler->HandleOutput("\n");
140 handler->HandleOutput("==== C stack trace ===============================\n");
141 handler->HandleOutput("\n");
142
143 bool printed = false;
144
145 // Below part is async-signal unsafe (uses malloc), so execute it only
146 // when we are not executing the signal handler.
147 if (in_signal_handler == 0) {
148 std::unique_ptr<char*, FreeDeleter> trace_symbols(
149 backtrace_symbols(trace, static_cast<int>(size)));
150 if (trace_symbols.get()) {
151 for (size_t i = 0; i < size; ++i) {
152 std::string trace_symbol = trace_symbols.get()[i];
153 DemangleSymbols(&trace_symbol);
154 handler->HandleOutput(" ");
155 handler->HandleOutput(trace_symbol.c_str());
156 handler->HandleOutput("\n");
157 }
158
159 printed = true;
160 }
161 }
162
163 if (!printed) {
164 for (size_t i = 0; i < size; ++i) {
165 handler->HandleOutput(" [");
166 OutputPointer(trace[i], handler);
167 handler->HandleOutput("]\n");
168 }
169 }
170 }
171
172 void PrintToStderr(const char* output) {
173 // NOTE: This code MUST be async-signal safe (it's used by in-process
174 // stack dumping signal handler). NO malloc or stdio is allowed here.
175 write(STDERR_FILENO, output, strlen(output));
176 }
177
178 void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
179 // NOTE: This code MUST be async-signal safe.
180 // NO malloc or stdio is allowed here.
181
182 // Record the fact that we are in the signal handler now, so that the rest
183 // of StackTrace can behave in an async-signal-safe manner.
184 in_signal_handler = 1;
185
186 PrintToStderr("Received signal ");
187 char buf[1024] = {0};
188 internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
189 PrintToStderr(buf);
190 if (signal == SIGBUS) {
191 if (info->si_code == BUS_ADRALN)
192 PrintToStderr(" BUS_ADRALN ");
193 else if (info->si_code == BUS_ADRERR)
194 PrintToStderr(" BUS_ADRERR ");
195 else if (info->si_code == BUS_OBJERR)
196 PrintToStderr(" BUS_OBJERR ");
197 else
198 PrintToStderr(" <unknown> ");
199 } else if (signal == SIGFPE) {
200 if (info->si_code == FPE_FLTDIV)
201 PrintToStderr(" FPE_FLTDIV ");
202 else if (info->si_code == FPE_FLTINV)
203 PrintToStderr(" FPE_FLTINV ");
204 else if (info->si_code == FPE_FLTOVF)
205 PrintToStderr(" FPE_FLTOVF ");
206 else if (info->si_code == FPE_FLTRES)
207 PrintToStderr(" FPE_FLTRES ");
208 else if (info->si_code == FPE_FLTSUB)
209 PrintToStderr(" FPE_FLTSUB ");
210 else if (info->si_code == FPE_FLTUND)
211 PrintToStderr(" FPE_FLTUND ");
212 else if (info->si_code == FPE_INTDIV)
213 PrintToStderr(" FPE_INTDIV ");
214 else if (info->si_code == FPE_INTOVF)
215 PrintToStderr(" FPE_INTOVF ");
216 else
217 PrintToStderr(" <unknown> ");
218 } else if (signal == SIGILL) {
219 if (info->si_code == ILL_BADSTK)
220 PrintToStderr(" ILL_BADSTK ");
221 else if (info->si_code == ILL_COPROC)
222 PrintToStderr(" ILL_COPROC ");
223 else if (info->si_code == ILL_ILLOPN)
224 PrintToStderr(" ILL_ILLOPN ");
225 else if (info->si_code == ILL_ILLADR)
226 PrintToStderr(" ILL_ILLADR ");
227 else if (info->si_code == ILL_ILLTRP)
228 PrintToStderr(" ILL_ILLTRP ");
229 else if (info->si_code == ILL_PRVOPC)
230 PrintToStderr(" ILL_PRVOPC ");
231 else if (info->si_code == ILL_PRVREG)
232 PrintToStderr(" ILL_PRVREG ");
233 else
234 PrintToStderr(" <unknown> ");
235 } else if (signal == SIGSEGV) {
236 if (info->si_code == SEGV_MAPERR)
237 PrintToStderr(" SEGV_MAPERR ");
238 else if (info->si_code == SEGV_ACCERR)
239 PrintToStderr(" SEGV_ACCERR ");
240 else
241 PrintToStderr(" <unknown> ");
242 }
243 if (signal == SIGBUS || signal == SIGFPE || signal == SIGILL ||
244 signal == SIGSEGV) {
245 internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr), buf,
246 sizeof(buf), 16, 12);
247 PrintToStderr(buf);
248 }
249 PrintToStderr("\n");
250 if (dump_stack_in_signal_handler) {
251 debug::StackTrace().Print();
252 PrintToStderr("[end of stack trace]\n");
253 }
254
255 if (::signal(signal, SIG_DFL) == SIG_ERR) _exit(1);
256 }
257
258 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
259 public:
260 PrintBacktraceOutputHandler() {}
261
262 void HandleOutput(const char* output) override {
263 // NOTE: This code MUST be async-signal safe (it's used by in-process
264 // stack dumping signal handler). NO malloc or stdio is allowed here.
265 PrintToStderr(output);
266 }
267
268 private:
269 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
270 };
271
272 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
273 public:
274 explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {}
275
276 void HandleOutput(const char* output) override { (*os_) << output; }
277
278 private:
279 std::ostream* os_;
280
281 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
282 };
283
284 void WarmUpBacktrace() {
285 // Warm up stack trace infrastructure. It turns out that on the first
286 // call glibc initializes some internal data structures using pthread_once,
287 // and even backtrace() can call malloc(), leading to hangs.
288 //
289 // Example stack trace snippet (with tcmalloc):
290 //
291 // #8 0x0000000000a173b5 in tc_malloc
292 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
293 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
294 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
295 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
296 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
297 // at dl-open.c:639
298 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
299 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
300 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
301 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
302 // #17 0x00007ffff61ef8f5 in init
303 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
304 // #18 0x00007ffff6aad400 in pthread_once
305 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
306 // #19 0x00007ffff61efa14 in __GI___backtrace
307 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
308 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
309 // at base/debug/stack_trace_posix.cc:175
310 // #21 0x00000000007a4ae5 in
311 // base::(anonymous namespace)::StackDumpSignalHandler
312 // at base/process_util_posix.cc:172
313 // #22 <signal handler called>
314 StackTrace stack_trace;
315 }
316
317 } // namespace
318
319 bool EnableInProcessStackDumping() {
320 // When running in an application, our code typically expects SIGPIPE
321 // to be ignored. Therefore, when testing that same code, it should run
322 // with SIGPIPE ignored as well.
323 struct sigaction sigpipe_action;
324 memset(&sigpipe_action, 0, sizeof(sigpipe_action));
325 sigpipe_action.sa_handler = SIG_IGN;
326 sigemptyset(&sigpipe_action.sa_mask);
327 bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
328
329 // Avoid hangs during backtrace initialization, see above.
330 WarmUpBacktrace();
331
332 struct sigaction action;
333 memset(&action, 0, sizeof(action));
334 action.sa_flags = SA_RESETHAND | SA_SIGINFO;
335 action.sa_sigaction = &StackDumpSignalHandler;
336 sigemptyset(&action.sa_mask);
337
338 success &= (sigaction(SIGILL, &action, NULL) == 0);
339 success &= (sigaction(SIGABRT, &action, NULL) == 0);
340 success &= (sigaction(SIGFPE, &action, NULL) == 0);
341 success &= (sigaction(SIGBUS, &action, NULL) == 0);
342 success &= (sigaction(SIGSEGV, &action, NULL) == 0);
343 success &= (sigaction(SIGSYS, &action, NULL) == 0);
344
345 dump_stack_in_signal_handler = true;
346
347 return success;
348 }
349
350 void DisableSignalStackDump() {
351 dump_stack_in_signal_handler = false;
352 }
353
354 StackTrace::StackTrace() {
355 // NOTE: This code MUST be async-signal safe (it's used by in-process
356 // stack dumping signal handler). NO malloc or stdio is allowed here.
357
358 // Though the backtrace API man page does not list any possible negative
359 // return values, we take no chance.
360 count_ = static_cast<size_t>(backtrace(trace_, arraysize(trace_)));
361 }
362
363 void StackTrace::Print() const {
364 // NOTE: This code MUST be async-signal safe (it's used by in-process
365 // stack dumping signal handler). NO malloc or stdio is allowed here.
366
367 PrintBacktraceOutputHandler handler;
368 ProcessBacktrace(trace_, count_, &handler);
369 }
370
371 void StackTrace::OutputToStream(std::ostream* os) const {
372 StreamBacktraceOutputHandler handler(os);
373 ProcessBacktrace(trace_, count_, &handler);
374 }
375
376 namespace internal {
377
378 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
379 char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
380 // Make sure we can write at least one NUL byte.
381 size_t n = 1;
382 if (n > sz) return NULL;
383
384 if (base < 2 || base > 16) {
385 buf[0] = '\000';
386 return NULL;
387 }
388
389 char* start = buf;
390
391 uintptr_t j = i;
392
393 // Handle negative numbers (only for base 10).
394 if (i < 0 && base == 10) {
395 // This does "j = -i" while avoiding integer overflow.
396 j = static_cast<uintptr_t>(-(i + 1)) + 1;
397
398 // Make sure we can write the '-' character.
399 if (++n > sz) {
400 buf[0] = '\000';
401 return NULL;
402 }
403 *start++ = '-';
404 }
405
406 // Loop until we have converted the entire number. Output at least one
407 // character (i.e. '0').
408 char* ptr = start;
409 do {
410 // Make sure there is still enough space left in our output buffer.
411 if (++n > sz) {
412 buf[0] = '\000';
413 return NULL;
414 }
415
416 // Output the next digit.
417 *ptr++ = "0123456789abcdef"[j % base];
418 j /= base;
419
420 if (padding > 0) padding--;
421 } while (j > 0 || padding > 0);
422
423 // Terminate the output with a NUL character.
424 *ptr = '\000';
425
426 // Conversion to ASCII actually resulted in the digits being in reverse
427 // order. We can't easily generate them in forward order, as we can't tell
428 // the number of characters needed until we are done converting.
429 // So, now, we reverse the string (except for the possible "-" sign).
430 while (--ptr > start) {
431 char ch = *ptr;
432 *ptr = *start;
433 *start++ = ch;
434 }
435 return buf;
436 }
437
438 } // namespace internal
439
440 } // namespace debug
441 } // namespace base
442 } // namespace v8
OLDNEW

Powered by Google App Engine