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