Last active
December 30, 2015 12:19
-
-
Save jorendorff/7828447 to your computer and use it in GitHub Desktop.
A first experiment in creating and running x86 machine code on the fly. By Nick Desaulniers: http://nickdesaulniers.github.io/blog/2013/04/03/basic-jit/
This file contains hidden or 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
// To compile this on mac: gcc -m32 -o rawcode rawcode.c | |
// Probably the same on linux, or drop the -m32. | |
// Then: ./rawcode | |
#include <stdio.h> // printf | |
#include <string.h> // memcpy | |
#include <sys/mman.h> // mmap, munmap | |
int main () { | |
// x86 machine code for: int mul (int a, int b) { return a * b; } | |
unsigned char code [] = { | |
0x55, // push %ebp | |
0x89, 0xe5, // mov %esp,%ebp | |
0x8b, 0x45, 0x08, // mov 0x8(%ebp),%eax | |
0x0f, 0xaf, 0x45, 0x0c, // imul 0xc(%ebp),%eax | |
0x5d, // pop %ebp | |
0xc3 // ret | |
}; | |
// allocate executable memory via sys call | |
void* mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC, | |
MAP_ANON | MAP_PRIVATE, -1, 0); | |
// copy runtime code into allocated memory | |
memcpy(mem, code, sizeof(code)); | |
// typecast allocated memory to a function pointer | |
int (*func) () = mem; | |
// call function pointer | |
printf("19 * 11 = %d\n", func(19, 11)); | |
// free up allocated memory | |
munmap(mem, sizeof(code)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment