Stack size is the memory a program needs for its active execution path, including nested calls and interrupt handling. In embedded firmware, compare peak demand with the stack region available in RAM. section 7.4.2
Estimate or measure stack use with complementary checks:
- Use cargo-call-stack to estimate per-function maxima and the deepest call path. Its estimate can miss indirect calls and does not combine interrupt depths with the code they preempt, so treat it as a lower bound and leave a safety margin. section 7.4.2
- Fill unused stack with a recognizable canary pattern, then inspect it later to measure how much was overwritten. This captures actual use during observed runs, at the cost of a startup write and periodic checks. section 7.4.4
cargo +nightly call-stack --target thumbv7em-none-eabihf --bin myapp > cg.dot dot -Tsvg cg.dot > cg.svg
Run the call-stack analysis on a nightly-built release binary with LTO, then render its call graph for inspection. section 7.4.2
extern "C" {
static mut _stack_bottom: u32; // lowest address the stack should use
static _stack_start: u32; // highest address (initial SP)
}
const CANARY: u32 = 0xDEAD_BEEF;
/// Fill the unused stack region with a known pattern.
/// Call this once at the start of `main`, before any code that uses
/// significant stack space.
unsafe fn paint_stack() {
let bottom: *mut u32 = &raw mut _stack_bottom;
let top: *const u32 = &raw const _stack_start;
// Walk from the bottom of the stack upward to just below the
// current stack pointer, leaving a small safety margin so we
// do not overwrite live frames.
let mut p = bottom;
while (p as *const u32) < top {
p.write(CANARY);
p = p.add(1);
}
}
/// Return the number of 32-bit words still showing the canary pattern.
/// Multiplied by 4, this gives the amount of unused stack in bytes.
unsafe fn unused_stack_words() -> usize {
let bottom: *const u32 = &raw const _stack_bottom;
let mut p = bottom;
let mut count = 0;
while p.read() == CANARY {
count += 1;
p = p.add(1);
}
count
}
This canary implementation paints the stack region with a known pattern so later checks can find the high-water mark. section 7.4.4
