Reputation: 163
I have a DWORD value that I want to monitor changes, so I decided to use a guard page.
The problem is that the STATUS_GUARD_PAGE_VIOLATION
exception is triggered right after marking the memory as PAGE_GUARD
using VirtualProtect
:
DWORD* lpAddress = (DWORD*)0xDEADBEEF;
void test()
{
AddVectoredExceptionHandler(0x1, MyHandler);
DWORD oldprotection;
VirtualProtect(lpAddress, sizeof(DWORD), PAGE_READWRITE | PAGE_GUARD, &oldProtection);
//Here, the STATUS_GUARD_PAGE_VIOLATION is triggered and MyHandler is immediately called
MessageBox(NULL, L"Just a test", L"", MB_OK);
}
LONG WINAPI MyHandler(PEXCEPTION_POINTERS pExc)
{
if(pExc->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION)
{
//Immediately called after VirtualProtect
//If I try to use VirtualProtect again, it will also immediately trigger MyHandler
}
return EXCEPTION_CONTINUE_EXECUTION;
}
I've read something about that VirtualProtect
is accessing the address inside its function body so that's why the trigger happens (first trigger is from VirtualProtect
itself), but I'm not sure.
Is there any way to avoid this?
Or maybe I am doing something wrong?
Upvotes: 1
Views: 702
Reputation: 32717
VirtualProtect
protects the entire 4K page (or possibly pages) that contain the 4 bytes you want to guard. Any access to any part of that page (not just the address you want to guard) will result in the guard page alarm to trigger.
If you just want to monitor those 4 bytes a guard page isn't the way to do it.
Upvotes: 5