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_MACOSX)
35 #include <AvailabilityMacros.h>
36 #endif
37 
38 #if defined(OS_LINUX) || 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_MACOSX) || !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)
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)
419 
420   PrintToStderr("[end of stack trace]\n");
421 
422 #if defined(OS_MACOSX) && !defined(OS_IOS)
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_MACOSX) && !defined(OS_IOS)
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, int>
537       // using a const_iterator does not allocate dynamic memory, hense it is
538       // async-signal-safe.
539       std::map<std::string, int>::const_iterator it;
540       for (it = modules_.begin(); it != modules_.end(); ++it) {
541         if (strcmp((it->first).c_str(), file_path) == 0) {
542           // POSIX.1-2004 requires an implementation to guarantee that dup()
543           // is async-signal-safe.
544           fd = HANDLE_EINTR(dup(it->second));
545           break;
546         }
547       }
548       // POSIX.1-2004 requires an implementation to guarantee that lseek()
549       // is async-signal-safe.
550       if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
551         // Failed to seek.
552         fd = -1;
553       }
554     }
555 #endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
556 
557     return fd;
558   }
559 
560   // Searches for the object file (from /proc/self/maps) that contains
561   // the specified pc.  If found, sets |start_address| to the start address
562   // of where this object file is mapped in memory, sets the module base
563   // address into |base_address|, copies the object file name into
564   // |out_file_name|, and attempts to open the object file.  If the object
565   // file is opened successfully, returns the file descriptor.  Otherwise,
566   // returns -1.  |out_file_name_size| is the size of the file name buffer
567   // (including the null terminator).
568   // IMPORTANT: This function must be async-signal-safe because it can be
569   // 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)570   static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address,
571                                         uint64_t& base_address, char* file_path,
572                                         int file_path_size) {
573     // This method can only be called after the singleton is instantiated.
574     // This is ensured by the following facts:
575     // * This is the only static method in this class, it is private, and
576     //   the class has no friends (except for the DefaultSingletonTraits).
577     //   The compiler guarantees that it can only be called after the
578     //   singleton is instantiated.
579     // * This method is used as a callback for the stack tracing code and
580     //   the callback registration is done in the constructor, so logically
581     //   it cannot be called before the singleton is created.
582     SandboxSymbolizeHelper* instance = GetInstance();
583 
584     // Cannot use STL iterators here, since debug iterators use locks.
585     // NOLINTNEXTLINE(modernize-loop-convert)
586     for (size_t i = 0; i < instance->regions_.size(); ++i) {
587       const MappedMemoryRegion& region = instance->regions_[i];
588       if (region.start <= pc && pc < region.end) {
589         start_address = region.start;
590         base_address = region.base;
591         if (file_path && file_path_size > 0) {
592           strncpy(file_path, region.path.c_str(), file_path_size);
593           // Ensure null termination.
594           file_path[file_path_size - 1] = '\0';
595         }
596         return instance->GetFileDescriptor(region.path.c_str());
597       }
598     }
599     return -1;
600   }
601 
602   // Set the base address for each memory region by reading ELF headers in
603   // process memory.
SetBaseAddressesForMemoryRegions()604   void SetBaseAddressesForMemoryRegions() {
605     base::ScopedFD mem_fd(
606         HANDLE_EINTR(open("/proc/self/mem", O_RDONLY | O_CLOEXEC)));
607     if (!mem_fd.is_valid())
608       return;
609 
610     auto safe_memcpy = [&mem_fd](void* dst, uintptr_t src, size_t size) {
611       return HANDLE_EINTR(pread(mem_fd.get(), dst, size, src)) == ssize_t(size);
612     };
613 
614     uintptr_t cur_base = 0;
615     for (auto& r : regions_) {
616       ElfW(Ehdr) ehdr;
617       static_assert(SELFMAG <= sizeof(ElfW(Ehdr)), "SELFMAG too large");
618       if ((r.permissions & MappedMemoryRegion::READ) &&
619           safe_memcpy(&ehdr, r.start, sizeof(ElfW(Ehdr))) &&
620           memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
621         switch (ehdr.e_type) {
622           case ET_EXEC:
623             cur_base = 0;
624             break;
625           case ET_DYN:
626             // Find the segment containing file offset 0. This will correspond
627             // to the ELF header that we just read. Normally this will have
628             // virtual address 0, but this is not guaranteed. We must subtract
629             // the virtual address from the address where the ELF header was
630             // mapped to get the base address.
631             //
632             // If we fail to find a segment for file offset 0, use the address
633             // of the ELF header as the base address.
634             cur_base = r.start;
635             for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
636               ElfW(Phdr) phdr;
637               if (safe_memcpy(&phdr, r.start + ehdr.e_phoff + i * sizeof(phdr),
638                               sizeof(phdr)) &&
639                   phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
640                 cur_base = r.start - phdr.p_vaddr;
641                 break;
642               }
643             }
644             break;
645           default:
646             // ET_REL or ET_CORE. These aren't directly executable, so they
647             // don't affect the base address.
648             break;
649         }
650       }
651 
652       r.base = cur_base;
653     }
654   }
655 
656   // Parses /proc/self/maps in order to compile a list of all object file names
657   // for the modules that are loaded in the current process.
658   // Returns true on success.
CacheMemoryRegions()659   bool CacheMemoryRegions() {
660     // Reads /proc/self/maps.
661     std::string contents;
662     if (!ReadProcMaps(&contents)) {
663       LOG(ERROR) << "Failed to read /proc/self/maps";
664       return false;
665     }
666 
667     // Parses /proc/self/maps.
668     if (!ParseProcMaps(contents, &regions_)) {
669       LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
670       return false;
671     }
672 
673     SetBaseAddressesForMemoryRegions();
674 
675     is_initialized_ = true;
676     return true;
677   }
678 
679   // Opens all object files and caches their file descriptors.
OpenSymbolFiles()680   void OpenSymbolFiles() {
681     // Pre-opening and caching the file descriptors of all loaded modules is
682     // not safe for production builds.  Hence it is only done in non-official
683     // builds.  For more details, take a look at: http://crbug.com/341966.
684 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
685     // Open the object files for all read-only executable regions and cache
686     // their file descriptors.
687     std::vector<MappedMemoryRegion>::const_iterator it;
688     for (it = regions_.begin(); it != regions_.end(); ++it) {
689       const MappedMemoryRegion& region = *it;
690       // Only interesed in read-only executable regions.
691       if ((region.permissions & MappedMemoryRegion::READ) ==
692               MappedMemoryRegion::READ &&
693           (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
694           (region.permissions & MappedMemoryRegion::EXECUTE) ==
695               MappedMemoryRegion::EXECUTE) {
696         if (region.path.empty()) {
697           // Skip regions with empty file names.
698           continue;
699         }
700 #if defined(OS_BSD)
701 	if (region.path[0] == '-') {
702 #else
703         if (region.path[0] == '[') {
704 #endif
705           // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
706           continue;
707         }
708         if (base::EndsWith(region.path, " (deleted)",
709                            base::CompareCase::SENSITIVE)) {
710           // Skip deleted files.
711           continue;
712         }
713         // Avoid duplicates.
714         if (modules_.find(region.path) == modules_.end()) {
715           int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
716           if (fd >= 0) {
717             modules_.insert(std::make_pair(region.path, fd));
718           } else {
719             LOG(WARNING) << "Failed to open file: " << region.path
720                          << "\n  Error: " << strerror(errno);
721           }
722         }
723       }
724     }
725 #endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
726   }
727 
728   // Initializes and installs the symbolization callback.
729   void Init() {
730     if (CacheMemoryRegions()) {
731       OpenSymbolFiles();
732       google::InstallSymbolizeOpenObjectFileCallback(
733           &OpenObjectFileContainingPc);
734     }
735   }
736 
737   // Unregister symbolization callback.
738   void UnregisterCallback() {
739     if (is_initialized_) {
740       google::InstallSymbolizeOpenObjectFileCallback(nullptr);
741       is_initialized_ = false;
742     }
743   }
744 
745   // Closes all file descriptors owned by this instance.
746   void CloseObjectFiles() {
747 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
748     std::map<std::string, int>::iterator it;
749     for (it = modules_.begin(); it != modules_.end(); ++it) {
750       int ret = IGNORE_EINTR(close(it->second));
751       DCHECK(!ret);
752       it->second = -1;
753     }
754     modules_.clear();
755 #endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
756   }
757 
758   // Set to true upon successful initialization.
759   bool is_initialized_;
760 
761 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
762   // Mapping from file name to file descriptor.  Includes file descriptors
763   // for all successfully opened object files and the file descriptor for
764   // /proc/self/maps.  This code is not safe for production builds.
765   std::map<std::string, int> modules_;
766 #endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
767 
768   // Cache for the process memory regions.  Produced by parsing the contents
769   // of /proc/self/maps cache.
770   std::vector<MappedMemoryRegion> regions_;
771 
772   DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper);
773 };
774 #endif  // USE_SYMBOLIZE
775 
776 }  // namespace
777 
EnableInProcessStackDumping()778 bool EnableInProcessStackDumping() {
779 #if defined(USE_SYMBOLIZE)
780   SandboxSymbolizeHelper::GetInstance();
781 #endif  // USE_SYMBOLIZE
782 
783   // When running in an application, our code typically expects SIGPIPE
784   // to be ignored.  Therefore, when testing that same code, it should run
785   // with SIGPIPE ignored as well.
786   struct sigaction sigpipe_action;
787   memset(&sigpipe_action, 0, sizeof(sigpipe_action));
788   sigpipe_action.sa_handler = SIG_IGN;
789   sigemptyset(&sigpipe_action.sa_mask);
790   bool success = (sigaction(SIGPIPE, &sigpipe_action, nullptr) == 0);
791 
792   // Avoid hangs during backtrace initialization, see above.
793   WarmUpBacktrace();
794 
795   struct sigaction action;
796   memset(&action, 0, sizeof(action));
797   action.sa_flags = SA_RESETHAND | SA_SIGINFO;
798   action.sa_sigaction = &StackDumpSignalHandler;
799   sigemptyset(&action.sa_mask);
800 
801   success &= (sigaction(SIGILL, &action, nullptr) == 0);
802   success &= (sigaction(SIGABRT, &action, nullptr) == 0);
803   success &= (sigaction(SIGFPE, &action, nullptr) == 0);
804   success &= (sigaction(SIGBUS, &action, nullptr) == 0);
805   success &= (sigaction(SIGSEGV, &action, nullptr) == 0);
806 // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
807 #if !defined(OS_LINUX)
808   success &= (sigaction(SIGSYS, &action, nullptr) == 0);
809 #endif  // !defined(OS_LINUX)
810 
811   return success;
812 }
813 
814 #if !defined(OS_NACL)
SetStackDumpFirstChanceCallback(bool (* handler)(int,siginfo_t *,void *))815 bool SetStackDumpFirstChanceCallback(bool (*handler)(int, siginfo_t*, void*)) {
816   DCHECK(try_handle_signal == nullptr || handler == nullptr);
817   try_handle_signal = handler;
818 
819 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
820     defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) ||    \
821     defined(UNDEFINED_SANITIZER)
822   struct sigaction installed_handler;
823   CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0);
824   // If the installed handler does not point to StackDumpSignalHandler, then
825   // allow_user_segv_handler is 0.
826   if (installed_handler.sa_sigaction != StackDumpSignalHandler) {
827     LOG(WARNING)
828         << "WARNING: sanitizers are preventing signal handler installation. "
829         << "WebAssembly trap handlers are disabled.\n";
830     return false;
831   }
832 #endif
833   return true;
834 }
835 #endif
836 
CollectStackTrace(void ** trace,size_t count)837 size_t CollectStackTrace(void** trace, size_t count) {
838   // NOTE: This code MUST be async-signal safe (it's used by in-process
839   // stack dumping signal handler). NO malloc or stdio is allowed here.
840 
841 #if !defined(__UCLIBC__) && !defined(_AIX)
842   // Though the backtrace API man page does not list any possible negative
843   // return values, we take no chance.
844   return base::saturated_cast<size_t>(backtrace(trace, count));
845 #else
846   return 0;
847 #endif
848 }
849 
PrintWithPrefix(const char * prefix_string) const850 void StackTrace::PrintWithPrefix(const char* prefix_string) const {
851 // NOTE: This code MUST be async-signal safe (it's used by in-process
852 // stack dumping signal handler). NO malloc or stdio is allowed here.
853 
854 #if !defined(__UCLIBC__) && !defined(_AIX)
855   PrintBacktraceOutputHandler handler;
856   ProcessBacktrace(trace_, count_, prefix_string, &handler);
857 #endif
858 }
859 
860 #if !defined(__UCLIBC__) && !defined(_AIX)
OutputToStreamWithPrefix(std::ostream * os,const char * prefix_string) const861 void StackTrace::OutputToStreamWithPrefix(std::ostream* os,
862                                           const char* prefix_string) const {
863   StreamBacktraceOutputHandler handler(os);
864   ProcessBacktrace(trace_, count_, prefix_string, &handler);
865 }
866 #endif
867 
868 namespace internal {
869 
870 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
itoa_r(intptr_t i,char * buf,size_t sz,int base,size_t padding)871 char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
872   // Make sure we can write at least one NUL byte.
873   size_t n = 1;
874   if (n > sz)
875     return nullptr;
876 
877   if (base < 2 || base > 16) {
878     buf[0] = '\000';
879     return nullptr;
880   }
881 
882   char* start = buf;
883 
884   uintptr_t j = i;
885 
886   // Handle negative numbers (only for base 10).
887   if (i < 0 && base == 10) {
888     // This does "j = -i" while avoiding integer overflow.
889     j = static_cast<uintptr_t>(-(i + 1)) + 1;
890 
891     // Make sure we can write the '-' character.
892     if (++n > sz) {
893       buf[0] = '\000';
894       return nullptr;
895     }
896     *start++ = '-';
897   }
898 
899   // Loop until we have converted the entire number. Output at least one
900   // character (i.e. '0').
901   char* ptr = start;
902   do {
903     // Make sure there is still enough space left in our output buffer.
904     if (++n > sz) {
905       buf[0] = '\000';
906       return nullptr;
907     }
908 
909     // Output the next digit.
910     *ptr++ = "0123456789abcdef"[j % base];
911     j /= base;
912 
913     if (padding > 0)
914       padding--;
915   } while (j > 0 || padding > 0);
916 
917   // Terminate the output with a NUL character.
918   *ptr = '\000';
919 
920   // Conversion to ASCII actually resulted in the digits being in reverse
921   // order. We can't easily generate them in forward order, as we can't tell
922   // the number of characters needed until we are done converting.
923   // So, now, we reverse the string (except for the possible "-" sign).
924   while (--ptr > start) {
925     char ch = *ptr;
926     *ptr = *start;
927     *start++ = ch;
928   }
929   return buf;
930 }
931 
932 }  // namespace internal
933 
934 }  // namespace debug
935 }  // namespace base
936