0

I want to protect the certain memory area, like 0x12345678 ~ 0x12345679. so if another thread accesses to that area, I want to generate exception.

To solve my problem, I've found and used VirtualProtectEx win32 api. https://msdn.microsoft.com/en-us/library/windows/desktop/aa366899(v=vs.85).aspx

And my code looks as follows.

...
DWORD dwA = 0xFFFFFFFF;
DWORD dwC = 0xCCCCCCCC;
int main()
{
    DWORD dwProtect = PAGE_READONLY;

    HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, GetCurrentProcessId());
    VirtualProtectEx((HANDLE)handle, (PVOID)&dwA, 4, dwProtect, &dwProtect);
    DWORD dwB = dwA;
    dwC = 0x00000000;
    dwA = 0x00000000;
...

Here, I set read-only protection to dwA's memory. But at dwC = 0x00000000, I got exception. I think it's because VirtualProtectEx protects the page, not the certain memory.

But I just want to protect only dwA's memory.

Can anybody please help me by leading me to correct direction?

1 Answer 1

1

The protections are supported only on page granularity by the CPU and you cannot change that. What you can do is in your exception handler check which address generated the fault, and if it's not the variable you want to "protect", restore permissions to the original value, single-step to allow the write be performed, then disable writes again. This is complicated and pretty slow so should be used only when necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.