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