Step 52 of 56
Stack usage: measuring what analysis cannot see
Static worst-case analysis cannot see the prebuilt runtime, the C startup, ISRs or hand-written assembly. Painting the stack can.
How it works
Fill the unused part of a stack with a sentinel word, run the workload, then scan for the lowest word the program actually overwrote. The gap between that and the top is the peak depth ever reached.
This is the measured counterpart to the static
x stack worst-case analysis — and it is the only way to
account for the parts static analysis structurally cannot see: the prebuilt
runtime, the C startup, interrupt service routines, and hand-written
assembly.
The direction of the error
A sentinel-valued word that the program legitimately wrote looks pristine, so the scan stops at the first overwritten word from the bottom. That means it can only ever be conservative: it never under-reports the peak. Read the figure as "at least this much was used", never as an exact high-water mark.
The measurement is only as good as the workload. A run that never takes the deep path reports a comfortable number that means nothing about the path you did not exercise — so drive a real workload, including the error paths and the interrupt load, before believing the headroom.
Why both approaches
Use the static analysis to find the theoretical worst case in code it can see, and this to catch what it cannot. Agreement between them is meaningful evidence; a measured figure that exceeds the static bound means the static model is missing a path, which is worth knowing before it is a stack overflow on hardware.
The runtime already guards the running task with a hardware watchpoint a redzone above its stack limit, re-armed on every context switch (step 44). That catches an overflow precisely when it happens; this tells you how close you were before it did.