Embedded HandbookApps
All sections › II. Core and system mechanisms
STM32F405, STM32F407, STM32U585 · level intermediate · 16 min read
Open in the interactive handbook

11г. Stack overflow protection: how the stack crosses its boundary, how to catch it and how to prevent it

The handbook speaks about stack overflow in several places, and each time briefly. Section 11.4 warns that on M3 and M4 it gives no error. Section 11а puts an MPU guard under the stack, 66.7 shows the MSPLIM limit of the Cortex-M33, 12б puts a canary at the bottom of the stack, 35.4 and 26.7 measure the stack of a FreeRTOS task, 129.8 turns on frame protection in armclang. The whole picture is nowhere: which of these catches the overflow before the damage, which after it, which does not catch it at all, and what each method costs.

Here all the methods are gathered on one small firmware. It deliberately overflows the stack by recursion, and runs in QEMU show what happens: without protection, with a canary, with frame protection, with an MPU guard, with the stack at the bottom of RAM and with the Cortex-M33 stack limit. Plus two things that are needed before any trap: how to estimate the stack size before running and how to measure its use on a working board.

Sources: 11.4 (stack and heap), 11а (MPU and the guard), 7а (the exception frame), 35.2 and 35в (fault analysis and a record that survives a reset), 35.4 and 26.7 (the FreeRTOS task stack), 2е (MSPLIM with TrustZone), 12б (the canary in the self-test), 126.9 (stack alignment). The experiment is in the stm-arm:1 image: arm-none-eabi-gcc 12.2.1, QEMU 7.2.22, the machines netduinoplus2 (STM32F405, Cortex-M4) and mps2-an505 (Cortex-M33); FreeRTOS 11.2.0 from the CMSIS-FreeRTOS pack.

Terms used in the documentation

Term Meaning
stack overflow the stack grows past its area
stack usage, -fstack-usage, .su stack use, the GCC option and the file with frame sizes
call graph, worst-case stack depth the call graph, the largest stack depth
high water mark the largest use over the whole run time
stack canary, guard word a canary, a check word
stack protector, __stack_chk_guard, __stack_chk_fail frame protection, its check word and its handler
guard region an MPU guard region
stack limit registers MSPLIM, PSPLIM the ARMv8-M stack lower-bound registers
STKOF (UFSR) the stack overflow flag in UsageFault
MSTKERR, STKERR a failure to write the frame on exception entry (MemManage, BusFault)

11г.1 How the stack overflows and why silently

The stack on Cortex-M grows down: from _estack towards lower addresses. In the usual linker-script layout (4в) below it lie the heap, .bss and .data — the program's variables. Each push instruction and each sub sp simply decreases SP, and a write to the new address is an ordinary write to RAM. There is memory there, and without an MPU there are no access rights, so the core notices nothing: the stack silently runs over other variables.

Four RAM layouts and where a stack overflow goes in each: with the usual layout the write lands in .bss and .data with no fault; with an MPU guard under the stack it is a MemManage fault on the first write to the guard; with the stack at the bottom of RAM it is a bus fault, because there is no memory below 0x20000000; with the ARMv8-M PSPLIM limit it is a UsageFault STKOF, and the stack pointer does not go past the limit

The experiment is _verify/stk11e/stk11e.c. Under a 1 KB stack lie 32 bytes of a "guard" and 128 bytes of "other data" (victim), filled with known words. Recursion on the task stack (PSP) goes down level by level:

__attribute__((noinline)) uint32_t dive(uint32_t n, uint32_t max)
{
    volatile uint8_t buf[64];
    uint32_t sp;
    __asm volatile("mov %0, sp" : "=r"(sp));
    for (uint32_t i = 0; i < sizeof buf; i++)   /* весь кадр в работе, как у настоящего буфера */
        buf[i] = (uint8_t)n;
    depth = n;
    if (!first_cross && sp < (uint32_t)&area.guard[GUARD_WORDS])
        first_cross = n;
#ifdef MODE_CANARY
    cal_loop(100u);                  /* 200 команд на уровень: тики SysTick приходят по ходу рекурсии */
#endif
    if (n >= max || sp < stop_sp)
        return buf[0];
    return dive(n + 1u, max) + buf[63];
}

The dive frame is 72 bytes (the .su file, 11г.2). The level with number 14 — the fifteenth call — is already below the stack. The run without protection: the recursion returned as if nothing had happened (returned, no fault), all 8 words of the guard and 23 words out of 32 of the "other data" are overwritten, the top word of victim now holds 0x0e0e0e0e — the bytes of level number 14. The program keeps working with damaged variables, and it will break in a place unrelated to the cause.

What leads to an overflow:


11г.2 How much stack is needed: an estimate before running

The compiler gives the size of each frame. The -fstack-usage option writes a .su file next to the object file: function, bytes, kind. For the experiment:

stk11e.c:75:36:dive 72  static
stk11e.c:218:33:copy_packet 16  static

static means the size is constant; dynamic means it depends on data, as in a function with a variable-length array. Two warnings catch large frames already at build time: -Wstack-usage=N and -Wframe-larger-than=N. On the teaching program _verify/stk11e/callg11e.c with thresholds of 160 and 128 bytes:

callg11e.c:60:32: warning: stack usage is 168 bytes [-Wstack-usage=]
callg11e.c:65:1: warning: the frame size of 160 bytes is larger than 128 bytes [-Wframe-larger-than=]
callg11e.c:110:32: warning: stack usage might be unbounded [-Wstack-usage=]

The first two are log_line with a 160-byte line buffer; the third is the variable-length array in pad_vla: in .su it has 8 dynamic.

The program's use is the worst path through the call graph. Each path from main down is the sum of the frames on it; the largest one is needed. Keil computes this by itself (66.7, 35.4); for GCC here is the script callgraph11e.py: frames come from .su, edges come from the bl instructions in the disassembly. The teaching program contains everything that gets in the way of counting: formatted output, a call through a table of pointers and recursion. Here is what the script sees by itself:

worst main > parse > walk = 64 bytes
cycle: walk > walk
indirect call in dispatch: targets unknown

64 bytes is not true. dispatch calls a command through a pointer (bx r3), and the target is not visible in the code. If you give the targets by hand, the path is different:

worst main > parse > dispatch > cmd_status > log_line > fmt > vfmt > fmt_u = 412 bytes

The error is six-fold, and almost all of it is the command and the formatted output under it: 104 + 168 + 12 + 48 + 32 bytes. Two caveats remain with any tool. Recursion (walk) gives a cycle: only the author knows its depth, and it is bounded explicitly. Calls through a pointer have to be written in by hand — without them the graph counts less than there is.

Interrupts are added to the worst path. On exception entry the core puts a frame on the current stack (7а). The experiment measures it with an SVC call from PSP: 32 bytes without FPU context and 36 if SP was not a multiple of 8; after the first FPU instruction — 104 and 108 bytes. On top come the frames of the handler itself. Without an RTOS all handlers run on the main stack, and with nesting each priority level adds an exception frame and the stack of its handler: as many preemption levels as are allowed, that many layers. With an RTOS a task on PSP gets only one frame — the first one, the rest goes to MSP. So the stack of each task is counted as "the task's worst path + 104–108 bytes" (with FPU), and the main stack as the sum of the handlers' worst paths over all nesting levels.


11г.3 How much stack is really used: the high water mark

An estimate needs a check on the board. The method is old: at startup fill the stack with a known word and later count how many words from the bottom stayed untouched. The use is everything else. In the experiment the stack is filled with 0xA5A5A5A5, then the recursion goes 0, 4 and 8 levels deep:

water depth=0 untouched_words=238 used_bytes=72
water depth=4 untouched_words=166 used_bytes=360
water depth=8 untouched_words=94 used_bytes=648

Every four levels add another 288 bytes, exactly 4 × 72: the measurement matched .su. The fill shows the largest use over the whole time, not the current one: an overwritten word does not come back. For it to mean something, the device is run under the worst load — all branches, all interrupts; a quarter of the stack is considered a healthy margin (35.4).

FreeRTOS has the same thing built in: a task stack is filled at creation with the byte 0xa5, and uxTaskGetStackHighWaterMark counts the untouched part in words (26.7). The experiment rtos11e.c — a task with a 256-word stack after recursion 0, 4 and 8 levels deep:

rtos depth=0 watermark_words=221
rtos depth=4 watermark_words=149
rtos depth=8 watermark_words=77

The difference is 72 words per four levels, the same 288 bytes.


11г.4 Traps after the fact: the canary, FreeRTOS checks, frame protection

The canary. A few known words are put under the stack and checked from time to time (in 12б.6 — four words in each self-test pass). In the experiment the canary is 8 words of 0xC0DEC0DE, the check is in the SysTick interrupt. It fired on the fifth tick, at level 14: all 8 canary words are overwritten, and 14 words of the "other data" are already overwritten too. The canary reports the fact but does not stop the damage: time passes between the write and the check.

FreeRTOS checks. configCHECK_FOR_STACK_OVERFLOW turns on a check at every task switch (stack_macros.h). Method 1 compares the saved stack pointer with the bottom: it catches only if the task at the moment of the switch is below the boundary. Method 2 in addition compares with 0xa5a5a5a5 four words at the bottom — 16 bytes. The experiment: the task hog with a 128-word stack goes 7 levels deep by recursion, past the bottom, returns and goes to sleep.

Method Trap Words overwritten under the stack
1 did not fire (hook_called=0) 19
2 vApplicationStackOverflowHook, task hog 19

Method 1 missed the overflow entirely: by the switch the stack had already come back. Method 2 saw it — but also after 19 words under the stack were lost. So method 2 is used during development, and the margin is still measured in advance (35.4).

Frame protection -fstack-protector-strong is about something else. It puts the check word __stack_chk_guard into the frame of a function with a local array and compares it before the return; on a mismatch __stack_chk_fail is called (129.8). It protects the return address from a write past the end of its own array. In the experiment copy_packet with a 16-byte buffer copies 24:

copy16=17
stack_chk_fail_lr=0x08000417

The return address in LR points inside copy_packet — the culprit is found. But the same protection does not see a stack overflow by recursion: each frame is entirely its own, the check words are intact. The run with the option: the recursion returned without a fault, 30 words of the "other data" are overwritten. The price of the option for copy_packet: code 50 → 88 bytes, frame 16 → 32 bytes, 11 extra instructions (5 on entry, 6 on exit). In QEMU a call is 83 instructions without the option and 94 with it, 13 % more. Clock cycles on the chip were not measured.


11г.5 Traps at the moment of the write: the MPU guard, the stack at the bottom of RAM, MSPLIM and PSPLIM

The MPU guard (11а.4) is a "no access" region under the stack. The experiment puts it on the same 32 bytes:

    MPU_RNR = 0;
    MPU_RBAR = (uint32_t)area.guard;            /* база кратна размеру области */
    MPU_RASR = (1u << 28) | (0u << 24) | ((uint32_t)(31 - __builtin_clz(GUARD_WORDS * 4u)) - 1u) << 1 | 1u;
    kv("guard_bytes", GUARD_WORDS * 4u);       /* XN, AP=0 «нет доступа», размер 2^(SIZE+1), вкл */
    MPU_CTRL = (1u << 2) | 1u;                  /* PRIVDEFENA + ENABLE */
    __asm volatile("dsb \n isb");
Guard Fault CFSR MMFAR PSP "Other" words overwritten
32 bytes MemManage 0x00000082 0x20000180 — start of the guard 0x20000148 — below the guard 14
128 bytes MemManage 0x00000092 0x200001c8 0x200001a8 0

The 32-byte guard did not save the data: the dive frame is 72 bytes, sub sp stepped over the whole guard, and the fill loop began writing from the lowest address of the frame — below the guard. The fault came, but only when the writes reached the guard from below, and 14 words were already lost. The 128-byte guard is larger than the frame — the very first write hit it, the "other data" are intact. The rule: the guard is no smaller than the largest frame from .su. In the CFSR of the second run the bit MSTKERR (0x10) was added: the exception frame also did not fit on the PSP that lay in the guard. The handler works on the main stack, and that does not bother it. The region size on M3/M4 is a power of two from 32 bytes, the base is a multiple of the size; on M0+ the smallest region is 256 bytes, on M33 a region is set in steps of 32 bytes (11а).

The stack at the bottom of RAM. If you put the stack first, from 0x20000000, there will be no memory under it at all. The linker script change is one section before all the others (m4low.ld):

SECTIONS
{
  .stack (NOLOAD) : { _sstack = .; . += 0x400; _estack = .; } > RAM   /* первым: с 0x20000000 */
}
INCLUDE sect11e.ld

The run on the main stack: at level 12 a BusFault, CFSR = 0x00009200 (PRECISERR, STKERR, BFARVALID), BFAR = 0x1ffffff8, SP = 0x1fffffd8. The variables above the stack are intact — the overflow cannot reach them at all. The price is zero bytes and zero cycles, but the method protects only one stack: RTOS task stacks lie in .bss and stay unprotected.

MSPLIM and PSPLIM on ARMv8-M. On the Cortex-M33 (STM32 L5, U5, H5, C5) and M55/M85 each stack pointer has a lower bound. An instruction that would move SP below it is not executed, and the core raises a UsageFault with the flag STKOF. In the experiment on mps2-an505:

    __asm volatile("msr psplim, %0" :: "r"(&area.stack[0]));   /* предел — дно стека */

