CSE Roadmap

Core tier · about 4 hours · 7 parts

Part 3 of 7 · 1 min read

Growing on demand

In plain words: The stack does not start at its full size of 8 MiB. When a process starts, the kernel creates a stack region of a few dozen pages. When a call touches a page just below the region, a page fault occurs (page 7 of Level 6). The kernel sees that the address is close to the stack, extends the region downward and gives the process a zero page. The program does not notice. This is demand paging used for the stack.

A program that recurses to a depth of 3,000 calls with a frame of about 1,000 bytes shows it. It reads /proc/self/maps and /proc/self/status before and after:

Moment Size of the [stack] region VmStk
At start 148 kB 148 kB
After 3,000 frames of about 1,000 bytes 3,076 kB 3,076 kB

The region grew from 148 kB to 3,076 kB, an increase of 2,928 kB, close to the 3,000 × 1,000 bytes that the frames needed. The growth is not unlimited. Each process has a stack size limit, set by the resource limit RLIMIT_STACK, and shown by ulimit -s in the shell, which gives 8,192 (KiB) here. When the stack would pass the limit, the kernel refuses to extend it, and the process receives SIGSEGV.

Stack size limit

The stack size limit is the largest size to which the kernel will grow the stack of a process, held in the resource limit RLIMIT_STACK (8 MiB by default on most Linux systems, shown in KiB by ulimit -s).

Example: a shell started with ulimit -s 1024 runs its programs with a 1 MiB stack.

Check yourself: 1. How does the stack grow from 148 kB to 3,076 kB? 2. What event triggers the growth? 3. What happens when the limit is reached?