-
-
Save cho45/9251465 to your computer and use it in GitHub Desktop.
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
//#!gcc -O0 -g3 -gdwarf-2 -Wall c.c -o /tmp/a.out && /tmp/a.out 1 2 | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <sys/mman.h> | |
uint8_t* memory[255]; | |
uint8_t program_counter; | |
void incr(void) { | |
program_counter++; | |
} | |
void decr(void) { | |
program_counter--; | |
} | |
void template(void) { | |
asm volatile ("nop"); | |
} | |
void get_function_body(void* func, uint8_t** buf, uint8_t* len) { | |
uint8_t* sub = (uint8_t*)func; | |
int i; | |
int start = 4, end; | |
// skip push %rbp, mov %rsp,%rbp | |
for (i = start; i < 255; i++) { | |
if (sub[i] == 0xc9) { // leaveq | |
end = i; | |
break; | |
} | |
printf("%x ", sub[i]); | |
} | |
printf("\n"); | |
printf("\n"); | |
printf("len=%d\n", end-start); | |
*buf = sub + start; | |
*len = end - start; | |
} | |
int main (int argc, char* argv[]) { | |
int i; | |
program_counter = 0; | |
printf("pc=%d\n", program_counter); | |
uint8_t* buf; uint8_t len; | |
// get function body pointer and length | |
get_function_body(incr, &buf, &len); | |
uint8_t code_len = len + 6; | |
uint8_t* code = mmap(NULL, code_len, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
int x = 0; | |
// push %rbp | |
code[x++] = 0x55; | |
// mov %rsp,%rbp | |
code[x++] = 0x48; | |
code[x++] = 0x89; | |
code[x++] = 0xe5; | |
for (i = 0; i < len; i++) { | |
code[x++] = buf[i]; | |
} | |
// leaveq | |
code[x++] = 0xc9; | |
// retq | |
code[x++] = 0xc3; | |
printf("code=%x\n", code); | |
for (i = 0; i < code_len; i++) { | |
printf("%x ", code[i]); | |
} | |
printf("\n"); | |
// asm volatile ("callq %0;" : : "r"(code) ); | |
((void (*)(void))code )(); | |
munmap(code, code_len); | |
printf("pc=%d\n", program_counter); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment