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]"
DemangleSymbols(std::string * text)80 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 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 text->find(kMangledSymbolPrefix, search_from);
91 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 text->find_first_not_of(kSymbolCharacters, mangled_start);
98 if (mangled_end == std::string::npos) {
99 mangled_end = text->size();
100 }
101 std::string mangled_symbol =
102 text->substr(mangled_start, mangled_end - mangled_start);
103
104 // Try to demangle the mangled symbol candidate.
105 int status = 0;
106 std::unique_ptr<char, FreeDeleter> demangled_symbol(
107 abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
108 if (status == 0) { // Demangling is successful.
109 // Remove the mangled symbol.
110 text->erase(mangled_start, mangled_end - mangled_start);
111 // Insert the demangled symbol.
112 text->insert(mangled_start, demangled_symbol.get());
113 // Next time, we'll start right after the demangled symbol we inserted.
114 search_from = mangled_start + strlen(demangled_symbol.get());
115 } else {
116 // Failed to demangle. Retry after the "_Z" we just found.
117 search_from = mangled_start + 2;
118 }
119 }
120
121 #endif // HAVE_EXECINFO_H
122 }
123
124 class BacktraceOutputHandler {
125 public:
126 virtual void HandleOutput(const char* output) = 0;
127
128 protected:
~BacktraceOutputHandler()129 virtual ~BacktraceOutputHandler() {}
130 };
131
OutputPointer(void * pointer,BacktraceOutputHandler * handler)132 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 char buf[17] = {'\0'};
136 handler->HandleOutput("0x");
137 internal::itoa_r(reinterpret_cast<intptr_t>(pointer), buf, sizeof(buf), 16,
138 12);
139 handler->HandleOutput(buf);
140 }
141
142 #if HAVE_EXECINFO_H
ProcessBacktrace(void * const * trace,size_t size,BacktraceOutputHandler * handler)143 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 handler->HandleOutput("\n");
148 handler->HandleOutput("==== C stack trace ===============================\n");
149 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 if (in_signal_handler == 0) {
156 std::unique_ptr<char*, FreeDeleter> trace_symbols(
157 backtrace_symbols(trace, static_cast<int>(size)));
158 if (trace_symbols.get()) {
159 for (size_t i = 0; i < size; ++i) {
160 std::string trace_symbol = trace_symbols.get()[i];
161 DemangleSymbols(&trace_symbol);
162 handler->HandleOutput(" ");
163 handler->HandleOutput(trace_symbol.c_str());
164 handler->HandleOutput("\n");
165 }
166
167 printed = true;
168 }
169 }
170
171 if (!printed) {
172 for (size_t i = 0; i < size; ++i) {
173 handler->HandleOutput(" [");
174 OutputPointer(trace[i], handler);
175 handler->HandleOutput("]\n");
176 }
177 }
178 }
179 #endif // HAVE_EXECINFO_H
180
PrintToStderr(const char * output)181 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 ssize_t return_val = write(STDERR_FILENO, output, strlen(output));
185 USE(return_val);
186 }
187
StackDumpSignalHandler(int signal,siginfo_t * info,void * void_context)188 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 in_signal_handler = 1;
195
196 PrintToStderr("Received signal ");
197 char buf[1024] = {0};
198 internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
199 PrintToStderr(buf);
200 if (signal == SIGBUS) {
201 if (info->si_code == BUS_ADRALN)
202 PrintToStderr(" BUS_ADRALN ");
203 else if (info->si_code == BUS_ADRERR)
204 PrintToStderr(" BUS_ADRERR ");
205 else if (info->si_code == BUS_OBJERR)
206 PrintToStderr(" BUS_OBJERR ");
207 else
208 PrintToStderr(" <unknown> ");
209 } else if (signal == SIGFPE) {
210 if (info->si_code == FPE_FLTDIV)
211 PrintToStderr(" FPE_FLTDIV ");
212 else if (info->si_code == FPE_FLTINV)
213 PrintToStderr(" FPE_FLTINV ");
214 else if (info->si_code == FPE_FLTOVF)
215 PrintToStderr(" FPE_FLTOVF ");
216 else if (info->si_code == FPE_FLTRES)
217 PrintToStderr(" FPE_FLTRES ");
218 else if (info->si_code == FPE_FLTSUB)
219 PrintToStderr(" FPE_FLTSUB ");
220 else if (info->si_code == FPE_FLTUND)
221 PrintToStderr(" FPE_FLTUND ");
222 else if (info->si_code == FPE_INTDIV)
223 PrintToStderr(" FPE_INTDIV ");
224 else if (info->si_code == FPE_INTOVF)
225 PrintToStderr(" FPE_INTOVF ");
226 else
227 PrintToStderr(" <unknown> ");
228 } else if (signal == SIGILL) {
229 if (info->si_code == ILL_BADSTK)
230 PrintToStderr(" ILL_BADSTK ");
231 else if (info->si_code == ILL_COPROC)
232 PrintToStderr(" ILL_COPROC ");
233 else if (info->si_code == ILL_ILLOPN)
234 PrintToStderr(" ILL_ILLOPN ");
235 else if (info->si_code == ILL_ILLADR)
236 PrintToStderr(" ILL_ILLADR ");
237 else if (info->si_code == ILL_ILLTRP)
238 PrintToStderr(" ILL_ILLTRP ");
239 else if (info->si_code == ILL_PRVOPC)
240 PrintToStderr(" ILL_PRVOPC ");
241 else if (info->si_code == ILL_PRVREG)
242 PrintToStderr(" ILL_PRVREG ");
243 else
244 PrintToStderr(" <unknown> ");
245 } else if (signal == SIGSEGV) {
246 if (info->si_code == SEGV_MAPERR)
247 PrintToStderr(" SEGV_MAPERR ");
248 else if (info->si_code == SEGV_ACCERR)
249 PrintToStderr(" SEGV_ACCERR ");
250 else
251 PrintToStderr(" <unknown> ");
252 }
253 if (signal == SIGBUS || signal == SIGFPE || signal == SIGILL ||
254 signal == SIGSEGV) {
255 internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr), buf,
256 sizeof(buf), 16, 12);
257 PrintToStderr(buf);
258 }
259 PrintToStderr("\n");
260 if (dump_stack_in_signal_handler) {
261 debug::StackTrace().Print();
262 PrintToStderr("[end of stack trace]\n");
263 }
264
265 if (::signal(signal, SIG_DFL) == SIG_ERR) _exit(1);
266 }
267
268 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
269 public:
PrintBacktraceOutputHandler()270 PrintBacktraceOutputHandler() {}
271
HandleOutput(const char * output)272 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 PrintToStderr(output);
276 }
277
278 private:
279 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
280 };
281
282 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
283 public:
StreamBacktraceOutputHandler(std::ostream * os)284 explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {}
285
HandleOutput(const char * output)286 void HandleOutput(const char* output) override { (*os_) << output; }
287
288 private:
289 std::ostream* os_;
290
291 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
292 };
293
WarmUpBacktrace()294 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 StackTrace stack_trace;
325 }
326
327 } // namespace
328
EnableInProcessStackDumping()329 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 sigpipe_action.sa_handler = SIG_IGN;
336 sigemptyset(&sigpipe_action.sa_mask);
337 bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
338
339 // Avoid hangs during backtrace initialization, see above.
340 WarmUpBacktrace();
341
342 struct sigaction action;
343 memset(&action, 0, sizeof(action));
344 action.sa_flags = SA_RESETHAND | SA_SIGINFO;
345 action.sa_sigaction = &StackDumpSignalHandler;
346 sigemptyset(&action.sa_mask);
347
348 success &= (sigaction(SIGILL, &action, NULL) == 0);
349 success &= (sigaction(SIGABRT, &action, NULL) == 0);
350 success &= (sigaction(SIGFPE, &action, NULL) == 0);
351 success &= (sigaction(SIGBUS, &action, NULL) == 0);
352 success &= (sigaction(SIGSEGV, &action, NULL) == 0);
353 success &= (sigaction(SIGSYS, &action, NULL) == 0);
354
355 dump_stack_in_signal_handler = true;
356
357 return success;
358 }
359
DisableSignalStackDump()360 void DisableSignalStackDump() {
361 dump_stack_in_signal_handler = false;
362 }
363
StackTrace()364 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 count_ = static_cast<size_t>(backtrace(trace_, arraysize(trace_)));
372 #else
373 count_ = 0;
374 #endif
375 }
376
Print() const377 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 ProcessBacktrace(trace_, count_, &handler);
384 #endif
385 }
386
OutputToStream(std::ostream * os) const387 void StackTrace::OutputToStream(std::ostream* os) const {
388 #if HAVE_EXECINFO_H
389 StreamBacktraceOutputHandler handler(os);
390 ProcessBacktrace(trace_, count_, &handler);
391 #endif
392 }
393
394 namespace internal {
395
396 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
itoa_r(intptr_t i,char * buf,size_t sz,int base,size_t padding)397 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 if (n > sz) return NULL;
401
402 if (base < 2 || base > 16) {
403 buf[0] = '\000';
404 return NULL;
405 }
406
407 char* start = buf;
408
409 uintptr_t j = i;
410
411 // Handle negative numbers (only for base 10).
412 if (i < 0 && base == 10) {
413 // This does "j = -i" while avoiding integer overflow.
414 j = static_cast<uintptr_t>(-(i + 1)) + 1;
415
416 // Make sure we can write the '-' character.
417 if (++n > sz) {
418 buf[0] = '\000';
419 return NULL;
420 }
421 *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 do {
428 // Make sure there is still enough space left in our output buffer.
429 if (++n > sz) {
430 buf[0] = '\000';
431 return NULL;
432 }
433
434 // Output the next digit.
435 *ptr++ = "0123456789abcdef"[j % base];
436 j /= base;
437
438 if (padding > 0) padding--;
439 } while (j > 0 || padding > 0);
440
441 // Terminate the output with a NUL character.
442 *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 while (--ptr > start) {
449 char ch = *ptr;
450 *ptr = *start;
451 *start++ = ch;
452 }
453 return buf;
454 }
455
456 } // namespace internal
457
458 } // namespace debug
459 } // namespace base
460 } // namespace v8
461