VirtualProtect call for associated file

I use the CreateFileMapping and MapViewOfFile functions to map a file to memory. After a certain point, I call VirtualProtect to change its read-only read-write protection. This call fails, and GetLastError gives ERROR_INVALID_PARAMETER.

Here is a simplified version of my code that demonstrates the problem.

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main() {
    HANDLE fd, md;
    char *addr;
    DWORD old;
    BOOL ok;

    fd = CreateFile("filename", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    md = CreateFileMapping(fd, NULL, PAGE_READWRITE, 0, 100, NULL);
    addr = MapViewOfFile(md, FILE_MAP_READ, 0, 0, 100);
    ok = VirtualProtect(addr, 100, PAGE_READWRITE, &old);
    if (!ok) {
        // we fall into this if block
        DWORD err = GetLastError();
        // this outputs "error protecting: 87"
        printf("error protecting: %u\n", err);
        return 1;
    }
    UnmapViewOfFile(addr);
    CloseHandle(md);
    CloseHandle(fd);
    return 0;
}

What am I doing wrong here? Am I not allowed to invoke VirtualProtect in the area containing the associated file?

+5
source share
3 answers

FILE_MAP_READ | FILE_MAP_WRITE PAGE_READONLY. PAGE_READWRITE :

addr = MapViewOfFile(md, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 100);
ok = VirtualProtect(addr, 100, PAGE_READONLY, &old);
//...
ok = VirtualProtect(addr, 100, PAGE_READWRITE, &old);
+5

, , VirtualProtectEx ( VirtualProtect ) STATUS_SECTION_PROTECTION (0xC000004E) - " , ", , , (FILE_MAP_READ).

, , , , , .

+3

According to http://msdn.microsoft.com/en-us/library/aa366556(v=vs.85).aspx , this should be legal. According to the VirtualProtect documentation, the new flags should be compatible with the "VirtualAlloc" flags - if this transfer to the "MapViewOfFile" flags, I suspect that you can tighten, but not weaken the protection. Try matching readwrite and changing read protection.

+1
source

All Articles