Another use for VirtualAllocEx
which hasn't been mentioned yet, is to allocate memory in another process' address space. Note that the first parameter is the handle to a process - the function allocates the memory within the virtual address space of that process.
I've used this before when injecting code into another process, by forcing a LoadLibrary
call in the target process. The basic steps are as follows:
- Get the process id of the target process (e.g. with something like
GetWindowThreadProcessId
). - Get a handle to the process with the appropriate permissions using
OpenProcess
. - Allocate some memory in that process with
VirtualAllocEx
. - Copy the name of your DLL into that memory with
WriteProcessMemory
. - Get the address of the
LoadLibrary
function usingGetProcAddress
. - Call
CreateRemoteThread
to start theLoadLibrary
call in the target process, with the thread parameter being the memory you've allocated withVirtualAllocEx
(containing the name of the DLL).
Not that you needed to know all of that, but I though it was an interesting use case.