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 = true;
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, nullptr, &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:
128 virtual ~BacktraceOutputHandler() = default;
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:
269 PrintBacktraceOutputHandler() = default;
270 PrintBacktraceOutputHandler(const PrintBacktraceOutputHandler&) = delete;
271 PrintBacktraceOutputHandler& operator=(const PrintBacktraceOutputHandler&) =
272 delete;
273
HandleOutput(const char * output)274 void HandleOutput(const char* output) override {
275 // NOTE: This code MUST be async-signal safe (it's used by in-process
276 // stack dumping signal handler). NO malloc or stdio is allowed here.
277 PrintToStderr(output);
278 }
279 };
280
281 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
282 public:
StreamBacktraceOutputHandler(std::ostream * os)283 explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {}
284 StreamBacktraceOutputHandler(const StreamBacktraceOutputHandler&) = delete;
285 StreamBacktraceOutputHandler& operator=(const StreamBacktraceOutputHandler&) =
286 delete;
287
HandleOutput(const char * output)288 void HandleOutput(const char* output) override { (*os_) << output; }
289
290 private:
291 std::ostream* os_;
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, nullptr) == 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, nullptr) == 0);
349 success &= (sigaction(SIGABRT, &action, nullptr) == 0);
350 success &= (sigaction(SIGFPE, &action, nullptr) == 0);
351 success &= (sigaction(SIGBUS, &action, nullptr) == 0);
352 success &= (sigaction(SIGSEGV, &action, nullptr) == 0);
353 success &= (sigaction(SIGSYS, &action, nullptr) == 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 nullptr;
401
402 if (base < 2 || base > 16) {
403 buf[0] = '\0';
404 return nullptr;
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] = '\0';
419 return nullptr;
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] = '\0';
431 return nullptr;
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 = '\0';
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