debug: remove #ifdef's and use dumb logger
[mate.git] / ffi / trap.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stddef.h>
4
5 /* TODO(bernhard): use {u,}int* types */
6
7 #define __USE_GNU
8 // Note by hs: my signal.h includes sys/uconctext which conflicts with
9 // asm/ucontext - this hack kinda solves the problem for me ;-) 
10 // so feel free to blame me for that s**t
11 #if defined __USE_XOPEN2K8
12 #undef __USE_XOPEN2K8
13 #define RESTORE
14 #warning hs-hack: undefining __USE_XOPEN2K8 for signal.h
15 #endif
16 #include <signal.h>
17 #ifdef RESTORE
18 #define __USE_XOPEN2K8
19 #endif
20
21 #include <sys/ucontext.h>
22
23 ptrdiff_t mateHandler(ptrdiff_t, ptrdiff_t, ptrdiff_t, ptrdiff_t);
24
25 #ifdef DBG_TRAP
26 #define dprintf(args...) do { printf (args); } while (0);
27 #else
28 #define dprintf(args...)
29 #endif
30
31 void chandler(int nSignal, siginfo_t *info, void *ctx)
32 {
33         mcontext_t *mctx = &((ucontext_t *) ctx)->uc_mcontext;
34         greg_t *regs = mctx->gregs;
35
36         ptrdiff_t eip = (ptrdiff_t) regs[REG_EIP];
37         ptrdiff_t eax = (ptrdiff_t) regs[REG_EAX];
38         ptrdiff_t ebx = (ptrdiff_t) regs[REG_EBX];
39         ptrdiff_t esp = (ptrdiff_t) regs[REG_ESP];
40         ptrdiff_t esi = (ptrdiff_t) regs[REG_ESI];
41         ptrdiff_t ebp = (ptrdiff_t) regs[REG_EBP];
42         dprintf("trap: type %d, eip 0x%08x, eax 0x%08x, ebx 0x%08x, \n"
43                         "esp 0x%08x, *esp 0x%08x, *(ebp+8) 0x%08x\n", nSignal, eip,
44                         eax, ebx, esp, *(ptrdiff_t*) esp, *(ptrdiff_t *) (ebp + 8));
45
46         ptrdiff_t ret = mateHandler(eip, eax, ebx, esi);
47         if (ret == -1) {
48                 dprintf("regdump @ EIP: 0x%08x\n", regs[REG_EIP]);
49                 dprintf("\tEAX: 0x%08lx EBX: 0x%08lx ECX: 0x%08lx EDX: 0x%08lx\n",
50                         regs[REG_EAX], regs[REG_EBX], regs[REG_ECX], regs[REG_EDX]);
51                 dprintf("\tESI: 0x%08lx EDI: 0x%08lx EBP: 0x%08lx ESP: 0x%08lx\n",
52                         regs[REG_ESI], regs[REG_EDI], regs[REG_EBP], regs[REG_ESP]);
53                 mctx->gregs[REG_EIP] = eip + 6;
54         } else {
55                 mctx->gregs[REG_EIP] = ret;
56         }
57 }
58
59 void register_signal(void)
60 {
61         struct sigaction illaction;
62         illaction.sa_sigaction = chandler;
63         sigemptyset(&illaction.sa_mask);
64         illaction.sa_flags = SA_SIGINFO | SA_RESTART | SA_NODEFER;
65         sigaction(SIGILL, &illaction, NULL);
66
67         struct sigaction segvaction;
68         segvaction.sa_sigaction = chandler;
69         sigemptyset(&segvaction.sa_mask);
70         segvaction.sa_flags = SA_SIGINFO | SA_RESTART | SA_NODEFER;
71         sigaction(SIGSEGV, &segvaction, NULL);
72 }