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