73b4256da5933fd094405d9bda8b853e03a05380
[mate.git] / trap.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <signal.h>
4 #include <asm/ucontext.h>
5
6 unsigned int patchme = 0;
7 void print_foo(unsigned int addr)
8 {
9         // printf("\n\nprint foo: 0x%08x\n", addr);
10         patchme = addr;
11 }
12
13 void callertrap(int nSignal, siginfo_t *info, void *ctx)
14 {
15         struct ucontext *uctx = (struct ucontext *) ctx;
16
17         printf("callertrap(mctx)  by 0x%08x\n", uctx->uc_mcontext.eip);
18         // printf("callertrap(addr)  by 0x%08x\n", info->si_addr);
19         // printf("callertrap(*esp)  by 0x%08x\n", * (unsigned int *) uctx->uc_mcontext.esp);
20
21         unsigned int *to_patch = (unsigned int *) (uctx->uc_mcontext.eip + 2);
22         unsigned char *insn = (unsigned int *) (uctx->uc_mcontext.eip);
23         *insn = 0x90; // nop
24         insn++;
25         *insn = 0xe8; // call
26         printf(" to_patch: 0x%08x\n", to_patch);
27         printf("*to_patch: 0x%08x\n", *to_patch);
28         if (*to_patch != 0x00000000) {
29                 printf("something is wrong here. abort\n");
30                 exit(0);
31         }
32         *to_patch = (unsigned int) patchme - ((unsigned int) insn + 5);
33         printf("*to_patch: 0x%08x\n", *to_patch);
34         uctx->uc_mcontext.eip = insn;
35         // while (1) ;
36 }
37
38 void register_signal(void)
39 {
40         struct sigaction segvaction;
41         segvaction.sa_sigaction = callertrap;
42         sigemptyset(&segvaction.sa_mask);
43         segvaction.sa_flags = SA_SIGINFO | SA_RESTART;
44         sigaction(SIGSEGV, &segvaction, NULL);
45 }
46
47 unsigned int getaddr(void)
48 {
49         return (unsigned int) print_foo;
50 }