This source file includes following definitions.
- DemangleSymbols
- OutputPointer
- OutputFrameId
- ProcessBacktrace
- PrintToStderr
- StackDumpSignalHandler
- HandleOutput
- HandleOutput
- WarmUpBacktrace
- GetInstance
- GetFileDescriptor
- OpenObjectFileContainingPc
- CacheMemoryRegions
- OpenSymbolFiles
- Init
- UnregisterCallback
- CloseObjectFiles
- EnableInProcessStackDumpingForSandbox
- EnableInProcessStackDumping
- Print
- OutputToStream
- itoa_r
#include "base/debug/stack_trace.h"
#include <errno.h>
#include <execinfo.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <map>
#include <ostream>
#include <string>
#include <vector>
#if defined(__GLIBCXX__)
#include <cxxabi.h>
#endif
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
#endif
#include "base/basictypes.h"
#include "base/debug/debugger.h"
#include "base/debug/proc_maps_linux.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/numerics/safe_conversions.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#if defined(USE_SYMBOLIZE)
#include "base/third_party/symbolize/symbolize.h"
#endif
namespace base {
namespace debug {
namespace {
volatile sig_atomic_t in_signal_handler = 0;
#if !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
const char kMangledSymbolPrefix[] = "_Z";
const char kSymbolCharacters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
#endif
#if !defined(USE_SYMBOLIZE)
void DemangleSymbols(std::string* text) {
#if defined(__GLIBCXX__)
std::string::size_type search_from = 0;
while (search_from < text->size()) {
std::string::size_type mangled_start =
text->find(kMangledSymbolPrefix, search_from);
if (mangled_start == std::string::npos) {
break;
}
std::string::size_type mangled_end =
text->find_first_not_of(kSymbolCharacters, mangled_start);
if (mangled_end == std::string::npos) {
mangled_end = text->size();
}
std::string mangled_symbol =
text->substr(mangled_start, mangled_end - mangled_start);
int status = 0;
scoped_ptr<char, base::FreeDeleter> demangled_symbol(
abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
if (status == 0) {
text->erase(mangled_start, mangled_end - mangled_start);
text->insert(mangled_start, demangled_symbol.get());
search_from = mangled_start + strlen(demangled_symbol.get());
} else {
search_from = mangled_start + 2;
}
}
#endif
}
#endif
class BacktraceOutputHandler {
public:
virtual void HandleOutput(const char* output) = 0;
protected:
virtual ~BacktraceOutputHandler() {}
};
void OutputPointer(void* pointer, BacktraceOutputHandler* handler) {
char buf[17] = { '\0' };
handler->HandleOutput("0x");
internal::itoa_r(reinterpret_cast<intptr_t>(pointer),
buf, sizeof(buf), 16, 12);
handler->HandleOutput(buf);
}
#if defined(USE_SYMBOLIZE)
void OutputFrameId(intptr_t frame_id, BacktraceOutputHandler* handler) {
char buf[30] = { '\0' };
handler->HandleOutput("#");
internal::itoa_r(frame_id, buf, sizeof(buf), 10, 1);
handler->HandleOutput(buf);
}
#endif
void ProcessBacktrace(void *const *trace,
size_t size,
BacktraceOutputHandler* handler) {
#if defined(USE_SYMBOLIZE)
for (size_t i = 0; i < size; ++i) {
OutputFrameId(i, handler);
handler->HandleOutput(" ");
OutputPointer(trace[i], handler);
handler->HandleOutput(" ");
char buf[1024] = { '\0' };
void* address = static_cast<char*>(trace[i]) - 1;
if (google::Symbolize(address, buf, sizeof(buf)))
handler->HandleOutput(buf);
else
handler->HandleOutput("<unknown>");
handler->HandleOutput("\n");
}
#else
bool printed = false;
if (in_signal_handler == 0) {
scoped_ptr<char*, FreeDeleter>
trace_symbols(backtrace_symbols(trace, size));
if (trace_symbols.get()) {
for (size_t i = 0; i < size; ++i) {
std::string trace_symbol = trace_symbols.get()[i];
DemangleSymbols(&trace_symbol);
handler->HandleOutput(trace_symbol.c_str());
handler->HandleOutput("\n");
}
printed = true;
}
}
if (!printed) {
for (size_t i = 0; i < size; ++i) {
handler->HandleOutput(" [");
OutputPointer(trace[i], handler);
handler->HandleOutput("]\n");
}
}
#endif
}
void PrintToStderr(const char* output) {
ignore_result(HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output))));
}
void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
in_signal_handler = 1;
if (BeingDebugged())
BreakDebugger();
PrintToStderr("Received signal ");
char buf[1024] = { 0 };
internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
PrintToStderr(buf);
if (signal == SIGBUS) {
if (info->si_code == BUS_ADRALN)
PrintToStderr(" BUS_ADRALN ");
else if (info->si_code == BUS_ADRERR)
PrintToStderr(" BUS_ADRERR ");
else if (info->si_code == BUS_OBJERR)
PrintToStderr(" BUS_OBJERR ");
else
PrintToStderr(" <unknown> ");
} else if (signal == SIGFPE) {
if (info->si_code == FPE_FLTDIV)
PrintToStderr(" FPE_FLTDIV ");
else if (info->si_code == FPE_FLTINV)
PrintToStderr(" FPE_FLTINV ");
else if (info->si_code == FPE_FLTOVF)
PrintToStderr(" FPE_FLTOVF ");
else if (info->si_code == FPE_FLTRES)
PrintToStderr(" FPE_FLTRES ");
else if (info->si_code == FPE_FLTSUB)
PrintToStderr(" FPE_FLTSUB ");
else if (info->si_code == FPE_FLTUND)
PrintToStderr(" FPE_FLTUND ");
else if (info->si_code == FPE_INTDIV)
PrintToStderr(" FPE_INTDIV ");
else if (info->si_code == FPE_INTOVF)
PrintToStderr(" FPE_INTOVF ");
else
PrintToStderr(" <unknown> ");
} else if (signal == SIGILL) {
if (info->si_code == ILL_BADSTK)
PrintToStderr(" ILL_BADSTK ");
else if (info->si_code == ILL_COPROC)
PrintToStderr(" ILL_COPROC ");
else if (info->si_code == ILL_ILLOPN)
PrintToStderr(" ILL_ILLOPN ");
else if (info->si_code == ILL_ILLADR)
PrintToStderr(" ILL_ILLADR ");
else if (info->si_code == ILL_ILLTRP)
PrintToStderr(" ILL_ILLTRP ");
else if (info->si_code == ILL_PRVOPC)
PrintToStderr(" ILL_PRVOPC ");
else if (info->si_code == ILL_PRVREG)
PrintToStderr(" ILL_PRVREG ");
else
PrintToStderr(" <unknown> ");
} else if (signal == SIGSEGV) {
if (info->si_code == SEGV_MAPERR)
PrintToStderr(" SEGV_MAPERR ");
else if (info->si_code == SEGV_ACCERR)
PrintToStderr(" SEGV_ACCERR ");
else
PrintToStderr(" <unknown> ");
}
if (signal == SIGBUS || signal == SIGFPE ||
signal == SIGILL || signal == SIGSEGV) {
internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
buf, sizeof(buf), 16, 12);
PrintToStderr(buf);
}
PrintToStderr("\n");
debug::StackTrace().Print();
#if defined(OS_LINUX)
#if ARCH_CPU_X86_FAMILY
ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
const struct {
const char* label;
greg_t value;
} registers[] = {
#if ARCH_CPU_32_BITS
{ " gs: ", context->uc_mcontext.gregs[REG_GS] },
{ " fs: ", context->uc_mcontext.gregs[REG_FS] },
{ " es: ", context->uc_mcontext.gregs[REG_ES] },
{ " ds: ", context->uc_mcontext.gregs[REG_DS] },
{ " edi: ", context->uc_mcontext.gregs[REG_EDI] },
{ " esi: ", context->uc_mcontext.gregs[REG_ESI] },
{ " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
{ " esp: ", context->uc_mcontext.gregs[REG_ESP] },
{ " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
{ " edx: ", context->uc_mcontext.gregs[REG_EDX] },
{ " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
{ " eax: ", context->uc_mcontext.gregs[REG_EAX] },
{ " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
{ " err: ", context->uc_mcontext.gregs[REG_ERR] },
{ " ip: ", context->uc_mcontext.gregs[REG_EIP] },
{ " cs: ", context->uc_mcontext.gregs[REG_CS] },
{ " efl: ", context->uc_mcontext.gregs[REG_EFL] },
{ " usp: ", context->uc_mcontext.gregs[REG_UESP] },
{ " ss: ", context->uc_mcontext.gregs[REG_SS] },
#elif ARCH_CPU_64_BITS
{ " r8: ", context->uc_mcontext.gregs[REG_R8] },
{ " r9: ", context->uc_mcontext.gregs[REG_R9] },
{ " r10: ", context->uc_mcontext.gregs[REG_R10] },
{ " r11: ", context->uc_mcontext.gregs[REG_R11] },
{ " r12: ", context->uc_mcontext.gregs[REG_R12] },
{ " r13: ", context->uc_mcontext.gregs[REG_R13] },
{ " r14: ", context->uc_mcontext.gregs[REG_R14] },
{ " r15: ", context->uc_mcontext.gregs[REG_R15] },
{ " di: ", context->uc_mcontext.gregs[REG_RDI] },
{ " si: ", context->uc_mcontext.gregs[REG_RSI] },
{ " bp: ", context->uc_mcontext.gregs[REG_RBP] },
{ " bx: ", context->uc_mcontext.gregs[REG_RBX] },
{ " dx: ", context->uc_mcontext.gregs[REG_RDX] },
{ " ax: ", context->uc_mcontext.gregs[REG_RAX] },
{ " cx: ", context->uc_mcontext.gregs[REG_RCX] },
{ " sp: ", context->uc_mcontext.gregs[REG_RSP] },
{ " ip: ", context->uc_mcontext.gregs[REG_RIP] },
{ " efl: ", context->uc_mcontext.gregs[REG_EFL] },
{ " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
{ " erf: ", context->uc_mcontext.gregs[REG_ERR] },
{ " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
{ " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
{ " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
#endif
};
#if ARCH_CPU_32_BITS
const int kRegisterPadding = 8;
#elif ARCH_CPU_64_BITS
const int kRegisterPadding = 16;
#endif
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(registers); i++) {
PrintToStderr(registers[i].label);
internal::itoa_r(registers[i].value, buf, sizeof(buf),
16, kRegisterPadding);
PrintToStderr(buf);
if ((i + 1) % 4 == 0)
PrintToStderr("\n");
}
PrintToStderr("\n");
#endif
#elif defined(OS_MACOSX)
#if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
size_t len;
len = static_cast<size_t>(
snprintf(buf, sizeof(buf),
"ax: %x, bx: %x, cx: %x, dx: %x\n",
context->uc_mcontext->__ss.__eax,
context->uc_mcontext->__ss.__ebx,
context->uc_mcontext->__ss.__ecx,
context->uc_mcontext->__ss.__edx));
write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
len = static_cast<size_t>(
snprintf(buf, sizeof(buf),
"di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
context->uc_mcontext->__ss.__edi,
context->uc_mcontext->__ss.__esi,
context->uc_mcontext->__ss.__ebp,
context->uc_mcontext->__ss.__esp,
context->uc_mcontext->__ss.__ss,
context->uc_mcontext->__ss.__eflags));
write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
len = static_cast<size_t>(
snprintf(buf, sizeof(buf),
"ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
context->uc_mcontext->__ss.__eip,
context->uc_mcontext->__ss.__cs,
context->uc_mcontext->__ss.__ds,
context->uc_mcontext->__ss.__es,
context->uc_mcontext->__ss.__fs,
context->uc_mcontext->__ss.__gs));
write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
#endif
#endif
_exit(1);
}
class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
public:
PrintBacktraceOutputHandler() {}
virtual void HandleOutput(const char* output) OVERRIDE {
PrintToStderr(output);
}
private:
DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
};
class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
public:
explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
}
virtual void HandleOutput(const char* output) OVERRIDE {
(*os_) << output;
}
private:
std::ostream* os_;
DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
};
void WarmUpBacktrace() {
StackTrace stack_trace;
}
}
#if defined(USE_SYMBOLIZE)
class SandboxSymbolizeHelper {
public:
static SandboxSymbolizeHelper* GetInstance() {
return Singleton<SandboxSymbolizeHelper>::get();
}
private:
friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
SandboxSymbolizeHelper()
: is_initialized_(false) {
Init();
}
~SandboxSymbolizeHelper() {
UnregisterCallback();
CloseObjectFiles();
}
int GetFileDescriptor(const char* file_path) {
int fd = -1;
#if !defined(NDEBUG)
if (file_path) {
std::map<std::string, int>::const_iterator it;
for (it = modules_.begin(); it != modules_.end(); ++it) {
if (strcmp((it->first).c_str(), file_path) == 0) {
fd = dup(it->second);
break;
}
}
if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
fd = -1;
}
}
#endif
return fd;
}
static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address,
uint64_t& base_address, char* file_path,
int file_path_size) {
SandboxSymbolizeHelper* instance = GetInstance();
std::vector<MappedMemoryRegion>::const_iterator it;
bool is_first = true;
for (it = instance->regions_.begin(); it != instance->regions_.end();
++it, is_first = false) {
const MappedMemoryRegion& region = *it;
if (region.start <= pc && pc < region.end) {
start_address = region.start;
base_address = (is_first ? 0U : start_address) - region.offset;
if (file_path && file_path_size > 0) {
strncpy(file_path, region.path.c_str(), file_path_size);
file_path[file_path_size - 1] = '\0';
}
return instance->GetFileDescriptor(region.path.c_str());
}
}
return -1;
}
bool CacheMemoryRegions() {
std::string contents;
if (!ReadProcMaps(&contents)) {
LOG(ERROR) << "Failed to read /proc/self/maps";
return false;
}
if (!ParseProcMaps(contents, ®ions_)) {
LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
return false;
}
is_initialized_ = true;
return true;
}
void OpenSymbolFiles() {
#if !defined(NDEBUG)
std::vector<MappedMemoryRegion>::const_iterator it;
for (it = regions_.begin(); it != regions_.end(); ++it) {
const MappedMemoryRegion& region = *it;
if ((region.permissions & MappedMemoryRegion::READ) ==
MappedMemoryRegion::READ &&
(region.permissions & MappedMemoryRegion::WRITE) == 0 &&
(region.permissions & MappedMemoryRegion::EXECUTE) ==
MappedMemoryRegion::EXECUTE) {
if (region.path.empty()) {
continue;
}
if (region.path[0] == '[') {
continue;
}
if (modules_.find(region.path) == modules_.end()) {
int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
modules_.insert(std::make_pair(region.path, fd));
} else {
LOG(WARNING) << "Failed to open file: " << region.path
<< "\n Error: " << strerror(errno);
}
}
}
}
#endif
}
void Init() {
if (CacheMemoryRegions()) {
OpenSymbolFiles();
google::InstallSymbolizeOpenObjectFileCallback(
&OpenObjectFileContainingPc);
}
}
void UnregisterCallback() {
if (is_initialized_) {
google::InstallSymbolizeOpenObjectFileCallback(NULL);
is_initialized_ = false;
}
}
void CloseObjectFiles() {
#if !defined(NDEBUG)
std::map<std::string, int>::iterator it;
for (it = modules_.begin(); it != modules_.end(); ++it) {
int ret = IGNORE_EINTR(close(it->second));
DCHECK(!ret);
it->second = -1;
}
modules_.clear();
#endif
}
bool is_initialized_;
#if !defined(NDEBUG)
std::map<std::string, int> modules_;
#endif
std::vector<MappedMemoryRegion> regions_;
DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper);
};
#endif
bool EnableInProcessStackDumpingForSandbox() {
#if defined(USE_SYMBOLIZE)
SandboxSymbolizeHelper::GetInstance();
#endif
return EnableInProcessStackDumping();
}
bool EnableInProcessStackDumping() {
struct sigaction sigpipe_action;
memset(&sigpipe_action, 0, sizeof(sigpipe_action));
sigpipe_action.sa_handler = SIG_IGN;
sigemptyset(&sigpipe_action.sa_mask);
bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
WarmUpBacktrace();
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_flags = SA_RESETHAND | SA_SIGINFO;
action.sa_sigaction = &StackDumpSignalHandler;
sigemptyset(&action.sa_mask);
success &= (sigaction(SIGILL, &action, NULL) == 0);
success &= (sigaction(SIGABRT, &action, NULL) == 0);
success &= (sigaction(SIGFPE, &action, NULL) == 0);
success &= (sigaction(SIGBUS, &action, NULL) == 0);
success &= (sigaction(SIGSEGV, &action, NULL) == 0);
#if !defined(OS_LINUX)
success &= (sigaction(SIGSYS, &action, NULL) == 0);
#endif
return success;
}
StackTrace::StackTrace() {
count_ = base::saturated_cast<size_t>(backtrace(trace_, arraysize(trace_)));
}
void StackTrace::Print() const {
PrintBacktraceOutputHandler handler;
ProcessBacktrace(trace_, count_, &handler);
}
void StackTrace::OutputToStream(std::ostream* os) const {
StreamBacktraceOutputHandler handler(os);
ProcessBacktrace(trace_, count_, &handler);
}
namespace internal {
char *itoa_r(intptr_t i, char *buf, size_t sz, int base, size_t padding) {
size_t n = 1;
if (n > sz)
return NULL;
if (base < 2 || base > 16) {
buf[0] = '\000';
return NULL;
}
char *start = buf;
uintptr_t j = i;
if (i < 0 && base == 10) {
j = -i;
if (++n > sz) {
buf[0] = '\000';
return NULL;
}
*start++ = '-';
}
char *ptr = start;
do {
if (++n > sz) {
buf[0] = '\000';
return NULL;
}
*ptr++ = "0123456789abcdef"[j % base];
j /= base;
if (padding > 0)
padding--;
} while (j > 0 || padding > 0);
*ptr = '\000';
while (--ptr > start) {
char ch = *ptr;
*ptr = *start;
*start++ = ch;
}
return buf;
}
}
}
}