Separate library code, build .a/.so
[centaur.git] / src / libelfu / modelops / detour.c
1 #include <libelfu/libelfu.h>
2 #include <string.h>
3
4 static void* subFindByAddr(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
5 {
6   GElf_Addr a = *(GElf_Addr*)aux1;
7
8   if (OVERLAPPING(ms->shdr.sh_addr, ms->shdr.sh_size, a, 1)) {
9     return ms;
10   }
11
12   /* Continue */
13   return NULL;
14 }
15
16
17 void elfu_mDetour(ElfuElf *me, GElf_Addr from, GElf_Addr to)
18 {
19   ElfuScn *ms;
20   GElf_Word scnoffset;
21   unsigned char detourcode[] = {0xe9, 0xfc, 0xff, 0xff, 0xff};
22
23   ms = elfu_mScnForall(me, subFindByAddr, &from, NULL);
24
25   if (!ms) {
26     ELFU_WARN("mDetour: Cannot find address %x in any section.\n",
27               (unsigned)from);
28     return;
29   }
30
31   if (ms->shdr.sh_type != SHT_PROGBITS) {
32     ELFU_WARN("mDetour: Cannot detour in non-PROGBITS section %s.\n",
33               elfu_mScnName(me, ms));
34     return;
35   }
36
37   scnoffset = from - ms->shdr.sh_addr;
38
39   if (ms->shdr.sh_size - scnoffset < 5) {
40     ELFU_WARN("mDetour: Not enough space to insert a detour.\n");
41     return;
42   }
43
44   ELFU_DEBUG("mDetour: Detouring at address %x in section %s to %x.\n",
45              (unsigned)from,
46              elfu_mScnName(me, ms),
47              (unsigned)to);
48
49   *(Elf32_Word*)(detourcode + 1) = to - from - 5;
50   memcpy((char*)ms->data.d_buf + scnoffset, detourcode, 5);
51 }