CSE Roadmap

Core tier · about 4 hours · 7 parts

Part 5 of 7 · 2 min read

Guard pages

In plain words: Without protection, a stack that ran past its end would write over whatever memory is below it, which is a far worse bug than a crash. The kernel prevents it by keeping a guard, a gap that no other region may enter. If the stack grows into the gap, the access faults, the kernel finds no region there, and the process gets SIGSEGV at once. (On recent Linux kernels, the gap below the main stack is 256 pages, which is 1 MiB, by default.)

Threads need the same, with a difference. The main thread's stack grows on demand, and the stack of every other thread is a fixed region that pthread_create allocates with mmap (Level 2). Its size is set at creation. The test program reports the defaults:

Setting Value on this machine
Default thread stack size 8,388,608 bytes (8,192 KiB), the same as the stack limit
Default guard size 4,096 bytes (one page)

The library puts a guard page, a page with no permissions, at the low end of each thread stack. A thread that runs past the end touches the guard page and gets SIGSEGV, instead of damaging the next thread's stack. The thread stacks are demand paged like everything else: a thread with an 8 MiB stack costs only the pages it touches, but the address space is reserved. A program with 1,000 threads reserves 8 GiB of address space, which is allowed because of overcommit (page 7). To make threads cheaper, a program can set the stack size with pthread_attr_setstacksize before the thread is created.

Guard page

A guard page is a page with no access permission placed next to a stack (or another buffer) so that any access that runs over the end faults at once instead of silently damaging the memory beyond.

Example: each thread stack made by pthread_create has a 4,096-byte guard page at its low end by default.

Check yourself: 1. What does a guard page protect against? 2. How is a thread stack different from the main stack in how it is created? 3. Does a thread with an 8 MiB stack use 8 MiB of memory?