Created
December 12, 2012 03:33
-
-
Save haberman/4264659 to your computer and use it in GitHub Desktop.
Code for a trivial (but real) JIT. Part of an upcoming article / blog post.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
int main(int argc, char *argv[]) { | |
// Machine code for: | |
// mov eax, 0 | |
// ret | |
unsigned char code[] = {0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3}; | |
if (argc < 2) { | |
fprintf(stderr, "Usage: jit1 <integer>\n"); | |
return 1; | |
} | |
// Overwrite immediate value "0" in the instruction | |
// with the user's value. This will make our code: | |
// mov eax, <user's value> | |
// ret | |
int num = atoi(argv[1]); | |
memcpy(&code[1], &num, 4); | |
// 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_ANONYMOUS | MAP_PRIVATE, -1, 0); | |
memcpy(mem, code, sizeof(code)); | |
// The function will return the user's value. | |
int (*func)() = mem; | |
return func(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment