Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active December 30, 2015 12:19
Show Gist options
  • Save jorendorff/7828447 to your computer and use it in GitHub Desktop.
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/
// 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