What is mmap, and what is mprotect used for?
Short answer: mmap() maps a file or anonymous memory into the process's address space, so the program can access it with normal pointers instead of read()/write(). Pages are loaded on demand by page faults, and with MAP_SHARED changes go back to the file (or are visible to other processes mapping it). mprotect() changes the access permissions (read, write, execute) of pages that are already mapped.
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void)
{
int fd = open("data.bin", O_RDONLY);
struct stat st;
fstat(fd, &st);
const unsigned char *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (p == MAP_FAILED) { perror("mmap"); return 1; }
close(fd); /* the mapping stays valid */
printf("first byte: %02x\n", p[0]);
munmap((void *)p, st.st_size);
return 0;
}
Uses of mmap
| Use | Flags |
|---|---|
| Read a large file randomly without copying it into a buffer | MAP_PRIVATE, PROT_READ |
| Share memory between processes | MAP_SHARED on a shm_open() fd or a file |
Allocate large memory (glibc malloc does this above 128 KB) |
MAP_PRIVATE | MAP_ANONYMOUS |
| Access device memory / frame buffers / DMA buffers from user space | MAP_SHARED on a /dev node (driver implements mmap) |
| Load executables and shared libraries | used by the kernel's ELF loader and ld.so |
mprotect scenarios
- Read-only after initialisation: build a configuration table or lookup table at start-up, then
mprotect(p, len, PROT_READ). Any later accidental write causes an immediateSIGSEGVinstead of silent corruption, and the table cannot be modified by an attacker exploiting a memory bug. - JIT compilers (W^X): write generated machine code into a
PROT_READ | PROT_WRITEpage, then switch it toPROT_READ | PROT_EXECbefore running it. A page should never be writable and executable at the same time. - Guard pages:
PROT_NONEpages around buffers or thread stacks catch overflows. - Garbage collectors and checkpointing: write-protect pages to detect which ones change (the fault handler records the page and re-enables writing).
Rules: addresses and lengths are page-aligned (sysconf(_SC_PAGESIZE)); mprotect works on whole pages; and accessing beyond the end of a mapped file (in the last partial page and beyond) gives SIGBUS.
mmap vs read: mmap avoids a copy and is great for random access to large files. For sequential reads, read() with a big buffer is often just as fast and handles errors (an I/O error becomes a SIGBUS with mmap, which is harder to handle).