c++winapishared-memorymemory-mapped-filescopy-on-write

Copy-on-write file mapping on windows


I have 3 processes communicating over named pipes: server, writer, reader. The basic idea is that the writer can store huge (~GB) binary blobs on the server, and the reader(s) can retrieve it. But instead of sending data on the named pipe, memory mapping is used.

The server creates an unnamed file-backed mapping with CreateFileMapping with PAGE_READWRITE protection, then duplicates the handle into the writer. After the writer has done its job, the handle is duplicated into any number of interested readers.

The writer maps the handle with MapViewOfFile in FILE_MAP_WRITE mode.

The reader maps the handle with MapViewOfFile in FILE_MAP_READ|FILE_MAP_COPY mode.

On the reader I want copy-on-write semantics, so as long the mapping is only read it is shared between all reader instances. But if a reader wants to write into it (eg. in-place parsing or image processing), the impacts should be limited to the modifying process with the least number of copied pages possible.

The problem
When the reader tries to write into the mapping it dies with segmentation fault as if FILE_MAP_COPY was not considered. What's wrong with the above described method? According to MSDN this should work...

We have the same mechanism implemented on linux as well (with mmap and fd passing in AF_UNIX ancillary buffers) and it works as expected.


Solution

  • problem here that MapViewOfFile bad designed or/and documented. this is shell (with restricted functionality) over ZwMapViewOfSection. the dwDesiredAccess parameter of MapViewOfFile converted to Win32Protect parameter of ZwMapViewOfSection.

    the FILE_MAP_READ|FILE_MAP_COPY combination converted to PAGE_READONLY page protection, because this you and get page fault on write.

    you need use FILE_MAP_COPY only flag - it converted to PAGE_WRITECOPY page protection and in this case all will be work.

    the best solution of course direct use ZwMapViewOfSection with PAGE_WRITECOPY page protection