Glossary
mmap
mmap on macOS maps a file or anonymous memory into a process. The signature, the flags that matter (MAP_PRIVATE, MAP_SHARED, MAP_ANON, MAP_JIT) and an example.
mmap(2) maps a file or anonymous memory into a process's virtual address space. It's the most widely used VM syscall on XNU — malloc reaches for it on large allocations, dyld uses it to map every dylib, every file-backed memory region in every running process arrived via mmap.
The semantics: pass a length, a file descriptor, an offset, and protection flags; get back a pointer. Reads and writes through the pointer go to the file (or zero-fill anonymous memory). The kernel handles paging in and out.
apple-oss-distributions/xnubsd/kern/kern_mman.cThe BSD-side mmap, munmap, mprotect handlers.View on GitHub(line —)Crucially, mmap is lazy. The call returns having allocated zero physical pages — the kernel only creates the vm_map_entry pointing at the file. Real pages arrive via page fault on first touch.
This is why you can mmap a 50 GB file on a Mac with 16 GB of RAM and the call succeeds instantly: nothing was loaded.
mmap on macOS: signature and flags
#include <sys/mman.h>
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset);
It returns the mapped address, or MAP_FAILED with errno set. offset must be a multiple of the page size, which is 16 KB on Apple Silicon and 4 KB on Intel Macs. Ask getpagesize() or sysconf(_SC_PAGESIZE) rather than hard-coding it.
| Flag | What it does on macOS |
|---|---|
MAP_PRIVATE | Copy-on-write: your writes never reach the file. This is how dyld maps the writable data of a dylib. |
MAP_SHARED | Writes go back to the file and are visible to every other process that maps it. |
MAP_ANON / MAP_ANONYMOUS | No file: zero-filled memory. Pass fd = -1, or a VM_MAKE_TAG() value so the region shows up labelled in vmmap. |
MAP_FIXED | Place the mapping exactly at addr, replacing whatever was there. |
MAP_JIT | Memory that can switch between writable and executable. Under the hardened runtime this needs the com.apple.security.cs.allow-jit entitlement, and on Apple Silicon each thread flips the region with pthread_jit_write_protect_np(). |
A minimal read-only file mapping:
int fd = open("/path/to/file", O_RDONLY);
struct stat st;
fstat(fd, &st);
void *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd); /* the mapping keeps the file referenced */
/* ... read through p ... */
munmap(p, st.st_size);
The thing that bites people porting code from Linux: on Apple Silicon you cannot just ask for PROT_WRITE | PROT_EXEC. Without MAP_JIT that request fails, and with it you still never get both at once on a thread, you toggle. Any JIT, emulator or hand-rolled trampoline hits this on day one.
To see what a process actually has mapped, run vmmap <pid>. Every file-backed and anonymous region listed there came through mmap or the Mach mach_vm_map() call underneath it.
See also: vm_map, pmap, and the mmap walkthrough article.