On this page

malloc returns a virtual address, yet physical memory only materializes behind it on the first touch: the kernel builds the page tables, and a hardware unit translates every address.

The vector registers from lesson 21 speed up arithmetic over an existing buffer. Now we look at where the buffer itself comes from: how the kernel maps pages, why mmap doesn’t consume physical RAM upfront, and how to build an arena allocator that hands out a thousand blocks from a single system call.

Mental Model: Virtual Addresses vs. Physical RAM

Intuition What the testbed shows
malloc is a thin wrapper around a syscall glibc grows the heap via brk and serves small allocations in userspace without a syscall
A pointer printed by printf is a physical address It is a virtual address translated by the MMU
A 1 MiB mmap consumes 1 MiB of RAM immediately Until touched, pages are not resident and VmRSS barely moves
Files can only be read via read mmap maps the kernel’s page cache directly, with zero read calls in strace

Pages, MMU, and TLB

Every address printed by GDB or printf is virtual. It belongs to a memory page, and mapping boundaries are always multiples of 4096.

Virtual-to-physical address translation is performed by the MMU. Recent translations are cached in the TLB.

A Single-mmap Arena Allocator

The mmap syscall can reserve an entire region at once, and an arena slices it up in userspace.

The arena struct is defined in the C99 harness arena_test.c and matches the exact field layout expected by assembly:

typedef struct {
    uint8_t *base;
    size_t size;
    size_t used;
} arena_t;

The fields sit at byte offsets 0, 8, and 16—exactly where arena.asm reads them.

arena.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; arena.asm — bump arena backed by mmap: one page-aligned region for all allocations.

default rel

%define SYS_MMAP 9
%define SYS_MUNMAP 11
%define PROT_READ_WRITE 3
%define MAP_PRIVATE_ANON 0x22
%define PAGE_SHIFT 12
%define ARENA_ALIGN 16

; Layout of arena_t: [0] base, [8] size, [16] used.

section .text
    global asm_arena_init
    global asm_arena_alloc
    global asm_arena_destroy

