How does copy-on-write work with read-only virtual pages in mmap function?

Unix & Linux Asked by secondimage on November 29, 2020

I’m new to C and Linux, just a question on the usage of mmap function, the function prototype of mmap is

void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);

and I saw code like this:

char *srcp = mmap(0, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0);

and we know that PROT_READ means the virtual pages can be read only.
and MAP_PRIVATE indiacates it is a private copy-on-write object. copy-on-write technique is sth like, when two processes uses the same object, when process A modify the object, those changes belong to process A only and invisible to process B. so MAP_PRIVATE allow users to write sth, but PROT_READ indicates read-only, since we can only read it, there is no meanning to use COW(to use COW,you need to be able to write sth first then COW will make the change only visible for your process), are’t them contradicting to each other?

One Answer

When calling mmap, the caller must choose between a shared (MAP_SHARED) or private (MAP_PRIVATE) mapping. The use of copy-on-write is an implementation detail; compare with the POSIX definition of mmap.

The type of mapping (shared or private) only determines what happens to writes. Thus with PROT_READ, it doesn’t matter, and the use of copy-on-write doesn’t either. Any change made to the backing file will ultimately be visible in the process’ mapping, even with a private mapping. In theory, this behaviour could change:

Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

(from the MAP_PRIVATE description in man 2 mmap).

Note too that a process can change the memory protection with mprotect, assuming it is able to write to the underlying file. The type of mapping can’t be changed, but the protection can, so a process can map a file read-only, then change to read-write (if the file itself was opened read-write); copy-on-write becomes relevant then.

(Thanks to user414777 for correcting a number of errors in previous versions of this answer. Any remaining errors are my own.)

Correct answer by Stephen Kitt on November 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP