Section 4.10

Stack overflow

Definition

A stack overflow is the error in which a thread’s stack needs more memory than the region reserved for it. The stack is the memory where a thread keeps one frame for each function call still in progress; a frame holds the call’s local variables, saved register values and return address. Each call adds a frame and each return removes it. When the frames present at one moment exceed the region, the newest frame extends into other memory, unless hardware stops the access with a fault.

The idea

A thread on a microcontroller §6.1 runs with a stack of 1 KiB, where a desktop thread usually has 1 MiB or more. Most of the time the thread uses half of its stack. Once a week, an error is logged while a long message is being parsed, at the moment an interrupt §6.11 arrives. That combination needs more than 1 KiB, and the frame at the deepest point overwrites the memory next to the stack: perhaps another thread’s stack, perhaps a variable. Nothing fails at that moment. The damage shows up later, somewhere else.

A pile of plates under a shelf is a fair picture. Each call puts a plate on the pile and each return takes the top plate off. What matters is the greatest height the pile ever reaches, not how many plates pass through it in a day: a thousand calls made one after another never pile up. The picture stops being accurate in one respect. A pile that reaches the shelf stops visibly. A stack that reaches the end of its region keeps going into the neighboring memory, unless something has been placed there to stop it.

How it works

Three parts are involved.

The stack depth at a moment is the sum of the frames present at that moment. Three things decide the greatest depth.

  1. The deepest call path. In the call graph, each function points to every function it can call. A path runs from the thread’s entry function, where the thread starts, down to a function that calls nothing. The demand of a path is the sum of its frame sizes, and the deepest path is the one with the largest sum. It need not be the path with the most calls: one function with a large local array §14.5 can outweigh five small ones. Calls made one after another do not add up, because each frame is gone before the next call starts.

  2. Recursion. A function that calls itself, directly or through other functions, adds its frames again at every level. The depth is bounded only if the number of levels is bounded, and that number is often set by the input, such as how deeply the elements of a received message are nested.

  3. Interrupts and exceptions. An interrupt is a signal, usually from a hardware device, that makes the processor suspend the running code and run a handler; an exception, such as a fault, works the same way. The processor saves the interrupted state, and the handler needs frames of its own. Whether these land on the interrupted thread’s stack depends on the processor and the operating system. If handlers of higher priority can interrupt handlers §6.12 of lower priority, which is called nesting, the worst case puts one handler of each priority level on top of the deepest thread path.

Arm Cortex-M processors, common in microcontrollers, split the interrupt demand between two stacks. On an interrupt, the processor saves 8 registers, 32 bytes, onto the stack in use, which under a typical real-time operating system is the interrupted thread’s stack; with floating-point registers to save as well, it saves 104 bytes, and it may add 4 bytes of padding to keep the stack aligned to 8 bytes. The handler then runs on a separate main stack, where nested handlers also go. So every thread stack must leave room for one saved state, and the main stack must hold the deepest nesting of handlers.

Two methods find the depth.

The static analysis must settle four hard cases.

Detecting an overflow at the moment it happens needs something at the end of the region.

Worked example

A thread has a stack of 1024 bytes. The compiler reports these frame sizes, in bytes: main_loop 48, handle_msg 160, parse 320, checksum 64, send 200, log_error 96 and format 400. The calls are as follows: main_loop calls handle_msg or log_error; handle_msg calls parse and, after parse has returned, send; parse calls checksum; log_error calls format. The three paths are:

The deepest path needs 592 bytes, and it does not contain the largest frame, the 400 bytes of format. The sum of all seven frames, 48+160+320+64+200+96+400=128848 + 160 + 320 + 64 + 200 + 96 + 400 = 1288 bytes, is not the demand, because send runs only after parse has returned, and the two branches of main_loop are never active together.

Suppose this processor runs interrupt handlers on the interrupted stack and has two interrupt priority levels. The low-priority handler needs 152 bytes, saved state included. The high-priority handler needs 232 bytes and can interrupt the low-priority one. Neither can interrupt itself. The worst nesting adds 152+232=384152 + 232 = 384 bytes, so the peak is 592+384=976592 + 384 = 976 bytes, which leaves 1024−976=481024 - 976 = 48 bytes to spare.

Now a new message format lets an element contain another element, and parse calls itself for the inner one. With one level of nesting, the deepest path is main_loop, handle_msg, parse, parse, checksum: 592+320=912592 + 320 = 912 bytes. With both interrupts on top, the peak is 912+384=1296912 + 384 = 1296 bytes, which exceeds the 1024-byte stack by 1296−1024=2721296 - 1024 = 272 bytes. The overflow happens only when a nested message is being checked while both interrupts are active. With dd levels of nesting the thread path alone needs 592+320d592 + 320 d bytes, so from d=2d = 2 on the stack overflows even without interrupts: 592+320×2=1232592 + 320 \times 2 = 1232 bytes.

A test that sends only messages without nesting, and in which no interrupt happens to arrive at the deepest point, reports a high-water mark of 592 bytes. That number is true for the test, and it is 1296−592=7041296 - 592 = 704 bytes short of the worst case with one level of nesting.

Frame sizes come from the compiled code, not from the declarations. GCC 13, compiling for x86-64 with the optimization option -O2, reported a function big whose only local variable is a 300-byte array with the line s.c:1:6:big 336 static in its .su file. The line gives the file, line and column, the function name, a frame of 336 bytes, and the word static, meaning that the size is fixed at compile time. The 36 bytes beyond the array are space the compiler added, such as alignment §4.22 padding and saved values.

