The stack isn’t a warehouse with fixed shelves—it’s a pointer into virtual memory that moves on every
push.
Intuition says a large local array “reserves space” upfront and passing a big object by value might push a program into swap. On a real testbed, the opposite happens: the stack grows downward in virtual addresses, physical pages only materialize on touch, and a guard page sits just past the limit. In this lesson, I unpack $rsp, push/pop, the red zone, and recursive crashes at the stack limit.
Mental Model: A Pointer and a Boundary
| What it looks like in C99 | What happens in hardware |
|---|---|
| A local array immediately allocates memory | sub rsp, N only moves the pointer; physical pages are faulted in on first touch |
| Passing a large object by value goes to swap | The copy lands on the stack as long as RLIMIT_STACK holds; paging to disk follows normal VM rules |
push “adds to the stack” |
First rsp is decremented by 8, then the value is written to the new address |
| The stack can grow indefinitely | Past the limit, the next page is unmapped, so writing to it raises SIGSEGV |
| The red zone is free scratch memory | It is the 128 bytes below $rsp that a function may use without adjusting $rsp, but only until the first function call (call, lesson 10) |
Virtual Memory: The Stack’s Bare Minimum
A process address space is virtual memory that grants a range of addresses rather than pre-allocated bytes. Three numbers define the stack’s bounds:
getconf PAGESIZEprints4096on the testbed: one page is 4 KiB.ulimit -sprints8192: the stack limit is 8192 KiB, or 8 MiB.- the top of user space is
0x7ffffffff000, spanning a 47-bit space of 128 TiB.
That space size in bytes is:
The stack grows downward: push decrements $rsp rather than incrementing it. The kernel does not pre-allocate all 8 MiB. It extends the [stack] mapping on demand when the program touches a new page below the current pointer, and refuses to extend it once the next step exceeds RLIMIT_STACK.
High addresses: 0x7ffffffff000 top of user-space stack
... argc, argv, envp (initial startup frame)
[rsp + 8] previous stack slot
$rsp ──────► [rsp + 0] most recently pushed qword (top of stack)
─ ─ ─ ─ ─ ─ ─ ─ ┐
[rsp - 8] │ Red Zone (128 bytes below $rsp)
... │ call writes the return address to [rsp - 8]!
[rsp - 128] ┘
▼ stack grows downward (push decrements $rsp)
────────────── RLIMIT_STACK boundary (8 MiB)
Low addresses: (unmapped) writing here ──► #PF ──► SIGSEGV (exit 139)rsp, push, and pop
The stack_lab.asm testbed saves the initial $rsp, pushes two values, and pops them back off:
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; stack_lab.asm — push/pop move rsp; the red zone sits below rsp without moving it.
; r15 is unused in arithmetic and preserved across syscalls — it holds initial rsp.
; Checkpoints at_pushed, at_popped, and at_red_zone are inspected by GDB.
default rel
%define SYS_EXIT 60
section .text
global _start
_start:
mov r15, rsp
mov r8, 0x1111111111111111
push r8
mov r9, 0x2222222222222222
push r9
at_pushed:
mov rax, qword [rsp]
pop rdx
pop rcx
at_popped:
mov r10, 0xAAAA0000BBBB1111
mov qword [rsp - 8], r10
mov r11, 0xCCCC0000DDDD2222
mov qword [rsp - 128], r11
mov r10, 0xEEEE0000FFFF3333
mov qword [rsp - 120], r10
at_red_zone:
; syscall: exit(0)
mov eax, SYS_EXIT
xor edi, edi
syscall
section .note.GNU-stack noalloc noexec nowrite progbitsDisassembly shows the machine encodings of both pairs:
40100d: 41 50 push r8
...
401019: 41 51 push r9
...
40101f: 5a pop rdx
401020: 59 pop rcx41 50—REX.Bprefix pluspush r8: without the prefix,50encodespush rax.41 51— same forr9; the lower eight registers encode in a single byte.5a—pop rdx,59—pop rcx:popfor lower registers is also a single byte.
push and pop do not allocate memory—they move a pointer within an already-mapped range.
In GDB at at_pushed, you can verify both pointer arithmetic and stack contents:
Breakpoint 1, at_pushed () at stack_lab.asm:24
24 mov rax, qword [rsp]
(gdb) print/d $rsp == $r15 - 16
$1 = 1
(gdb) x/4gx $rsp
0x7fffffffd6f0: 0x2222222222222222 0x1111111111111111
0x7fffffffd700: 0x0000000000000001 0x00007fffffffdb81
...print/d $rsp == $r15 - 16 evaluates to 1: two pushes moved the pointer down by 16 bytes. At $rsp sits 0x2222..., because it was pushed last.
The next two qwords belong to the process’s initial startup frame:
- at
0x7fffffffd700sitsargcwith value1; - right after it lies
argv[0], pointing to the string at0x7fffffffdb81(covered in lesson 13).
After two pops, $rsp returns to its starting value and the registers receive the popped numbers:
Breakpoint 1, at_popped () at stack_lab.asm:29
29 mov r10, 0xAAAA0000BBBB1111
(gdb) print/d $rsp == $r15
$1 = 1
(gdb) info registers rdx rcx
rdx 0x2222222222222222 2459565876494606882
rcx 0x1111111111111111 1229782938247303441Red Zone
Compilers take advantage of this red zone (the ABI itself is covered in lesson 18): a small leaf function can skip emitting sub rsp.
stack_lab.asm makes three writes into the red zone—at $rsp - 8, $rsp - 128, and $rsp - 120—without touching $rsp. The first write mov qword [rsp - 8], r10 sits immediately below the stack pointer; the disassembly below shows the two deeper writes:
40103a: 4c 89 5c 24 80 mov QWORD PTR [rsp-0x80],r11
401049: 4c 89 54 24 88 mov QWORD PTR [rsp-0x78],r1080in the displacement byte is-128as a signed byte: an 8-bit displacementdisp8spans-128..+127.88is-120; both writes stay inside the red zone.$rspnever moves, so the function frame never “grew.”
Inspecting GDB confirms the contents:
Breakpoint 1, at_red_zone () at stack_lab.asm:40
40 mov eax, SYS_EXIT
0x7fffffffd680: 0xcccc0000dddd2222 0xeeee0000ffff3333The boundary matters: the red zone only survives until the first call or an incoming signal. call writes the return address directly to $rsp - 8 (covered in lesson 10), and the kernel builds signal frames below $rsp with a 128-byte cushion.
Guard Page and the Stack Limit
A Guard Page (for pthread threads in lesson 23, it’s marked PROT_NONE, just like in the mprotect experiment in lesson 14, while page allocation itself is covered in lesson 22) doesn’t prevent a recursion bug—it turns it into a predictable crash instead of silently corrupting adjacent pages.
The stack_guard_bad.c testbed intentionally consumes 64 KiB per frame:
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */
/* stack_guard_bad.c — deliberate stack overflow: 64 KiB per frame.
* Excluded from -Werror and strict checks: it demonstrates SIGSEGV
* on the guard page rather than a valid program. */
#include <stdint.h>
#include <stdio.h>
static void descend(uint32_t depth)
{
volatile uint8_t page[65536];
page[0] = (uint8_t)depth;
page[65535] = (uint8_t)(depth + 1);
if (depth % 16u == 0u) {
fprintf(stderr, "depth = %u, frame = %p\n", (unsigned)depth, (void *)&page[0]);
}
descend(depth + 1);
}
int main(void)
{
descend(0);
return 0;
}Running it with an explicit 8 MiB stack limit (ulimit -s 8192) and core dumps disabled (ulimit -c 0) exits with 139—that’s , meaning termination by SIGSEGV:
$ (ulimit -c 0; ulimit -s 8192; ./build/stack_guard_bad); echo $?
depth = 0, frame = 0x7ffffffed590
depth = 16, frame = 0x7fffffeed290
...
depth = 112, frame = 0x7fffff8ec090
139Each frame takes slightly over 64 KiB. Subtracting the addresses of two frames 16 calls apart:
That’s 64 KiB + 48 bytes per frame. At a rough 64 KiB per frame, an 8 MiB limit fits 128 frames:
That explains why it fails at depth = 126: the extra 48 bytes per frame eat up the headroom. So recursion isn’t “spilling objects to disk”—it simply walks $rsp downward until it hits the wall.
In GDB, you can see the exact fault point and unmapped address:
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555154 in descend (depth=<error reading variable: Cannot access memory at address 0x7fffff7fbf5c>) at stack_guard_bad.c:11
11 {
#1 0x00005555555551c6 in descend (depth=126) at stack_guard_bad.c:21
(gdb) info registers rsp
rsp 0x7fffff7fbf50 0x7fffff7fbf50
(gdb) x/i $rip
=> 0x555555555154 <descend+11>: mov DWORD PTR [rbp-0x10014],edi
(gdb) print/x $_siginfo._sifields._sigfault.si_addr
$1 = 0x7fffff7fbf5cdepth=126— the frame where 8 MiB ran out.$rsp = 0x7fffff7fbf50— the pointer is already below the start of the[stack]mapping.si_addr = 0x7fffff7fbf5c— the address accessed by themovinstruction.[rbp-0x10014]— offset to the localpagearray, i.e., a write into the first page of the frame (rbpis the frame pointer, covered in lesson 10; the binary is built as PIE by default, so code addresses start at base0x555555554000, which GDB pins for reproducibility).
The process memory map in GDB (info proc mappings) confirms the boundary. The [stack] mapping ends at 0x7ffffffff000, with total size:
The faulting address lies below the start of that mapping.
The [stack] size is 0x7f4000 (about 7.95 MiB) rather than a full 0x800000 (8 MiB) because the VMA grows on demand up to the address that triggered #PF. The next frame allocates 0x10030 bytes and overshoots the remaining limit, so the kernel refuses to grow the VMA at all: the lowest mapped page stays 0xc000 bytes above the theoretical 8 MiB ceiling.
(gdb) info proc mappings
0x00007fffff80b000 0x00007ffffffff000 0x7f4000 0x0 rw-p [stack]strace clarifies the failure reason: SEGV_MAPERR indicates an access to an unmapped address rather than a permissions violation. Addresses in this run differ from GDB due to ASLR; the fault code matters, not the exact number.
--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x7ffe2fc0a97c} ---
+++ killed by SIGSEGV (core dumped) +++What the Kernel Logs in dmesg
strace shows signal delivery to the process, while the kernel separately records the page fault in its ring buffer. For the stack, the key takeaway is simple: it grows down, hits RLIMIT_STACK, and writing to the first page past [stack] raises SIGSEGV, which the shell reports as exit status 139 (). The kernel log format, error field bits, and Code: byte breakdown are tucked into the spoiler below.
Under the hood: how the Linux kernel logs a page fault in dmesg
Two runs of stack_guard_bad produced these lines:
[89587.732258] stack_guard_bad[396617]: segfault at 7ffc5c9e9f2c ip 000056217596a154 sp 00007ffc5c9e9f20 error 6 in stack_guard_bad[1154,56217596a000+1000] likely on CPU 0 (core 0, socket 0)
[89587.732278] Code: 84 00 00 00 00 00 c3 0f 1f 40 00 66 66 2e 0f 1f 84 00 00 00 00 00 f3 0f 1e fa e9 67 ff ff ff 55 48 89 e5 48 81 ec 20 00 01 00 <89> bd ec ff fe ff 64 48 8b 04 25 28 00 00 00 48 89 45 f8 31 c0 8b
[89672.013946] stack_guard_bad[399897]: segfault at 7ffe4c69f26c ip 0000560a67fd7154 sp 00007ffe4c69f260 error 6 in stack_guard_bad[1154,560a67fd7000+1000] likely on CPU 4 (core 2, socket 0)
[89672.013959] Code: 84 00 00 00 00 00 c3 0f 1f 40 00 66 66 2e 0f 1f 84 00 00 00 00 00 f3 0f 1e fa e9 67 ff ff ff 55 48 89 e5 48 81 ec 20 00 01 00 <89> bd ec ff fe ff 64 48 8b 04 25 28 00 00 00 48 89 45 f8 31 c0 8bsegfault at 7ffc5c9e9f2c— the faulting virtual address; matchessi_addrin GDB andstrace.ip 000056217596a154— address of the faultingmovinstruction; the low 12 bits (0x154) match GDB, while upper bits vary with ASLR.sp 00007ffc5c9e9f20— user stack pointer at the time of the fault.error 6— page-fault error code,0b110in binary: bit 0 is zero (page not present), bit 1 is set (write access), bit 2 is set (user mode). That’s a write to an unmapped page rather than a protection violation—matchingsi_code=SEGV_MAPERRfromstrace.
Metadata fields in the line:
in stack_guard_bad[1154,56217596a000+1000]— the mapping containingip: file offset0x1154, base0x56217596a000, size0x1000. Base plus0x154yieldsip.likely on CPU 0andCPU 4— the kernel’s best guess at which core executed the instruction; irrelevant to the fault itself.- In
Code:, the byte in angle brackets (<89>) starts the faulting instruction:89 bd ec ff fe ffdecodes tomov DWORD PTR [rbp-0x10014], edi. The bytes right before it decode aspush rbp; mov rbp, rsp; sub rsp, 0x10020.
The frame math matches GDB. The prologue allocates sub rsp, 0x10020, so rbp = rsp + 0x10020, and the write targets [rbp - 0x10014]. The faulting address is:
In both runs, 0x7ffc5c9e9f2c - 0x7ffc5c9e9f20 = 0xc and 0x7ffe4c69f26c - 0x7ffe4c69f260 = 0xc. GDB shows the same difference: 0x7fffff7fbf5c - 0x7fffff7fbf50 = 0xc; only the base addresses differ due to ASLR.
Common Pitfalls
-
"
pushwithout a matchingpopleaves the frame shifted."
Fact: after twopushes,$rsp == $r15 - 16evaluates to1, and after twopops,$rsp == $r15.
Cause: everypushdecrements$rspby 8, and onlypopor an explicitadd rsp, Nrestores it.
Fix: keeppush/poppairs in reverse order and verify$rspin GDB on function exit. -
“A value in the red zone survives a
call.”
Fact:red_zone_bad.asmstores a constant in[rsp - 8]and calls an empty helper:nasmmov qword [rsp - 8], rax call helper mov rbx, qword [rsp - 8]The program exits with
1, and after the call[rsp - 8]holds0x401014—the return address:text0x7fffffffd6e8: 0x0000000000401014Cause:
callwrites the return address straight to$rsp - 8, the exact same red-zone slot.
Fix: never keep data in the red zone across acall; allocate withsub rsp, Nfirst and restore it before returning. -
“Passing a large object by value pushes the program into swap.”
Fact: recursion with a 64 KiB frame crashes atdepth=126with exit code139before ever touching disk.
Cause: the 8 MiBRLIMIT_STACKlimit runs out after ~128 frames, and the page past the boundary is unmapped.
Fix: shrink the frame, rewrite recursion as a loop, or pass by pointer; only raise the stack limit deliberately.
Lab
Goal. Build stack_probe.asm to verify three stack mechanisms: a push/pop pair, the red zone, and an unchanged $rsp after popping values back.
Contract and requirements.
- Three constants:
0x10,0x20,0x40. - Push the first two, then pop them into two different registers.
- Write the third constant into the red zone at
$rsp - 8and read it back from there. - Exit code is the low byte of the XOR of all three values; do not issue a
callbetween writing and reading the red zone. - Save the initial
$rspin a free register unused by arithmetic and preserved bysyscall(such asr15).
Verification criteria.
./build/stack_probe; echo $?prints the expected byte.- In GDB at a label after the
pops,$rspmatches its initial value. - In GDB at a label before exiting,
$rsp - 8holds0x40. objdump -d -M intel build/stack_probeshows thepushandpopencodings for your chosen registers.
Hints, expected output, and walkthrough
0x10 ^ 0x20 ^ 0x40 = 0x70, so the exit code is 112. Any other result means one of the three paths broke.
The pop order must reverse the push order: if 0x10 was pushed first, it must be popped last; otherwise the registers swap values, and since XOR is commutative, the bug would go unnoticed. Verify each register’s contents at the post-pop label, not just the final XOR.
If $rsp - 8 shows an address like 0x4010xx instead of 0x40, a call slipped in between the write and the read and overwrote the red zone with a return address.
Testbed sources, Makefile, and automated tests for this lesson: lessons/09-stack.
Summary
- The stack is a region of virtual memory whose active boundary is
$rsp. pushdecrements$rspand writes a value;popreads it and increments the pointer back.- A
push/poppair restores$rsp; an unmatchedpushleaves it shifted. - The red zone is 128 bytes below
$rspavailable to leaf functions without adjusting the pointer. calland signal delivery overwrite the red zone because both write below$rsp.- Past
RLIMIT_STACK, the next page is unmapped, and touching it triggersSIGSEGVwith exit code139.
call pushes a return address, the prologue builds a frame, and ret pops the address back. In lesson 10, I dissect call/ret, the rbp frame, and how the compiler turns tail recursion into a loop.