Ask: execute program from memory
I want to activate an exe file but without having the file on the disk but the file is all in the memory.
Reply:
allocate memory.
Load/compile/create/whatever the programcode into that part of memory.
Arrange for any needed address fixups.
Call/jump to the code loaded in memory.
Pretty straightforward stuff really.
Some extra info:
You will need to alloacte the memory with VirtualAlloc so you can set the memory flags correctly. Specifically, you will need the Execute permission.
Something like....
// typedef functionpointer to the type of function you need.
typedef void (*PFMyFunc)();
// actual functionpointer
PFMyFunc pfMyFunc;
LPVOID lpMem = VirtualAlloc (NULL, dwSizeNeeded, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
pfMyFunc = (PFMyFunc)lpMem; // Store address in function pointer so we can call it.
// create/copy code to lpMem....
// Do any required address fixups
pfMyFunc(); // Call the code.
VirtualFree (lpMem);
ask:
After it has been loaded in memory
does anyone know how to dynamically call the main() or winmain function in any executable ,just like the OS does it ?
Without having to look through dumpbin and whatnot.
Looked everywhere, it should be so easy but it's nowhere documented. Or is it?
reply:
PE structure
Inside the IMAGE_NT_HEADERS structure of the executables PE structure is a field for the address of entry point. You just get the IMAGE_NT_HEADERS from the IMAGE_DOS_HEADER, and use that as your pointer to the runtime startup code (use proper calling convention!).
reply:
You can't easily run an EXE file this way, but you can use it to run code you create on the fly (I've used this in programs that had a built in programming language that gets compiled to native intel code).
An exe requires a whole lot more than the simple outline I gave. An Exe won't usually work since it'll require a separate process. Some exe's require to be loaded at specific memory addresses and such.
Running another exe inside the process space of your own program will violate many rules/assumptions that programs rely on, and I doubt highly it would work. The closest you could get to running another 'program' inside your own process space would be to compile the other 'program' to a DLL instead of an EXE.