#ifdef UNSAFE_BUFFERS_BUILD
#pragma allow_unsafe_libc_calls
#endif
#include "base/debug/stack_trace.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <map>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <vector>
#include "base/containers/heap_array.h"
#include "base/containers/span.h"
#include "base/containers/span_writer.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/cstring_view.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_IOS) && defined(OFFICIAL_BUILD)
#define HAVE_DLADDR
#include <dlfcn.h>
#endif
#if BUILDFLAG(IS_APPLE) || \
(defined(__GLIBC__) && !defined(__UCLIBC__) && !defined(__AIX))
#define HAVE_BACKTRACE
#include <execinfo.h>
#endif
#if !defined(USE_SYMBOLIZE) && defined(HAVE_BACKTRACE) && !defined(HAVE_DLADDR)
#define DEMANGLE_SYMBOLS
#endif
#if defined(DEMANGLE_SYMBOLS)
#include <cxxabi.h>
#endif
#if BUILDFLAG(IS_APPLE)
#include <AvailabilityMacros.h>
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include <sys/prctl.h>
#include "base/debug/proc_maps_linux.h"
#endif
#include "base/cfi_buildflags.h"
#include "base/debug/debugger.h"
#include "base/debug/debugging_buildflags.h"
#include "base/debug/stack_trace.h"
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/memory/free_deleter.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 "base/strings/string_util.h"
#include "build/build_config.h"
#if defined(USE_SYMBOLIZE)
#include "base/third_party/symbolize/symbolize.h"
#if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
#include "base/debug/dwarf_line_no.h"
#endif
#endif
namespace base::debug {
namespace {
volatile sig_atomic_t in_signal_handler = 0;
bool (*try_handle_signal)(int, siginfo_t*, void*) = nullptr;
#if defined(DEMANGLE_SYMBOLS)
const char kMangledSymbolPrefix[] = "_Z";
const char kSymbolCharacters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
void DemangleSymbols(std::string* text) {
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;
std::unique_ptr<char, base::FreeDeleter> demangled_symbol(
abi::__cxa_demangle(mangled_symbol.c_str(), nullptr, 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
class BacktraceOutputHandler {
public:
virtual void HandleOutput(const char* output) = 0;
protected:
virtual ~BacktraceOutputHandler() = default;
};
#if defined(HAVE_BACKTRACE)
void OutputPointer(const void* pointer, BacktraceOutputHandler* handler) {
char buf[17] = {'\0'};
handler->HandleOutput("0x");
internal::itoa_r(reinterpret_cast<intptr_t>(pointer), 16, 12, buf);
handler->HandleOutput(buf);
}
#if defined(HAVE_DLADDR) || defined(USE_SYMBOLIZE)
void OutputValue(size_t value, BacktraceOutputHandler* handler) {
char buf[30] = {'\0'};
internal::itoa_r(static_cast<intptr_t>(value), 10, 1, buf);
handler->HandleOutput(buf);
}
#endif
#if defined(USE_SYMBOLIZE)
void OutputFrameId(size_t frame_id, BacktraceOutputHandler* handler) {
handler->HandleOutput("#");
OutputValue(frame_id, handler);
}
#endif
void ProcessBacktrace(span<const void* const> traces,
cstring_view prefix_string,
BacktraceOutputHandler* handler) {
traces = traces.first(std::min(traces.size(), StackTrace::kMaxTraces));
#if defined(USE_SYMBOLIZE)
#if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
std::array<uint64_t, StackTrace::kMaxTraces> cu_offsets = {};
GetDwarfCompileUnitOffsets(traces.data(), cu_offsets.data(), traces.size());
#endif
for (size_t i = 0; i < traces.size(); ++i) {
if (!prefix_string.empty()) {
handler->HandleOutput(prefix_string.c_str());
}
OutputFrameId(i, handler);
handler->HandleOutput(" ");
OutputPointer(traces[i], handler);
handler->HandleOutput(" ");
std::array<char, 1024> buf = {};
const void* address =
UNSAFE_BUFFERS(static_cast<const char*>(traces[i]) - 1);
if (google::Symbolize(const_cast<void*>(address), buf.data(), buf.size())) {
handler->HandleOutput(buf.data());
#if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
if (GetDwarfSourceLineNumber(address, cu_offsets[i], buf.data(),
buf.size())) {
handler->HandleOutput(" [");
handler->HandleOutput(buf.data());
handler->HandleOutput("]");
}
#endif
} else {
handler->HandleOutput("<unknown>");
}
handler->HandleOutput("\n");
}
#else
bool printed = false;
if (in_signal_handler == 0 &&
IsValueInRangeForNumericType<int>(traces.size())) {
#if defined(HAVE_DLADDR)
Dl_info dl_info;
for (size_t i = 0; i < traces.size(); ++i) {
if (!prefix_string.empty()) {
handler->HandleOutput(prefix_string.c_str());
}
OutputValue(i, handler);
handler->HandleOutput(" ");
const bool dl_info_found = dladdr(traces[i], &dl_info) != 0;
if (dl_info_found) {
auto dli_fname = UNSAFE_BUFFERS(base::cstring_view(dl_info.dli_fname));
if (size_t last_sep = dli_fname.rfind('/');
last_sep != base::cstring_view::npos) {
dli_fname.remove_prefix(last_sep + 1u);
}
handler->HandleOutput(dli_fname.c_str());
} else {
handler->HandleOutput("???");
}
handler->HandleOutput(" ");
OutputPointer(traces[i], handler);
handler->HandleOutput("\n");
}
printed = true;
#else
auto trace_symbols =
UNSAFE_BUFFERS(base::HeapArray<char*, FreeDeleter>::FromOwningPointer(
backtrace_symbols(const_cast<void* const*>(traces.data()),
static_cast<int>(traces.size())),
traces.size()));
if (!trace_symbols.empty()) {
for (char* s : trace_symbols) {
auto trace_symbol = std::string(s);
DemangleSymbols(&trace_symbol);
if (!prefix_string.empty()) {
handler->HandleOutput(prefix_string.c_str());
}
handler->HandleOutput(trace_symbol.c_str());
handler->HandleOutput("\n");
}
printed = true;
}
#endif
}
if (!printed) {
for (const void* const trace : traces) {
handler->HandleOutput(" [");
OutputPointer(trace, handler);
handler->HandleOutput("]\n");
}
}
#endif
}
#endif
void PrintToStderr(const char* output) {
std::ignore = HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output)));
}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
void AlarmSignalHandler(int signal, siginfo_t* info, void* void_context) {
PrintToStderr(
"Warning: Default signal handler failed to terminate process.\n");
PrintToStderr("Calling exit_group() directly to prevent timeout.\n");
syscall(SYS_exit_group, EXIT_FAILURE);
}
#endif
void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
if (try_handle_signal != nullptr &&
try_handle_signal(signal, info, void_context)) {
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_flags = static_cast<int>(SA_RESETHAND | SA_SIGINFO);
action.sa_sigaction = &StackDumpSignalHandler;
sigemptyset(&action.sa_mask);
sigaction(signal, &action, nullptr);
return;
}
#if !BUILDFLAG(IS_APPLE) || !DCHECK_IS_ON()
in_signal_handler = 1;
#endif
if (BeingDebugged()) {
BreakDebugger();
}
PrintToStderr("Received signal ");
char buf[1024] = {0};
internal::itoa_r(signal, 10, 0, buf);
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 ");
}
#if defined(ARCH_CPU_X86_64) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
else if (info->si_code == SI_KERNEL) {
PrintToStderr(" SI_KERNEL");
}
#endif
else {
PrintToStderr(" <unknown> ");
}
}
if (signal == SIGBUS || signal == SIGFPE || signal == SIGILL ||
signal == SIGSEGV) {
internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr), 16, 12, buf);
PrintToStderr(buf);
}
PrintToStderr("\n");
#if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
if (signal == SIGILL && info->si_code == ILL_ILLOPN) {
PrintToStderr(
"CFI: Most likely a control flow integrity violation; for more "
"information see:\n");
PrintToStderr(
"https://www.chromium.org/developers/testing/control-flow-integrity\n");
}
#endif
#if defined(ARCH_CPU_X86_64) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
if (signal == SIGSEGV && info->si_code == SI_KERNEL) {
PrintToStderr(
" Possibly a General Protection Fault, can be due to a non-canonical "
"address dereference. See \"Intel 64 and IA-32 Architectures Software "
"Developer’s Manual\", Volume 1, Section 3.3.7.1.\n");
}
#endif
debug::StackTrace().Print();
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if ARCH_CPU_X86_FAMILY
ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
auto gregs = base::span(context->uc_mcontext.gregs);
struct Register {
const char* label;
greg_t value;
};
const auto registers = std::to_array<Register>({
#if ARCH_CPU_32_BITS
{" gs: ", gregs[REG_GS]}, {" fs: ", gregs[REG_FS]},
{" es: ", gregs[REG_ES]}, {" ds: ", gregs[REG_DS]},
{" edi: ", gregs[REG_EDI]}, {" esi: ", gregs[REG_ESI]},
{" ebp: ", gregs[REG_EBP]}, {" esp: ", gregs[REG_ESP]},
{" ebx: ", gregs[REG_EBX]}, {" edx: ", gregs[REG_EDX]},
{" ecx: ", gregs[REG_ECX]}, {" eax: ", gregs[REG_EAX]},
{" trp: ", gregs[REG_TRAPNO]}, {" err: ", gregs[REG_ERR]},
{" ip: ", gregs[REG_EIP]}, {" cs: ", gregs[REG_CS]},
{" efl: ", gregs[REG_EFL]}, {" usp: ", gregs[REG_UESP]},
{" ss: ", gregs[REG_SS]},
#elif ARCH_CPU_64_BITS
{" r8: ", gregs[REG_R8]}, {" r9: ", gregs[REG_R9]},
{" r10: ", gregs[REG_R10]}, {" r11: ", gregs[REG_R11]},
{" r12: ", gregs[REG_R12]}, {" r13: ", gregs[REG_R13]},
{" r14: ", gregs[REG_R14]}, {" r15: ", gregs[REG_R15]},
{" di: ", gregs[REG_RDI]}, {" si: ", gregs[REG_RSI]},
{" bp: ", gregs[REG_RBP]}, {" bx: ", gregs[REG_RBX]},
{" dx: ", gregs[REG_RDX]}, {" ax: ", gregs[REG_RAX]},
{" cx: ", gregs[REG_RCX]}, {" sp: ", gregs[REG_RSP]},
{" ip: ", gregs[REG_RIP]}, {" efl: ", gregs[REG_EFL]},
{" cgf: ", gregs[REG_CSGSFS]}, {" erf: ", gregs[REG_ERR]},
{" trp: ", gregs[REG_TRAPNO]}, {" msk: ", gregs[REG_OLDMASK]},
{" cr2: ", 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 < std::size(registers); i++) {
PrintToStderr(registers[i].label);
internal::itoa_r(registers[i].value, 16, kRegisterPadding, buf);
PrintToStderr(buf);
if ((i + 1) % 4 == 0) {
PrintToStderr("\n");
}
}
PrintToStderr("\n");
#endif
#endif
PrintToStderr("[end of stack trace]\n");
if (::signal(signal, SIG_DFL) == SIG_ERR) {
_exit(EXIT_FAILURE);
}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_flags = static_cast<int>(SA_RESETHAND);
action.sa_sigaction = &AlarmSignalHandler;
sigemptyset(&action.sa_mask);
sigaction(SIGALRM, &action, nullptr);
constexpr unsigned int kAlarmSignalDelaySeconds = 5;
alarm(kAlarmSignalDelaySeconds);
long retval = syscall(SYS_rt_tgsigqueueinfo, getpid(), syscall(SYS_gettid),
info->si_signo, info);
if (retval == 0) {
return;
}
if (errno != EPERM) {
_exit(EXIT_FAILURE);
}
#endif
if (raise(signal) != 0) {
_exit(EXIT_FAILURE);
}
}
class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
public:
PrintBacktraceOutputHandler() = default;
PrintBacktraceOutputHandler(const PrintBacktraceOutputHandler&) = delete;
PrintBacktraceOutputHandler& operator=(const PrintBacktraceOutputHandler&) =
delete;
void HandleOutput(const char* output) override {
PrintToStderr(output);
}
};
class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
public:
explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {}
StreamBacktraceOutputHandler(const StreamBacktraceOutputHandler&) = delete;
StreamBacktraceOutputHandler& operator=(const StreamBacktraceOutputHandler&) =
delete;
void HandleOutput(const char* output) override { (*os_) << output; }
private:
raw_ptr<std::ostream> os_;
};
void WarmUpBacktrace() {
StackTrace stack_trace;
}
#if defined(USE_SYMBOLIZE)
class SandboxSymbolizeHelper {
public:
static SandboxSymbolizeHelper* GetInstance() {
return Singleton<SandboxSymbolizeHelper,
LeakySingletonTraits<SandboxSymbolizeHelper>>::get();
}
SandboxSymbolizeHelper(const SandboxSymbolizeHelper&) = delete;
SandboxSymbolizeHelper& operator=(const SandboxSymbolizeHelper&) = delete;
private:
friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
SandboxSymbolizeHelper() { Init(); }
~SandboxSymbolizeHelper() {
UnregisterCallback();
CloseObjectFiles();
}
int GetFileDescriptor(const char* file_path) {
int fd = -1;
#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
if (file_path) {
for (const auto& filepath_fd : modules_) {
if (strcmp(filepath_fd.first.c_str(), file_path) == 0) {
fd = HANDLE_EINTR(dup(filepath_fd.second.get()));
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_ptr,
size_t file_path_size) {
auto file_path =
UNSAFE_BUFFERS(base::span(file_path_ptr, file_path_size));
SandboxSymbolizeHelper* instance = GetInstance();
for (size_t i = 0; i < instance->regions_.size(); ++i) {
const MappedMemoryRegion& region = instance->regions_[i];
if (region.start <= pc && pc < region.end) {
start_address = region.start;
base_address = region.base;
if (!file_path.empty()) {
strlcpy(file_path, region.path);
}
return instance->GetFileDescriptor(region.path.c_str());
}
}
return -1;
}
class ScopedPrSetDumpable {
public:
explicit ScopedPrSetDumpable() {
int result = prctl(PR_GET_DUMPABLE, 0, 0, 0, 0);
was_dumpable_ = result > 0;
if (!was_dumpable_) {
std::ignore = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
}
}
ScopedPrSetDumpable(const ScopedPrSetDumpable&) = delete;
ScopedPrSetDumpable& operator=(const ScopedPrSetDumpable&) = delete;
~ScopedPrSetDumpable() {
if (!was_dumpable_) {
std::ignore = prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
}
}
private:
bool was_dumpable_;
};
void SetBaseAddressesForMemoryRegions() {
base::ScopedFD mem_fd;
{
ScopedPrSetDumpable s;
mem_fd = base::ScopedFD(
HANDLE_EINTR(open("/proc/self/mem", O_RDONLY | O_CLOEXEC)));
if (!mem_fd.is_valid()) {
return;
}
}
auto safe_memcpy = [&mem_fd](void* dst, uintptr_t src, size_t size) {
return HANDLE_EINTR(pread(mem_fd.get(), dst, size,
static_cast<off_t>(src))) == ssize_t(size);
};
uintptr_t cur_base = 0;
for (auto& r : regions_) {
ElfW(Ehdr) ehdr;
static_assert(SELFMAG <= sizeof(ElfW(Ehdr)), "SELFMAG too large");
if ((r.permissions & MappedMemoryRegion::READ) &&
safe_memcpy(&ehdr, r.start, sizeof(ElfW(Ehdr))) &&
memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
switch (ehdr.e_type) {
case ET_EXEC:
cur_base = 0;
break;
case ET_DYN:
cur_base = r.start;
for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
ElfW(Phdr) phdr;
if (safe_memcpy(&phdr, r.start + ehdr.e_phoff + i * sizeof(phdr),
sizeof(phdr)) &&
phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
cur_base = r.start - phdr.p_vaddr;
break;
}
}
break;
default:
break;
}
}
r.base = cur_base;
}
}
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;
}
SetBaseAddressesForMemoryRegions();
is_initialized_ = true;
return true;
}
void OpenSymbolFiles() {
#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
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 (base::EndsWith(region.path, " (deleted)",
base::CompareCase::SENSITIVE)) {
continue;
}
if (modules_.find(region.path) == modules_.end()) {
int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
modules_.emplace(region.path, base::ScopedFD(fd));
} else {
PLOG(WARNING) << "Failed to open file: " << region.path;
}
}
}
}
#endif
}
void Init() {
if (CacheMemoryRegions()) {
OpenSymbolFiles();
google::InstallSymbolizeOpenObjectFileCallback(
&OpenObjectFileContainingPc);
}
}
void UnregisterCallback() {
if (is_initialized_) {
google::InstallSymbolizeOpenObjectFileCallback(nullptr);
is_initialized_ = false;
}
}
void CloseObjectFiles() {
#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
modules_.clear();
#endif
}
bool is_initialized_ = false;
#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
std::map<std::string, base::ScopedFD> modules_;
#endif
std::vector<MappedMemoryRegion> regions_;
};
#endif
}
bool EnableInProcessStackDumping() {
#if defined(USE_SYMBOLIZE)
SandboxSymbolizeHelper::GetInstance();
#endif
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, nullptr) == 0);
WarmUpBacktrace();
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_flags = static_cast<int>(SA_RESETHAND | SA_SIGINFO);
action.sa_sigaction = &StackDumpSignalHandler;
sigemptyset(&action.sa_mask);
success &= (sigaction(SIGILL, &action, nullptr) == 0);
success &= (sigaction(SIGABRT, &action, nullptr) == 0);
success &= (sigaction(SIGFPE, &action, nullptr) == 0);
success &= (sigaction(SIGBUS, &action, nullptr) == 0);
success &= (sigaction(SIGSEGV, &action, nullptr) == 0);
#if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
success &= (sigaction(SIGSYS, &action, nullptr) == 0);
#endif
return success;
}
bool SetStackDumpFirstChanceCallback(bool (*handler)(int, siginfo_t*, void*)) {
DCHECK(try_handle_signal == nullptr || handler == nullptr);
try_handle_signal = handler;
#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) || \
defined(UNDEFINED_SANITIZER)
struct sigaction installed_handler;
CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0);
if (installed_handler.sa_sigaction != StackDumpSignalHandler) {
LOG(WARNING)
<< "WARNING: sanitizers are preventing signal handler installation. "
<< "WebAssembly trap handlers are disabled.\n";
return false;
}
#endif
return true;
}
size_t CollectStackTrace(span<const void*> trace) {
#if defined(NO_UNWIND_TABLES) && BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
return base::debug::TraceStackFramePointers(trace, 0);
#elif defined(HAVE_BACKTRACE)
return base::saturated_cast<size_t>(
backtrace(const_cast<void**>(trace.data()),
base::saturated_cast<int>(trace.size())));
#else
return 0;
#endif
}
void StackTrace::PrintMessageWithPrefix(cstring_view prefix_string,
cstring_view message) {
if (!prefix_string.empty()) {
PrintToStderr(prefix_string.c_str());
}
PrintToStderr(message.c_str());
}
void StackTrace::PrintWithPrefixImpl(cstring_view prefix_string) const {
#if defined(HAVE_BACKTRACE)
PrintBacktraceOutputHandler handler;
ProcessBacktrace(addresses(), prefix_string, &handler);
#endif
}
#if defined(HAVE_BACKTRACE)
void StackTrace::OutputToStreamWithPrefixImpl(
std::ostream* os,
cstring_view prefix_string) const {
StreamBacktraceOutputHandler handler(os);
ProcessBacktrace(addresses(), prefix_string, &handler);
}
#endif
namespace internal {
void itoa_r(intptr_t i, int base, size_t padding, base::span<char> buf) {
if (buf.empty()) {
return;
}
if (base < 2 || base > 16) {
buf[0u] = '\000';
return;
}
auto writer = base::SpanWriter(buf);
size_t start = 0u;
uintptr_t j = static_cast<uintptr_t>(i);
if (i < 0 && base == 10) {
j = static_cast<uintptr_t>(-(i + 1)) + 1;
if (!writer.Write('-')) {
buf[0u] = '\000';
return;
}
start += 1u;
}
constexpr std::string_view digits = "0123456789abcdef";
do {
if (!writer.Write(digits[j % static_cast<uintptr_t>(base)])) {
buf[0] = '\000';
return;
}
j /= static_cast<uintptr_t>(base);
if (padding > 0) {
padding--;
}
} while (j > 0 || padding > 0);
if (!writer.Write('\000')) {
buf[0] = '\000';
return;
}
std::ranges::reverse(buf.first(writer.num_written() - 1u).subspan(start));
}
}
}