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.
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. Next I need to dig-into MSDN for virtualAlloc()
i guess.
You are getting this error because you are trying to declare
ptr
in the middle of the block.Classic ANSI C language (C89/90) does not allow declarations in the middle of the block. Declarations must reside at the beginning of the block. Declaring variables in the middle is only allowed in C99.
GCC compiler, even in C89/90 mode, allows declaring variables in the middle as a non-standard extension. MSVC compiler is a strict C89/90 compiler, it doesn't allow such declarations.