swissChili | b71e027 | 2020-08-08 15:56:14 -0700 | [diff] [blame] | 1 | #include "common.h" |
| 2 | |
| 3 | #include <signal.h> |
| 4 | #include <stdlib.h> |
| 5 | #include <stdio.h> |
| 6 | |
| 7 | catch_t g_catch[MAX_CATCH_LEN]; |
| 8 | unsigned g_catch_len; |
| 9 | |
| 10 | void throw_(const char *msg, const char *file, unsigned int line) |
| 11 | { |
| 12 | printf("\033[31mException thrown:\033[33m %s:%d\033[0m %s\n", file, line, msg); |
| 13 | |
| 14 | for (int i = g_catch_len - 1; i >= 0; i--) |
| 15 | { |
| 16 | g_catch[i].fn(g_catch[i].arg); |
| 17 | } |
| 18 | |
| 19 | exit(1); |
| 20 | } |
| 21 | |
| 22 | void catch_(handle_t hdl, intptr_t arg) |
| 23 | { |
| 24 | if (g_catch_len > MAX_CATCH_LEN) |
| 25 | { |
| 26 | THROW("Catch overflow"); |
| 27 | } |
| 28 | |
| 29 | g_catch[g_catch_len++] = (catch_t){ .fn = hdl, .arg = arg }; |
| 30 | } |
| 31 | |
| 32 | void catch_signal(int sig) |
| 33 | { |
| 34 | if (sig == SIGSEGV) |
| 35 | throw_("Segmentation fault", "unknown", 0); |
| 36 | } |
| 37 | |
| 38 | __attribute__((constructor)) void init_catch() |
| 39 | { |
| 40 | signal(SIGSEGV, catch_signal); |
| 41 | } |