Allocate virtual memory and run code in it?

I'm 50% sure that I don't know what I'm doing.

Let's say I have some executable code in some file.

If I want to execute that code I can do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    HANDLE hFile = 0;
    HANDLE hMap = 0;
    char *code = NULL;

    DWORD (*func)();


    hFile = CreateFileA("fileName.bin",
	GENERIC_ALL,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
        NULL);  

    if(INVALID_HANDLE_VALUE == hFile)
    {
        printf("INVALID_HANDLE_VALUE\n");
        return 0;
    }

    hMap = CreateFileMapping(hFile, 
		NULL,
		PAGE_EXECUTE_READWRITE, 
		0, 0, 0);

    if(!hMap)
    {
        printf("GetLastError() = %d\n", GetLastError());
        CloseHandle(hFile);
        return 0;
    }

    code = (char *)MapViewOfFile(hMap, 
        FILE_MAP_READ | FILE_MAP_EXECUTE,
        0, 0, 0 );

    if(NULL == code)
    {
        printf("code == NULL\n");
        printf("GetLastError() = %d", GetLastError());
        UnmapViewOfFile(code);
	CloseHandle(hMap);
	CloseHandle(hFile);
        return 0;
    }
    func = (DWORD (*)()) code;
    (DWORD)(*func)();


    UnmapViewOfFile(code);
    CloseHandle(hMap);
    CloseHandle(hFile);


Assuming that whatever I have in fileName.bin has it's entry point right at the beginning this works.

But can I make this in another way?

For example, can I use VirtualAlloc to allocate virtual memory and then run that code in the reserved space? How can I do that?
Last edited on
Topic archived. No new replies allowed.