forked from jserv/jit-construct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjit0-arm.c
50 lines (43 loc) · 1.4 KB
/
jit0-arm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
int main(int argc, char *argv[]) {
// Machine code for:
// 000082e0 <main>:
// 82e0: e3a00000 mov r0, #0
// 82e4: e12fff1e bx lr
char code[] = {
0x00, 0x00, 0xa0, 0xe3, // 0xe3a00000
0x1e, 0xff, 0x2f, 0xe1 // 0xe12fff1e
};
if (argc < 2) {
fprintf(stderr, "Usage: jit0-arm <integer>\n");
return 1;
}
// Overwrite immediate value "0" in the instruction
// with the user's value. This will make our code:
// mov r0, <user's value>
// bx lr
int num = atoi(argv[1]);
memcpy(&code[0], &num, 2);
// Allocate writable/executable memory.
// Note: real programs should not map memory both writable
// and executable because it is a security risk.
void *mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC,
MAP_ANON | MAP_PRIVATE, -1, 0);
memcpy(mem, code, sizeof(code));
// Clear caches to prevent self-modifying code execute failed due to I-cache
// and D-cache not coherent.
//
// Please see:
// http://community.arm.com/groups/processors/blog/2010/02/17/caches-and-self-modifying-code
#if defined(__GNUC__)
__builtin___clear_cache((char*) mem, (char*) (mem + sizeof(code)));
#else
#error "Missing builtin to flush instruction cache."
#endif
// The function will return the user's value.
int (*func)() = mem;
return func();
}