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 #include "base/debug/stack_trace.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <signal.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/param.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19
20 #include <algorithm>
21 #include <map>
22 #include <memory>
23 #include <ostream>
24 #include <string>
25 #include <vector>
26
27 #if !defined(USE_SYMBOLIZE)
28 #include <cxxabi.h>
29 #endif
30 #if !defined(__UCLIBC__) && !defined(_AIX)
31 #include <execinfo.h>
32 #endif
33
34 #if defined(OS_APPLE)
35 #include <AvailabilityMacros.h>
36 #endif
37
38 #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD)
39 #include "base/debug/proc_maps_linux.h"
40 #endif
41
42 #include "base/cfi_buildflags.h"
43 #include "base/debug/debugger.h"
44 #include "base/files/scoped_file.h"
45 #include "base/logging.h"
46 #include "base/memory/free_deleter.h"
47 #include "base/memory/singleton.h"
48 #include "base/numerics/safe_conversions.h"
49 #include "base/posix/eintr_wrapper.h"
50 #include "base/stl_util.h"
51 #include "base/strings/string_number_conversions.h"
52 #include "base/strings/string_util.h"
53 #include "build/build_config.h"
54
55 #if defined(USE_SYMBOLIZE)
56 #include "base/third_party/symbolize/symbolize.h"
57 #endif
58
59 namespace base {
60 namespace debug {
61
62 namespace {
63
64 volatile sig_atomic_t in_signal_handler = 0;
65
66 #if !defined(OS_NACL)
67 bool (*try_handle_signal)(int, siginfo_t*, void*) = nullptr;
68 #endif
69
70 #if !defined(USE_SYMBOLIZE)
71 // The prefix used for mangled symbols, per the Itanium C++ ABI:
72 // http://www.codesourcery.com/cxx-abi/abi.html#mangling
73 const char kMangledSymbolPrefix[] = "_Z";
74
75 // Characters that can be used for symbols, generated by Ruby:
76 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
77 const char kSymbolCharacters[] =
78 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
79 #endif // !defined(USE_SYMBOLIZE)
80
81 #if !defined(USE_SYMBOLIZE)
82 // Demangles C++ symbols in the given text. Example:
83 //
84 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
85 // =>
86 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
DemangleSymbols(std::string * text)87 void DemangleSymbols(std::string* text) {
88 // Note: code in this function is NOT async-signal safe (std::string uses
89 // malloc internally).
90
91 #if !defined(__UCLIBC__) && !defined(_AIX)
92 std::string::size_type search_from = 0;
93 while (search_from < text->size()) {
94 // Look for the start of a mangled symbol, from search_from.
95 std::string::size_type mangled_start =
96 text->find(kMangledSymbolPrefix, search_from);
97 if (mangled_start == std::string::npos) {
98 break; // Mangled symbol not found.
99 }
100
101 // Look for the end of the mangled symbol.
102 std::string::size_type mangled_end =
103 text->find_first_not_of(kSymbolCharacters, mangled_start);
104 if (mangled_end == std::string::npos) {
105 mangled_end = text->size();
106 }
107 std::string mangled_symbol =
108 text->substr(mangled_start, mangled_end - mangled_start);
109
110 // Try to demangle the mangled symbol candidate.
111 int status = 0;
112 std::unique_ptr<char, base::FreeDeleter> demangled_symbol(
113 abi::__cxa_demangle(mangled_symbol.c_str(), nullptr, 0, &status));
114 if (status == 0) { // Demangling is successful.
115 // Remove the mangled symbol.
116 text->erase(mangled_start, mangled_end - mangled_start);
117 // Insert the demangled symbol.
118 text->insert(mangled_start, demangled_symbol.get());
119 // Next time, we'll start right after the demangled symbol we inserted.
120 search_from = mangled_start + strlen(demangled_symbol.get());
121 } else {
122 // Failed to demangle. Retry after the "_Z" we just found.
123 search_from = mangled_start + 2;
124 }
125 }
126 #endif // !defined(__UCLIBC__) && !defined(_AIX)
127 }
128 #endif // !defined(USE_SYMBOLIZE)
129
130 class BacktraceOutputHandler {
131 public:
132 virtual void HandleOutput(const char* output) = 0;
133
134 protected:
135 virtual ~BacktraceOutputHandler() = default;
136 };
137
138 #if !defined(__UCLIBC__) && !defined(_AIX)
OutputPointer(void * pointer,BacktraceOutputHandler * handler)139 void OutputPointer(void* pointer, BacktraceOutputHandler* handler) {
140 // This should be more than enough to store a 64-bit number in hex:
141 // 16 hex digits + 1 for null-terminator.
142 char buf[17] = { '\0' };
143 handler->HandleOutput("0x");
144 internal::itoa_r(reinterpret_cast<intptr_t>(pointer),
145 buf, sizeof(buf), 16, 12);
146 handler->HandleOutput(buf);
147 }
148
149 #if defined(USE_SYMBOLIZE)
OutputFrameId(intptr_t frame_id,BacktraceOutputHandler * handler)150 void OutputFrameId(intptr_t frame_id, BacktraceOutputHandler* handler) {
151 // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615).
152 // Hence, 30 digits should be more than enough to represent it in decimal
153 // (including the null-terminator).
154 char buf[30] = { '\0' };
155 handler->HandleOutput("#");
156 internal::itoa_r(frame_id, buf, sizeof(buf), 10, 1);
157 handler->HandleOutput(buf);
158 }
159 #endif // defined(USE_SYMBOLIZE)
160
ProcessBacktrace(void * const * trace,size_t size,const char * prefix_string,BacktraceOutputHandler * handler)161 void ProcessBacktrace(void* const* trace,
162 size_t size,
163 const char* prefix_string,
164 BacktraceOutputHandler* handler) {
165 // NOTE: This code MUST be async-signal safe (it's used by in-process
166 // stack dumping signal handler). NO malloc or stdio is allowed here.
167
168 #if defined(USE_SYMBOLIZE)
169 for (size_t i = 0; i < size; ++i) {
170 if (prefix_string)
171 handler->HandleOutput(prefix_string);
172
173 OutputFrameId(i, handler);
174 handler->HandleOutput(" ");
175 OutputPointer(trace[i], handler);
176 handler->HandleOutput(" ");
177
178 char buf[1024] = { '\0' };
179
180 // Subtract by one as return address of function may be in the next
181 // function when a function is annotated as noreturn.
182 void* address = static_cast<char*>(trace[i]) - 1;
183 if (google::Symbolize(address, buf, sizeof(buf)))
184 handler->HandleOutput(buf);
185 else
186 handler->HandleOutput("<unknown>");
187
188 handler->HandleOutput("\n");
189 }
190 #else
191 bool printed = false;
192
193 // Below part is async-signal unsafe (uses malloc), so execute it only
194 // when we are not executing the signal handler.
195 if (in_signal_handler == 0) {
196 std::unique_ptr<char*, FreeDeleter> trace_symbols(
197 backtrace_symbols(trace, size));
198 if (trace_symbols.get()) {
199 for (size_t i = 0; i < size; ++i) {
200 std::string trace_symbol = trace_symbols.get()[i];
201 DemangleSymbols(&trace_symbol);
202 if (prefix_string)
203 handler->HandleOutput(prefix_string);
204 handler->HandleOutput(trace_symbol.c_str());
205 handler->HandleOutput("\n");
206 }
207
208 printed = true;
209 }
210 }
211
212 if (!printed) {
213 for (size_t i = 0; i < size; ++i) {
214 handler->HandleOutput(" [");
215 OutputPointer(trace[i], handler);
216 handler->HandleOutput("]\n");
217 }
218 }
219 #endif // defined(USE_SYMBOLIZE)
220 }
221 #endif // !defined(__UCLIBC__) && !defined(_AIX)
222
PrintToStderr(const char * output)223 void PrintToStderr(const char* output) {
224 // NOTE: This code MUST be async-signal safe (it's used by in-process
225 // stack dumping signal handler). NO malloc or stdio is allowed here.
226 ignore_result(HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output))));
227 }
228
StackDumpSignalHandler(int signal,siginfo_t * info,void * void_context)229 void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
230 // NOTE: This code MUST be async-signal safe.
231 // NO malloc or stdio is allowed here.
232
233 #if !defined(OS_NACL)
234 // Give a registered callback a chance to recover from this signal
235 //
236 // V8 uses guard regions to guarantee memory safety in WebAssembly. This means
237 // some signals might be expected if they originate from Wasm code while
238 // accessing the guard region. We give V8 the chance to handle and recover
239 // from these signals first.
240 if (try_handle_signal != nullptr &&
241 try_handle_signal(signal, info, void_context)) {
242 // The first chance handler took care of this. The SA_RESETHAND flag
243 // replaced this signal handler upon entry, but we want to stay
244 // installed. Thus, we reinstall ourselves before returning.
245 struct sigaction action;
246 memset(&action, 0, sizeof(action));
247 action.sa_flags = SA_RESETHAND | SA_SIGINFO;
248 action.sa_sigaction = &StackDumpSignalHandler;
249 sigemptyset(&action.sa_mask);
250
251 sigaction(signal, &action, nullptr);
252 return;
253 }
254 #endif
255
256 // Do not take the "in signal handler" code path on Mac in a DCHECK-enabled
257 // build, as this prevents seeing a useful (symbolized) stack trace on a crash
258 // or DCHECK() failure. While it may not be fully safe to run the stack symbol
259 // printing code, in practice it's better to provide meaningful stack traces -
260 // and the risk is low given we're likely crashing already.
261 #if !defined(OS_APPLE) || !DCHECK_IS_ON()
262 // Record the fact that we are in the signal handler now, so that the rest
263 // of StackTrace can behave in an async-signal-safe manner.
264 in_signal_handler = 1;
265 #endif
266
267 if (BeingDebugged())
268 BreakDebugger();
269
270 PrintToStderr("Received signal ");
271 char buf[1024] = { 0 };
272 internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
273 PrintToStderr(buf);
274 if (signal == SIGBUS) {
275 if (info->si_code == BUS_ADRALN)
276 PrintToStderr(" BUS_ADRALN ");
277 else if (info->si_code == BUS_ADRERR)
278 PrintToStderr(" BUS_ADRERR ");
279 else if (info->si_code == BUS_OBJERR)
280 PrintToStderr(" BUS_OBJERR ");
281 else
282 PrintToStderr(" <unknown> ");
283 } else if (signal == SIGFPE) {
284 if (info->si_code == FPE_FLTDIV)
285 PrintToStderr(" FPE_FLTDIV ");
286 else if (info->si_code == FPE_FLTINV)
287 PrintToStderr(" FPE_FLTINV ");
288 else if (info->si_code == FPE_FLTOVF)
289 PrintToStderr(" FPE_FLTOVF ");
290 else if (info->si_code == FPE_FLTRES)
291 PrintToStderr(" FPE_FLTRES ");
292 else if (info->si_code == FPE_FLTSUB)
293 PrintToStderr(" FPE_FLTSUB ");
294 else if (info->si_code == FPE_FLTUND)
295 PrintToStderr(" FPE_FLTUND ");
296 else if (info->si_code == FPE_INTDIV)
297 PrintToStderr(" FPE_INTDIV ");
298 else if (info->si_code == FPE_INTOVF)
299 PrintToStderr(" FPE_INTOVF ");
300 else
301 PrintToStderr(" <unknown> ");
302 } else if (signal == SIGILL) {
303 if (info->si_code == ILL_BADSTK)
304 PrintToStderr(" ILL_BADSTK ");
305 else if (info->si_code == ILL_COPROC)
306 PrintToStderr(" ILL_COPROC ");
307 else if (info->si_code == ILL_ILLOPN)
308 PrintToStderr(" ILL_ILLOPN ");
309 else if (info->si_code == ILL_ILLADR)
310 PrintToStderr(" ILL_ILLADR ");
311 else if (info->si_code == ILL_ILLTRP)
312 PrintToStderr(" ILL_ILLTRP ");
313 else if (info->si_code == ILL_PRVOPC)
314 PrintToStderr(" ILL_PRVOPC ");
315 else if (info->si_code == ILL_PRVREG)
316 PrintToStderr(" ILL_PRVREG ");
317 else
318 PrintToStderr(" <unknown> ");
319 } else if (signal == SIGSEGV) {
320 if (info->si_code == SEGV_MAPERR)
321 PrintToStderr(" SEGV_MAPERR ");
322 else if (info->si_code == SEGV_ACCERR)
323 PrintToStderr(" SEGV_ACCERR ");
324 else
325 PrintToStderr(" <unknown> ");
326 }
327 if (signal == SIGBUS || signal == SIGFPE ||
328 signal == SIGILL || signal == SIGSEGV) {
329 internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
330 buf, sizeof(buf), 16, 12);
331 PrintToStderr(buf);
332 }
333 PrintToStderr("\n");
334
335 #if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
336 if (signal == SIGILL && info->si_code == ILL_ILLOPN) {
337 PrintToStderr(
338 "CFI: Most likely a control flow integrity violation; for more "
339 "information see:\n");
340 PrintToStderr(
341 "https://www.chromium.org/developers/testing/control-flow-integrity\n");
342 }
343 #endif // BUILDFLAG(CFI_ENFORCEMENT_TRAP)
344
345 debug::StackTrace().Print();
346
347 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
348 #if ARCH_CPU_X86_FAMILY
349 ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
350 const struct {
351 const char* label;
352 greg_t value;
353 } registers[] = {
354 #if ARCH_CPU_32_BITS
355 { " gs: ", context->uc_mcontext.gregs[REG_GS] },
356 { " fs: ", context->uc_mcontext.gregs[REG_FS] },
357 { " es: ", context->uc_mcontext.gregs[REG_ES] },
358 { " ds: ", context->uc_mcontext.gregs[REG_DS] },
359 { " edi: ", context->uc_mcontext.gregs[REG_EDI] },
360 { " esi: ", context->uc_mcontext.gregs[REG_ESI] },
361 { " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
362 { " esp: ", context->uc_mcontext.gregs[REG_ESP] },
363 { " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
364 { " edx: ", context->uc_mcontext.gregs[REG_EDX] },
365 { " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
366 { " eax: ", context->uc_mcontext.gregs[REG_EAX] },
367 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
368 { " err: ", context->uc_mcontext.gregs[REG_ERR] },
369 { " ip: ", context->uc_mcontext.gregs[REG_EIP] },
370 { " cs: ", context->uc_mcontext.gregs[REG_CS] },
371 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
372 { " usp: ", context->uc_mcontext.gregs[REG_UESP] },
373 { " ss: ", context->uc_mcontext.gregs[REG_SS] },
374 #elif ARCH_CPU_64_BITS
375 { " r8: ", context->uc_mcontext.gregs[REG_R8] },
376 { " r9: ", context->uc_mcontext.gregs[REG_R9] },
377 { " r10: ", context->uc_mcontext.gregs[REG_R10] },
378 { " r11: ", context->uc_mcontext.gregs[REG_R11] },
379 { " r12: ", context->uc_mcontext.gregs[REG_R12] },
380 { " r13: ", context->uc_mcontext.gregs[REG_R13] },
381 { " r14: ", context->uc_mcontext.gregs[REG_R14] },
382 { " r15: ", context->uc_mcontext.gregs[REG_R15] },
383 { " di: ", context->uc_mcontext.gregs[REG_RDI] },
384 { " si: ", context->uc_mcontext.gregs[REG_RSI] },
385 { " bp: ", context->uc_mcontext.gregs[REG_RBP] },
386 { " bx: ", context->uc_mcontext.gregs[REG_RBX] },
387 { " dx: ", context->uc_mcontext.gregs[REG_RDX] },
388 { " ax: ", context->uc_mcontext.gregs[REG_RAX] },
389 { " cx: ", context->uc_mcontext.gregs[REG_RCX] },
390 { " sp: ", context->uc_mcontext.gregs[REG_RSP] },
391 { " ip: ", context->uc_mcontext.gregs[REG_RIP] },
392 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
393 { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
394 { " erf: ", context->uc_mcontext.gregs[REG_ERR] },
395 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
396 { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
397 { " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
398 #endif // ARCH_CPU_32_BITS
399 };
400
401 #if ARCH_CPU_32_BITS
402 const int kRegisterPadding = 8;
403 #elif ARCH_CPU_64_BITS
404 const int kRegisterPadding = 16;
405 #endif
406
407 for (size_t i = 0; i < base::size(registers); i++) {
408 PrintToStderr(registers[i].label);
409 internal::itoa_r(registers[i].value, buf, sizeof(buf),
410 16, kRegisterPadding);
411 PrintToStderr(buf);
412
413 if ((i + 1) % 4 == 0)
414 PrintToStderr("\n");
415 }
416 PrintToStderr("\n");
417 #endif // ARCH_CPU_X86_FAMILY
418 #endif // defined(OS_LINUX) || defined(OS_CHROMEOS)
419
420 PrintToStderr("[end of stack trace]\n");
421
422 #if defined(OS_MAC)
423 if (::signal(signal, SIG_DFL) == SIG_ERR)
424 _exit(1);
425 #else
426 // Non-Mac OSes should probably reraise the signal as well, but the Linux
427 // sandbox tests break on CrOS devices.
428 // https://code.google.com/p/chromium/issues/detail?id=551681
429 PrintToStderr("Calling _exit(1). Core file will not be generated.\n");
430 _exit(1);
431 #endif // defined(OS_MAC)
432 }
433
434 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
435 public:
436 PrintBacktraceOutputHandler() = default;
437
HandleOutput(const char * output)438 void HandleOutput(const char* output) override {
439 // NOTE: This code MUST be async-signal safe (it's used by in-process
440 // stack dumping signal handler). NO malloc or stdio is allowed here.
441 PrintToStderr(output);
442 }
443
444 private:
445 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
446 };
447
448 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
449 public:
StreamBacktraceOutputHandler(std::ostream * os)450 explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
451 }
452
HandleOutput(const char * output)453 void HandleOutput(const char* output) override { (*os_) << output; }
454
455 private:
456 std::ostream* os_;
457
458 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
459 };
460
WarmUpBacktrace()461 void WarmUpBacktrace() {
462 // Warm up stack trace infrastructure. It turns out that on the first
463 // call glibc initializes some internal data structures using pthread_once,
464 // and even backtrace() can call malloc(), leading to hangs.
465 //
466 // Example stack trace snippet (with tcmalloc):
467 //
468 // #8 0x0000000000a173b5 in tc_malloc
469 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
470 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
471 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
472 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
473 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
474 // at dl-open.c:639
475 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
476 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
477 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
478 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
479 // #17 0x00007ffff61ef8f5 in init
480 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
481 // #18 0x00007ffff6aad400 in pthread_once
482 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
483 // #19 0x00007ffff61efa14 in __GI___backtrace
484 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
485 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
486 // at base/debug/stack_trace_posix.cc:175
487 // #21 0x00000000007a4ae5 in
488 // base::(anonymous namespace)::StackDumpSignalHandler
489 // at base/process_util_posix.cc:172
490 // #22 <signal handler called>
491 StackTrace stack_trace;
492 }
493
494 #if defined(USE_SYMBOLIZE)
495
496 // class SandboxSymbolizeHelper.
497 //
498 // The purpose of this class is to prepare and install a "file open" callback
499 // needed by the stack trace symbolization code
500 // (base/third_party/symbolize/symbolize.h) so that it can function properly
501 // in a sandboxed process. The caveat is that this class must be instantiated
502 // before the sandboxing is enabled so that it can get the chance to open all
503 // the object files that are loaded in the virtual address space of the current
504 // process.
505 class SandboxSymbolizeHelper {
506 public:
507 // Returns the singleton instance.
GetInstance()508 static SandboxSymbolizeHelper* GetInstance() {
509 return Singleton<SandboxSymbolizeHelper,
510 LeakySingletonTraits<SandboxSymbolizeHelper>>::get();
511 }
512
513 private:
514 friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
515
SandboxSymbolizeHelper()516 SandboxSymbolizeHelper()
517 : is_initialized_(false) {
518 Init();
519 }
520
~SandboxSymbolizeHelper()521 ~SandboxSymbolizeHelper() {
522 UnregisterCallback();
523 CloseObjectFiles();
524 }
525
526 // Returns a O_RDONLY file descriptor for |file_path| if it was opened
527 // successfully during the initialization. The file is repositioned at
528 // offset 0.
529 // IMPORTANT: This function must be async-signal-safe because it can be
530 // called from a signal handler (symbolizing stack frames for a crash).
GetFileDescriptor(const char * file_path)531 int GetFileDescriptor(const char* file_path) {
532 int fd = -1;
533
534 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
535 if (file_path) {
536 // The assumption here is that iterating over std::map<std::string,
537 // base::ScopedFD> does not allocate dynamic memory, hence it is
538 // async-signal-safe.
539 for (const auto& filepath_fd : modules_) {
540 if (strcmp(filepath_fd.first.c_str(), file_path) == 0) {
541 // POSIX.1-2004 requires an implementation to guarantee that dup()
542 // is async-signal-safe.
543 fd = HANDLE_EINTR(dup(filepath_fd.second.get()));
544 break;
545 }
546 }
547 // POSIX.1-2004 requires an implementation to guarantee that lseek()
548 // is async-signal-safe.
549 if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
550 // Failed to seek.
551 fd = -1;
552 }
553 }
554 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
555
556 return fd;
557 }
558
559 // Searches for the object file (from /proc/self/maps) that contains
560 // the specified pc. If found, sets |start_address| to the start address
561 // of where this object file is mapped in memory, sets the module base
562 // address into |base_address|, copies the object file name into
563 // |out_file_name|, and attempts to open the object file. If the object
564 // file is opened successfully, returns the file descriptor. Otherwise,
565 // returns -1. |out_file_name_size| is the size of the file name buffer
566 // (including the null terminator).
567 // IMPORTANT: This function must be async-signal-safe because it can be
568 // called from a signal handler (symbolizing stack frames for a crash).
OpenObjectFileContainingPc(uint64_t pc,uint64_t & start_address,uint64_t & base_address,char * file_path,int file_path_size)569 static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address,
570 uint64_t& base_address, char* file_path,
571 int file_path_size) {
572 // This method can only be called after the singleton is instantiated.
573 // This is ensured by the following facts:
574 // * This is the only static method in this class, it is private, and
575 // the class has no friends (except for the DefaultSingletonTraits).
576 // The compiler guarantees that it can only be called after the
577 // singleton is instantiated.
578 // * This method is used as a callback for the stack tracing code and
579 // the callback registration is done in the constructor, so logically
580 // it cannot be called before the singleton is created.
581 SandboxSymbolizeHelper* instance = GetInstance();
582
583 // Cannot use STL iterators here, since debug iterators use locks.
584 // NOLINTNEXTLINE(modernize-loop-convert)
585 for (size_t i = 0; i < instance->regions_.size(); ++i) {
586 const MappedMemoryRegion& region = instance->regions_[i];
587 if (region.start <= pc && pc < region.end) {
588 start_address = region.start;
589 base_address = region.base;
590 if (file_path && file_path_size > 0) {
591 strncpy(file_path, region.path.c_str(), file_path_size);
592 // Ensure null termination.
593 file_path[file_path_size - 1] = '\0';
594 }
595 return instance->GetFileDescriptor(region.path.c_str());
596 }
597 }
598 return -1;
599 }
600
601 // Set the base address for each memory region by reading ELF headers in
602 // process memory.
SetBaseAddressesForMemoryRegions()603 void SetBaseAddressesForMemoryRegions() {
604 base::ScopedFD mem_fd(
605 #if defined(OS_BSD)
606 HANDLE_EINTR(open("/proc/curproc/mem", O_RDONLY | O_CLOEXEC)));
607 #else
608 HANDLE_EINTR(open("/proc/self/mem", O_RDONLY | O_CLOEXEC)));
609 #endif
610
611 if (!mem_fd.is_valid())
612 return;
613
614 auto safe_memcpy = [&mem_fd](void* dst, uintptr_t src, size_t size) {
615 return HANDLE_EINTR(pread(mem_fd.get(), dst, size, src)) == ssize_t(size);
616 };
617
618 uintptr_t cur_base = 0;
619 for (auto& r : regions_) {
620 ElfW(Ehdr) ehdr;
621 static_assert(SELFMAG <= sizeof(ElfW(Ehdr)), "SELFMAG too large");
622 if ((r.permissions & MappedMemoryRegion::READ) &&
623 safe_memcpy(&ehdr, r.start, sizeof(ElfW(Ehdr))) &&
624 memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
625 switch (ehdr.e_type) {
626 case ET_EXEC:
627 cur_base = 0;
628 break;
629 case ET_DYN:
630 // Find the segment containing file offset 0. This will correspond
631 // to the ELF header that we just read. Normally this will have
632 // virtual address 0, but this is not guaranteed. We must subtract
633 // the virtual address from the address where the ELF header was
634 // mapped to get the base address.
635 //
636 // If we fail to find a segment for file offset 0, use the address
637 // of the ELF header as the base address.
638 cur_base = r.start;
639 for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
640 ElfW(Phdr) phdr;
641 if (safe_memcpy(&phdr, r.start + ehdr.e_phoff + i * sizeof(phdr),
642 sizeof(phdr)) &&
643 phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
644 cur_base = r.start - phdr.p_vaddr;
645 break;
646 }
647 }
648 break;
649 default:
650 // ET_REL or ET_CORE. These aren't directly executable, so they
651 // don't affect the base address.
652 break;
653 }
654 }
655
656 r.base = cur_base;
657 }
658 }
659
660 // Parses /proc/self/maps in order to compile a list of all object file names
661 // for the modules that are loaded in the current process.
662 // Returns true on success.
663 // XXX (tuxillo) needs review, not complete?
CacheMemoryRegions()664 bool CacheMemoryRegions() {
665 // Reads /proc/self/maps.
666 std::string contents;
667 if (!ReadProcMaps(&contents)) {
668 #if defined(OS_BSD)
669 LOG(ERROR) << "Failed to read /proc/curproc/map";
670 #else
671 LOG(ERROR) << "Failed to read /proc/self/maps";
672 #endif
673 return false;
674 }
675
676 // Parses /proc/self/maps.
677 if (!ParseProcMaps(contents, ®ions_)) {
678 #if defined(OS_BSD)
679 LOG(ERROR) << "Failed to parse the contents of /proc/curproc/map";
680 #else
681 LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
682 #endif
683 return false;
684 }
685
686 SetBaseAddressesForMemoryRegions();
687
688 is_initialized_ = true;
689 return true;
690 }
691
692 // Opens all object files and caches their file descriptors.
OpenSymbolFiles()693 void OpenSymbolFiles() {
694 // Pre-opening and caching the file descriptors of all loaded modules is
695 // not safe for production builds. Hence it is only done in non-official
696 // builds. For more details, take a look at: http://crbug.com/341966.
697 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
698 // Open the object files for all read-only executable regions and cache
699 // their file descriptors.
700 std::vector<MappedMemoryRegion>::const_iterator it;
701 for (it = regions_.begin(); it != regions_.end(); ++it) {
702 const MappedMemoryRegion& region = *it;
703 // Only interesed in read-only executable regions.
704 if ((region.permissions & MappedMemoryRegion::READ) ==
705 MappedMemoryRegion::READ &&
706 (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
707 (region.permissions & MappedMemoryRegion::EXECUTE) ==
708 MappedMemoryRegion::EXECUTE) {
709 if (region.path.empty()) {
710 // Skip regions with empty file names.
711 continue;
712 }
713 #if defined(OS_BSD)
714 if (region.path[0] == '-') {
715 #else
716 if (region.path[0] == '[') {
717 #endif
718 // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
719 continue;
720 }
721 if (base::EndsWith(region.path, " (deleted)",
722 base::CompareCase::SENSITIVE)) {
723 // Skip deleted files.
724 continue;
725 }
726 // Avoid duplicates.
727 if (modules_.find(region.path) == modules_.end()) {
728 int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
729 if (fd >= 0) {
730 modules_.emplace(region.path, base::ScopedFD(fd));
731 } else {
732 LOG(WARNING) << "Failed to open file: " << region.path
733 << "\n Error: " << strerror(errno);
734 }
735 }
736 }
737 }
738 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
739 }
740
741 // Initializes and installs the symbolization callback.
742 void Init() {
743 if (CacheMemoryRegions()) {
744 OpenSymbolFiles();
745 google::InstallSymbolizeOpenObjectFileCallback(
746 &OpenObjectFileContainingPc);
747 }
748 }
749
750 // Unregister symbolization callback.
751 void UnregisterCallback() {
752 if (is_initialized_) {
753 google::InstallSymbolizeOpenObjectFileCallback(nullptr);
754 is_initialized_ = false;
755 }
756 }
757
758 // Closes all file descriptors owned by this instance.
759 void CloseObjectFiles() {
760 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
761 modules_.clear();
762 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
763 }
764
765 // Set to true upon successful initialization.
766 bool is_initialized_;
767
768 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
769 // Mapping from file name to file descriptor. Includes file descriptors
770 // for all successfully opened object files and the file descriptor for
771 // /proc/self/maps. This code is not safe for production builds.
772 std::map<std::string, base::ScopedFD> modules_;
773 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
774
775 // Cache for the process memory regions. Produced by parsing the contents
776 // of /proc/self/maps cache.
777 std::vector<MappedMemoryRegion> regions_;
778
779 DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper);
780 };
781 #endif // USE_SYMBOLIZE
782
783 } // namespace
784
EnableInProcessStackDumping()785 bool EnableInProcessStackDumping() {
786 #if defined(USE_SYMBOLIZE)
787 SandboxSymbolizeHelper::GetInstance();
788 #endif // USE_SYMBOLIZE
789
790 // When running in an application, our code typically expects SIGPIPE
791 // to be ignored. Therefore, when testing that same code, it should run
792 // with SIGPIPE ignored as well.
793 struct sigaction sigpipe_action;
794 memset(&sigpipe_action, 0, sizeof(sigpipe_action));
795 sigpipe_action.sa_handler = SIG_IGN;
796 sigemptyset(&sigpipe_action.sa_mask);
797 bool success = (sigaction(SIGPIPE, &sigpipe_action, nullptr) == 0);
798
799 // Avoid hangs during backtrace initialization, see above.
800 WarmUpBacktrace();
801
802 struct sigaction action;
803 memset(&action, 0, sizeof(action));
804 action.sa_flags = SA_RESETHAND | SA_SIGINFO;
805 action.sa_sigaction = &StackDumpSignalHandler;
806 sigemptyset(&action.sa_mask);
807
808 success &= (sigaction(SIGILL, &action, nullptr) == 0);
809 success &= (sigaction(SIGABRT, &action, nullptr) == 0);
810 success &= (sigaction(SIGFPE, &action, nullptr) == 0);
811 success &= (sigaction(SIGBUS, &action, nullptr) == 0);
812 success &= (sigaction(SIGSEGV, &action, nullptr) == 0);
813 // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
814 #if !defined(OS_LINUX) && !defined(OS_CHROMEOS)
815 success &= (sigaction(SIGSYS, &action, nullptr) == 0);
816 #endif // !defined(OS_LINUX) && !defined(OS_CHROMEOS)
817
818 return success;
819 }
820
821 #if !defined(OS_NACL)
SetStackDumpFirstChanceCallback(bool (* handler)(int,siginfo_t *,void *))822 bool SetStackDumpFirstChanceCallback(bool (*handler)(int, siginfo_t*, void*)) {
823 DCHECK(try_handle_signal == nullptr || handler == nullptr);
824 try_handle_signal = handler;
825
826 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
827 defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) || \
828 defined(UNDEFINED_SANITIZER)
829 struct sigaction installed_handler;
830 CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0);
831 // If the installed handler does not point to StackDumpSignalHandler, then
832 // allow_user_segv_handler is 0.
833 if (installed_handler.sa_sigaction != StackDumpSignalHandler) {
834 LOG(WARNING)
835 << "WARNING: sanitizers are preventing signal handler installation. "
836 << "WebAssembly trap handlers are disabled.\n";
837 return false;
838 }
839 #endif
840 return true;
841 }
842 #endif
843
CollectStackTrace(void ** trace,size_t count)844 size_t CollectStackTrace(void** trace, size_t count) {
845 // NOTE: This code MUST be async-signal safe (it's used by in-process
846 // stack dumping signal handler). NO malloc or stdio is allowed here.
847
848 #if !defined(__UCLIBC__) && !defined(_AIX)
849 // Though the backtrace API man page does not list any possible negative
850 // return values, we take no chance.
851 return base::saturated_cast<size_t>(backtrace(trace, count));
852 #else
853 return 0;
854 #endif
855 }
856
PrintWithPrefix(const char * prefix_string) const857 void StackTrace::PrintWithPrefix(const char* prefix_string) const {
858 // NOTE: This code MUST be async-signal safe (it's used by in-process
859 // stack dumping signal handler). NO malloc or stdio is allowed here.
860
861 #if !defined(__UCLIBC__) && !defined(_AIX)
862 PrintBacktraceOutputHandler handler;
863 ProcessBacktrace(trace_, count_, prefix_string, &handler);
864 #endif
865 }
866
867 #if !defined(__UCLIBC__) && !defined(_AIX)
OutputToStreamWithPrefix(std::ostream * os,const char * prefix_string) const868 void StackTrace::OutputToStreamWithPrefix(std::ostream* os,
869 const char* prefix_string) const {
870 StreamBacktraceOutputHandler handler(os);
871 ProcessBacktrace(trace_, count_, prefix_string, &handler);
872 }
873 #endif
874
875 namespace internal {
876
877 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
itoa_r(intptr_t i,char * buf,size_t sz,int base,size_t padding)878 char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
879 // Make sure we can write at least one NUL byte.
880 size_t n = 1;
881 if (n > sz)
882 return nullptr;
883
884 if (base < 2 || base > 16) {
885 buf[0] = '\000';
886 return nullptr;
887 }
888
889 char* start = buf;
890
891 uintptr_t j = i;
892
893 // Handle negative numbers (only for base 10).
894 if (i < 0 && base == 10) {
895 // This does "j = -i" while avoiding integer overflow.
896 j = static_cast<uintptr_t>(-(i + 1)) + 1;
897
898 // Make sure we can write the '-' character.
899 if (++n > sz) {
900 buf[0] = '\000';
901 return nullptr;
902 }
903 *start++ = '-';
904 }
905
906 // Loop until we have converted the entire number. Output at least one
907 // character (i.e. '0').
908 char* ptr = start;
909 do {
910 // Make sure there is still enough space left in our output buffer.
911 if (++n > sz) {
912 buf[0] = '\000';
913 return nullptr;
914 }
915
916 // Output the next digit.
917 *ptr++ = "0123456789abcdef"[j % base];
918 j /= base;
919
920 if (padding > 0)
921 padding--;
922 } while (j > 0 || padding > 0);
923
924 // Terminate the output with a NUL character.
925 *ptr = '\000';
926
927 // Conversion to ASCII actually resulted in the digits being in reverse
928 // order. We can't easily generate them in forward order, as we can't tell
929 // the number of characters needed until we are done converting.
930 // So, now, we reverse the string (except for the possible "-" sign).
931 while (--ptr > start) {
932 char ch = *ptr;
933 *ptr = *start;
934 *start++ = ch;
935 }
936 return buf;
937 }
938
939 } // namespace internal
940
941 } // namespace debug
942 } // namespace base
943