10 Dec, 2011, Tyche wrote in the 1st comment:
Votes: 0
I was trying to speed up my VM for Aphrodite by translating the bytecode and
ran across the following technique to create amd execute self-modifying code.

The won't work on Windows Vista/7 if DEP is turned on, but then it's off by default for
non-system applications anyway.

Here's some C examples that copies functions to the heap and executes them.

For Windows:
#include <windows.h>

void override(void* dest, void* src, size_t pagesz) {
CopyMemory(dest, src, pagesz);
FlushInstructionCache(GetCurrentProcess(), NULL, 0);
}

int add(int a, int b) {
printf("%d + %d = %d\n",a,b,a+b);
return a+b;
}

int multiply(int a, int b) {
printf("%d * %d = %d\n",a,b,a*b);
return a*b;
}

int main() {
int result;
size_t pagesz = 4096;
int (*overlay)(int,int) = VirtualAlloc(NULL,pagesz,MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE);

override(overlay,&add,pagesz);
result = (*overlay)(3,4);
printf("add result = %d\n",result);

override(overlay,&multiply,pagesz);
result = (*overlay)(3,4);
printf("multiply result = %d\n",result);

VirtualFree(overlay,0,MEM_RELEASE);
return 0;
}


For Linux/Cygwin:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

void override(void* dest, void* src, size_t pagesz) {
__asm__ __volatile__ ("cpuid");
memcpy(dest, src, pagesz);
}

int add(int a, int b) {
printf("%d + %d = %d\n",a,b,a+b);
return a+b;
}

int multiply(int a, int b) {
printf("%d * %d = %d\n",a,b,a*b);
return a*b;
}

int main() {
int result;
size_t pagesz = 4096;
int (*overlay)(int,int) = malloc(pagesz);

mprotect(overlay, pagesz, PROT_READ|PROT_WRITE|PROT_EXEC);

override(overlay,&add,pagesz);
result = (*overlay)(3,4);
printf("add result = %d\n",result);

override(overlay,&multiply,pagesz);
result = (*overlay)(3,4);
printf("multiply result = %d\n",result);

free(overlay);
return 0;
}
0.0/1