Stated precisely

Let GG be the call graph of one thread: its nodes are functions, and it has an edge from ff to gg when ff can call gg. Let frame(f)\mathrm{frame}(f) be the number of bytes that the compiled function ff adds to the stack. If GG has no cycles, the greatest demand of a call of ff, counting the calls it makes, is D(f)=frame(f)+maxg called by fD(g),D(f) = \mathrm{frame}(f) + \max_{g \text{ called by } f} D(g), with the maximum taken as 0 when ff calls nothing. The thread needs D(e)D(e) bytes, where ee is its entry function.

Let the interrupt handlers that run on this stack have PP priority levels, and let HpH_p be the set of handlers at level pp. Let cc be the number of bytes the processor saves on entry to a handler, alignment padding included. If a handler can be interrupted only by a handler of a strictly higher level, the worst nesting holds at most one handler of each level, and the interrupt demand is I=∑p=1Pmaxh∈Hp(c+D(h)).I = \sum_{p=1}^{P} \max_{h \in H_p} \bigl(c + D(h)\bigr). A stack of SS bytes cannot overflow if D(e)+I≤SD(e) + I \le S. On a processor that runs handlers on a separate stack, as Cortex-M does, the thread’s stack needs D(e)+cD(e) + c bytes instead, and the same reasoning bounds the separate stack.

The bound holds under five assumptions.

  1. Complete call graph. GG contains every call that can happen, including indirect calls through function pointers, calls into libraries and calls from assembly code.

  2. Frame sizes of the running build. Each frame(f)\mathrm{frame}(f) comes from the same build, with the same compiler, version and options, as the program that runs.

  3. No unbounded stack allocation. Every variable-length array and every call of alloca has a known largest size, included in its frame.

  4. Bounded recursion. Each cycle in GG has a stated largest number of levels and is counted that many times.

  5. Known nesting. The priority levels, and the rule that only a strictly higher level can interrupt, hold as stated.

Under these assumptions D(e)+ID(e) + I is an upper bound on the stack depth. A measured high-water mark WW is a lower bound: it is the greatest depth that the measured runs actually reached. The true worst case MM therefore satisfies W≤M≤D(e)+IW \le M \le D(e) + I.

Limits and common mistakes

A high-water mark is not a bound. It covers only the paths, inputs and interrupt timings that occurred during the runs. It can even miss part of what did occur: a function that reserves a large array but writes only part of it can leave the deepest bytes holding the pattern, and a byte written with a value equal to the pattern looks unwritten.

A static bound can be too large, or wrong. It counts paths that may never run together, so it is usually larger than any measurement; that is the price of covering every path. It is wrong, meaning too small, if the call graph misses a target of an indirect call or if the analyzed build differs from the one that runs.

A guard catches only what touches it. A function whose frame is larger than the guard region can move the stack pointer past the whole guard and then write beyond it without ever touching it. This is known as a stack clash. GCC’s option -fstack-clash-protection makes a function with a large frame touch the stack at regular steps while reserving the frame, so that the guard is always hit.

A stack overflow is not a buffer overflow §4.4. A buffer overflow writes past the end of one array, and the array may sit on a stack with room to spare. The compiler’s stack protector (GCC’s option -fstack-protector) places a canary next to the return address in each frame and checks it before the function returns. It detects that buffer overflow inside one frame, not the stack running out of room.

Optimization changes frame sizes. Inlining, in which the compiler copies a called function into its caller, merges two frames into one, and the merged frame can be larger than either. A build without optimization often uses much more stack than an optimized one. Analyze and measure the build that runs.

Recursion driven by input is a known weakness. A parser that recurses once for each level of nesting in its input lets the sender choose the stack depth. The CWE (Common Weakness Enumeration), a public catalog of software weaknesses, lists this as CWE-674, uncontrolled recursion. The repair is a limit on the depth, checked before each recursive call, or a loop with an explicit work stack of fixed capacity.

An interpreter §2.13 has two stacks. A VM §2.3 (virtual machine), a computer defined in software, keeps the stack of the guest program it runs in memory of its own. A bound on that guest stack §2.25 says nothing about the native stack of the thread that runs the interpreter and the routines it calls.

Questions answered

Which call path, recursion, or interrupt nesting produces the deepest stack?

The deepest stack comes from the combination that puts the most bytes on the stack at one moment: the call path from the thread’s entry function whose frames add up to the most bytes, with each recursive cycle repeated as many times as it can repeat, plus the deepest chain of nested interrupt handlers that can run on the same stack at that moment. A frame is the memory one function call occupies on the stack, and its size comes from the compiled code, not from counting calls or local variables in the source. The path with the most calls, or with the largest single frame, is not necessarily the deepest.

Find the combination by static analysis: take each function’s frame size from the compiler (for GCC, the GNU Compiler Collection, the option -fstack-usage), walk the call graph to find the path with the largest sum, include every possible target of indirect calls, require a stated largest depth for every recursion, and add one handler for each interrupt priority level that can nest, with the processor’s saved state for each. Confirm with stack painting, which fills the stack with a known pattern and reports the deepest byte overwritten. That high-water mark is only a lower bound, because it shows only what the test runs reached.

Related entries: VM stack (§2.25), Buffer overflow (§4.4), Static, stack, and heap storage (§4.11), Memory protection unit (MPU) (§6.8), Exception and fault handler (§6.15), Static analysis (§3.1).