A stack overflow occurs when the stack pointer moves beyond the space reserved for the stack. On a Cortex-M microcontroller, the stack grows downward as functions are called. Deep recursion, a large local buffer, or nested interrupts can exhaust it. section 7.4.1
The stack holds function arguments, local variables, return addresses, and exception frames. In the default cortex-m-rt layout, an overflowing stack can overwrite adjacent .bss or .data storage. The program may continue running with corrupted values, making the failure look like an unrelated bug. section 7.4 section 7.4.1
static mut DEVICE_ID: u32 = 0xDEADBEEF;
fn recurse() {
let _buffer = [0u8; 1024]; // 1 KiB allocated on
// every call
recurse(); // never returns;
// stack keeps growing
}
Each recursive call adds a 1 KiB local buffer; because the calls never return, the stack keeps growing toward static data. section 7.4.1
Use several layers to estimate and detect overflow. Static analysis cannot generally prove the worst-case stack usage: recursion, function pointers, and interrupt nesting limit what it can determine. section 7.4 section 7.5
Practical defenses include:
- Estimate stack use with cargo-call-stack and emitted stack sizes. Treat the estimate cautiously where calls or interrupt nesting cannot be fully analyzed. section 7.5 section 7.4
- Use flip-link to put the main stack at the bottom of RAM. A downward overflow that writes below RAM triggers a fault instead of silently overwriting static data. section 7.4.3
- Paint the stack with a known pattern during startup or use software canaries to help detect overflow and measure usage. section 4.3.3 section 7.5
- Configure an MPU no-access guard at the bottom of a stack. An access into the guard causes a fault; guard regions can also protect individual task stacks. section 7.4.5
cargo install flip-link
# .cargo/config.toml
[target.thumbv7em-none-eabihf]
rustflags = [
"-C", "linker=flip-link",
# ...any other rustflags the project already uses
]
Install flip-link and configure it as the linker for the target. The standard cortex-m-rt memory.x does not need modification. section 7.4.3
flip-link protects the main stack, not each stack allocated within RAM by an RTOS. An MPU guard complements it, but consumes a limited hardware region; its base must meet the required alignment. Configure the fault handler to log registers or break into a debugger so a detected overflow is useful to diagnose. section 7.4.3 section 7.4.5

