mmap man page on Mac

536 views Asked by At

The mmap man page on my mac says the following

The mmap() system call causes the pages starting at addr and continuing for at most len bytes to be mapped from the object described by fd, starting at byte offset offset.

Does this mean that the call can fail without an error and return a portion of memory mapped to an address range that is smaller than what was asked for?

For example if I do the following

void* memory = mmap(nullptr, range, PROT_READ | PROT_WRITE, MAP_ANONYMOUS, -1, 0);

Then can the call succeed without an error and return an address range that is not range bytes long?

2

There are 2 answers

0
Rob Napier On

The "address range" will still be range bytes long (or possibly longer if you haven't aligned things properly), but may not be mapped. len + offset may extend past the end of the mapped object (for example, past the end of a file). If that occurs, then the docs indicate "any extension beyond the end of the mapped object will be zero-filled."

0
user3344003 On

The problem you are facing is a system service that does many different related things.

(assuming "offset=0") IF you were mapping a 65-byte file and you specified "range=50000" (assuming the page size is less than 50000) then the mapped region is going to be smaller than the range because the file size is less than the range.

Thus, While not usually documented, you are likely to get a virtual memory allocation that is "range" rounded DOWN to the file size then rounded UP to a page size WHEN you are mapping to a file (which you are not doing in your example).

In your case, where you are not mapping to file, the allocation is likely to be rounded up to the nearest page.

Again, I am assuming that you are using a paging system.