#include <windows.h>
#include <stdio.h>
/* In the beginning we'll have to define the function pointer. */
/* I called the function 'dyncode' and gave it an int argument */
/* as well as an int return value just to show what's possible. */
int (*dyncode)(int); /* prototype for call of dynamic code */
/* The following char array is initialized with some binary code */
/* which takes the first argument from the stack, increases it, */
/* and returns to the caller. */
/* Just very simple code for testing purposes... */
unsigned char code[] = {0x8B,0x44,0x24,0x04, /* mov eax, [esp+4] */
0x40, /* inc eax */
0xC3 /* ret */
};
/* Include the prototypes of the functions we are using... */
int main()
{
/* To show you that the code can be dynamically generated */
/* although I defined static data above, the code is copied */
/* into an allocated memory area and the starting address is */
/* assigned to the function pointer 'dyncode'. */
/* The strange stuff in front of the malloc is just to cast */
/* the address to the same format the function pointer is */
/* definded with, otherwise you'd get a compiler warning. */
dyncode = (int (*)(int)) VirtualAlloc(NULL, sizeof(code),
MEM_COMMIT, PAGE_EXECUTE_READWRITE);
/* We now have a page of memory that is readable, writeable */
/* and executable. so the memcpy will work without any */
/* problems! */
memcpy(dyncode, code, sizeof(code));
/* To show that the code works it is called with the argument 41 */
/* and the retval sould be 42, obviously. */
/* This code will now execute correctly! */
printf("retval = %d\n", (*dyncode)(41) ); /* call the code and print the return value */
/* Freeing the page allocated. */
VirtualFree(dyncode, NULL, MEM_RELEASE);
return 0;
}