The fault is a UsageFault, CFSR = 0x00100000 (STKOF), level 13, PSP = 0x380001a0 — exactly the bottom of the stack. The guard and the "other data" are untouched: not a single write below the limit. This is the only method that stops the overflow before the write and needs not a single byte of RAM. For the main stack the limit is set in the startup code (__set_MSPLIM, 2е, 66.7), for tasks at every switch. The FreeRTOS port for the Cortex-M33 does this by itself: in portasm.c the PSPLIM value is saved together with the task context (mrs r2, psplim) and restored on return to it (msr psplim, r1). M3/M4/M7 have no such registers.


11г.6 What to do in the handler and which method to choose

The stack is already damaged — do not trust it. When the fault is caused by an overflow of the main stack, the handler gets the same overflowed stack: its very first write to the stack gives a new fault (11а.4). So the first instruction of the handler is a switch to its own stack, reserved in advance; only then C:

__attribute__((naked)) void Fault_Entry(void)
{
    __asm volatile("mrs r0, psp \n"
                   "mov r1, sp \n"
                   "ldr r2, =fault_stack+512 \n"
                   "msr msp, r2 \n"
                   "b fault_c \n");
}

Then — a minimum of code: write a trace into the .noinit section, which the startup code does not zero, and restart the chip (35в). The trace is the exception number, CFSR, the address from MMFAR or BFAR, the stack pointer, the task (in the experiment, the recursion depth). The MPU guard is removed before counting, otherwise the handler runs into it itself. After the reset the firmware finds the record:

boot after fault
exc=4
cfsr=0x00000092
guard=0x20000180
mmfar=0x200001c8
psp=0x200001a8
depth=13
guard_bad=0
victim_bad=0

Continuing to work after an overflow is not allowed: it is unknown what else was overwritten.

Comparison of the methods (the numbers come from the runs of this section):

Method When it catches RAM Time Cores
.su and the call graph before running; recursion and pointers by hand 0 0 all
high water mark does not catch — measures the largest use 0 counting words now and then all
canary at the next check, after the damage (14 words) 32 bytes a check in the tick all
FreeRTOS, method 1 only if SP is below the bottom at the moment of the switch 0 at the switch all
FreeRTOS, method 2 at the switch, by 16 bytes at the bottom; after the damage (19 words) 0 at the switch all
-fstack-protector-strong on return — only a write past its own array; does not see recursion +16 bytes of frame +11 instructions per call all
MPU guard on the first write to the guard, if it is no smaller than the frame 32 bytes is too little, 128 was enough 0 M3/M4/M7, M0+, M33
stack at the bottom of RAM on the first write below RAM 0 0 all, the main stack only
MSPLIM, PSPLIM before the write: SP does not go past the limit 0 0 M33, M55, M85

The order in practice: estimate by .su and the graph, check with the high water mark under the worst load, give a margin — and set a trap that fires at the moment of the write: the stack limit on M33, the MPU guard on M3/M4 (for the main stack it is even simpler: the stack at the bottom of RAM). The canary and the FreeRTOS checks stay as diagnostics: they name the culprit, but no longer save the memory.


11г.7 Pitfalls

There is an MPU guard, but the data under it are damaged. The frame is larger than the guard: sub sp steps over it, the write goes below. The guard is no smaller than the largest frame from .su.

The canary is intact, but the data are damaged. A function with a large array that it does not write in full steps over the canary in the same way as over the guard (11а.4).

The FreeRTOS trap is silent, but memory is being damaged. Method 1 sees only the position of SP at the moment of the switch. Method 2 is needed — and a margin all the same.

-fstack-protector-strong is on, but recursion still damages data. The option guards the return address against its own array, not the stack boundary.

The fault handler itself falls into HardFault. It runs on the same overflowed stack; the first instruction must switch to its own stack.

After the guard was turned on, the handler ran into it during analysis. The guarded memory can be read only after the MPU region is removed.

The call graph gave too little. A call through a pointer or a tail call bx rN — the targets are not visible; recursion is a cycle without a depth.

A task "with a margin" fails in the field. The stack was measured without interrupts; the exception frame with FPU is 104–108 bytes on the task stack.

uxTaskGetStackHighWaterMark returned 77 — it looks small. These are words: 308 bytes.


11г.8 Summary

Next: section 12 "Service blocks" — watchdog timers, hardware CRC and the real-time clock.

Open in the interactive handbook