Created
August 31, 2014 05:17
-
-
Save emctoo/1c58e6ac7409b5eeefdf to your computer and use it in GitHub Desktop.
jit trick in c
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
// from http://dginasa.blogspot.com/2012/05/jit-compilation-without-much-assembler.html | |
// gcc -std=gnu99 jit.c -o jit | |
// still some warnings, need refinement, and put into some bigger works. | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/mman.h> | |
#include <unistd.h> | |
#define COPY_SECTION(sec_s, sec_e, dest) ({ \ | |
unsigned char *buff = NULL; \ | |
for (buff = &&sec_s; buff < &&sec_e; buff++, (dest)++) \ | |
*(dest) = *buff; \ | |
}) | |
int main(void) { | |
unsigned char *buff, *d; | |
int v = 0; | |
printf ("Address: \n" | |
"\tinc_v = %p\n" | |
"\tdec_v = %p\n" | |
"\tjump_end = %p\n" | |
"\tend = %p\n", &&inc_v, &&dec_v, &&jump_end, &&end); | |
/* Allocate. */ | |
void *dyn = mmap (0, 1024, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
/* Here's our sample program, `inc, inc, inc, dec, done` */ | |
d = dyn; | |
COPY_SECTION (inc_v, dec_v, d); | |
COPY_SECTION (inc_v, dec_v, d); | |
COPY_SECTION (inc_v, dec_v, d); | |
COPY_SECTION (dec_v, jump_end, d); | |
COPY_SECTION (jump_end, end, d); | |
/* Now call the code. */ | |
goto *dyn; | |
inc_v: | |
v++; | |
dec_v: | |
v--; | |
jump_end: | |
__asm__ volatile ("jmp *%0" :: "r" (&&end)); | |
end: | |
printf ("Value of v: %d\n", v); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment