I have written a short program to read a windows obj file and find the .text section and run the code in it. To do this I make the following Windows API function calls (Full code [gist.github.com], for those interested):
HANDLE FileHandle = CreateFile("lib.obj",
GENERIC_READ | GENERIC_EXECUTE,
FILE_SHARE_READ, 0,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
HANDLE MappingHandle = CreateFileMapping(FileHandle, 0, PAGE_EXECUTE_READ, 0, 0, 0);
void *Address = MapViewOfFile(MappingHandle, FILE_MAP_EXECUTE | FILE_MAP_READ,
0, 0, 0);
I then find the .text section in the file and cast the pointer to the code to a function pointer in C++ and simply call the function. This actually appeared to work for me.
Have I made a mistake not calling FlushInstructonCache on the range of virtual memory mapped to the file?
I ask this because I was recently reading the VirtualAlloc documentation and it notes at the bottom:
When creating a region that will be executable, the calling program bears responsibility for ensuring cache coherency via an appropriate call to FlushInstructionCache once the code has been set in place. Otherwise attempts to execute code out of the newly executable region may produce unpredictable results.
Is it possible that my code will cause the CPU to execute old instructions in the instruction cache?
There is no such note on the MapViewOfFile or CreateFileMapping pages.