| 1 | // vim:shiftwidth=2:expandtab |
| 2 | #include <stdio.h> |
| 3 | #include <string.h> |
| 4 | #include <sys/types.h> |
| 5 | #include <sys/stat.h> |
| 6 | #include <fcntl.h> |
| 7 | #include <sys/mman.h> |
| 8 | |
| 9 | #include "header.h" |
| 10 | #include "sys_cacheflush.h" |
| 11 | |
| 12 | static const unsigned int sig_open[] = { |
| 13 | 0xe59cc000, 0xe33c0000, 0x1a000003, 0xef900005 |
| 14 | }; |
| 15 | |
| 16 | static const unsigned int sig_mmap[] = { |
| 17 | 0xe92d000f, 0xe1a0000d, 0xef90005a, 0xe28dd010 |
| 18 | }; |
| 19 | |
| 20 | static const unsigned int sig_mmap_[] = { |
| 21 | 0xe52d5004, 0xe59d5008, 0xe52d4004, 0xe59d4008, |
| 22 | 0xe1b0ca05, 0x1a000006, 0xe1a05625, 0xef9000c0 |
| 23 | }; |
| 24 | |
| 25 | #define FAKE_DEVMEM_DEVICE 10001 |
| 26 | |
| 27 | static int w_open(const char *pathname, int flags, mode_t mode) |
| 28 | { |
| 29 | int ret; |
| 30 | if (strcmp(pathname, "/dev/mem") != 0) |
| 31 | ret = open(pathname, flags, mode); |
| 32 | else |
| 33 | ret = FAKE_DEVMEM_DEVICE; |
| 34 | |
| 35 | printf("open(%s) = %d\n", pathname, ret); |
| 36 | return ret; |
| 37 | } |
| 38 | |
| 39 | static void *w_mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset) |
| 40 | { |
| 41 | void *ret; |
| 42 | if (fd != FAKE_DEVMEM_DEVICE) |
| 43 | ret = mmap(addr, length, prot, flags, fd, offset); |
| 44 | else |
| 45 | ret = emu_mmap_dev(length, prot, flags, offset); |
| 46 | |
| 47 | printf("mmap(%p, %x, %x, %x, %d, %lx) = %p\n", addr, length, prot, flags, fd, (long)offset, ret); |
| 48 | return ret; |
| 49 | } |
| 50 | #define w_mmap_ w_mmap |
| 51 | |
| 52 | #define PATCH(f) { sig_##f, ARRAY_SIZE(sig_##f), w_##f } |
| 53 | |
| 54 | static const struct { |
| 55 | const unsigned int *sig; |
| 56 | size_t sig_cnt; |
| 57 | void *func; |
| 58 | } patches[] = { |
| 59 | PATCH(open), |
| 60 | PATCH(mmap), |
| 61 | PATCH(mmap_), // mmap using mmap2 syscall |
| 62 | }; |
| 63 | |
| 64 | void do_patches(void *ptr, unsigned int size) |
| 65 | { |
| 66 | int i, s; |
| 67 | |
| 68 | for (i = 0; i < ARRAY_SIZE(patches); i++) { |
| 69 | const unsigned int *sig = patches[i].sig; |
| 70 | unsigned int *seg = (void *)(((long)ptr + 3) & ~3); |
| 71 | unsigned int *seg_end = seg + size / 4; |
| 72 | unsigned int sig0 = sig[0]; |
| 73 | |
| 74 | for (; seg < seg_end; seg++) { |
| 75 | if (*seg != sig0) |
| 76 | continue; |
| 77 | |
| 78 | for (s = 1; s < patches[i].sig_cnt; s++) |
| 79 | if (seg[s] != sig[s]) |
| 80 | break; |
| 81 | |
| 82 | if (s == patches[i].sig_cnt) |
| 83 | goto found; |
| 84 | } |
| 85 | continue; |
| 86 | |
| 87 | found: |
| 88 | printf(" patch #%i @ %08x\n", i, (int)seg); |
| 89 | seg[0] = 0xe59ff000; // ldr pc, [pc] |
| 90 | seg[1] = 0; |
| 91 | seg[2] = (unsigned int)patches[i].func; |
| 92 | } |
| 93 | |
| 94 | sys_cacheflush(ptr, (char *)ptr + size); |
| 95 | } |
| 96 | |