Hi everyone,
As an experiment i am trying to write the following program which allows me to generate code during runtime. i.e. i do the following:
1. Fill a buffer with op-codes of the instructions i want to execute.
2. Declare a function-pointer and make it point to the start of the buffer.
3. Call the function using the above func-ptr.
The code is as follows: ( Updated following AndreyT's instructions below.)
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
//#include <sys/mman.h>
int main(int argc, char *argv[])
{
int u32;
int (*ptr)(void);
uint8_t *buf = malloc(1000);
//uint8_t *buf = mmap(NULL, 1000, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
buf[0] = 0xb8;
u32= 42;
memcpy(buf + 1, &u32, 4);
buf[5] = 0xc3;
ptr = (int (*)(void)) buf;
printf("return is %d\n", ptr());
return 0;
}
This code compiles fine on a linux-machine using gcc.
Now i'm migrating it to windows (visual-studio-2010).
AFAIK, mmap functionality is provided by virtualAlloc and virtualProtect on windows.
I have been through MSDN and other documentation on the net,
but am still unable to figure out a way to get this program to run on VS-2010 on windows.
regards
CVS-2600Hertz
UPDATE:
@AndreyT Thank you. It seems to be working now. Though i get the following error:
1>MSVCRTD.lib(crtexew.obj) :
error LNK2019: unresolved external symbol WinMain@16 referenced in function __tmainCRTStartup
1>file.exe : fatal error LNK1120: 1 unresolved externals
Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped
I'm thinking i need to swap the mmap call with virtualAlloc now.
Thanks a lot everyone. I need to dig-into MSDN for virtualAlloc now i guess.