POSIX Memory Management (mmap, mprotect & madvise)

The POSIX Virtual Memory Management interface (standardized under <sys/mman.h>) provides user-space applications with direct control over their virtual address space.

Rather than relying solely on high-level heap allocators (malloc(), free()), systems software—including database engines (RocksDB, SQLite, PostgreSQL), runtime garbage collectors (Go, JVM, V8), and container sandboxes—relies directly on POSIX memory primitives to map files into memory, allocate large aligned buffers, set page permissions, and advise the kernel's virtual memory subsystem.

1. Virtual Memory Mapping: mmap() and munmap()

POSIX defines mmap() as the universal mechanism for creating virtual memory mappings:

#include <sys/mman.h>

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);
┌────────────────────────────────────────────────────────┐
│            Process Virtual Address Space               │
│               [0x7fff0000 - 0x7fff1000]                │
└───────────────────────────┬────────────────────────────┘
                            │ Page Fault (On First Touch)
                            ▼
┌────────────────────────────────────────────────────────┐
│                  Operating System MMU                  │
│               (Page Tables & PTE Flags)                │
└─────────────┬────────────────────────────┬─────────────┘
              │ File-Backed                │ Anonymous
              ▼                            ▼
┌───────────────────────────┐┌───────────────────────────┐
│     Kernel Page Cache     ││   Physical RAM (Zeroed)   │
│  (Disk Inode In-Core RAM) ││    (Heap / JIT Buffers)   │
└───────────────────────────┘└───────────────────────────┘

Memory Protection Flags (prot)

The prot parameter specifies access permissions enforced by the hardware Memory Management Unit (MMU):

  • PROT_NONE: Page cannot be accessed. Any read or write triggers immediate hardware trap SIGSEGV. Used to implement guard pages against stack overflow.
  • PROT_READ: Pages can be read.
  • PROT_WRITE: Pages can be written.
  • PROT_EXEC: Pages can be executed as CPU machine instructions.

Mapping Flags: Private vs. Shared

The flags argument controls whether writes are visible to other processes and whether changes are committed to the underlying file:

Flag Combination Mapping Type Primary Use Case & Characteristics
MAP_PRIVATE | MAP_ANONYMOUS Private Anonymous General heap allocators (malloc for large chunks), thread stacks. Initialized with zeros.
MAP_SHARED | MAP_ANONYMOUS Shared Anonymous Parent-child inter-process communication without creating a filesystem artifact.
MAP_PRIVATE (with valid fd) Copy-On-Write (COW) Dynamic linkers loading shared libraries (.so / .dylib). Executable code is shared; modified globals trigger local COW page copy.
MAP_SHARED (with valid fd) Shared File Mapping Database storage engines, memory-mapped files. Writes dirty the kernel page cache and are persisted to disk.

Allocating 64MB of Zero-Initialized Anonymous Memory

size_t size = 64 * 1024 * 1024; // 64 MB
void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

if (ptr == MAP_FAILED) {
    perror("mmap failed");
    return NULL;
}

// Memory is lazily allocated by kernel on first touch
memset(ptr, 0x42, size);

// Cleanup
munmap(ptr, size);

2. Dynamic Memory Protection: mprotect() and W^X Policies

The mprotect() system call dynamically changes access protections for an existing memory mapping:

int mprotect(void *addr, size_t len, int prot);
  • addr must be aligned to a system page boundary (typically 4096 bytes, queried via sysconf(_SC_PAGESIZE)).

Enforcing W^X (Write XOR Execute) Security

Modern security architectures mandate that memory must never be simultaneously writable and executable. A buffer that is writable allows an attacker to inject shellcode; a buffer that is executable allows arbitrary CPU instruction execution.

JIT compilers (JavaScript V8, PyPy, JVM) use mprotect() to alternate states:

  1. Allocate memory with PROT_READ | PROT_WRITE.
  2. Compile and emit CPU machine code instructions into the buffer.
  3. Call mprotect(ptr, size, PROT_READ | PROT_EXEC) to strip write permission before calling into the generated code.

3. Physical Memory Pinning: mlock() and mlockall()

By default, the operating system kernel is free to evict inactive pages from physical RAM and swap them out to disk or swap partitions.

int mlock(const void *addr, size_t len);
int munlock(const void *addr, size_t len);
int mlockall(int flags); // MCL_CURRENT | MCL_FUTURE

Critical Use Cases for Memory Pinning:

  1. Security & Cryptography: Sensitive credentials, TLS private keys, and passwords stored in heap memory must never be written to plaintext swap space on disk.
  2. Deterministic Hard Real-Time Systems: Trading systems, audio processing engines, and industrial controllers cannot tolerate millisecond-long page-fault freezes caused by disk swap paging.

4. Virtual Memory Advisory: posix_madvise()

Applications can inform the kernel's virtual memory manager about expected future memory access patterns, allowing the OS to optimize page replacement algorithms:

int posix_madvise(void *addr, size_t len, int advice);
Advice Constant Kernel Behavior Optimal Use Case
POSIX_MADV_NORMAL Default heuristic page clustering and readahead. Standard memory access.
POSIX_MADV_SEQUENTIAL Aggressively pre-fetches sequential pages and quickly evicts consumed pages. Large sequential table scans, linear processing.
POSIX_MADV_RANDOM Disables readahead heuristics entirely. B-Tree index traversal, graph search.
POSIX_MADV_WILLNEED Initiates non-blocking page-in from disk into RAM. Pre-warming memory before real-time execution.
POSIX_MADV_DONTNEED Signals that memory range is no longer required. Kernel can immediately discard pages. Large memory pool resets, arena allocators.

NOTE: On Linux, the native madvise() system call supports extended non-POSIX advice flags such as MADV_HUGEPAGE (Transparent Huge Pages), MADV_MERGEABLE (Kernel Samepage Merging), and MADV_DONTDUMP (exclude memory from core dumps).

Related Topics