• 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 // 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 nullptr otherwise. It never writes more than
55 // "sz" 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 #if HAVE_EXECINFO_H
76 // Demangles C++ symbols in the given text. Example:
77 //
78 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
79 // =>
80 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
DemangleSymbols(std::string * text)81 void DemangleSymbols(std::string* text) {
82   // Note: code in this function is NOT async-signal safe (std::string uses
83   // malloc internally).
84 
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(), nullptr, 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 class BacktraceOutputHandler {
124  public:
125   virtual void HandleOutput(const char* output) = 0;
126 
127  protected:
~BacktraceOutputHandler()128   virtual ~BacktraceOutputHandler() {}
129 };
130 
131 #if HAVE_EXECINFO_H
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 
ProcessBacktrace(void * const * trace,size_t size,BacktraceOutputHandler * handler)142 void ProcessBacktrace(void* const* trace, size_t size,
143                       BacktraceOutputHandler* handler) {
144   // NOTE: This code MUST be async-signal safe (it's used by in-process
145   // stack dumping signal handler). NO malloc or stdio is allowed here.
146   handler->HandleOutput("\n");
147   handler->HandleOutput("==== C stack trace ===============================\n");
148   handler->HandleOutput("\n");
149 
150   bool printed = false;
151 
152   // Below part is async-signal unsafe (uses malloc), so execute it only
153   // when we are not executing the signal handler.
154   if (in_signal_handler == 0) {
155     std::unique_ptr<char*, FreeDeleter> trace_symbols(
156         backtrace_symbols(trace, static_cast<int>(size)));
157     if (trace_symbols.get()) {
158       for (size_t i = 0; i < size; ++i) {
159         std::string trace_symbol = trace_symbols.get()[i];
160         DemangleSymbols(&trace_symbol);
161         handler->HandleOutput("    ");
162         handler->HandleOutput(trace_symbol.c_str());
163         handler->HandleOutput("\n");
164       }
165 
166       printed = true;
167     }
168   }
169 
170   if (!printed) {
171     for (size_t i = 0; i < size; ++i) {
172       handler->HandleOutput(" [");
173       OutputPointer(trace[i], handler);
174       handler->HandleOutput("]\n");
175     }
176   }
177 }
178 #endif  // HAVE_EXECINFO_H
179 
PrintToStderr(const char * output)180 void PrintToStderr(const char* output) {
181   // NOTE: This code MUST be async-signal safe (it's used by in-process
182   // stack dumping signal handler). NO malloc or stdio is allowed here.
183   ssize_t return_val = write(STDERR_FILENO, output, strlen(output));
184   USE(return_val);
185 }
186 
StackDumpSignalHandler(int signal,siginfo_t * info,void * void_context)187 void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
188   // NOTE: This code MUST be async-signal safe.
189   // NO malloc or stdio is allowed here.
190 
191   // Record the fact that we are in the signal handler now, so that the rest
192   // of StackTrace can behave in an async-signal-safe manner.
193   in_signal_handler = 1;
194 
195   PrintToStderr("Received signal ");
196   char buf[1024] = {0};
197   internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
198   PrintToStderr(buf);
199   if (signal == SIGBUS) {
200     if (info->si_code == BUS_ADRALN)
201       PrintToStderr(" BUS_ADRALN ");
202     else if (info->si_code == BUS_ADRERR)
203       PrintToStderr(" BUS_ADRERR ");
204     else if (info->si_code == BUS_OBJERR)
205       PrintToStderr(" BUS_OBJERR ");
206     else
207       PrintToStderr(" <unknown> ");
208   } else if (signal == SIGFPE) {
209     if (info->si_code == FPE_FLTDIV)
210       PrintToStderr(" FPE_FLTDIV ");
211     else if (info->si_code == FPE_FLTINV)
212       PrintToStderr(" FPE_FLTINV ");
213     else if (info->si_code == FPE_FLTOVF)
214       PrintToStderr(" FPE_FLTOVF ");
215     else if (info->si_code == FPE_FLTRES)
216       PrintToStderr(" FPE_FLTRES ");
217     else if (info->si_code == FPE_FLTSUB)
218       PrintToStderr(" FPE_FLTSUB ");
219     else if (info->si_code == FPE_FLTUND)
220       PrintToStderr(" FPE_FLTUND ");
221     else if (info->si_code == FPE_INTDIV)
222       PrintToStderr(" FPE_INTDIV ");
223     else if (info->si_code == FPE_INTOVF)
224       PrintToStderr(" FPE_INTOVF ");
225     else
226       PrintToStderr(" <unknown> ");
227   } else if (signal == SIGILL) {
228     if (info->si_code == ILL_BADSTK)
229       PrintToStderr(" ILL_BADSTK ");
230     else if (info->si_code == ILL_COPROC)
231       PrintToStderr(" ILL_COPROC ");
232     else if (info->si_code == ILL_ILLOPN)
233       PrintToStderr(" ILL_ILLOPN ");
234     else if (info->si_code == ILL_ILLADR)
235       PrintToStderr(" ILL_ILLADR ");
236     else if (info->si_code == ILL_ILLTRP)
237       PrintToStderr(" ILL_ILLTRP ");
238     else if (info->si_code == ILL_PRVOPC)
239       PrintToStderr(" ILL_PRVOPC ");
240     else if (info->si_code == ILL_PRVREG)
241       PrintToStderr(" ILL_PRVREG ");
242     else
243       PrintToStderr(" <unknown> ");
244   } else if (signal == SIGSEGV) {
245     if (info->si_code == SEGV_MAPERR)
246       PrintToStderr(" SEGV_MAPERR ");
247     else if (info->si_code == SEGV_ACCERR)
248       PrintToStderr(" SEGV_ACCERR ");
249     else
250       PrintToStderr(" <unknown> ");
251   }
252   if (signal == SIGBUS || signal == SIGFPE || signal == SIGILL ||
253       signal == SIGSEGV) {
254     internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr), buf,
255                      sizeof(buf), 16, 12);
256     PrintToStderr(buf);
257   }
258   PrintToStderr("\n");
259   if (dump_stack_in_signal_handler) {
260     debug::StackTrace().Print();
261     PrintToStderr("[end of stack trace]\n");
262   }
263 
264   if (::signal(signal, SIG_DFL) == SIG_ERR) _exit(1);
265 }
266 
267 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
268  public:
PrintBacktraceOutputHandler()269   PrintBacktraceOutputHandler() {}
270 
HandleOutput(const char * output)271   void HandleOutput(const char* output) override {
272     // NOTE: This code MUST be async-signal safe (it's used by in-process
273     // stack dumping signal handler). NO malloc or stdio is allowed here.
274     PrintToStderr(output);
275   }
276 
277  private:
278   DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
279 };
280 
281 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
282  public:
StreamBacktraceOutputHandler(std::ostream * os)283   explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {}
284 
HandleOutput(const char * output)285   void HandleOutput(const char* output) override { (*os_) << output; }
286 
287  private:
288   std::ostream* os_;
289 
290   DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
291 };
292 
WarmUpBacktrace()293 void WarmUpBacktrace() {
294   // Warm up stack trace infrastructure. It turns out that on the first
295   // call glibc initializes some internal data structures using pthread_once,
296   // and even backtrace() can call malloc(), leading to hangs.
297   //
298   // Example stack trace snippet (with tcmalloc):
299   //
300   // #8  0x0000000000a173b5 in tc_malloc
301   //             at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
302   // #9  0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
303   // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
304   // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
305   // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
306   //             at dl-open.c:639
307   // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
308   // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
309   // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
310   // #16 __GI___libc_dlopen_mode at dl-libc.c:165
311   // #17 0x00007ffff61ef8f5 in init
312   //             at ../sysdeps/x86_64/../ia64/backtrace.c:53
313   // #18 0x00007ffff6aad400 in pthread_once
314   //             at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
315   // #19 0x00007ffff61efa14 in __GI___backtrace
316   //             at ../sysdeps/x86_64/../ia64/backtrace.c:104
317   // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
318   //             at base/debug/stack_trace_posix.cc:175
319   // #21 0x00000000007a4ae5 in
320   //             base::(anonymous namespace)::StackDumpSignalHandler
321   //             at base/process_util_posix.cc:172
322   // #22 <signal handler called>
323   StackTrace stack_trace;
324 }
325 
326 }  // namespace
327 
EnableInProcessStackDumping()328 bool EnableInProcessStackDumping() {
329   // When running in an application, our code typically expects SIGPIPE
330   // to be ignored.  Therefore, when testing that same code, it should run
331   // with SIGPIPE ignored as well.
332   struct sigaction sigpipe_action;
333   memset(&sigpipe_action, 0, sizeof(sigpipe_action));
334   sigpipe_action.sa_handler = SIG_IGN;
335   sigemptyset(&sigpipe_action.sa_mask);
336   bool success = (sigaction(SIGPIPE, &sigpipe_action, nullptr) == 0);
337 
338   // Avoid hangs during backtrace initialization, see above.
339   WarmUpBacktrace();
340 
341   struct sigaction action;
342   memset(&action, 0, sizeof(action));
343   action.sa_flags = SA_RESETHAND | SA_SIGINFO;
344   action.sa_sigaction = &StackDumpSignalHandler;
345   sigemptyset(&action.sa_mask);
346 
347   success &= (sigaction(SIGILL, &action, nullptr) == 0);
348   success &= (sigaction(SIGABRT, &action, nullptr) == 0);
349   success &= (sigaction(SIGFPE, &action, nullptr) == 0);
350   success &= (sigaction(SIGBUS, &action, nullptr) == 0);
351   success &= (sigaction(SIGSEGV, &action, nullptr) == 0);
352   success &= (sigaction(SIGSYS, &action, nullptr) == 0);
353 
354   dump_stack_in_signal_handler = true;
355 
356   return success;
357 }
358 
DisableSignalStackDump()359 void DisableSignalStackDump() {
360   dump_stack_in_signal_handler = false;
361 }
362 
StackTrace()363 StackTrace::StackTrace() {
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 #if HAVE_EXECINFO_H
368   // Though the backtrace API man page does not list any possible negative
369   // return values, we take no chance.
370   count_ = static_cast<size_t>(backtrace(trace_, arraysize(trace_)));
371 #else
372   count_ = 0;
373 #endif
374 }
375 
Print() const376 void StackTrace::Print() const {
377   // NOTE: This code MUST be async-signal safe (it's used by in-process
378   // stack dumping signal handler). NO malloc or stdio is allowed here.
379 
380 #if HAVE_EXECINFO_H
381   PrintBacktraceOutputHandler handler;
382   ProcessBacktrace(trace_, count_, &handler);
383 #endif
384 }
385 
OutputToStream(std::ostream * os) const386 void StackTrace::OutputToStream(std::ostream* os) const {
387 #if HAVE_EXECINFO_H
388   StreamBacktraceOutputHandler handler(os);
389   ProcessBacktrace(trace_, count_, &handler);
390 #endif
391 }
392 
393 namespace internal {
394 
395 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
itoa_r(intptr_t i,char * buf,size_t sz,int base,size_t padding)396 char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
397   // Make sure we can write at least one NUL byte.
398   size_t n = 1;
399   if (n > sz) return nullptr;
400 
401   if (base < 2 || base > 16) {
402     buf[0] = '\0';
403     return nullptr;
404   }
405 
406   char* start = buf;
407 
408   uintptr_t j = i;
409 
410   // Handle negative numbers (only for base 10).
411   if (i < 0 && base == 10) {
412     // This does "j = -i" while avoiding integer overflow.
413     j = static_cast<uintptr_t>(-(i + 1)) + 1;
414 
415     // Make sure we can write the '-' character.
416     if (++n > sz) {
417       buf[0] = '\0';
418       return nullptr;
419     }
420     *start++ = '-';
421   }
422 
423   // Loop until we have converted the entire number. Output at least one
424   // character (i.e. '0').
425   char* ptr = start;
426   do {
427     // Make sure there is still enough space left in our output buffer.
428     if (++n > sz) {
429       buf[0] = '\0';
430       return nullptr;
431     }
432 
433     // Output the next digit.
434     *ptr++ = "0123456789abcdef"[j % base];
435     j /= base;
436 
437     if (padding > 0) padding--;
438   } while (j > 0 || padding > 0);
439 
440   // Terminate the output with a NUL character.
441   *ptr = '\0';
442 
443   // Conversion to ASCII actually resulted in the digits being in reverse
444   // order. We can't easily generate them in forward order, as we can't tell
445   // the number of characters needed until we are done converting.
446   // So, now, we reverse the string (except for the possible "-" sign).
447   while (--ptr > start) {
448     char ch = *ptr;
449     *ptr = *start;
450     *start++ = ch;
451   }
452   return buf;
453 }
454 
455 }  // namespace internal
456 
457 }  // namespace debug
458 }  // namespace base
459 }  // namespace v8
460