Created
May 5, 2022 01:14
-
-
Save m417z/7177d820252ab42f4d86c905589b6f05 to your computer and use it in GitHub Desktop.
A reproduction test case for https://github.com/ramensoftware/windhawk/issues/3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
// Compile as x86 with the following linker flag: /LARGEADDRESSAWARE | |
DWORD WINAPI TestThread(LPVOID lpThreadParameter) | |
{ | |
if ((INT32)&lpThreadParameter >= 0) { | |
return 0; | |
} | |
WinExec("C:\\Windows\\sysnative\\notepad.exe", SW_SHOWDEFAULT); | |
return 1; | |
} | |
LPVOID FindNextFreeRegion(LPVOID pAddress, LPVOID pMaxAddr, DWORD dwAllocationGranularity, DWORD* dwSize) | |
{ | |
ULONG_PTR tryAddr = (ULONG_PTR)pAddress; | |
// Round down to the allocation granularity. | |
tryAddr -= tryAddr % dwAllocationGranularity; | |
// Start from the next allocation granularity multiply. | |
tryAddr += dwAllocationGranularity; | |
while (tryAddr <= (ULONG_PTR)pMaxAddr) { | |
MEMORY_BASIC_INFORMATION mbi; | |
if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) | |
break; | |
if (mbi.State == MEM_FREE) { | |
*dwSize = mbi.RegionSize; | |
return (LPVOID)tryAddr; | |
} | |
tryAddr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; | |
// Round up to the next allocation granularity. | |
tryAddr += dwAllocationGranularity - 1; | |
tryAddr -= tryAddr % dwAllocationGranularity; | |
} | |
return NULL; | |
} | |
bool Test() | |
{ | |
DWORD dwFreeSize; | |
LPVOID dwFreeAddress = FindNextFreeRegion((LPVOID)0x10000, (LPVOID)0x7FFFFFFF, 0x1000, &dwFreeSize); | |
while (true) { | |
if (!VirtualAlloc((LPVOID)dwFreeAddress, dwFreeSize, MEM_RESERVE, PAGE_NOACCESS)) { | |
//return false; | |
} | |
HANDLE hThread = CreateThread(nullptr, 0, TestThread, nullptr, 0, nullptr); | |
if (!hThread) { | |
return false; | |
} | |
WaitForSingleObject(hThread, INFINITE); | |
DWORD dwExitCode; | |
GetExitCodeThread(hThread, &dwExitCode); | |
CloseHandle(hThread); | |
if (dwExitCode) { | |
return true; | |
} | |
dwFreeAddress = FindNextFreeRegion(dwFreeAddress, (LPVOID)0x7FFFFFFF, 0x1000, &dwFreeSize); | |
} | |
} | |
int main() | |
{ | |
MessageBox(nullptr, Test() ? L"Test succeeded" : L"Test failed", L"Result", 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment