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"
12 #include <sys/param.h>
14 #include <sys/types.h>
22 #if defined(__GLIBCXX__)
25 #if !defined(__UCLIBC__)
29 #if defined(OS_MACOSX)
30 #include <AvailabilityMacros.h>
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"
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]"
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.
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());
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
{
119 virtual void HandleOutput(const char* output
) = 0;
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
,
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
);
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");
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;
219 PrintToStderr("Received signal ");
220 char buf
[1024] = { 0 };
221 internal::itoa_r(signal
, buf
, sizeof(buf
), 10, 0);
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 ");
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 ");
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 ");
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 ");
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);
284 #if defined(CFI_ENFORCEMENT)
285 if (signal
== SIGILL
&& info
->si_code
== ILL_ILLOPN
) {
287 "CFI: Most likely a control flow integrity violation; for more "
288 "information see:\n");
290 "https://www.chromium.org/developers/testing/control-flow-integrity\n");
294 debug::StackTrace().Print();
296 #if defined(OS_LINUX)
297 #if ARCH_CPU_X86_FAMILY
298 ucontext_t
* context
= reinterpret_cast<ucontext_t
*>(void_context
);
304 { " gs: ", context
->uc_mcontext
.gregs
[REG_GS
] },
305 { " fs: ", context
->uc_mcontext
.gregs
[REG_FS
] },
306 { " es: ", context
->uc_mcontext
.gregs
[REG_ES
] },
307 { " ds: ", context
->uc_mcontext
.gregs
[REG_DS
] },
308 { " edi: ", context
->uc_mcontext
.gregs
[REG_EDI
] },
309 { " esi: ", context
->uc_mcontext
.gregs
[REG_ESI
] },
310 { " ebp: ", context
->uc_mcontext
.gregs
[REG_EBP
] },
311 { " esp: ", context
->uc_mcontext
.gregs
[REG_ESP
] },
312 { " ebx: ", context
->uc_mcontext
.gregs
[REG_EBX
] },
313 { " edx: ", context
->uc_mcontext
.gregs
[REG_EDX
] },
314 { " ecx: ", context
->uc_mcontext
.gregs
[REG_ECX
] },
315 { " eax: ", context
->uc_mcontext
.gregs
[REG_EAX
] },
316 { " trp: ", context
->uc_mcontext
.gregs
[REG_TRAPNO
] },
317 { " err: ", context
->uc_mcontext
.gregs
[REG_ERR
] },
318 { " ip: ", context
->uc_mcontext
.gregs
[REG_EIP
] },
319 { " cs: ", context
->uc_mcontext
.gregs
[REG_CS
] },
320 { " efl: ", context
->uc_mcontext
.gregs
[REG_EFL
] },
321 { " usp: ", context
->uc_mcontext
.gregs
[REG_UESP
] },
322 { " ss: ", context
->uc_mcontext
.gregs
[REG_SS
] },
323 #elif ARCH_CPU_64_BITS
324 { " r8: ", context
->uc_mcontext
.gregs
[REG_R8
] },
325 { " r9: ", context
->uc_mcontext
.gregs
[REG_R9
] },
326 { " r10: ", context
->uc_mcontext
.gregs
[REG_R10
] },
327 { " r11: ", context
->uc_mcontext
.gregs
[REG_R11
] },
328 { " r12: ", context
->uc_mcontext
.gregs
[REG_R12
] },
329 { " r13: ", context
->uc_mcontext
.gregs
[REG_R13
] },
330 { " r14: ", context
->uc_mcontext
.gregs
[REG_R14
] },
331 { " r15: ", context
->uc_mcontext
.gregs
[REG_R15
] },
332 { " di: ", context
->uc_mcontext
.gregs
[REG_RDI
] },
333 { " si: ", context
->uc_mcontext
.gregs
[REG_RSI
] },
334 { " bp: ", context
->uc_mcontext
.gregs
[REG_RBP
] },
335 { " bx: ", context
->uc_mcontext
.gregs
[REG_RBX
] },
336 { " dx: ", context
->uc_mcontext
.gregs
[REG_RDX
] },
337 { " ax: ", context
->uc_mcontext
.gregs
[REG_RAX
] },
338 { " cx: ", context
->uc_mcontext
.gregs
[REG_RCX
] },
339 { " sp: ", context
->uc_mcontext
.gregs
[REG_RSP
] },
340 { " ip: ", context
->uc_mcontext
.gregs
[REG_RIP
] },
341 { " efl: ", context
->uc_mcontext
.gregs
[REG_EFL
] },
342 { " cgf: ", context
->uc_mcontext
.gregs
[REG_CSGSFS
] },
343 { " erf: ", context
->uc_mcontext
.gregs
[REG_ERR
] },
344 { " trp: ", context
->uc_mcontext
.gregs
[REG_TRAPNO
] },
345 { " msk: ", context
->uc_mcontext
.gregs
[REG_OLDMASK
] },
346 { " cr2: ", context
->uc_mcontext
.gregs
[REG_CR2
] },
351 const int kRegisterPadding
= 8;
352 #elif ARCH_CPU_64_BITS
353 const int kRegisterPadding
= 16;
356 for (size_t i
= 0; i
< arraysize(registers
); i
++) {
357 PrintToStderr(registers
[i
].label
);
358 internal::itoa_r(registers
[i
].value
, buf
, sizeof(buf
),
359 16, kRegisterPadding
);
362 if ((i
+ 1) % 4 == 0)
367 #elif defined(OS_MACOSX)
368 // TODO(shess): Port to 64-bit, and ARM architecture (32 and 64-bit).
369 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
370 ucontext_t
* context
= reinterpret_cast<ucontext_t
*>(void_context
);
373 // NOTE: Even |snprintf()| is not on the approved list for signal
374 // handlers, but buffered I/O is definitely not on the list due to
375 // potential for |malloc()|.
376 len
= static_cast<size_t>(
377 snprintf(buf
, sizeof(buf
),
378 "ax: %x, bx: %x, cx: %x, dx: %x\n",
379 context
->uc_mcontext
->__ss
.__eax
,
380 context
->uc_mcontext
->__ss
.__ebx
,
381 context
->uc_mcontext
->__ss
.__ecx
,
382 context
->uc_mcontext
->__ss
.__edx
));
383 write(STDERR_FILENO
, buf
, std::min(len
, sizeof(buf
) - 1));
385 len
= static_cast<size_t>(
386 snprintf(buf
, sizeof(buf
),
387 "di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
388 context
->uc_mcontext
->__ss
.__edi
,
389 context
->uc_mcontext
->__ss
.__esi
,
390 context
->uc_mcontext
->__ss
.__ebp
,
391 context
->uc_mcontext
->__ss
.__esp
,
392 context
->uc_mcontext
->__ss
.__ss
,
393 context
->uc_mcontext
->__ss
.__eflags
));
394 write(STDERR_FILENO
, buf
, std::min(len
, sizeof(buf
) - 1));
396 len
= static_cast<size_t>(
397 snprintf(buf
, sizeof(buf
),
398 "ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
399 context
->uc_mcontext
->__ss
.__eip
,
400 context
->uc_mcontext
->__ss
.__cs
,
401 context
->uc_mcontext
->__ss
.__ds
,
402 context
->uc_mcontext
->__ss
.__es
,
403 context
->uc_mcontext
->__ss
.__fs
,
404 context
->uc_mcontext
->__ss
.__gs
));
405 write(STDERR_FILENO
, buf
, std::min(len
, sizeof(buf
) - 1));
406 #endif // ARCH_CPU_32_BITS
407 #endif // defined(OS_MACOSX)
409 PrintToStderr("[end of stack trace]\n");
414 class PrintBacktraceOutputHandler
: public BacktraceOutputHandler
{
416 PrintBacktraceOutputHandler() {}
418 void HandleOutput(const char* output
) override
{
419 // NOTE: This code MUST be async-signal safe (it's used by in-process
420 // stack dumping signal handler). NO malloc or stdio is allowed here.
421 PrintToStderr(output
);
425 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler
);
428 class StreamBacktraceOutputHandler
: public BacktraceOutputHandler
{
430 explicit StreamBacktraceOutputHandler(std::ostream
* os
) : os_(os
) {
433 void HandleOutput(const char* output
) override
{ (*os_
) << output
; }
438 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler
);
441 void WarmUpBacktrace() {
442 // Warm up stack trace infrastructure. It turns out that on the first
443 // call glibc initializes some internal data structures using pthread_once,
444 // and even backtrace() can call malloc(), leading to hangs.
446 // Example stack trace snippet (with tcmalloc):
448 // #8 0x0000000000a173b5 in tc_malloc
449 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
450 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
451 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
452 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
453 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
455 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
456 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
457 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
458 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
459 // #17 0x00007ffff61ef8f5 in init
460 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
461 // #18 0x00007ffff6aad400 in pthread_once
462 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
463 // #19 0x00007ffff61efa14 in __GI___backtrace
464 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
465 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
466 // at base/debug/stack_trace_posix.cc:175
467 // #21 0x00000000007a4ae5 in
468 // base::(anonymous namespace)::StackDumpSignalHandler
469 // at base/process_util_posix.cc:172
470 // #22 <signal handler called>
471 StackTrace stack_trace
;
476 #if defined(USE_SYMBOLIZE)
478 // class SandboxSymbolizeHelper.
480 // The purpose of this class is to prepare and install a "file open" callback
481 // needed by the stack trace symbolization code
482 // (base/third_party/symbolize/symbolize.h) so that it can function properly
483 // in a sandboxed process. The caveat is that this class must be instantiated
484 // before the sandboxing is enabled so that it can get the chance to open all
485 // the object files that are loaded in the virtual address space of the current
487 class SandboxSymbolizeHelper
{
489 // Returns the singleton instance.
490 static SandboxSymbolizeHelper
* GetInstance() {
491 return Singleton
<SandboxSymbolizeHelper
>::get();
495 friend struct DefaultSingletonTraits
<SandboxSymbolizeHelper
>;
497 SandboxSymbolizeHelper()
498 : is_initialized_(false) {
502 ~SandboxSymbolizeHelper() {
503 UnregisterCallback();
507 // Returns a O_RDONLY file descriptor for |file_path| if it was opened
508 // sucessfully during the initialization. The file is repositioned at
510 // IMPORTANT: This function must be async-signal-safe because it can be
511 // called from a signal handler (symbolizing stack frames for a crash).
512 int GetFileDescriptor(const char* file_path
) {
515 #if !defined(OFFICIAL_BUILD)
517 // The assumption here is that iterating over std::map<std::string, int>
518 // using a const_iterator does not allocate dynamic memory, hense it is
519 // async-signal-safe.
520 std::map
<std::string
, int>::const_iterator it
;
521 for (it
= modules_
.begin(); it
!= modules_
.end(); ++it
) {
522 if (strcmp((it
->first
).c_str(), file_path
) == 0) {
523 // POSIX.1-2004 requires an implementation to guarantee that dup()
524 // is async-signal-safe.
525 fd
= dup(it
->second
);
529 // POSIX.1-2004 requires an implementation to guarantee that lseek()
530 // is async-signal-safe.
531 if (fd
>= 0 && lseek(fd
, 0, SEEK_SET
) < 0) {
536 #endif // !defined(OFFICIAL_BUILD)
541 // Searches for the object file (from /proc/self/maps) that contains
542 // the specified pc. If found, sets |start_address| to the start address
543 // of where this object file is mapped in memory, sets the module base
544 // address into |base_address|, copies the object file name into
545 // |out_file_name|, and attempts to open the object file. If the object
546 // file is opened successfully, returns the file descriptor. Otherwise,
547 // returns -1. |out_file_name_size| is the size of the file name buffer
548 // (including the null terminator).
549 // IMPORTANT: This function must be async-signal-safe because it can be
550 // called from a signal handler (symbolizing stack frames for a crash).
551 static int OpenObjectFileContainingPc(uint64_t pc
, uint64_t& start_address
,
552 uint64_t& base_address
, char* file_path
,
553 int file_path_size
) {
554 // This method can only be called after the singleton is instantiated.
555 // This is ensured by the following facts:
556 // * This is the only static method in this class, it is private, and
557 // the class has no friends (except for the DefaultSingletonTraits).
558 // The compiler guarantees that it can only be called after the
559 // singleton is instantiated.
560 // * This method is used as a callback for the stack tracing code and
561 // the callback registration is done in the constructor, so logically
562 // it cannot be called before the singleton is created.
563 SandboxSymbolizeHelper
* instance
= GetInstance();
565 // The assumption here is that iterating over
566 // std::vector<MappedMemoryRegion> using a const_iterator does not allocate
567 // dynamic memory, hence it is async-signal-safe.
568 std::vector
<MappedMemoryRegion
>::const_iterator it
;
569 bool is_first
= true;
570 for (it
= instance
->regions_
.begin(); it
!= instance
->regions_
.end();
571 ++it
, is_first
= false) {
572 const MappedMemoryRegion
& region
= *it
;
573 if (region
.start
<= pc
&& pc
< region
.end
) {
574 start_address
= region
.start
;
575 // Don't subtract 'start_address' from the first entry:
576 // * If a binary is compiled w/o -pie, then the first entry in
577 // process maps is likely the binary itself (all dynamic libs
578 // are mapped higher in address space). For such a binary,
579 // instruction offset in binary coincides with the actual
580 // instruction address in virtual memory (as code section
581 // is mapped to a fixed memory range).
582 // * If a binary is compiled with -pie, all the modules are
583 // mapped high at address space (in particular, higher than
584 // shadow memory of the tool), so the module can't be the
586 base_address
= (is_first
? 0U : start_address
) - region
.offset
;
587 if (file_path
&& file_path_size
> 0) {
588 strncpy(file_path
, region
.path
.c_str(), file_path_size
);
589 // Ensure null termination.
590 file_path
[file_path_size
- 1] = '\0';
592 return instance
->GetFileDescriptor(region
.path
.c_str());
598 // Parses /proc/self/maps in order to compile a list of all object file names
599 // for the modules that are loaded in the current process.
600 // Returns true on success.
601 bool CacheMemoryRegions() {
602 // Reads /proc/self/maps.
603 std::string contents
;
604 if (!ReadProcMaps(&contents
)) {
605 LOG(ERROR
) << "Failed to read /proc/self/maps";
609 // Parses /proc/self/maps.
610 if (!ParseProcMaps(contents
, ®ions_
)) {
611 LOG(ERROR
) << "Failed to parse the contents of /proc/self/maps";
615 is_initialized_
= true;
619 // Opens all object files and caches their file descriptors.
620 void OpenSymbolFiles() {
621 // Pre-opening and caching the file descriptors of all loaded modules is
622 // not safe for production builds. Hence it is only done in non-official
623 // builds. For more details, take a look at: http://crbug.com/341966.
624 #if !defined(OFFICIAL_BUILD)
625 // Open the object files for all read-only executable regions and cache
626 // their file descriptors.
627 std::vector
<MappedMemoryRegion
>::const_iterator it
;
628 for (it
= regions_
.begin(); it
!= regions_
.end(); ++it
) {
629 const MappedMemoryRegion
& region
= *it
;
630 // Only interesed in read-only executable regions.
631 if ((region
.permissions
& MappedMemoryRegion::READ
) ==
632 MappedMemoryRegion::READ
&&
633 (region
.permissions
& MappedMemoryRegion::WRITE
) == 0 &&
634 (region
.permissions
& MappedMemoryRegion::EXECUTE
) ==
635 MappedMemoryRegion::EXECUTE
) {
636 if (region
.path
.empty()) {
637 // Skip regions with empty file names.
640 if (region
.path
[0] == '[') {
641 // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
645 if (modules_
.find(region
.path
) == modules_
.end()) {
646 int fd
= open(region
.path
.c_str(), O_RDONLY
| O_CLOEXEC
);
648 modules_
.insert(std::make_pair(region
.path
, fd
));
650 LOG(WARNING
) << "Failed to open file: " << region
.path
651 << "\n Error: " << strerror(errno
);
656 #endif // !defined(OFFICIAL_BUILD)
659 // Initializes and installs the symbolization callback.
661 if (CacheMemoryRegions()) {
663 google::InstallSymbolizeOpenObjectFileCallback(
664 &OpenObjectFileContainingPc
);
668 // Unregister symbolization callback.
669 void UnregisterCallback() {
670 if (is_initialized_
) {
671 google::InstallSymbolizeOpenObjectFileCallback(NULL
);
672 is_initialized_
= false;
676 // Closes all file descriptors owned by this instance.
677 void CloseObjectFiles() {
678 #if !defined(OFFICIAL_BUILD)
679 std::map
<std::string
, int>::iterator it
;
680 for (it
= modules_
.begin(); it
!= modules_
.end(); ++it
) {
681 int ret
= IGNORE_EINTR(close(it
->second
));
686 #endif // !defined(OFFICIAL_BUILD)
689 // Set to true upon successful initialization.
690 bool is_initialized_
;
692 #if !defined(OFFICIAL_BUILD)
693 // Mapping from file name to file descriptor. Includes file descriptors
694 // for all successfully opened object files and the file descriptor for
695 // /proc/self/maps. This code is not safe for production builds.
696 std::map
<std::string
, int> modules_
;
697 #endif // !defined(OFFICIAL_BUILD)
699 // Cache for the process memory regions. Produced by parsing the contents
700 // of /proc/self/maps cache.
701 std::vector
<MappedMemoryRegion
> regions_
;
703 DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper
);
705 #endif // USE_SYMBOLIZE
707 bool EnableInProcessStackDumping() {
708 #if defined(USE_SYMBOLIZE)
709 SandboxSymbolizeHelper::GetInstance();
710 #endif // USE_SYMBOLIZE
712 // When running in an application, our code typically expects SIGPIPE
713 // to be ignored. Therefore, when testing that same code, it should run
714 // with SIGPIPE ignored as well.
715 struct sigaction sigpipe_action
;
716 memset(&sigpipe_action
, 0, sizeof(sigpipe_action
));
717 sigpipe_action
.sa_handler
= SIG_IGN
;
718 sigemptyset(&sigpipe_action
.sa_mask
);
719 bool success
= (sigaction(SIGPIPE
, &sigpipe_action
, NULL
) == 0);
721 // Avoid hangs during backtrace initialization, see above.
724 struct sigaction action
;
725 memset(&action
, 0, sizeof(action
));
726 action
.sa_flags
= SA_RESETHAND
| SA_SIGINFO
;
727 action
.sa_sigaction
= &StackDumpSignalHandler
;
728 sigemptyset(&action
.sa_mask
);
730 success
&= (sigaction(SIGILL
, &action
, NULL
) == 0);
731 success
&= (sigaction(SIGABRT
, &action
, NULL
) == 0);
732 success
&= (sigaction(SIGFPE
, &action
, NULL
) == 0);
733 success
&= (sigaction(SIGBUS
, &action
, NULL
) == 0);
734 success
&= (sigaction(SIGSEGV
, &action
, NULL
) == 0);
735 // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
736 #if !defined(OS_LINUX)
737 success
&= (sigaction(SIGSYS
, &action
, NULL
) == 0);
738 #endif // !defined(OS_LINUX)
743 StackTrace::StackTrace() {
744 // NOTE: This code MUST be async-signal safe (it's used by in-process
745 // stack dumping signal handler). NO malloc or stdio is allowed here.
747 #if !defined(__UCLIBC__)
748 // Though the backtrace API man page does not list any possible negative
749 // return values, we take no chance.
750 count_
= base::saturated_cast
<size_t>(backtrace(trace_
, arraysize(trace_
)));
756 void StackTrace::Print() const {
757 // NOTE: This code MUST be async-signal safe (it's used by in-process
758 // stack dumping signal handler). NO malloc or stdio is allowed here.
760 #if !defined(__UCLIBC__)
761 PrintBacktraceOutputHandler handler
;
762 ProcessBacktrace(trace_
, count_
, &handler
);
766 #if !defined(__UCLIBC__)
767 void StackTrace::OutputToStream(std::ostream
* os
) const {
768 StreamBacktraceOutputHandler
handler(os
);
769 ProcessBacktrace(trace_
, count_
, &handler
);
775 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
776 char *itoa_r(intptr_t i
, char *buf
, size_t sz
, int base
, size_t padding
) {
777 // Make sure we can write at least one NUL byte.
782 if (base
< 2 || base
> 16) {
791 // Handle negative numbers (only for base 10).
792 if (i
< 0 && base
== 10) {
793 // This does "j = -i" while avoiding integer overflow.
794 j
= static_cast<uintptr_t>(-(i
+ 1)) + 1;
796 // Make sure we can write the '-' character.
804 // Loop until we have converted the entire number. Output at least one
805 // character (i.e. '0').
808 // Make sure there is still enough space left in our output buffer.
814 // Output the next digit.
815 *ptr
++ = "0123456789abcdef"[j
% base
];
820 } while (j
> 0 || padding
> 0);
822 // Terminate the output with a NUL character.
825 // Conversion to ASCII actually resulted in the digits being in reverse
826 // order. We can't easily generate them in forward order, as we can't tell
827 // the number of characters needed until we are done converting.
828 // So, now, we reverse the string (except for the possible "-" sign).
829 while (--ptr
> start
) {
837 } // namespace internal