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