Page 1 of 1
Memory Related Functions mmap() munmap() and mprotect()
Posted: Sat Mar 04, 2023 1:05 pm
by FunnyGuy9796
While looking at
liballoc I noticed the use of a few functions which belong to the “sys/mman.h” header file. I was wondering if there was any documentation available for these functions or an explanation of how they work.
Re: Memory Related Functions mmap() munmap() and mprotect()
Posted: Sat Mar 04, 2023 3:23 pm
by iansjack
The “man” command in Linux will tell you what these functions do. Or just Google (e.g.) “man map”.
Re: Memory Related Functions mmap() munmap() and mprotect()
Posted: Sat Mar 04, 2023 3:26 pm
by Barry
mmap(), munmap() and mprotect() are system calls. Technically they're BSD system calls, but they're present on most *nix systems.
They're the functions related to mapping, unmapping and protecting regions of memory, backed by either a named or anonymous file. The all typically operate at page granularity.
You can checkout the POSIX Programmer's Manual page for sys/mman.h for a good explanation of the different #defines it provides and for a list of the functions it exports. If you're interested in any of those, you can check the manual page for them individually. The POSIX standard may differ from the implementation on an OS, so it's worth checking both the POSIX and system manuals.
If you want to see how they work you could give the Linux/BSD implementations a glance, but they're probably not the most straightforward to read.
Brief explanation of them:
mmap() maps the content of a file, or part of a file, into the address space of the process. Reading the area of memory will return the data in the file. Writing to the area of memory will, if the file was mapped with the MAP_SHARED flag, write through to the file transparently.
munmap() removes a file mapping, or part of a file mapping.
mprotect() modifies the protection on a region of memory, allowing you to specify it as readable, writeable, executable or any combination thereof.
Liballoc is a memory allocator for user-space, and allocates at page-granularity for the process' heap. The heap has to actually be backed by some physical memory, so liballoc requests that from the kernel with a call to mmap(), using the MAP_ANONYMOUS flag. The kernel will back an area of the process' address space with physical memory, but not with a actual file. In liballoc's case, mmap() is just used as the kernel's interface to back some virtual memory with page frames to avoid a page fault. When user-space is done with this memory it can free it, again using the kernel's interface in the form of munmap().