Windows OS – Effect of Demoting Copy-On-Write Page to Read-Write on Other Processes

operating systemswindows

The Windows OS tries to conserve physical memory usage by allowing DLLs loaded in their base (desired) address in different processes to use the same physical pages with copy-on-write semantics; this article, for example, describes the mechanism.

Now, the Windows Virtual Memory API allows you to change the protection mode of memory pages via the VirtualProtect function. You'll notice that two of the available protection modes include copy-on-write semantics.

Now that we have the prelude out of the way, the question is: if you take a copy-on-write memory page from a just-loaded DLL and change its protection mode to, say, read-write, how does it affect the other processes? Before the change all the processes use the same physical memory page, so does that single page suddenly lose its copy-on-write voodoo and becomes a weird kind of shared memory?

For sanity's sake I have to assume that if you change the protection mode of a copy-on-write page to read-write (or any non-COW protection mode), the kernel will spawn your own private page with the identical content and the other processes will live happily with their original COW page. The trouble is, I couldn't find any reference to support this, so if anyone could point me to anything that says explicitly that this is indeed the case I'd appreciate that.

EDIT: An even more interesting question would be what happens if you change the COW page to read-write and then write in it – does the change affect the other processes (since the page is no longer COW, and mapped in other processes too, it sounds like it should, but that would be clearly unsafe)?

Best Answer

Typically when something is "copy on write"; if a process writes to their instance of it, then that page is converted to "read/write" by creating a copy of the page and replacing the original with the copy for that process. Other processes keep using the original (until/unless they write to the page too and get their own copy).

If a process uses Windows Virtual Memory API to convert their instance of a page from "copy on write" to "read/write"; then (I assume) it'd have exactly the same effect as writing to the page - Windows would create a copy it, and that copy would be "read/write" for that process; and it wouldn't effect the original and wouldn't effect any other process' instance of it.