-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCrashHandler_UNIX.cpp
More file actions
74 lines (63 loc) · 2.09 KB
/
Copy pathCrashHandler_UNIX.cpp
File metadata and controls
74 lines (63 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "hacklib/CrashHandler.h"
#include <cstring>
#include <csetjmp>
#include <csignal>
#include <cstdio>
#include <unistd.h>
static thread_local sigjmp_buf t_currentEnv;
static thread_local bool t_hasHandler = false;
static void SignalHandler(int sigNum)
{
if (t_hasHandler)
{
// Jump out of the protected region to sigsetjmp.
siglongjmp(t_currentEnv, sigNum);
}
else
{
// No handling requested. Defer to default handler.
struct sigaction oldAction{}, currentAction{};
currentAction.sa_handler = SIG_DFL;
sigemptyset(¤tAction.sa_mask);
currentAction.sa_flags = 0;
sigaction(sigNum, ¤tAction, &oldAction);
kill(getpid(), sigNum);
sigaction(sigNum, &oldAction, NULL);
}
}
void hl::CrashHandler(const std::function<void()>& body, const std::function<void(uint32_t)>& handler)
{
struct sigaction oldAction[5]{}, currentAction{};
sigjmp_buf oldEnv;
currentAction.sa_handler = SignalHandler;
sigemptyset(¤tAction.sa_mask);
currentAction.sa_flags = 0;
// Backup nested contexts.
memcpy(oldEnv, t_currentEnv, sizeof(oldEnv));
const bool hadHandler = t_hasHandler;
t_hasHandler = true;
// Will return 0 first, then when siglongjmp is called, it returns the signal code.
const int sigNum = sigsetjmp(t_currentEnv, 1);
if (!sigNum)
{
// Setup signal handlers.
sigaction(SIGSEGV, ¤tAction, &oldAction[0]);
sigaction(SIGBUS, ¤tAction, &oldAction[1]);
sigaction(SIGFPE, ¤tAction, &oldAction[2]);
sigaction(SIGILL, ¤tAction, &oldAction[3]);
sigaction(SIGSYS, ¤tAction, &oldAction[4]);
body();
}
else
{
handler(sigNum);
}
// Restore signal handlers.
sigaction(SIGSEGV, &oldAction[0], NULL);
sigaction(SIGBUS, &oldAction[1], NULL);
sigaction(SIGFPE, &oldAction[2], NULL);
sigaction(SIGILL, &oldAction[3], NULL);
sigaction(SIGSYS, &oldAction[4], NULL);
memcpy(t_currentEnv, oldEnv, sizeof(oldEnv));
t_hasHandler = hadHandler;
}