Properly attach InfoBarContainer when it is swapped to a new WebContents
[chromium-blink-merge.git] / base / debug / stack_trace_posix.cc
blob2eac14e35380d12dd426add3001de08d910ecc08
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.
5 #include "base/debug/stack_trace.h"
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>
17 #include <map>
18 #include <ostream>
19 #include <string>
20 #include <vector>
22 #if defined(__GLIBCXX__)
23 #include <cxxabi.h>
24 #endif
25 #if !defined(__UCLIBC__)
26 #include <execinfo.h>
27 #endif
29 #if defined(OS_MACOSX)
30 #include <AvailabilityMacros.h>
31 #endif
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"
44 #if defined(USE_SYMBOLIZE)
45 #include "base/third_party/symbolize/symbolize.h"
46 #endif
48 namespace base {
49 namespace debug {
51 namespace {
53 volatile sig_atomic_t in_signal_handler = 0;
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";
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__)
66 #if !defined(USE_SYMBOLIZE)
67 // Demangles C++ symbols in the given text. Example:
69 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
70 // =>
71 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
72 void DemangleSymbols(std::string* text) {
73 // Note: code in this function is NOT async-signal safe (std::string uses
74 // malloc internally).
76 #if defined(__GLIBCXX__) && !defined(__UCLIBC__)
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.
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();
93 std::string mangled_symbol =
94 text->substr(mangled_start, mangled_end - mangled_start);
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;
113 #endif // defined(__GLIBCXX__) && !defined(__UCLIBC__)
115 #endif // !defined(USE_SYMBOLIZE)
117 class BacktraceOutputHandler {
118 public:
119 virtual void HandleOutput(const char* output) = 0;
121 protected:
122 virtual ~BacktraceOutputHandler() {}
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);
135 #if defined(USE_SYMBOLIZE)
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);
145 #endif // defined(USE_SYMBOLIZE)
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.
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(" ");
160 char buf[1024] = { '\0' };
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>");
170 handler->HandleOutput("\n");
172 #elif !defined(__UCLIBC__)
173 bool printed = false;
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");
188 printed = true;
192 if (!printed) {
193 for (size_t i = 0; i < size; ++i) {
194 handler->HandleOutput(" [");
195 OutputPointer(trace[i], handler);
196 handler->HandleOutput("]\n");
199 #endif // defined(USE_SYMBOLIZE)
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))));
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.
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;
216 if (BeingDebugged())
217 BreakDebugger();
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> ");
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);
282 PrintToStderr("\n");
284 debug::StackTrace().Print();
286 #if defined(OS_LINUX)
287 #if ARCH_CPU_X86_FAMILY
288 ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
289 const struct {
290 const char* label;
291 greg_t value;
292 } registers[] = {
293 #if ARCH_CPU_32_BITS
294 { " gs: ", context->uc_mcontext.gregs[REG_GS] },
295 { " fs: ", context->uc_mcontext.gregs[REG_FS] },
296 { " es: ", context->uc_mcontext.gregs[REG_ES] },
297 { " ds: ", context->uc_mcontext.gregs[REG_DS] },
298 { " edi: ", context->uc_mcontext.gregs[REG_EDI] },
299 { " esi: ", context->uc_mcontext.gregs[REG_ESI] },
300 { " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
301 { " esp: ", context->uc_mcontext.gregs[REG_ESP] },
302 { " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
303 { " edx: ", context->uc_mcontext.gregs[REG_EDX] },
304 { " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
305 { " eax: ", context->uc_mcontext.gregs[REG_EAX] },
306 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
307 { " err: ", context->uc_mcontext.gregs[REG_ERR] },
308 { " ip: ", context->uc_mcontext.gregs[REG_EIP] },
309 { " cs: ", context->uc_mcontext.gregs[REG_CS] },
310 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
311 { " usp: ", context->uc_mcontext.gregs[REG_UESP] },
312 { " ss: ", context->uc_mcontext.gregs[REG_SS] },
313 #elif ARCH_CPU_64_BITS
314 { " r8: ", context->uc_mcontext.gregs[REG_R8] },
315 { " r9: ", context->uc_mcontext.gregs[REG_R9] },
316 { " r10: ", context->uc_mcontext.gregs[REG_R10] },
317 { " r11: ", context->uc_mcontext.gregs[REG_R11] },
318 { " r12: ", context->uc_mcontext.gregs[REG_R12] },
319 { " r13: ", context->uc_mcontext.gregs[REG_R13] },
320 { " r14: ", context->uc_mcontext.gregs[REG_R14] },
321 { " r15: ", context->uc_mcontext.gregs[REG_R15] },
322 { " di: ", context->uc_mcontext.gregs[REG_RDI] },
323 { " si: ", context->uc_mcontext.gregs[REG_RSI] },
324 { " bp: ", context->uc_mcontext.gregs[REG_RBP] },
325 { " bx: ", context->uc_mcontext.gregs[REG_RBX] },
326 { " dx: ", context->uc_mcontext.gregs[REG_RDX] },
327 { " ax: ", context->uc_mcontext.gregs[REG_RAX] },
328 { " cx: ", context->uc_mcontext.gregs[REG_RCX] },
329 { " sp: ", context->uc_mcontext.gregs[REG_RSP] },
330 { " ip: ", context->uc_mcontext.gregs[REG_RIP] },
331 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
332 { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
333 { " erf: ", context->uc_mcontext.gregs[REG_ERR] },
334 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
335 { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
336 { " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
337 #endif
340 #if ARCH_CPU_32_BITS
341 const int kRegisterPadding = 8;
342 #elif ARCH_CPU_64_BITS
343 const int kRegisterPadding = 16;
344 #endif
346 for (size_t i = 0; i < arraysize(registers); i++) {
347 PrintToStderr(registers[i].label);
348 internal::itoa_r(registers[i].value, buf, sizeof(buf),
349 16, kRegisterPadding);
350 PrintToStderr(buf);
352 if ((i + 1) % 4 == 0)
353 PrintToStderr("\n");
355 PrintToStderr("\n");
356 #endif
357 #elif defined(OS_MACOSX)
358 // TODO(shess): Port to 64-bit, and ARM architecture (32 and 64-bit).
359 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
360 ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
361 size_t len;
363 // NOTE: Even |snprintf()| is not on the approved list for signal
364 // handlers, but buffered I/O is definitely not on the list due to
365 // potential for |malloc()|.
366 len = static_cast<size_t>(
367 snprintf(buf, sizeof(buf),
368 "ax: %x, bx: %x, cx: %x, dx: %x\n",
369 context->uc_mcontext->__ss.__eax,
370 context->uc_mcontext->__ss.__ebx,
371 context->uc_mcontext->__ss.__ecx,
372 context->uc_mcontext->__ss.__edx));
373 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
375 len = static_cast<size_t>(
376 snprintf(buf, sizeof(buf),
377 "di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
378 context->uc_mcontext->__ss.__edi,
379 context->uc_mcontext->__ss.__esi,
380 context->uc_mcontext->__ss.__ebp,
381 context->uc_mcontext->__ss.__esp,
382 context->uc_mcontext->__ss.__ss,
383 context->uc_mcontext->__ss.__eflags));
384 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
386 len = static_cast<size_t>(
387 snprintf(buf, sizeof(buf),
388 "ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
389 context->uc_mcontext->__ss.__eip,
390 context->uc_mcontext->__ss.__cs,
391 context->uc_mcontext->__ss.__ds,
392 context->uc_mcontext->__ss.__es,
393 context->uc_mcontext->__ss.__fs,
394 context->uc_mcontext->__ss.__gs));
395 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
396 #endif // ARCH_CPU_32_BITS
397 #endif // defined(OS_MACOSX)
398 _exit(1);
401 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
402 public:
403 PrintBacktraceOutputHandler() {}
405 void HandleOutput(const char* output) override {
406 // NOTE: This code MUST be async-signal safe (it's used by in-process
407 // stack dumping signal handler). NO malloc or stdio is allowed here.
408 PrintToStderr(output);
411 private:
412 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
415 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
416 public:
417 explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
420 void HandleOutput(const char* output) override { (*os_) << output; }
422 private:
423 std::ostream* os_;
425 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
428 void WarmUpBacktrace() {
429 // Warm up stack trace infrastructure. It turns out that on the first
430 // call glibc initializes some internal data structures using pthread_once,
431 // and even backtrace() can call malloc(), leading to hangs.
433 // Example stack trace snippet (with tcmalloc):
435 // #8 0x0000000000a173b5 in tc_malloc
436 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
437 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
438 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
439 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
440 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
441 // at dl-open.c:639
442 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
443 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
444 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
445 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
446 // #17 0x00007ffff61ef8f5 in init
447 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
448 // #18 0x00007ffff6aad400 in pthread_once
449 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
450 // #19 0x00007ffff61efa14 in __GI___backtrace
451 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
452 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
453 // at base/debug/stack_trace_posix.cc:175
454 // #21 0x00000000007a4ae5 in
455 // base::(anonymous namespace)::StackDumpSignalHandler
456 // at base/process_util_posix.cc:172
457 // #22 <signal handler called>
458 StackTrace stack_trace;
461 } // namespace
463 #if defined(USE_SYMBOLIZE)
465 // class SandboxSymbolizeHelper.
467 // The purpose of this class is to prepare and install a "file open" callback
468 // needed by the stack trace symbolization code
469 // (base/third_party/symbolize/symbolize.h) so that it can function properly
470 // in a sandboxed process. The caveat is that this class must be instantiated
471 // before the sandboxing is enabled so that it can get the chance to open all
472 // the object files that are loaded in the virtual address space of the current
473 // process.
474 class SandboxSymbolizeHelper {
475 public:
476 // Returns the singleton instance.
477 static SandboxSymbolizeHelper* GetInstance() {
478 return Singleton<SandboxSymbolizeHelper>::get();
481 private:
482 friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
484 SandboxSymbolizeHelper()
485 : is_initialized_(false) {
486 Init();
489 ~SandboxSymbolizeHelper() {
490 UnregisterCallback();
491 CloseObjectFiles();
494 // Returns a O_RDONLY file descriptor for |file_path| if it was opened
495 // sucessfully during the initialization. The file is repositioned at
496 // offset 0.
497 // IMPORTANT: This function must be async-signal-safe because it can be
498 // called from a signal handler (symbolizing stack frames for a crash).
499 int GetFileDescriptor(const char* file_path) {
500 int fd = -1;
502 #if !defined(NDEBUG)
503 if (file_path) {
504 // The assumption here is that iterating over std::map<std::string, int>
505 // using a const_iterator does not allocate dynamic memory, hense it is
506 // async-signal-safe.
507 std::map<std::string, int>::const_iterator it;
508 for (it = modules_.begin(); it != modules_.end(); ++it) {
509 if (strcmp((it->first).c_str(), file_path) == 0) {
510 // POSIX.1-2004 requires an implementation to guarantee that dup()
511 // is async-signal-safe.
512 fd = dup(it->second);
513 break;
516 // POSIX.1-2004 requires an implementation to guarantee that lseek()
517 // is async-signal-safe.
518 if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
519 // Failed to seek.
520 fd = -1;
523 #endif // !defined(NDEBUG)
525 return fd;
528 // Searches for the object file (from /proc/self/maps) that contains
529 // the specified pc. If found, sets |start_address| to the start address
530 // of where this object file is mapped in memory, sets the module base
531 // address into |base_address|, copies the object file name into
532 // |out_file_name|, and attempts to open the object file. If the object
533 // file is opened successfully, returns the file descriptor. Otherwise,
534 // returns -1. |out_file_name_size| is the size of the file name buffer
535 // (including the null terminator).
536 // IMPORTANT: This function must be async-signal-safe because it can be
537 // called from a signal handler (symbolizing stack frames for a crash).
538 static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address,
539 uint64_t& base_address, char* file_path,
540 int file_path_size) {
541 // This method can only be called after the singleton is instantiated.
542 // This is ensured by the following facts:
543 // * This is the only static method in this class, it is private, and
544 // the class has no friends (except for the DefaultSingletonTraits).
545 // The compiler guarantees that it can only be called after the
546 // singleton is instantiated.
547 // * This method is used as a callback for the stack tracing code and
548 // the callback registration is done in the constructor, so logically
549 // it cannot be called before the singleton is created.
550 SandboxSymbolizeHelper* instance = GetInstance();
552 // The assumption here is that iterating over
553 // std::vector<MappedMemoryRegion> using a const_iterator does not allocate
554 // dynamic memory, hence it is async-signal-safe.
555 std::vector<MappedMemoryRegion>::const_iterator it;
556 bool is_first = true;
557 for (it = instance->regions_.begin(); it != instance->regions_.end();
558 ++it, is_first = false) {
559 const MappedMemoryRegion& region = *it;
560 if (region.start <= pc && pc < region.end) {
561 start_address = region.start;
562 // Don't subtract 'start_address' from the first entry:
563 // * If a binary is compiled w/o -pie, then the first entry in
564 // process maps is likely the binary itself (all dynamic libs
565 // are mapped higher in address space). For such a binary,
566 // instruction offset in binary coincides with the actual
567 // instruction address in virtual memory (as code section
568 // is mapped to a fixed memory range).
569 // * If a binary is compiled with -pie, all the modules are
570 // mapped high at address space (in particular, higher than
571 // shadow memory of the tool), so the module can't be the
572 // first entry.
573 base_address = (is_first ? 0U : start_address) - region.offset;
574 if (file_path && file_path_size > 0) {
575 strncpy(file_path, region.path.c_str(), file_path_size);
576 // Ensure null termination.
577 file_path[file_path_size - 1] = '\0';
579 return instance->GetFileDescriptor(region.path.c_str());
582 return -1;
585 // Parses /proc/self/maps in order to compile a list of all object file names
586 // for the modules that are loaded in the current process.
587 // Returns true on success.
588 bool CacheMemoryRegions() {
589 // Reads /proc/self/maps.
590 std::string contents;
591 if (!ReadProcMaps(&contents)) {
592 LOG(ERROR) << "Failed to read /proc/self/maps";
593 return false;
596 // Parses /proc/self/maps.
597 if (!ParseProcMaps(contents, &regions_)) {
598 LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
599 return false;
602 is_initialized_ = true;
603 return true;
606 // Opens all object files and caches their file descriptors.
607 void OpenSymbolFiles() {
608 // Pre-opening and caching the file descriptors of all loaded modules is
609 // not considered safe for retail builds. Hence it is only done in debug
610 // builds. For more details, take a look at: http://crbug.com/341966
611 // Enabling this to release mode would require approval from the security
612 // team.
613 #if !defined(NDEBUG)
614 // Open the object files for all read-only executable regions and cache
615 // their file descriptors.
616 std::vector<MappedMemoryRegion>::const_iterator it;
617 for (it = regions_.begin(); it != regions_.end(); ++it) {
618 const MappedMemoryRegion& region = *it;
619 // Only interesed in read-only executable regions.
620 if ((region.permissions & MappedMemoryRegion::READ) ==
621 MappedMemoryRegion::READ &&
622 (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
623 (region.permissions & MappedMemoryRegion::EXECUTE) ==
624 MappedMemoryRegion::EXECUTE) {
625 if (region.path.empty()) {
626 // Skip regions with empty file names.
627 continue;
629 if (region.path[0] == '[') {
630 // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
631 continue;
633 // Avoid duplicates.
634 if (modules_.find(region.path) == modules_.end()) {
635 int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
636 if (fd >= 0) {
637 modules_.insert(std::make_pair(region.path, fd));
638 } else {
639 LOG(WARNING) << "Failed to open file: " << region.path
640 << "\n Error: " << strerror(errno);
645 #endif // !defined(NDEBUG)
648 // Initializes and installs the symbolization callback.
649 void Init() {
650 if (CacheMemoryRegions()) {
651 OpenSymbolFiles();
652 google::InstallSymbolizeOpenObjectFileCallback(
653 &OpenObjectFileContainingPc);
657 // Unregister symbolization callback.
658 void UnregisterCallback() {
659 if (is_initialized_) {
660 google::InstallSymbolizeOpenObjectFileCallback(NULL);
661 is_initialized_ = false;
665 // Closes all file descriptors owned by this instance.
666 void CloseObjectFiles() {
667 #if !defined(NDEBUG)
668 std::map<std::string, int>::iterator it;
669 for (it = modules_.begin(); it != modules_.end(); ++it) {
670 int ret = IGNORE_EINTR(close(it->second));
671 DCHECK(!ret);
672 it->second = -1;
674 modules_.clear();
675 #endif // !defined(NDEBUG)
678 // Set to true upon successful initialization.
679 bool is_initialized_;
681 #if !defined(NDEBUG)
682 // Mapping from file name to file descriptor. Includes file descriptors
683 // for all successfully opened object files and the file descriptor for
684 // /proc/self/maps. This code is not safe for release builds so
685 // this is only done for DEBUG builds.
686 std::map<std::string, int> modules_;
687 #endif // !defined(NDEBUG)
689 // Cache for the process memory regions. Produced by parsing the contents
690 // of /proc/self/maps cache.
691 std::vector<MappedMemoryRegion> regions_;
693 DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper);
695 #endif // USE_SYMBOLIZE
697 bool EnableInProcessStackDumpingForSandbox() {
698 #if defined(USE_SYMBOLIZE)
699 SandboxSymbolizeHelper::GetInstance();
700 #endif // USE_SYMBOLIZE
702 return EnableInProcessStackDumping();
705 bool EnableInProcessStackDumping() {
706 // When running in an application, our code typically expects SIGPIPE
707 // to be ignored. Therefore, when testing that same code, it should run
708 // with SIGPIPE ignored as well.
709 struct sigaction sigpipe_action;
710 memset(&sigpipe_action, 0, sizeof(sigpipe_action));
711 sigpipe_action.sa_handler = SIG_IGN;
712 sigemptyset(&sigpipe_action.sa_mask);
713 bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
715 // Avoid hangs during backtrace initialization, see above.
716 WarmUpBacktrace();
718 struct sigaction action;
719 memset(&action, 0, sizeof(action));
720 action.sa_flags = SA_RESETHAND | SA_SIGINFO;
721 action.sa_sigaction = &StackDumpSignalHandler;
722 sigemptyset(&action.sa_mask);
724 success &= (sigaction(SIGILL, &action, NULL) == 0);
725 success &= (sigaction(SIGABRT, &action, NULL) == 0);
726 success &= (sigaction(SIGFPE, &action, NULL) == 0);
727 success &= (sigaction(SIGBUS, &action, NULL) == 0);
728 success &= (sigaction(SIGSEGV, &action, NULL) == 0);
729 // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
730 #if !defined(OS_LINUX)
731 success &= (sigaction(SIGSYS, &action, NULL) == 0);
732 #endif // !defined(OS_LINUX)
734 return success;
737 StackTrace::StackTrace() {
738 // NOTE: This code MUST be async-signal safe (it's used by in-process
739 // stack dumping signal handler). NO malloc or stdio is allowed here.
741 #if !defined(__UCLIBC__)
742 // Though the backtrace API man page does not list any possible negative
743 // return values, we take no chance.
744 count_ = base::saturated_cast<size_t>(backtrace(trace_, arraysize(trace_)));
745 #else
746 count_ = 0;
747 #endif
750 void StackTrace::Print() const {
751 // NOTE: This code MUST be async-signal safe (it's used by in-process
752 // stack dumping signal handler). NO malloc or stdio is allowed here.
754 #if !defined(__UCLIBC__)
755 PrintBacktraceOutputHandler handler;
756 ProcessBacktrace(trace_, count_, &handler);
757 #endif
760 #if !defined(__UCLIBC__)
761 void StackTrace::OutputToStream(std::ostream* os) const {
762 StreamBacktraceOutputHandler handler(os);
763 ProcessBacktrace(trace_, count_, &handler);
765 #endif
767 namespace internal {
769 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
770 char *itoa_r(intptr_t i, char *buf, size_t sz, int base, size_t padding) {
771 // Make sure we can write at least one NUL byte.
772 size_t n = 1;
773 if (n > sz)
774 return NULL;
776 if (base < 2 || base > 16) {
777 buf[0] = '\000';
778 return NULL;
781 char *start = buf;
783 uintptr_t j = i;
785 // Handle negative numbers (only for base 10).
786 if (i < 0 && base == 10) {
787 j = -i;
789 // Make sure we can write the '-' character.
790 if (++n > sz) {
791 buf[0] = '\000';
792 return NULL;
794 *start++ = '-';
797 // Loop until we have converted the entire number. Output at least one
798 // character (i.e. '0').
799 char *ptr = start;
800 do {
801 // Make sure there is still enough space left in our output buffer.
802 if (++n > sz) {
803 buf[0] = '\000';
804 return NULL;
807 // Output the next digit.
808 *ptr++ = "0123456789abcdef"[j % base];
809 j /= base;
811 if (padding > 0)
812 padding--;
813 } while (j > 0 || padding > 0);
815 // Terminate the output with a NUL character.
816 *ptr = '\000';
818 // Conversion to ASCII actually resulted in the digits being in reverse
819 // order. We can't easily generate them in forward order, as we can't tell
820 // the number of characters needed until we are done converting.
821 // So, now, we reverse the string (except for the possible "-" sign).
822 while (--ptr > start) {
823 char ch = *ptr;
824 *ptr = *start;
825 *start++ = ch;
827 return buf;
830 } // namespace internal
832 } // namespace debug
833 } // namespace base