Created
May 11, 2014 10:20
-
-
Save bdw/05fcd9071b29edffd267 to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
/* note - for windows this is different */ | |
#include <sys/mman.h> | |
#include "dynasm/dasm_proto.h" | |
#include "dynasm/dasm_x86.h" | |
// DynASM directives. | |
|.arch x64 | |
|.actionlist actions | |
/* call a function (64 bit) | |
* and yes, i did steal this from jitdemo :-) */ | |
|.macro callp, addr | |
| mov64 rdx, (uintptr_t)addr | |
| call rdx | |
|.endmacro | |
int main(int argc, char **argv) { | |
dasm_State * state; | |
char * hello = "hello, %s\n"; | |
char * world = "world"; | |
size_t codesize; | |
char * memory; | |
void (*fp)(void); | |
/* initialize the assembler structure */ | |
dasm_init(&state, 1); | |
dasm_setup(&state, actions); | |
/* add some instructions */ | |
#define Dst &state | |
| mov64 rdi, (uintptr_t)hello | |
| mov64 rsi, (uintptr_t)world | |
| mov64 rax, (uint64_t)0 | |
| callp printf | |
| ret | |
#undef Dst | |
/* link the code and get its' final size */ | |
dasm_link(&state, &codesize); | |
/* get r/w memory */ | |
memory = mmap(NULL, codesize, PROT_READ | PROT_WRITE, | |
MAP_ANON | MAP_PRIVATE, -1, 0); | |
/* write the machine code */ | |
dasm_encode(&state, memory); | |
/* clear up the assembler */ | |
dasm_free(&state); | |
/* make the memory executable */ | |
mprotect(memory, codesize, PROT_EXEC | PROT_READ); | |
/* cast to function */ | |
fp = (void(*)(void)) memory; | |
/* call the function */ | |
fp(); | |
/* destroy the memory */ | |
munmap(memory, codesize); | |
/* and leave */ | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment