1
0
Fork 0
mirror of https://github.com/OpenMW/openmw.git synced 2025-01-16 21:29:56 +00:00
openmw/components/crashcatcher/crashcatcher.cpp

543 lines
15 KiB
C++
Raw Normal View History

#include <algorithm>
2022-05-25 18:29:02 +00:00
#include <cstring>
2022-09-22 18:26:05 +00:00
#include <filesystem>
#include <fstream>
#include <span>
2024-01-19 12:36:01 +00:00
#include <errno.h>
2022-09-22 18:26:05 +00:00
#include <limits.h>
2024-01-19 12:36:01 +00:00
#include <pthread.h>
#include <stdbool.h>
2022-09-22 18:26:05 +00:00
#include <stdio.h>
#include <stdlib.h>
2022-09-22 18:26:05 +00:00
#include <string.h>
#include <sys/param.h>
2024-01-19 12:36:01 +00:00
#include <sys/ptrace.h>
2022-09-22 18:26:05 +00:00
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
2022-09-22 18:26:05 +00:00
#include <sys/wait.h>
#include <unistd.h>
2018-08-14 15:42:41 +00:00
#include <components/debug/debuglog.hpp>
#include <SDL_messagebox.h>
#ifdef __linux__
#include <sys/prctl.h>
#include <sys/ucontext.h>
#ifndef PR_SET_PTRACER
#define PR_SET_PTRACER 0x59616d61
#endif
2022-09-22 18:26:05 +00:00
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__)
#include <signal.h>
#endif
#if defined(__APPLE__)
2022-08-28 15:28:41 +00:00
#include <cassert>
2022-09-22 18:26:05 +00:00
#include <libproc.h>
#include <sys/sysctl.h>
#endif
2019-01-17 10:38:34 +00:00
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#include <sys/user.h>
#endif
#include "crashcatcher.hpp"
static const char fatal_err[] = "\n\n*** Fatal Error ***\n";
static const char pipe_err[] = "!!! Failed to create pipe\n";
static const char fork_err[] = "!!! Failed to fork debug process\n";
static const char exec_err[] = "!!! Failed to exec debug process\n";
#ifndef PATH_MAX /* Not all platforms (GNU Hurd) have this. */
2022-09-22 18:26:05 +00:00
#define PATH_MAX 256
2014-08-18 12:41:46 +00:00
#endif
static char argv0[PATH_MAX];
2022-09-22 18:26:05 +00:00
static struct
{
int signum;
pid_t pid;
int has_siginfo;
siginfo_t siginfo;
char buf[1024];
} crash_info;
namespace
2022-09-22 18:26:05 +00:00
{
struct SignalInfo
{
int mCode;
const char* mDescription;
};
constexpr SignalInfo signals[] = {
{ SIGSEGV, "Segmentation fault" },
{ SIGILL, "Illegal instruction" },
{ SIGFPE, "FPU exception" },
{ SIGBUS, "System BUS error" },
};
constexpr SignalInfo sigIllCodes[] = {
2022-09-22 18:26:05 +00:00
#if !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
{ ILL_ILLOPC, "Illegal opcode" },
{ ILL_ILLOPN, "Illegal operand" },
{ ILL_ILLADR, "Illegal addressing mode" },
{ ILL_ILLTRP, "Illegal trap" },
{ ILL_PRVOPC, "Privileged opcode" },
{ ILL_PRVREG, "Privileged register" },
{ ILL_COPROC, "Coprocessor error" },
{ ILL_BADSTK, "Internal stack error" },
2022-09-22 18:26:05 +00:00
#endif
};
constexpr SignalInfo sigFpeCodes[] = {
{ FPE_INTDIV, "Integer divide by zero" },
{ FPE_INTOVF, "Integer overflow" },
{ FPE_FLTDIV, "Floating point divide by zero" },
{ FPE_FLTOVF, "Floating point overflow" },
{ FPE_FLTUND, "Floating point underflow" },
{ FPE_FLTRES, "Floating point inexact result" },
{ FPE_FLTINV, "Floating point invalid operation" },
{ FPE_FLTSUB, "Subscript out of range" },
};
constexpr SignalInfo sigSegvCodes[] = {
2022-09-22 18:26:05 +00:00
#ifndef __FreeBSD__
{ SEGV_MAPERR, "Address not mapped to object" },
{ SEGV_ACCERR, "Invalid permissions for mapped object" },
2022-09-22 18:26:05 +00:00
#endif
};
constexpr SignalInfo sigBusCodes[] = {
2022-09-22 18:26:05 +00:00
#ifndef __FreeBSD__
{ BUS_ADRALN, "Invalid address alignment" },
{ BUS_ADRERR, "Non-existent physical address" },
{ BUS_OBJERR, "Object specific hardware error" },
2022-09-22 18:26:05 +00:00
#endif
};
const char* findSignalDescription(std::span<const SignalInfo> info, int code)
{
const auto it = std::find_if(info.begin(), info.end(), [&](const SignalInfo& v) { return v.mCode == code; });
return it == info.end() ? "" : it->mDescription;
}
}
static int (*cc_user_info)(char*, char*);
static void gdb_info(pid_t pid)
{
char respfile[64];
2022-09-22 18:26:05 +00:00
FILE* f;
int fd;
/*
* Create a temp file to put gdb commands into.
* Note: POSIX.1-2008 declares that the file should be already created with mode 0600 by default.
2021-04-10 08:32:12 +00:00
* Modern systems implement it and suggest to do not touch masks in multithreaded applications.
* So CoverityScan warning is valid only for ancient versions of stdlib.
2022-09-22 18:26:05 +00:00
*/
strcpy(respfile, "/tmp/gdb-respfile-XXXXXX");
#ifdef __COVERITY__
umask(0600);
#endif
2022-09-22 18:26:05 +00:00
if ((fd = mkstemp(respfile)) >= 0 && (f = fdopen(fd, "w")) != nullptr)
{
2022-09-22 18:26:05 +00:00
fprintf(f,
"attach %d\n"
"shell echo \"\"\n"
"shell echo \"* Loaded Libraries\"\n"
"info sharedlibrary\n"
"shell echo \"\"\n"
"shell echo \"* Threads\"\n"
"info threads\n"
"shell echo \"\"\n"
"shell echo \"* FPU Status\"\n"
"info float\n"
"shell echo \"\"\n"
"shell echo \"* Registers\"\n"
"info registers\n"
"shell echo \"\"\n"
"shell echo \"* Backtrace\"\n"
"thread apply all backtrace full 1000\n"
"detach\n"
"quit\n",
pid);
fclose(f);
/* Run gdb and print process info. */
2014-09-26 15:12:48 +00:00
char cmd_buf[128];
snprintf(cmd_buf, sizeof(cmd_buf), "gdb --quiet --batch --command=%s", respfile);
printf("Executing: %s\n", cmd_buf);
fflush(stdout);
int ret = system(cmd_buf);
if (ret != 0)
2022-09-22 18:26:05 +00:00
printf(
"\nFailed to create a crash report. Please make sure that 'gdb' is installed and present in PATH then "
"crash again."
"\nCurrent PATH: %s\n",
getenv("PATH"));
fflush(stdout);
/* Clean up */
if (remove(respfile) != 0)
2023-01-29 20:56:59 +00:00
Log(Debug::Warning) << "Warning: can not remove file '" << respfile
<< "': " << std::generic_category().message(errno);
}
else
{
/* Error creating temp file */
2022-09-22 18:26:05 +00:00
if (fd >= 0)
{
if (close(fd) != 0)
2023-01-29 20:56:59 +00:00
Log(Debug::Warning) << "Warning: can not close file '" << respfile
<< "': " << std::generic_category().message(errno);
else if (remove(respfile) != 0)
2023-01-29 20:56:59 +00:00
Log(Debug::Warning) << "Warning: can not remove file '" << respfile
<< "': " << std::generic_category().message(errno);
}
printf("!!! Could not create gdb command file\n");
}
fflush(stdout);
}
static void sys_info(void)
{
#ifdef __unix__
struct utsname info;
2022-09-22 18:26:05 +00:00
if (uname(&info))
printf("!!! Failed to get system information\n");
else
2022-09-22 18:26:05 +00:00
printf("System: %s %s %s %s %s\n", info.sysname, info.nodename, info.release, info.version, info.machine);
fflush(stdout);
#endif
}
2022-09-22 18:26:05 +00:00
static size_t safe_write(int fd, const void* buf, size_t len)
{
size_t ret = 0;
2022-09-22 18:26:05 +00:00
while (ret < len)
{
ssize_t rem;
2022-09-22 18:26:05 +00:00
if ((rem = write(fd, (const char*)buf + ret, len - ret)) == -1)
{
2022-09-22 18:26:05 +00:00
if (errno == EINTR)
continue;
break;
}
ret += rem;
}
return ret;
}
2022-09-22 18:26:05 +00:00
static void crash_catcher(int signum, siginfo_t* siginfo, void* context)
{
2022-09-22 18:26:05 +00:00
// ucontext_t *ucontext = (ucontext_t*)context;
pid_t dbg_pid;
int fd[2];
/* Make sure the effective uid is the real uid */
2022-09-22 18:26:05 +00:00
if (getuid() != geteuid())
{
raise(signum);
return;
}
2022-09-22 18:26:05 +00:00
safe_write(STDERR_FILENO, fatal_err, sizeof(fatal_err) - 1);
if (pipe(fd) == -1)
{
2022-09-22 18:26:05 +00:00
safe_write(STDERR_FILENO, pipe_err, sizeof(pipe_err) - 1);
raise(signum);
return;
}
crash_info.signum = signum;
crash_info.pid = getpid();
crash_info.has_siginfo = !!siginfo;
2022-09-22 18:26:05 +00:00
if (siginfo)
crash_info.siginfo = *siginfo;
2022-09-22 18:26:05 +00:00
if (cc_user_info)
cc_user_info(crash_info.buf, crash_info.buf + sizeof(crash_info.buf));
/* Fork off to start a crash handler */
2022-09-22 18:26:05 +00:00
switch ((dbg_pid = fork()))
{
2022-09-22 18:26:05 +00:00
/* Error */
case -1:
safe_write(STDERR_FILENO, fork_err, sizeof(fork_err) - 1);
raise(signum);
return;
2022-09-22 18:26:05 +00:00
case 0:
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
2022-09-22 18:26:05 +00:00
execl(argv0, argv0, crash_switch, nullptr);
2022-09-22 18:26:05 +00:00
safe_write(STDERR_FILENO, exec_err, sizeof(exec_err) - 1);
_exit(1);
2022-09-22 18:26:05 +00:00
default:
#ifdef __linux__
2022-09-22 18:26:05 +00:00
prctl(PR_SET_PTRACER, dbg_pid, 0, 0, 0);
#endif
2022-09-22 18:26:05 +00:00
safe_write(fd[1], &crash_info, sizeof(crash_info));
close(fd[0]);
close(fd[1]);
/* Wait; we'll be killed when gdb is done */
do
{
2022-09-22 18:26:05 +00:00
int status;
if (waitpid(dbg_pid, &status, 0) == dbg_pid && (WIFEXITED(status) || WIFSIGNALED(status)))
{
/* The debug process died before it could kill us */
raise(signum);
break;
}
} while (1);
}
}
2022-09-22 18:26:05 +00:00
static void crash_handler(const char* logfile)
{
2022-09-22 18:26:05 +00:00
if (fread(&crash_info, sizeof(crash_info), 1, stdin) != 1)
{
fprintf(stderr, "!!! Failed to retrieve info from crashed process\n");
exit(1);
}
const char* sigdesc = findSignalDescription(signals, crash_info.signum);
2022-09-22 18:26:05 +00:00
if (crash_info.has_siginfo)
{
2022-09-22 18:26:05 +00:00
switch (crash_info.signum)
{
2022-09-22 18:26:05 +00:00
case SIGSEGV:
sigdesc = findSignalDescription(sigSegvCodes, crash_info.siginfo.si_code);
2022-09-22 18:26:05 +00:00
break;
2022-09-22 18:26:05 +00:00
case SIGFPE:
sigdesc = findSignalDescription(sigFpeCodes, crash_info.siginfo.si_code);
2022-09-22 18:26:05 +00:00
break;
2022-09-22 18:26:05 +00:00
case SIGILL:
sigdesc = findSignalDescription(sigIllCodes, crash_info.siginfo.si_code);
2022-09-22 18:26:05 +00:00
break;
2022-09-22 18:26:05 +00:00
case SIGBUS:
sigdesc = findSignalDescription(sigBusCodes, crash_info.siginfo.si_code);
2022-09-22 18:26:05 +00:00
break;
}
}
fprintf(stderr, "%s (signal %i)\n", sigdesc, crash_info.signum);
2022-09-22 18:26:05 +00:00
if (crash_info.has_siginfo)
fprintf(stderr, "Address: %p\n", crash_info.siginfo.si_addr);
fputc('\n', stderr);
2022-09-22 18:26:05 +00:00
if (logfile)
{
/* Create crash log file and redirect shell output to it */
2022-09-22 18:26:05 +00:00
if (freopen(logfile, "wa", stdout) != stdout)
{
fprintf(stderr, "!!! Could not create %s following signal\n", logfile);
exit(1);
}
fprintf(stderr, "Generating %s and killing process %d, please wait... ", logfile, crash_info.pid);
2022-09-22 18:26:05 +00:00
printf(
"*** Fatal Error ***\n"
"%s (signal %i)\n",
sigdesc, crash_info.signum);
if (crash_info.has_siginfo)
printf("Address: %p\n", crash_info.siginfo.si_addr);
fputc('\n', stdout);
fflush(stdout);
}
sys_info();
2022-09-22 18:26:05 +00:00
crash_info.buf[sizeof(crash_info.buf) - 1] = '\0';
printf("%s\n", crash_info.buf);
fflush(stdout);
2022-09-22 18:26:05 +00:00
if (crash_info.pid > 0)
{
gdb_info(crash_info.pid);
kill(crash_info.pid, SIGKILL);
}
// delay between killing of the crashed process and showing the message box to
// work around occasional X server lock-up. this can only be a bug in X11 since
// even faulty applications shouldn't be able to freeze the X server.
usleep(100000);
2022-09-22 18:26:05 +00:00
if (logfile)
{
2022-09-22 18:26:05 +00:00
std::string message = "OpenMW has encountered a fatal error.\nCrash log saved to '" + std::string(logfile)
+ "'.\n Please report this to https://gitlab.com/OpenMW/openmw/issues !";
2018-10-09 06:21:12 +00:00
SDL_ShowSimpleMessageBox(0, "Fatal Error", message.c_str(), nullptr);
}
exit(0);
}
2022-09-22 18:26:05 +00:00
static void getExecPath(char** argv)
2019-01-17 10:38:34 +00:00
{
2022-09-22 18:26:05 +00:00
#if defined(__FreeBSD__)
2019-01-17 10:38:34 +00:00
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
size_t size = sizeof(argv0);
if (sysctl(mib, 4, argv0, &size, nullptr, 0) == 0)
return;
#endif
2022-09-22 18:26:05 +00:00
#if defined(__APPLE__)
if (proc_pidpath(getpid(), argv0, sizeof(argv0)) > 0)
2019-01-17 10:38:34 +00:00
return;
#endif
int cwdlen;
2022-09-22 18:26:05 +00:00
const char* statusPaths[] = { "/proc/self/exe", "/proc/self/file", "/proc/curproc/exe", "/proc/curproc/file" };
2019-01-17 10:38:34 +00:00
memset(argv0, 0, sizeof(argv0));
2022-09-22 18:26:05 +00:00
for (const char* path : statusPaths)
2019-01-17 10:38:34 +00:00
{
if (readlink(path, argv0, sizeof(argv0)) != -1)
return;
}
2022-09-22 18:26:05 +00:00
if (argv[0][0] == '/')
2019-01-17 10:38:34 +00:00
snprintf(argv0, sizeof(argv0), "%s", argv[0]);
2020-11-13 07:39:47 +00:00
else if (getcwd(argv0, sizeof(argv0)) != nullptr)
2019-01-17 10:38:34 +00:00
{
cwdlen = strlen(argv0);
2022-09-22 18:26:05 +00:00
snprintf(argv0 + cwdlen, sizeof(argv0) - cwdlen, "/%s", argv[0]);
2019-01-17 10:38:34 +00:00
}
}
2022-09-22 18:26:05 +00:00
int crashCatcherInstallHandlers(
int argc, char** argv, int num_signals, int* signals, const char* logfile, int (*user_info)(char*, char*))
{
struct sigaction sa;
stack_t altss;
int retval;
2022-09-22 18:26:05 +00:00
if (argc == 2 && strcmp(argv[1], crash_switch) == 0)
crash_handler(logfile);
cc_user_info = user_info;
2019-01-17 10:38:34 +00:00
getExecPath(argv);
/* Set an alternate signal stack so SIGSEGVs caused by stack overflows
* still run */
2022-09-22 18:26:05 +00:00
static char* altstack = new char[SIGSTKSZ];
altss.ss_sp = altstack;
altss.ss_flags = 0;
altss.ss_size = SIGSTKSZ;
2018-10-09 06:21:12 +00:00
sigaltstack(&altss, nullptr);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = crash_catcher;
sa.sa_flags = SA_RESETHAND | SA_NODEFER | SA_SIGINFO | SA_ONSTACK;
sigemptyset(&sa.sa_mask);
retval = 0;
2022-09-22 18:26:05 +00:00
while (num_signals--)
{
2022-09-22 18:26:05 +00:00
if ((*signals != SIGSEGV && *signals != SIGILL && *signals != SIGFPE && *signals != SIGABRT
&& *signals != SIGBUS)
|| sigaction(*signals, &sa, nullptr) == -1)
{
*signals = 0;
retval = -1;
}
++signals;
}
return retval;
}
static bool is_debugger_present()
{
2022-09-22 18:26:05 +00:00
#if defined(__linux__)
2022-05-25 18:29:02 +00:00
std::filesystem::path procstatus = std::filesystem::path("/proc/self/status");
if (std::filesystem::exists(procstatus))
{
2022-05-25 18:29:02 +00:00
std::ifstream file((procstatus));
2019-01-17 10:38:34 +00:00
while (!file.eof())
{
2019-01-17 10:38:34 +00:00
std::string word;
file >> word;
2019-01-17 10:38:34 +00:00
if (word == "TracerPid:")
{
file >> word;
return word != "0";
}
}
}
return false;
2019-01-17 10:38:34 +00:00
#elif defined(__APPLE__)
int junk;
int mib[4];
struct kinfo_proc info;
size_t size;
// Initialize the flags so that, if sysctl fails for some bizarre
// reason, we get a predictable result.
info.kp_proc.p_flag = 0;
// Initialize mib, which tells sysctl the info we want, in this case
// we're looking for information about a specific process ID.
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = getpid();
// Call sysctl.
size = sizeof(info);
2018-10-09 06:21:12 +00:00
junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0);
assert(junk == 0);
// We're being debugged if the P_TRACED flag is set.
return (info.kp_proc.p_flag & P_TRACED) != 0;
2019-01-17 10:38:34 +00:00
#elif defined(__FreeBSD__)
struct kinfo_proc info;
size_t size = sizeof(info);
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) == 0)
return (info.ki_flag & P_TRACED) != 0;
else
perror("Failed to retrieve process info");
return false;
#else
return false;
#endif
}
2022-09-22 18:26:05 +00:00
void crashCatcherInstall(int argc, char** argv, const std::filesystem::path& crashLogPath)
{
2019-01-17 10:38:34 +00:00
if ((argc == 2 && strcmp(argv[1], crash_switch) == 0) || !is_debugger_present())
{
int s[5] = { SIGSEGV, SIGILL, SIGFPE, SIGBUS, SIGABRT };
2018-10-09 06:21:12 +00:00
if (crashCatcherInstallHandlers(argc, argv, 5, s, crashLogPath.c_str(), nullptr) == -1)
{
2018-08-14 15:42:41 +00:00
Log(Debug::Warning) << "Installing crash handler failed";
}
else
Log(Debug::Info) << "Crash handler installed";
}
}