For what do I need to use VirtualAlloc/VirtualAllocEx?

青春壹個敷衍的年華 提交于 2019-12-03 08:37:26

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:

  1. Get the process id of the target process (e.g. with something like GetWindowThreadProcessId).
  2. Get a handle to the process with the appropriate permissions using OpenProcess.
  3. Allocate some memory in that process with VirtualAllocEx.
  4. Copy the name of your DLL into that memory with WriteProcessMemory.
  5. Get the address of the LoadLibrary function using GetProcAddress.
  6. Call CreateRemoteThread to start the LoadLibrary call in the target process, with the thread parameter being the memory you've allocated with VirtualAllocEx (containing the name of the DLL).

Not that you needed to know all of that, but I though it was an interesting use case.

VirtualAlloc and VirtualAllocEx in very simplistic terms allocate raw pages, all other memory functions from malloc to GlobalAlloc all use VirtualAllocEx underneath. The problem with VirtualAlloc is that it is basically raw memory, there is no reallocation or relocation available. As such if your address space becomes fragmented you have no recourse but to release and rebuild.

The primary use case for VirtualAlloc is when you need to write your own memory manager, for say a SQL implementation where it can make a huge difference. Or if you were implementing a Just In Time Compiler (JIT), as you would need to be able to change the protection flags on the page you compile into from read/write to read/execute as to not trigger Data Execution Prevention.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!