How to use VirtualAllocEx to make a place for a code cave?

How to use VirtualAllocEx to make a place for a code cave ? I currently have a piece of software with very little โ€œfree spaceโ€, and I read that VirtualAllocEx is used to create this space.

+3
memory-management windows winapi
source share
2 answers

After the โ€œcode caveโ€ question is cleared, you can find an interesting following code that lists the blocks allocated by VirtualAllocEx in the current process and finds all the PEs (the DLL and the EXE itself).

 SYSTEM_INFO si; MEMORY_BASIC_INFORMATION mbi; DWORD nOffset = 0, cbReturned, dwMem; GetSystemInfo(&si); for (dwMem = 0; dwMem<(DWORD)si.lpMaximumApplicationAddress; dwMem+=mbi.RegionSize) { cbReturned = VirtualQueryEx (GetCurrentProcess(), (LPCVOID)dwMem, &mbi, sizeof(mbi)); if (cbReturned) { if ((mbi.AllocationProtect & PAGE_EXECUTE_WRITECOPY) && (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))) { if (*(LPWORD)mbi.AllocationBase == IMAGE_DOS_SIGNATURE) { IMAGE_DOS_HEADER *pDosHeader = (IMAGE_DOS_HEADER *)mbi.AllocationBase; if (pDosHeader->e_lfanew) { IMAGE_NT_HEADERS32 *pNtHeader = (IMAGE_NT_HEADERS32 *) ((PBYTE)pDosHeader + pDosHeader->e_lfanew); if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) continue; // now you can examine of module loaded in current process } } } } } 

The code may look like a big loop. In fact, this is a typical application, which is about 200 cycles, so it goes through all the blocks allocated to VirtualAllocEx very quickly during the loading of the EXE of all dependent DLLs.

+2
source share
 #include <stdio.h> #include <windows.h> #include <commctrl.h> unsigned long pid; HANDLE process; GetWindowThreadProcessId(listview, &pid); process = OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ | PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, pid); int *vptr = (int *)VirtualAllocEx(process, NULL, sizeof(int), MEM_COMMIT, PAGE_READWRITE); 

References
- MSDN VirtualAllocEx Function
- CodeProject Memory Theft Program
- StackOver What is a code cave ...?

NTN

+2
source share

All Articles