I was working with syscalls relating to virtual memory lately. From the manual of mmap I know that it can be very powerful when MAP_FIXED flag is set, creating new mappings everywhere in the memory.
MAP_FIXED
Don't interpret addr as a hint: place the mapping at exactly that address. addr must be suitably aligned: for most architectures a multiple of the page size is sufficient; however, some architectures may impose additional restrictions. If the memory region specified by addr and len overlaps pages of any existing mapping(s), then the overlapped part of the existing mapping(s) will be discarded. If the specified address cannot be used, mmap() will fail. Software that aspires to be portable should use the MAP_FIXED flag with care, keeping in mind that the exact layout of a process's memory mappings is allowed to change significantly between kernel versions, C library versions, and operating system releases. Carefully read the discussion of this flag in NOTES!
My question is, why there is a distinct syscall mprotect from mmap, given that mmap can do the exact same job by creating a new mapping with the same fd and offset, and set the new prot you want?
In my opinion, all operations about VM can be done ultimately with mmap and munmap, for those operations are basically just playing with the page table. Can someone tell me if this is a bad idea?
You need
mprotectif you want to change the permissions on an existing region of memory, while keeping its contents intact.mmapcan't do this. If you usemmapwithMAP_FIXEDto create a new mapping at the same address, then the region's previous contents will be replaced by the contents of the new file you mapped, or zeros if usingMAP_ANONYMOUS.Using the same
fdandoffsetdoes not solve this. If the map was originally created withMAP_ANONYMOUS(as is the case for most dynamically allocated memory) then there is nofd. Or, if the region was mapped to a file but withMAP_PRIVATE, then the contents could have been modified in your process's memory without being written back to the file. Attempting to map the file again withmmapwill lose the modified data and replace it with the file's original contents.