Skip to content

Instantly share code, notes, and snippets.

@icedraco
Created November 27, 2014 09:54
Show Gist options
  • Save icedraco/ea686725af5adc3543ab to your computer and use it in GitHub Desktop.
Save icedraco/ea686725af5adc3543ab to your computer and use it in GitHub Desktop.
An example of running bytecode from within a C program
#include <string.h>
#include <sys/mman.h>
int main(void) {
char rawr[] = "Rawr!\n";
char bytecode[] = {
0x60, // pusha
0xb8, 0x04, 0x00, 0x00, 0x00, // mov eax, 4
0xbb, 0x01, 0x00, 0x00, 0x00, // mov ebx, 1
0xb9, /* for rawr */ 0,0,0,0, // mov ecx, 0
0xba, sizeof(rawr), 0x00, 0x00, 0x00, // mov edx, sizeof(rawr) [6 or 7]
0xcd, 0x80, // int 0x80
0x61, // popa
0xc3 // ret
};
// Add the address of rawr to bytecode
*((int*)(bytecode + 12)) = rawr;
void* mmbytecode = mmap(0,
sizeof(bytecode),
PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_ANONYMOUS|MAP_PRIVATE,
-1, 0);
/* Store the bytecode in the newly mapped area */
memcpy(mmbytecode, bytecode, sizeof(bytecode));
/* Execute the bytecode */
((void(*)(void))mmbytecode)();
munmap(mmbytecode, sizeof(bytecode));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment