60 lines
1.9 KiB
C++
60 lines
1.9 KiB
C++
#include <Void/Testing/Detail/SignalHandler.hpp>
|
|
#include <Void/Testing/Detail/Stacktrace.hpp>
|
|
#include <csignal>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
|
|
namespace Void::Testing::Detail {
|
|
static CrashCallback g_crash_callback;
|
|
static int g_last_signal{0};
|
|
|
|
#ifndef _WIN32
|
|
static sigjmp_buf g_jump_buffer;
|
|
static bool g_jump_ready{false};
|
|
sigjmp_buf& get_jump_buffer() { return g_jump_buffer; }
|
|
void set_jump_ready(bool ready) { g_jump_ready = ready; }
|
|
#endif
|
|
|
|
const char* signal_name(int sig) {
|
|
switch (sig) {
|
|
case SIGSEGV: return "SIGSEGV (segmentation fault)";
|
|
case SIGABRT: return "SIGABRT (abort)";
|
|
case SIGFPE: return "SIGFPE (floating point exception)";
|
|
case SIGILL: return "SIGILL (illegal instruction)";
|
|
#ifdef SIGBUS
|
|
case SIGBUS: return "SIGBUS (bus error)";
|
|
#endif
|
|
default: return "UNKNOWN SIGNAL";
|
|
}
|
|
}
|
|
|
|
static void crash_handler(int sig) {
|
|
g_last_signal = sig;
|
|
auto frames = capture_stacktrace(1, 16);
|
|
auto trace = format_stacktrace(frames);
|
|
if (g_crash_callback) g_crash_callback(sig, trace);
|
|
#ifndef _WIN32
|
|
if (g_jump_ready) { g_jump_ready = false; siglongjmp(g_jump_buffer, sig); }
|
|
#endif
|
|
std::_Exit(128 + sig);
|
|
}
|
|
|
|
void install_signal_handlers(CrashCallback on_crash) {
|
|
g_crash_callback = std::move(on_crash);
|
|
struct sigaction sa{}; sa.sa_handler = crash_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0;
|
|
sigaction(SIGSEGV, &sa, nullptr); sigaction(SIGABRT, &sa, nullptr); sigaction(SIGFPE, &sa, nullptr); sigaction(SIGILL, &sa, nullptr);
|
|
#ifdef SIGBUS
|
|
sigaction(SIGBUS, &sa, nullptr);
|
|
#endif
|
|
}
|
|
|
|
void uninstall_signal_handlers() {
|
|
struct sigaction sa{}; sa.sa_handler = SIG_DFL;
|
|
sigaction(SIGSEGV, &sa, nullptr); sigaction(SIGABRT, &sa, nullptr); sigaction(SIGFPE, &sa, nullptr); sigaction(SIGILL, &sa, nullptr);
|
|
#ifdef SIGBUS
|
|
sigaction(SIGBUS, &sa, nullptr);
|
|
#endif
|
|
g_crash_callback = nullptr;
|
|
}
|
|
} // namespace Void::Testing::Detail
|