Reputation: 7157
I really want to reserve a specific set of memory locations with the MAP_FIXED
option to mmap
. However, by default mmap
will munmap
anything already at those addresses, which would be disastrous.
How can I tell mmap
to "reserve the memory at this address, but fail if it is already in use"?
Upvotes: 0
Views: 251
Reputation:
You can try using mincore(2)
This will be non-thread safe, unfortunately. Another thread might allocate that region after you check region status, but before you execute mmap
.
If you need to reserve a memory area, just create anonymous private mapping with PROT_NONE
. Later you can put different mappings on top of it using MAP_FIXED
.
EDIT: Looks like mincore
behavior is going to change in Linux 5.0 due to the fact that it can cause information leak (CVE-2019-5489):
So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use).
Vulnerability description can be found here.
Upvotes: 1
Reputation: 3675
Just omit MAP_FIXED
then Linux will use the requested address if free. If the requested address is not free some other address is used, in which case you can use munmap
.
Upvotes: 1