Pārlūkot izejas kodu

hello, jit world.

Lucas Stadler 11 gadi atpakaļ
vecāks
revīzija
fa6df0d8b1
2 mainītis faili ar 33 papildinājumiem un 0 dzēšanām
  1. 3 0
      c/jit/README.md
  2. 30 0
      c/jit/hello_jit.c

+ 3 - 0
c/jit/README.md

@ -0,0 +1,3 @@
1
# Hello, JIT World.
2
3
Following along the ["Hello, JIT World: The Joy of Simple JITs"](http://blog.reverberate.org/2012/12/hello-jit-world-joy-of-simple-jits.html) article.

+ 30 - 0
c/jit/hello_jit.c

@ -0,0 +1,30 @@
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
#include <sys/mman.h>
5
6
int main(int argc, char *argv[]) {
7
	// machine code for:
8
	//   mov eax, 0
9
	//   ret
10
	unsigned char code[] = {0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3};
11
12
	if (argc < 2) {
13
		fprintf(stderr, "Usage: hello_jit <integer>\n");
14
		return 1;
15
	}
16
17
	// copy the given number into the code, e.g:
18
	//   mov eax, <user's value>
19
	//   ret
20
	int num = atoi(argv[1]);
21
	memcpy(&code[1], &num, 4);
22
23
	// allocate writable & executable memory.
24
	// note: security risk!
25
	void *mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0);
26
	memcpy(mem, code, sizeof(code));
27
28
	int (*func)() = mem;
29
	return func();
30
}