wip, some dynamic stuff works
[ginge.git] / loader / patches.c
1 // vim:shiftwidth=2:expandtab
2 #include <stdio.h>
3
4 #include "header.h"
5 #include "sys_cacheflush.h"
6
7 #include "override.c"
8
9 // note: first mask must be always full for search algo
10 static const unsigned int sig_mask_all[] = {
11   0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
12   0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff
13 };
14
15 static const unsigned int sig_open[] = {
16   0xe59cc000, 0xe33c0000, 0x1a000003, 0xef900005
17 };
18 #define sig_mask_open sig_mask_all
19
20 static const unsigned int sig_mmap[] = {
21   0xe92d000f, 0xe1a0000d, 0xef90005a, 0xe28dd010
22 };
23 #define sig_mask_mmap sig_mask_all
24
25 static const unsigned int sig_mmap2[] = {
26   0xe52d5004, 0xe59d5008, 0xe52d4004, 0xe59d4008,
27   0xe1b0ca05, 0x1a000006, 0xe1a05625, 0xef9000c0
28 };
29 #define sig_mask_mmap2 sig_mask_all
30
31 static const unsigned int sig_read[] = {
32   0xe59fc080, 0xe59cc000, 0xe33c0000, 0x1a000003, 0xef900003
33 };
34 #define sig_mask_read sig_mask_all
35
36 static const unsigned int sig_ioctl[] = {
37   0xef900036, 0xe3700a01, 0x312fff1e
38 };
39 #define sig_mask_ioctl sig_mask_all
40
41 static const unsigned int sig_sigaction[] = {
42   0xe59f300c, 0xe3530000, 0x0a000000, 0xea000000, 0xea000000
43 };
44 static const unsigned int sig_mask_sigaction[] = {
45   0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000
46 };
47
48
49 #define PATCH(f) { sig_##f, sig_mask_##f, ARRAY_SIZE(sig_##f), w_##f }
50
51 static const struct {
52   const unsigned int *sig;
53   const unsigned int *sig_mask;
54   size_t sig_cnt;
55   void *func;
56 } patches[] = {
57   PATCH(open),
58   PATCH(mmap),
59   PATCH(mmap2), // mmap2 syscall
60   PATCH(read),
61   PATCH(ioctl),
62   PATCH(sigaction),
63 };
64
65 void do_patches(void *ptr, unsigned int size)
66 {
67   int i, s;
68
69   for (i = 0; i < ARRAY_SIZE(patches); i++) {
70     const unsigned int *sig = patches[i].sig;
71     const unsigned int *sig_mask = patches[i].sig_mask;
72     unsigned int *seg = (void *)(((long)ptr + 3) & ~3);
73     unsigned int *seg_end = seg + size / 4;
74     unsigned int sig0 = sig[0];
75
76     for (; seg < seg_end; seg++) {
77       if (*seg != sig0)
78         continue;
79
80       for (s = 1; s < patches[i].sig_cnt; s++)
81         if ((seg[s] ^ sig[s]) & sig_mask[s])
82           break;
83
84       if (s == patches[i].sig_cnt)
85         goto found;
86     }
87     continue;
88
89 found:
90     dbg("  patch #%i @ %08x\n", i, (int)seg);
91     seg[0] = 0xe59ff000; // ldr pc, [pc]
92     seg[1] = 0;
93     seg[2] = (unsigned int)patches[i].func;
94   }
95
96   sys_cacheflush(ptr, (char *)ptr + size);
97 }
98