; ------------------------------------------------------------------------------
; int asm_arena_init(arena_t *arena, size_t pages)
; Input:     rdi = arena, rsi = page count
; Output:    eax = 0 on success, -1 on failure; arena fields populated or zeroed
; Clobbers:  rax, rcx, rdx, rsi, rdi, r8, r9, r10, r11, flags
; Preserves: rbx (callee-saved; arena pointer anchor, push/pop)
; ------------------------------------------------------------------------------
asm_arena_init:
    push rbx
    mov rbx, rdi
    shl rsi, PAGE_SHIFT

    ; syscall: mmap(NULL, pages * PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
    mov eax, SYS_MMAP
    xor edi, edi
    mov edx, PROT_READ_WRITE
    mov r10, MAP_PRIVATE_ANON
    mov r8, -1
    xor r9d, r9d
    syscall

    cmp rax, -4095
    jae .fail

    mov [rbx], rax
    mov [rbx + 8], rsi
    mov qword [rbx + 16], 0
    xor eax, eax
    pop rbx

    ret

.fail:
    mov qword [rbx], 0
    mov qword [rbx + 8], 0
    mov qword [rbx + 16], 0
    mov eax, -1
    pop rbx

    ret

; ------------------------------------------------------------------------------
; void *asm_arena_alloc(arena_t *arena, size_t bytes)
; Input:     rdi = arena, rsi = requested byte count
; Output:    rax = aligned block pointer, or NULL if exhausted
; Clobbers:  rax, rcx, rdx, rsi, r8, flags
; ------------------------------------------------------------------------------
asm_arena_alloc:
    add rsi, ARENA_ALIGN - 1
    and rsi, -ARENA_ALIGN

    mov rdx, [rdi + 16]
    mov r8, rdx
    add r8, rsi

    mov rcx, [rdi + 8]
    cmp r8, rcx
    ja .oom

    mov rax, [rdi]
    add rax, rdx
    mov [rdi + 16], r8

    ret

.oom:
    xor eax, eax

    ret

; ------------------------------------------------------------------------------
; void asm_arena_destroy(arena_t *arena)
; Input:     rdi = arena
; Output:    none; arena fields zeroed
; Clobbers:  rax, rcx, rsi, rdi, r11, flags
; Preserves: rbx (callee-saved; push/pop)
; ------------------------------------------------------------------------------
asm_arena_destroy:
    push rbx
    mov rbx, rdi
    mov rsi, [rbx + 8]
    test rsi, rsi
    jz .clear
    mov rdi, [rbx]

    ; syscall: munmap(base, size)
    mov eax, SYS_MUNMAP
    syscall

.clear:
    mov qword [rbx], 0
    mov qword [rbx + 8], 0
    mov qword [rbx + 16], 0
    pop rbx

    ret

section .note.GNU-stack noalloc noexec nowrite progbits

The arena struct occupies three 8-byte fields:

  • base — the starting virtual address returned by mmap;
  • size — total size of the mapped region in bytes;
  • used — how many bytes have been handed out so far (the bump offset).
arena_t:  base ──► [ block 0 | block 1 | ... | free up to size ]
          used ──────────────────────────► ▲
                                           └─ next allocation

mmap takes six arguments using the kernel syscall register convention:

  • rdi — hint address (0 lets the kernel pick);
  • rsi — mapping length in bytes;
  • rdx — protection flags (PROT_READ|PROT_WRITE = 3);
  • r10 — mapping flags (MAP_PRIVATE|MAP_ANONYMOUS = 0x22);
  • r8 and r9 — file descriptor and offset (-1 and 0 for anonymous memory).

The fourth syscall argument goes in r10, not rcx, because the syscall instruction clobbers rcx and r11 in hardware. A raw Linux syscall doesn’t just return -1 on error: any unsigned value in -4095..-1 encodes -errno, so cmp rax, -4095; jae .fail catches every failure. In libc, that same failure maps to MAP_FAILED.

asm_arena_alloc rounds the requested size up to a 16-byte boundary, advances used, and returns base + old_used. There is no free list: individual allocations can’t be freed, only the entire arena via munmap. In return, serving a thousand allocations executes zero syscalls.

Rounding up via (bytes + 15) & -16 corresponds directly to add rsi, ARENA_ALIGN - 1 and and rsi, -ARENA_ALIGN. Tracing bytes = 17:

  • 17 + 15 = 32 (0x20);
  • ~15 = -16 (0xFFFFFFFFFFFFFFF0) clears the bottom four bits with a bitwise AND;
  • for 0x20, those four bits are already zero, so the aligned size is 32.

For bytes = 20, the sum 35 (0x23) under the same mask becomes 32: the low bits are cleared and the result is a multiple of 16. A request of bytes = 16 gives 31 & -16 = 16, fitting into a single 16-byte slot.

$ strace -e trace=mmap,munmap,brk ./build/arena_test 2>&1 | grep -E '1048576|brk'
brk(NULL)                               = 0x5616771fb000
mmap(NULL, 1048576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7eff41300000
brk(NULL)                               = 0x5616771fb000
brk(0x56167721d000)                     = 0x56167721d000
munmap(0x7eff41300000, 1048576)         = 0

The brk calls come from glibc’s heap backing printf’s internal buffers, not from our arena: malloc expands the heap ahead of time for small objects so it doesn’t enter the kernel on every call. Our arena makes exactly one 1 MiB mmap and one munmap on teardown.

Lazy Allocation and the Process Memory Map

mmap creates a virtual memory mapping entry, not physical pages. The kernel allocates a physical frame only when the process first touches a page: the page fault handler claims a free physical frame, zeroes it, and installs the page table entry. That is why the process’s resident memory barely changes right after mmap.

mmap(1 MiB)

Entry in process map
VmRSS hasn't grown yet

First write to a page

page fault:
no physical frame
allocated yet

Kernel maps a zeroed frame

VmRSS +4 KiB

mmap(1 MiB)

Entry in process map
VmRSS hasn't grown yet

First write to a page

page fault:
no physical frame
allocated yet

Kernel maps a zeroed frame

VmRSS +4 KiB

Fig. 1. Demand paging after mmap
$ ./build/arena_test
arena: base=0x7f7250700000 size=1048576
rss: before=1932 kB after=3020 kB
alloc: 1000 blocks ok, used=64000
mapping: 7f7250700000-7f7250800000 rw-p 00000000 00:00 0 
arena: ok

The harness touches one byte in each of the 256 pages, and VmRSS grows by roughly 1 MiB (3020 - 1932 = 1088 KiB including page-table/runtime overhead). Before those touches, the mapping already existed, yet zero physical pages backed it.

Reading the /proc/self/maps entry column by column:

  • 7f7250700000-7f7250800000 — virtual address bounds of the mapping, exactly 1 MiB;
  • rw-p — read/write permissions, private copy-on-write mapping;
  • 00000000 — file offset (zero for anonymous memory);
  • 00:00 — major and minor device numbers of the backing filesystem (00:00 for anonymous memory);
  • 0 — inode number (0 for anonymous memory).

The same mapping shows up in GDB if we break on the first allocation:

$ gdb -q --nx -batch -ex 'b asm_arena_alloc' -ex run -ex up \
    -ex 'p/x arena.base' -ex 'p arena.size' -ex 'info proc mappings' \
    ./build/arena_test
Breakpoint 1, asm_arena_alloc () at arena.asm:69
69	    add rsi, ARENA_ALIGN - 1
$1 = 0x7ffff7e80000
$2 = 1048576
0x00007ffff7e80000 0x00007ffff7f85000 0x105000 0x0 rw-p

up steps GDB out of the assembly function into main’s frame, where arena lives. Notice the mapped span 0x105000 is larger than the requested 0x100000: the kernel merged the arena VMA with an adjacent 0x5000-byte anonymous mapping that had matching flags and permissions.

Files as Pages

The second testbed opens a file and maps it read-only. The kernel maps the page cache pages straight into the process’s page tables, making the file’s contents readable without read or intermediate buffer copies.

    ; syscall: mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0)
    mov eax, SYS_MMAP
    xor edi, edi
    mov rsi, r13
    mov edx, PROT_READ
    mov r10, MAP_PRIVATE
    mov r8, r12
    xor r9d, r9d
    syscall

    cmp rax, -4095
    jae .fail_map
    mov r14, rax

The length passed to mmap doesn’t have to be a multiple of the page size: the kernel still allocates mappings in 4 KiB pages, exposes the file bytes up to EOF, and zero-pads the rest of the final page. Touching past the page-aligned end of the mapping triggers SIGSEGV, whereas SIGBUS triggers when the mapping was requested longer than the file and you touch a whole page past EOF—inside the virtual mapping, yet past the backing file. strace confirms that read never appears anywhere in the run:

read(): [ disk ] ─► [ kernel page cache ] ──(copy)──► [ process buffer ]
mmap(): [ disk ] ─► [ kernel page cache ] ──(same pages)──► [ address space ]
$ strace -e trace=open,mmap,munmap,read,write ./build/mmap_file
open("build/sample.txt", O_RDONLY)      = 3
mmap(NULL, 28, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fb0f7b61000
write(1, "mmap reads pages, not bytes\n", 28) = 28
munmap(0x7fb0f7b61000, 28)              = 0
+++ exited with 0 +++

Here read is never called: write pulls bytes directly from the mapped page-cache pages. Even for a 28-byte file, the kernel maps a full page, keeping reads bounded so they cannot overrun past the file’s contents.

Terminal Verification

$ make test
22-mmap-allocator: arena and file mapping OK

The test suite verifies three invariants: all 1,000 blocks are 16-byte aligned and contiguous, the arena mapping carries rw-p permissions, and the file written via mmap matches the source file byte-for-byte.

Common Failure Modes

  1. Believing malloc is a syscall.
    Symptom: strace shows glibc’s brk calls and a single mmap for our arena, not a syscall per malloc.
    Cause: malloc is a user-space allocator: it carves blocks out of pre-allocated regions and only enters the kernel when it needs more memory.
    Fix: Trace allocations with strace -e trace=mmap,brk instead of assuming every malloc crosses into kernel space.

  2. Assuming a 1 MiB mmap immediately uses 1 MiB of physical RAM.
    Symptom: Right after mmap, VmRSS sits at 1932 KiB, rising to 3020 KiB only after touching 256 pages.
    Cause: mmap only creates the virtual mapping; physical frames are demand-paged via page faults on first touch.
    Fix: Measure VmRSS before and after touching pages rather than trusting the requested mapping length.

  3. Checking rax only against -1.
    Symptom: Raw mmap returns -ENOMEM, -EINVAL, and other -errno codes in -4095..-1; -1 (-EPERM) is only one of them.
    Cause: libc converts any negative return into errno and returns MAP_FAILED, whereas a raw syscall returns -errno directly.
    Fix: Use an unsigned comparison: cmp rax, -4095; jae .fail.

  4. Skipping munmap because the process will exit anyway.
    Symptom: asm_arena_destroy invokes munmap, logged as munmap(0x7eff41300000, 1048576) = 0.
    Cause: While the kernel reclaims mappings at process exit, long-running programs leak virtual address space and physical backing if they don’t unmap.
    Fix: Unmap arenas explicitly and zero the struct fields so a double-destroy never calls munmap on stale pointers.

Lab

Goal. Add asm_arena_alloc_aligned(arena_t *arena, size_t bytes, size_t align) to allocate blocks with alignments larger than 16 bytes.

Contract.

  • align is a power of two between 16 and 4096; values smaller than 16 are clamped up to 16.
  • The returned pointer is aligned to align, and the block never crosses the end of the arena.
  • On out-of-memory, return NULL and leave used unchanged.
  • The C99 test harness verifies alignments of 64 and 4096 and confirms total allocations stay within size.

Acceptance criteria.

  1. make test passes.
  2. objdump -d -M intel build/arena.o shows alignment via and with a negated mask.
  3. make leaks reports zero ASan errors.
  4. After a failed allocation, used matches its value prior to the call.
Hints, expected output, and walkthrough

You must align the current offset—not just the requested size: compute aligned_used = (used + align - 1) & -align, then check aligned_used + bytes <= size. If you only align bytes, the returned pointer remains stuck on a 16-byte boundary and the 4096-byte alignment check will fail.

Expected testbed output:

aligned: 64 ok, 4096 ok
arena: ok

If used advances after a failed allocation, you wrote the updated used before checking aligned_used + bytes <= size. If a 4096-aligned block fails its alignment check, you masked with align instead of -align.

Testbed sources, Makefile, and automated tests for this lesson: lessons/22-mmap-allocator.

Summary

  1. The MMU translates virtual addresses via page tables, while the TLB caches recent translations.
  2. mmap creates a virtual mapping, and physical frames are demand-paged on first touch via page faults.
  3. Raw mmap errors span -4095..-1, not just -1.
  4. An arena acquires memory with one syscall and serves allocations by bumping an offset.
  5. /proc/self/maps and info proc mappings expose mapping bounds and permissions.
  6. A file mapped with mmap is read straight from the kernel’s page cache without read syscalls.
Bridge to the next lesson
Memory is mapped and backed by pages, yet two threads writing to the same word still drop updates. In lesson 23, we unpack TSO, lock cmpxchg, futex, and TLS—how the CPU and kernel preserve ordering under concurrent writes.