• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <stdio.h>
11 #include <stdlib.h>
12 #include <sys/param.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 
17 #include <map>
18 #include <ostream>
19 #include <string>
20 #include <vector>
21 
22 #if defined(__GLIBCXX__)
23 #include <cxxabi.h>
24 #endif
25 #if !defined(__UCLIBC__)
26 #include <execinfo.h>
27 #endif
28 
29 #if defined(OS_MACOSX)
30 #include <AvailabilityMacros.h>
31 #endif
32 
33 #include "base/basictypes.h"
34 #include "base/debug/debugger.h"
35 #include "base/debug/proc_maps_linux.h"
36 #include "base/logging.h"
37 #include "base/memory/scoped_ptr.h"
38 #include "base/memory/singleton.h"
39 #include "base/numerics/safe_conversions.h"
40 #include "base/posix/eintr_wrapper.h"
41 #include "base/strings/string_number_conversions.h"
42 #include "build/build_config.h"
43 
44 #if defined(USE_SYMBOLIZE)
45 #include "base/third_party/symbolize/symbolize.h"
46 #endif
47 
48 namespace base {
49 namespace debug {
50 
51 namespace {
52 
53 volatile sig_atomic_t in_signal_handler = 0;
54 
55 #if !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
56 // The prefix used for mangled symbols, per the Itanium C++ ABI:
57 // http://www.codesourcery.com/cxx-abi/abi.html#mangling
58 const char kMangledSymbolPrefix[] = "_Z";
59 
60 // Characters that can be used for symbols, generated by Ruby:
61 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
62 const char kSymbolCharacters[] =
63     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
64 #endif  // !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
65 
66 #if !defined(USE_SYMBOLIZE)
67 // Demangles C++ symbols in the given text. Example:
68 //
69 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
70 // =>
71 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
DemangleSymbols(std::string * text)72 void DemangleSymbols(std::string* text) {
73   // Note: code in this function is NOT async-signal safe (std::string uses
74   // malloc internally).
75 
76 #if defined(__GLIBCXX__) && !defined(__UCLIBC__)
77 
78   std::string::size_type search_from = 0;
79   while (search_from < text->size()) {
80     // Look for the start of a mangled symbol, from search_from.
81     std::string::size_type mangled_start =
82         text->find(kMangledSymbolPrefix, search_from);
83     if (mangled_start == std::string::npos) {
84       break;  // Mangled symbol not found.
85     }
86 
87     // Look for the end of the mangled symbol.
88     std::string::size_type mangled_end =
89         text->find_first_not_of(kSymbolCharacters, mangled_start);
90     if (mangled_end == std::string::npos) {
91       mangled_end = text->size();
92     }
93     std::string mangled_symbol =
94         text->substr(mangled_start, mangled_end - mangled_start);
95 
96     // Try to demangle the mangled symbol candidate.
97     int status = 0;
98     scoped_ptr<char, base::FreeDeleter> demangled_symbol(
99         abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
100     if (status == 0) {  // Demangling is successful.
101       // Remove the mangled symbol.
102       text->erase(mangled_start, mangled_end - mangled_start);
103       // Insert the demangled symbol.
104       text->insert(mangled_start, demangled_symbol.get());
105       // Next time, we'll start right after the demangled symbol we inserted.
106       search_from = mangled_start + strlen(demangled_symbol.get());
107     } else {
108       // Failed to demangle.  Retry after the "_Z" we just found.
109       search_from = mangled_start + 2;
110     }
111   }
112 
113 #endif  // defined(__GLIBCXX__) && !defined(__UCLIBC__)
114 }
115 #endif  // !defined(USE_SYMBOLIZE)
116 
117 class BacktraceOutputHandler {
118  public:
119   virtual void HandleOutput(const char* output) = 0;
120 
121  protected:
~BacktraceOutputHandler()122   virtual ~BacktraceOutputHandler() {}
123 };
124 
OutputPointer(void * pointer,BacktraceOutputHandler * handler)125 void OutputPointer(void* pointer, BacktraceOutputHandler* handler) {
126   // This should be more than enough to store a 64-bit number in hex:
127   // 16 hex digits + 1 for null-terminator.
128   char buf[17] = { '\0' };
129   handler->HandleOutput("0x");
130   internal::itoa_r(reinterpret_cast<intptr_t>(pointer),
131                    buf, sizeof(buf), 16, 12);
132   handler->HandleOutput(buf);
133 }
134 
135 #if defined(USE_SYMBOLIZE)
OutputFrameId(intptr_t frame_id,BacktraceOutputHandler * handler)136 void OutputFrameId(intptr_t frame_id, BacktraceOutputHandler* handler) {
137   // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615).
138   // Hence, 30 digits should be more than enough to represent it in decimal
139   // (including the null-terminator).
140   char buf[30] = { '\0' };
141   handler->HandleOutput("#");
142   internal::itoa_r(frame_id, buf, sizeof(buf), 10, 1);
143   handler->HandleOutput(buf);
144 }
145 #endif  // defined(USE_SYMBOLIZE)
146 
ProcessBacktrace(void * const * trace,size_t size,BacktraceOutputHandler * handler)147 void ProcessBacktrace(void *const *trace,
148                       size_t size,
149                       BacktraceOutputHandler* handler) {
150   // NOTE: This code MUST be async-signal safe (it's used by in-process
151   // stack dumping signal handler). NO malloc or stdio is allowed here.
152 
153 #if defined(USE_SYMBOLIZE)
154   for (size_t i = 0; i < size; ++i) {
155     OutputFrameId(i, handler);
156     handler->HandleOutput(" ");
157     OutputPointer(trace[i], handler);
158     handler->HandleOutput(" ");
159 
160     char buf[1024] = { '\0' };
161 
162     // Subtract by one as return address of function may be in the next
163     // function when a function is annotated as noreturn.
164     void* address = static_cast<char*>(trace[i]) - 1;
165     if (google::Symbolize(address, buf, sizeof(buf)))
166       handler->HandleOutput(buf);
167     else
168       handler->HandleOutput("<unknown>");
169 
170     handler->HandleOutput("\n");
171   }
172 #elif !defined(__UCLIBC__)
173   bool printed = false;
174 
175   // Below part is async-signal unsafe (uses malloc), so execute it only
176   // when we are not executing the signal handler.
177   if (in_signal_handler == 0) {
178     scoped_ptr<char*, FreeDeleter>
179         trace_symbols(backtrace_symbols(trace, size));
180     if (trace_symbols.get()) {
181       for (size_t i = 0; i < size; ++i) {
182         std::string trace_symbol = trace_symbols.get()[i];
183         DemangleSymbols(&trace_symbol);
184         handler->HandleOutput(trace_symbol.c_str());
185         handler->HandleOutput("\n");
186       }
187 
188       printed = true;
189     }
190   }
191 
192   if (!printed) {
193     for (size_t i = 0; i < size; ++i) {
194       handler->HandleOutput(" [");
195       OutputPointer(trace[i], handler);
196       handler->HandleOutput("]\n");
197     }
198   }
199 #endif  // defined(USE_SYMBOLIZE)
200 }
201 
PrintToStderr(const char * output)202 void PrintToStderr(const char* output) {
203   // NOTE: This code MUST be async-signal safe (it's used by in-process
204   // stack dumping signal handler). NO malloc or stdio is allowed here.
205   ignore_result(HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output))));
206 }
207 
StackDumpSignalHandler(int signal,siginfo_t * info,void * void_context)208 void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
209   // NOTE: This code MUST be async-signal safe.
210   // NO malloc or stdio is allowed here.
211 
212   // Record the fact that we are in the signal handler now, so that the rest
213   // of StackTrace can behave in an async-signal-safe manner.
214   in_signal_handler = 1;
215 
216   if (BeingDebugged())
217     BreakDebugger();
218 
219   PrintToStderr("Received signal ");
220   char buf[1024] = { 0 };
221   internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
222   PrintToStderr(buf);
223   if (signal == SIGBUS) {
224     if (info->si_code == BUS_ADRALN)
225       PrintToStderr(" BUS_ADRALN ");
226     else if (info->si_code == BUS_ADRERR)
227       PrintToStderr(" BUS_ADRERR ");
228     else if (info->si_code == BUS_OBJERR)
229       PrintToStderr(" BUS_OBJERR ");
230     else
231       PrintToStderr(" <unknown> ");
232   } else if (signal == SIGFPE) {
233     if (info->si_code == FPE_FLTDIV)
234       PrintToStderr(" FPE_FLTDIV ");
235     else if (info->si_code == FPE_FLTINV)
236       PrintToStderr(" FPE_FLTINV ");
237     else if (info->si_code == FPE_FLTOVF)
238       PrintToStderr(" FPE_FLTOVF ");
239     else if (info->si_code == FPE_FLTRES)
240       PrintToStderr(" FPE_FLTRES ");
241     else if (info->si_code == FPE_FLTSUB)
242       PrintToStderr(" FPE_FLTSUB ");
243     else if (info->si_code == FPE_FLTUND)
244       PrintToStderr(" FPE_FLTUND ");
245     else if (info->si_code == FPE_INTDIV)
246       PrintToStderr(" FPE_INTDIV ");
247     else if (info->si_code == FPE_INTOVF)
248       PrintToStderr(" FPE_INTOVF ");
249     else
250       PrintToStderr(" <unknown> ");
251   } else if (signal == SIGILL) {
252     if (info->si_code == ILL_BADSTK)
253       PrintToStderr(" ILL_BADSTK ");
254     else if (info->si_code == ILL_COPROC)
255       PrintToStderr(" ILL_COPROC ");
256     else if (info->si_code == ILL_ILLOPN)
257       PrintToStderr(" ILL_ILLOPN ");
258     else if (info->si_code == ILL_ILLADR)
259       PrintToStderr(" ILL_ILLADR ");
260     else if (info->si_code == ILL_ILLTRP)
261       PrintToStderr(" ILL_ILLTRP ");
262     else if (info->si_code == ILL_PRVOPC)
263       PrintToStderr(" ILL_PRVOPC ");
264     else if (info->si_code == ILL_PRVREG)
265       PrintToStderr(" ILL_PRVREG ");
266     else
267       PrintToStderr(" <unknown> ");
268   } else if (signal == SIGSEGV) {
269     if (info->si_code == SEGV_MAPERR)
270       PrintToStderr(" SEGV_MAPERR ");
271     else if (info->si_code == SEGV_ACCERR)
272       PrintToStderr(" SEGV_ACCERR ");
273     else
274       PrintToStderr(" <unknown> ");
275   }
276   if (signal == SIGBUS || signal == SIGFPE ||
277       signal == SIGILL || signal == SIGSEGV) {
278     internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
279                      buf, sizeof(buf), 16, 12);
280     PrintToStderr(buf);
281   }
282   PrintToStderr("\n");
283 
284 #if !defined(__UCLIBC__)
285   debug::StackTrace().Print();
286 #endif
287 
288 #if defined(OS_LINUX)
289 #if ARCH_CPU_X86_FAMILY
290   ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
291   const struct {
292     const char* label;
293     greg_t value;
294   } registers[] = {
295 #if ARCH_CPU_32_BITS
296     { "  gs: ", context->uc_mcontext.gregs[REG_GS] },
297     { "  fs: ", context->uc_mcontext.gregs[REG_FS] },
298     { "  es: ", context->uc_mcontext.gregs[REG_ES] },
299     { "  ds: ", context->uc_mcontext.gregs[REG_DS] },
300     { " edi: ", context->uc_mcontext.gregs[REG_EDI] },
301     { " esi: ", context->uc_mcontext.gregs[REG_ESI] },
302     { " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
303     { " esp: ", context->uc_mcontext.gregs[REG_ESP] },
304     { " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
305     { " edx: ", context->uc_mcontext.gregs[REG_EDX] },
306     { " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
307     { " eax: ", context->uc_mcontext.gregs[REG_EAX] },
308     { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
309     { " err: ", context->uc_mcontext.gregs[REG_ERR] },
310     { "  ip: ", context->uc_mcontext.gregs[REG_EIP] },
311     { "  cs: ", context->uc_mcontext.gregs[REG_CS] },
312     { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
313     { " usp: ", context->uc_mcontext.gregs[REG_UESP] },
314     { "  ss: ", context->uc_mcontext.gregs[REG_SS] },
315 #elif ARCH_CPU_64_BITS
316     { "  r8: ", context->uc_mcontext.gregs[REG_R8] },
317     { "  r9: ", context->uc_mcontext.gregs[REG_R9] },
318     { " r10: ", context->uc_mcontext.gregs[REG_R10] },
319     { " r11: ", context->uc_mcontext.gregs[REG_R11] },
320     { " r12: ", context->uc_mcontext.gregs[REG_R12] },
321     { " r13: ", context->uc_mcontext.gregs[REG_R13] },
322     { " r14: ", context->uc_mcontext.gregs[REG_R14] },
323     { " r15: ", context->uc_mcontext.gregs[REG_R15] },
324     { "  di: ", context->uc_mcontext.gregs[REG_RDI] },
325     { "  si: ", context->uc_mcontext.gregs[REG_RSI] },
326     { "  bp: ", context->uc_mcontext.gregs[REG_RBP] },
327     { "  bx: ", context->uc_mcontext.gregs[REG_RBX] },
328     { "  dx: ", context->uc_mcontext.gregs[REG_RDX] },
329     { "  ax: ", context->uc_mcontext.gregs[REG_RAX] },
330     { "  cx: ", context->uc_mcontext.gregs[REG_RCX] },
331     { "  sp: ", context->uc_mcontext.gregs[REG_RSP] },
332     { "  ip: ", context->uc_mcontext.gregs[REG_RIP] },
333     { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
334     { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
335     { " erf: ", context->uc_mcontext.gregs[REG_ERR] },
336     { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
337     { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
338     { " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
339 #endif
340   };
341 
342 #if ARCH_CPU_32_BITS
343   const int kRegisterPadding = 8;
344 #elif ARCH_CPU_64_BITS
345   const int kRegisterPadding = 16;
346 #endif
347 
348   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(registers); i++) {
349     PrintToStderr(registers[i].label);
350     internal::itoa_r(registers[i].value, buf, sizeof(buf),
351                      16, kRegisterPadding);
352     PrintToStderr(buf);
353 
354     if ((i + 1) % 4 == 0)
355       PrintToStderr("\n");
356   }
357   PrintToStderr("\n");
358 #endif
359 #elif defined(OS_MACOSX)
360   // TODO(shess): Port to 64-bit, and ARM architecture (32 and 64-bit).
361 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
362   ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
363   size_t len;
364 
365   // NOTE: Even |snprintf()| is not on the approved list for signal
366   // handlers, but buffered I/O is definitely not on the list due to
367   // potential for |malloc()|.
368   len = static_cast<size_t>(
369       snprintf(buf, sizeof(buf),
370                "ax: %x, bx: %x, cx: %x, dx: %x\n",
371                context->uc_mcontext->__ss.__eax,
372                context->uc_mcontext->__ss.__ebx,
373                context->uc_mcontext->__ss.__ecx,
374                context->uc_mcontext->__ss.__edx));
375   write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
376 
377   len = static_cast<size_t>(
378       snprintf(buf, sizeof(buf),
379                "di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
380                context->uc_mcontext->__ss.__edi,
381                context->uc_mcontext->__ss.__esi,
382                context->uc_mcontext->__ss.__ebp,
383                context->uc_mcontext->__ss.__esp,
384                context->uc_mcontext->__ss.__ss,
385                context->uc_mcontext->__ss.__eflags));
386   write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
387 
388   len = static_cast<size_t>(
389       snprintf(buf, sizeof(buf),
390                "ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
391                context->uc_mcontext->__ss.__eip,
392                context->uc_mcontext->__ss.__cs,
393                context->uc_mcontext->__ss.__ds,
394                context->uc_mcontext->__ss.__es,
395                context->uc_mcontext->__ss.__fs,
396                context->uc_mcontext->__ss.__gs));
397   write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
398 #endif  // ARCH_CPU_32_BITS
399 #endif  // defined(OS_MACOSX)
400   _exit(1);
401 }
402 
403 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
404  public:
PrintBacktraceOutputHandler()405   PrintBacktraceOutputHandler() {}
406 
HandleOutput(const char * output)407   virtual void HandleOutput(const char* output) OVERRIDE {
408     // NOTE: This code MUST be async-signal safe (it's used by in-process
409     // stack dumping signal handler). NO malloc or stdio is allowed here.
410     PrintToStderr(output);
411   }
412 
413  private:
414   DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
415 };
416 
417 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
418  public:
StreamBacktraceOutputHandler(std::ostream * os)419   explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
420   }
421 
HandleOutput(const char * output)422   virtual void HandleOutput(const char* output) OVERRIDE {
423     (*os_) << output;
424   }
425 
426  private:
427   std::ostream* os_;
428 
429   DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
430 };
431 
WarmUpBacktrace()432 void WarmUpBacktrace() {
433   // Warm up stack trace infrastructure. It turns out that on the first
434   // call glibc initializes some internal data structures using pthread_once,
435   // and even backtrace() can call malloc(), leading to hangs.
436   //
437   // Example stack trace snippet (with tcmalloc):
438   //
439   // #8  0x0000000000a173b5 in tc_malloc
440   //             at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
441   // #9  0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
442   // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
443   // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
444   // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
445   //             at dl-open.c:639
446   // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
447   // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
448   // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
449   // #16 __GI___libc_dlopen_mode at dl-libc.c:165
450   // #17 0x00007ffff61ef8f5 in init
451   //             at ../sysdeps/x86_64/../ia64/backtrace.c:53
452   // #18 0x00007ffff6aad400 in pthread_once
453   //             at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
454   // #19 0x00007ffff61efa14 in __GI___backtrace
455   //             at ../sysdeps/x86_64/../ia64/backtrace.c:104
456   // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
457   //             at base/debug/stack_trace_posix.cc:175
458   // #21 0x00000000007a4ae5 in
459   //             base::(anonymous namespace)::StackDumpSignalHandler
460   //             at base/process_util_posix.cc:172
461   // #22 <signal handler called>
462   StackTrace stack_trace;
463 }
464 
465 }  // namespace
466 
467 #if defined(USE_SYMBOLIZE)
468 
469 // class SandboxSymbolizeHelper.
470 //
471 // The purpose of this class is to prepare and install a "file open" callback
472 // needed by the stack trace symbolization code
473 // (base/third_party/symbolize/symbolize.h) so that it can function properly
474 // in a sandboxed process.  The caveat is that this class must be instantiated
475 // before the sandboxing is enabled so that it can get the chance to open all
476 // the object files that are loaded in the virtual address space of the current
477 // process.
478 class SandboxSymbolizeHelper {
479  public:
480   // Returns the singleton instance.
GetInstance()481   static SandboxSymbolizeHelper* GetInstance() {
482     return Singleton<SandboxSymbolizeHelper>::get();
483   }
484 
485  private:
486   friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
487 
SandboxSymbolizeHelper()488   SandboxSymbolizeHelper()
489       : is_initialized_(false) {
490     Init();
491   }
492 
~SandboxSymbolizeHelper()493   ~SandboxSymbolizeHelper() {
494     UnregisterCallback();
495     CloseObjectFiles();
496   }
497 
498   // Returns a O_RDONLY file descriptor for |file_path| if it was opened
499   // sucessfully during the initialization.  The file is repositioned at
500   // offset 0.
501   // IMPORTANT: This function must be async-signal-safe because it can be
502   // called from a signal handler (symbolizing stack frames for a crash).
GetFileDescriptor(const char * file_path)503   int GetFileDescriptor(const char* file_path) {
504     int fd = -1;
505 
506 #if !defined(NDEBUG)
507     if (file_path) {
508       // The assumption here is that iterating over std::map<std::string, int>
509       // using a const_iterator does not allocate dynamic memory, hense it is
510       // async-signal-safe.
511       std::map<std::string, int>::const_iterator it;
512       for (it = modules_.begin(); it != modules_.end(); ++it) {
513         if (strcmp((it->first).c_str(), file_path) == 0) {
514           // POSIX.1-2004 requires an implementation to guarantee that dup()
515           // is async-signal-safe.
516           fd = dup(it->second);
517           break;
518         }
519       }
520       // POSIX.1-2004 requires an implementation to guarantee that lseek()
521       // is async-signal-safe.
522       if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
523         // Failed to seek.
524         fd = -1;
525       }
526     }
527 #endif  // !defined(NDEBUG)
528 
529     return fd;
530   }
531 
532   // Searches for the object file (from /proc/self/maps) that contains
533   // the specified pc.  If found, sets |start_address| to the start address
534   // of where this object file is mapped in memory, sets the module base
535   // address into |base_address|, copies the object file name into
536   // |out_file_name|, and attempts to open the object file.  If the object
537   // file is opened successfully, returns the file descriptor.  Otherwise,
538   // returns -1.  |out_file_name_size| is the size of the file name buffer
539   // (including the null terminator).
540   // IMPORTANT: This function must be async-signal-safe because it can be
541   // 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)542   static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address,
543                                         uint64_t& base_address, char* file_path,
544                                         int file_path_size) {
545     // This method can only be called after the singleton is instantiated.
546     // This is ensured by the following facts:
547     // * This is the only static method in this class, it is private, and
548     //   the class has no friends (except for the DefaultSingletonTraits).
549     //   The compiler guarantees that it can only be called after the
550     //   singleton is instantiated.
551     // * This method is used as a callback for the stack tracing code and
552     //   the callback registration is done in the constructor, so logically
553     //   it cannot be called before the singleton is created.
554     SandboxSymbolizeHelper* instance = GetInstance();
555 
556     // The assumption here is that iterating over
557     // std::vector<MappedMemoryRegion> using a const_iterator does not allocate
558     // dynamic memory, hence it is async-signal-safe.
559     std::vector<MappedMemoryRegion>::const_iterator it;
560     bool is_first = true;
561     for (it = instance->regions_.begin(); it != instance->regions_.end();
562          ++it, is_first = false) {
563       const MappedMemoryRegion& region = *it;
564       if (region.start <= pc && pc < region.end) {
565         start_address = region.start;
566         // Don't subtract 'start_address' from the first entry:
567         // * If a binary is compiled w/o -pie, then the first entry in
568         //   process maps is likely the binary itself (all dynamic libs
569         //   are mapped higher in address space). For such a binary,
570         //   instruction offset in binary coincides with the actual
571         //   instruction address in virtual memory (as code section
572         //   is mapped to a fixed memory range).
573         // * If a binary is compiled with -pie, all the modules are
574         //   mapped high at address space (in particular, higher than
575         //   shadow memory of the tool), so the module can't be the
576         //   first entry.
577         base_address = (is_first ? 0U : start_address) - region.offset;
578         if (file_path && file_path_size > 0) {
579           strncpy(file_path, region.path.c_str(), file_path_size);
580           // Ensure null termination.
581           file_path[file_path_size - 1] = '\0';
582         }
583         return instance->GetFileDescriptor(region.path.c_str());
584       }
585     }
586     return -1;
587   }
588 
589   // Parses /proc/self/maps in order to compile a list of all object file names
590   // for the modules that are loaded in the current process.
591   // Returns true on success.
CacheMemoryRegions()592   bool CacheMemoryRegions() {
593     // Reads /proc/self/maps.
594     std::string contents;
595     if (!ReadProcMaps(&contents)) {
596       LOG(ERROR) << "Failed to read /proc/self/maps";
597       return false;
598     }
599 
600     // Parses /proc/self/maps.
601     if (!ParseProcMaps(contents, &regions_)) {
602       LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
603       return false;
604     }
605 
606     is_initialized_ = true;
607     return true;
608   }
609 
610   // Opens all object files and caches their file descriptors.
OpenSymbolFiles()611   void OpenSymbolFiles() {
612     // Pre-opening and caching the file descriptors of all loaded modules is
613     // not considered safe for retail builds.  Hence it is only done in debug
614     // builds.  For more details, take a look at: http://crbug.com/341966
615     // Enabling this to release mode would require approval from the security
616     // team.
617 #if !defined(NDEBUG)
618     // Open the object files for all read-only executable regions and cache
619     // their file descriptors.
620     std::vector<MappedMemoryRegion>::const_iterator it;
621     for (it = regions_.begin(); it != regions_.end(); ++it) {
622       const MappedMemoryRegion& region = *it;
623       // Only interesed in read-only executable regions.
624       if ((region.permissions & MappedMemoryRegion::READ) ==
625               MappedMemoryRegion::READ &&
626           (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
627           (region.permissions & MappedMemoryRegion::EXECUTE) ==
628               MappedMemoryRegion::EXECUTE) {
629         if (region.path.empty()) {
630           // Skip regions with empty file names.
631           continue;
632         }
633         if (region.path[0] == '[') {
634           // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
635           continue;
636         }
637         // Avoid duplicates.
638         if (modules_.find(region.path) == modules_.end()) {
639           int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
640           if (fd >= 0) {
641             modules_.insert(std::make_pair(region.path, fd));
642           } else {
643             LOG(WARNING) << "Failed to open file: " << region.path
644                          << "\n  Error: " << strerror(errno);
645           }
646         }
647       }
648     }
649 #endif  // !defined(NDEBUG)
650   }
651 
652   // Initializes and installs the symbolization callback.
Init()653   void Init() {
654     if (CacheMemoryRegions()) {
655       OpenSymbolFiles();
656       google::InstallSymbolizeOpenObjectFileCallback(
657           &OpenObjectFileContainingPc);
658     }
659   }
660 
661   // Unregister symbolization callback.
UnregisterCallback()662   void UnregisterCallback() {
663     if (is_initialized_) {
664       google::InstallSymbolizeOpenObjectFileCallback(NULL);
665       is_initialized_ = false;
666     }
667   }
668 
669   // Closes all file descriptors owned by this instance.
CloseObjectFiles()670   void CloseObjectFiles() {
671 #if !defined(NDEBUG)
672     std::map<std::string, int>::iterator it;
673     for (it = modules_.begin(); it != modules_.end(); ++it) {
674       int ret = IGNORE_EINTR(close(it->second));
675       DCHECK(!ret);
676       it->second = -1;
677     }
678     modules_.clear();
679 #endif  // !defined(NDEBUG)
680   }
681 
682   // Set to true upon successful initialization.
683   bool is_initialized_;
684 
685 #if !defined(NDEBUG)
686   // Mapping from file name to file descriptor.  Includes file descriptors
687   // for all successfully opened object files and the file descriptor for
688   // /proc/self/maps.  This code is not safe for release builds so
689   // this is only done for DEBUG builds.
690   std::map<std::string, int> modules_;
691 #endif  // !defined(NDEBUG)
692 
693   // Cache for the process memory regions.  Produced by parsing the contents
694   // of /proc/self/maps cache.
695   std::vector<MappedMemoryRegion> regions_;
696 
697   DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper);
698 };
699 #endif  // USE_SYMBOLIZE
700 
EnableInProcessStackDumpingForSandbox()701 bool EnableInProcessStackDumpingForSandbox() {
702 #if defined(USE_SYMBOLIZE)
703   SandboxSymbolizeHelper::GetInstance();
704 #endif  // USE_SYMBOLIZE
705 
706   return EnableInProcessStackDumping();
707 }
708 
EnableInProcessStackDumping()709 bool EnableInProcessStackDumping() {
710   // When running in an application, our code typically expects SIGPIPE
711   // to be ignored.  Therefore, when testing that same code, it should run
712   // with SIGPIPE ignored as well.
713   struct sigaction sigpipe_action;
714   memset(&sigpipe_action, 0, sizeof(sigpipe_action));
715   sigpipe_action.sa_handler = SIG_IGN;
716   sigemptyset(&sigpipe_action.sa_mask);
717   bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
718 
719   // Avoid hangs during backtrace initialization, see above.
720   WarmUpBacktrace();
721 
722   struct sigaction action;
723   memset(&action, 0, sizeof(action));
724   action.sa_flags = SA_RESETHAND | SA_SIGINFO;
725   action.sa_sigaction = &StackDumpSignalHandler;
726   sigemptyset(&action.sa_mask);
727 
728   success &= (sigaction(SIGILL, &action, NULL) == 0);
729   success &= (sigaction(SIGABRT, &action, NULL) == 0);
730   success &= (sigaction(SIGFPE, &action, NULL) == 0);
731   success &= (sigaction(SIGBUS, &action, NULL) == 0);
732   success &= (sigaction(SIGSEGV, &action, NULL) == 0);
733 // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
734 #if !defined(OS_LINUX)
735   success &= (sigaction(SIGSYS, &action, NULL) == 0);
736 #endif  // !defined(OS_LINUX)
737 
738   return success;
739 }
740 
StackTrace()741 StackTrace::StackTrace() {
742   // NOTE: This code MUST be async-signal safe (it's used by in-process
743   // stack dumping signal handler). NO malloc or stdio is allowed here.
744 
745 #if !defined(__UCLIBC__)
746   // Though the backtrace API man page does not list any possible negative
747   // return values, we take no chance.
748   count_ = base::saturated_cast<size_t>(backtrace(trace_, arraysize(trace_)));
749 #else
750   count_ = 0;
751 #endif
752 }
753 
754 #if !defined(__UCLIBC__)
Print() const755 void StackTrace::Print() const {
756   // NOTE: This code MUST be async-signal safe (it's used by in-process
757   // stack dumping signal handler). NO malloc or stdio is allowed here.
758 
759   PrintBacktraceOutputHandler handler;
760   ProcessBacktrace(trace_, count_, &handler);
761 }
762 
OutputToStream(std::ostream * os) const763 void StackTrace::OutputToStream(std::ostream* os) const {
764   StreamBacktraceOutputHandler handler(os);
765   ProcessBacktrace(trace_, count_, &handler);
766 }
767 #endif
768 
769 namespace internal {
770 
771 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
itoa_r(intptr_t i,char * buf,size_t sz,int base,size_t padding)772 char *itoa_r(intptr_t i, char *buf, size_t sz, int base, size_t padding) {
773   // Make sure we can write at least one NUL byte.
774   size_t n = 1;
775   if (n > sz)
776     return NULL;
777 
778   if (base < 2 || base > 16) {
779     buf[0] = '\000';
780     return NULL;
781   }
782 
783   char *start = buf;
784 
785   uintptr_t j = i;
786 
787   // Handle negative numbers (only for base 10).
788   if (i < 0 && base == 10) {
789     j = -i;
790 
791     // Make sure we can write the '-' character.
792     if (++n > sz) {
793       buf[0] = '\000';
794       return NULL;
795     }
796     *start++ = '-';
797   }
798 
799   // Loop until we have converted the entire number. Output at least one
800   // character (i.e. '0').
801   char *ptr = start;
802   do {
803     // Make sure there is still enough space left in our output buffer.
804     if (++n > sz) {
805       buf[0] = '\000';
806       return NULL;
807     }
808 
809     // Output the next digit.
810     *ptr++ = "0123456789abcdef"[j % base];
811     j /= base;
812 
813     if (padding > 0)
814       padding--;
815   } while (j > 0 || padding > 0);
816 
817   // Terminate the output with a NUL character.
818   *ptr = '\000';
819 
820   // Conversion to ASCII actually resulted in the digits being in reverse
821   // order. We can't easily generate them in forward order, as we can't tell
822   // the number of characters needed until we are done converting.
823   // So, now, we reverse the string (except for the possible "-" sign).
824   while (--ptr > start) {
825     char ch = *ptr;
826     *ptr = *start;
827     *start++ = ch;
828   }
829   return buf;
830 }
831 
832 }  // namespace internal
833 
834 }  // namespace debug
835 }  // namespace base
836