HomeAbout UsContact Us

Fixing Rust HardFaults: Stack Overflow Detection with MSPLIM

By Jithin Tom
November 22, 2026
14 min read
Fixing Rust HardFaults: Stack Overflow Detection with MSPLIM

Table Of Contents

01
The Silent Corruption Problem
02
Compiler Optimization Profiles and Stack Frame Dynamics
03
MSPLIM: Hardware Stack Limit on ARMv8-M
04
Implementing MSPLIM Guard in Rust
05
Trapping and Diagnosing the STKOF Fault
06
Per-Core Guards on Dual-Core Architectures (RP2350, nRF5340)
07
On-Device Stack Telemetry
08
Comparison: flip-link vs MSPLIM vs MPU vs Canaries
09
Common Pitfalls and Failure Modes
10
Verification and Diagnostics
11
Summary
12
Related Reading
13
References
14
Frequently Asked Questions

A bare-metal embedded Rust program may reset or enter a HardFault without first invoking its Rust panic handler. Stack exhaustion is one possible cause: on a typical downward-growing main stack, excessive use can collide with other RAM allocations and corrupt unrelated state. HardFaults also have many other causes, so the diagnosis must be based on register evidence and the board’s memory layout, not merely on a missing panic message.

On supported ARMv8-M Mainline cores (for example Cortex-M33), the MSPLIM (Main Stack Pointer Limit) register can detect downward MSP limit violations. The processor can report STKOF in the UsageFault status register, but exception stacking and fault-handler execution are not guaranteed to succeed after stack exhaustion. Armv8-M Baseline/Cortex-M23 has important differences, particularly for Non-secure execution. This guide explains the limits of stack-limit hardware, the relevant Rust runtime interfaces, linker allocation, per-core configuration, and practical diagnostics. Code fragments are integration examples that require target-specific verification.

The Silent Corruption Problem

On many bare-metal Cortex-M projects, the initial Main Stack Pointer (MSP) points near the high end of a RAM region and grows toward lower addresses. Initialized .data, zero-initialized .bss, and other writable sections are generally placed at lower addresses. The exact placement is a linker-script decision, not a universal architectural layout.

+----------------------------------------------------------------------+
| Illustrative descending main-stack layout (not to scale) |
| |
| Higher addresses: initial MSP / stack top |
| | |
| v Stack grows toward lower addresses |
| [Main stack: current frames and reserved capacity] |
| [Unused space reserved for the main stack] |
| [Configured stack bottom / lower boundary] |
| [Other RAM allocations: .bss, .data, heap, etc.] |
| Lower addresses: RAM origin |
+----------------------------------------------------------------------+

Without an enforced lower bound, excessive stack use can collide with other allocations. On ARMv6-M/ARMv7-M, an MPU region or a deliberately flipped link layout can help detect this before unrelated state is overwritten. ARMv8-M Mainline processors add hardware stack-limit registers that can detect certain downward stack-pointer limit violations; they do not replace all other memory-safety checks.

How Corruption Manifests in Practice

A deep call path, recursion, large automatic arrays, and nested interrupts can consume more stack than the linker budget allows. The main stack is always used in Handler mode; Thread mode may use MSP or the Process Stack Pointer (PSP). In an RTOS, each thread may have a distinct PSP stack even while interrupt handlers consume MSP. Embassy async task futures typically live in statically allocated executor storage; that does not make the synchronous call and interrupt stacks free of overflow risk.

An overflow may damage task metadata, buffered messages, or a saved return address and manifest later as a BusFault, HardFault, unexpected reset, or silent application malfunction. Such symptoms are not proof of an overflow: investigate invalid pointers, memory protection, and peripheral access as well.

Why Traditional Debugging Misses This

Logging and fault reporting use stack and may fail if the active exception stack is exhausted. Conventional data watchpoints can catch writes at selected addresses but cannot provide a general stack-bound guarantee; some systems can also halt on writes before the application observes a failure. Stack canaries, RTOS stack high-water marks, and compiler stack-protector instrumentation can catch some overruns, but each has blind spots.

Stack-limit registers are a useful early fault detector, not a guarantee of a usable exception frame. A limit violation during normal instruction execution or exception entry may itself interfere with reliable exception stacking. Keep a debugger-accessible fault path and, where necessary, use a separately planned emergency fault stack or a reset-based strategy.

Compiler Optimization Profiles and Stack Frame Dynamics

Stack usage depends on the emitted machine code: optimization, inlining, register spills, alignment, recursion, interrupt nesting, and the particular async executor all matter. Higher optimization does not monotonically decrease stack usage. Compare builds and measure the actual firmware with the intended target, features, and linker configuration.

Stack Coloring in LLVM

LLVM can reuse stack slots whose lifetimes do not overlap and can avoid stack objects altogether when values fit in registers. Its IR and machine-level stack optimizations do not imply that every debug local occupies a separate slot, and there is no universally valid “3x to 5x” debug-versus-release stack ratio.

opt-level = 0 commonly retains more intermediate values and less-optimized frames, whereas optimized builds can also create larger frames through inlining or unrolling. Inspect disassembly, debug information, and compiler-generated stack-size metadata where available.

The Impact of Size Optimization (opt-level = "z")

Cargo’s opt-level = "z" requests very aggressive size optimization. It can change inlining and code layout, but it does not guarantee that any specific wrapper remains a call or that maximum stack depth increases. An inlined function can remove a call frame, yet its merged local lifetimes can also increase the caller’s frame size. The net stack effect is program- and compiler-specific.

// Illustrative call structure: whether calls are inlined is not guaranteed.
fn process_sensor_packet(raw: &[u8]) -> Result<DataPoint, Error> {
let framed = decode_framing(raw)?;
let checked = verify_checksum(&framed)?;
parse_payload(&checked)
}

The DataPoint, Error, and helper functions above are application-specific placeholders.

+----------------------------------------------------------------------+
| Illustrative call-stack comparison: actual sizes are build-specific |
| |
| Build A: helpers inlined |
| [ process_sensor_packet: possibly larger merged frame ] |
| |
| Build B: calls remain out of line |
| [ parse_payload frame ] <-- active callee |
| [ process_sensor_packet frame ] <-- caller |
| |
| The calls execute sequentially; not all helper frames are nested. |
+----------------------------------------------------------------------+

Do not interpret consecutive calls in source as three simultaneous nested frames. The deepest active call chain, not the number of functions referenced, sets instantaneous stack depth.

Auditing Stack Utilization in Firmware

Use compiler output, debugger stack measurements, and controlled load tests together. cargo-bloat reports code size, not stack consumption. cargo-call-stack can estimate whole-program stack usage on supported builds, but its accuracy is limited by indirect calls, recursion, compiler metadata, and toolchain version.

# Code-size analysis only; not a stack measurement
cargo bloat --release --crates
# Optional: install and inspect the help for the stack-analysis tool
cargo install cargo-call-stack
cargo call-stack --help
# Build the exact target/profile used in production
cargo build --release --target thumbv8m.main-none-eabihf

For stack-size metadata, consult the tool’s documented nightly/LLVM requirements. Also inspect the ELF/disassembly with llvm-objdump and test nested interrupt and worst-case call paths.

[profile.release]
opt-level = "s" # A size-oriented starting point, not a stack guarantee
lto = "fat"
codegen-units = 1
panic = "abort"
debug = true # Keep symbols for symbolication

Never introduce #[inline(always)] solely to assume a smaller stack; compare measured worst-case usage and binary size.

MSPLIM: Hardware Stack Limit on ARMv8-M

ARMv8-M provides MSPLIM for MSP and PSPLIM for PSP. They bound downward stack-pointer movement. The available registers and resulting exception classification depend on the profile, processor implementation, and Secure/Non-secure state. The implementation in this article targets ARMv8-M Mainline, such as a Cortex-M33 running software in a state with working stack-limit registers. In particular, Cortex-M23 Non-secure execution does not provide the equivalent Non-secure limit registers, and the Baseline profile does not provide the same configurable UsageFault/CFSR diagnostics.

+----------------------------------------------------------------------+
| Example address map: higher addresses at the top |
| |
| 0x20040000 Main-stack top (initial MSP) |
| | Allocated stack: grows DOWN |
| v |
| 0x2003C000 MSPLIM = lowest permitted MSP (example) |
| +------------------------------------------ |
| | No MSP accesses below limit allowed |
| | Other RAM sections / linker allocations |
| 0x20000000 RAM origin |
| |
| A separate emergency-stack design is needed if fault |
| handling must continue after MSP is exhausted. |
+----------------------------------------------------------------------+

A stack-limit exception can provide earlier detection than a later unrelated crash, but it is incorrect to promise that every memory access is protected or that the saved fault PC is always valid.

MSPLIM Architectural Specifications

MSPLIM and PSPLIM are core special registers accessed with MRS and MSR rather than ordinary memory-mapped writes. At the instruction level:

MRS R0, MSPLIM ; read current Main Stack Pointer limit
MSR MSPLIM, R0 ; update Main Stack Pointer limit
  • Alignment: Use an 8-byte-aligned stack limit. The architecture constrains low register bits and the active limit must be consistent with the linker allocation.
  • Reset state: A zero limit generally leaves useful RAM addresses unprotected by the limit check. Configure an explicit bound in startup code.
  • Security state: TrustZone-enabled processors can have separate Secure and Non-secure stack-limit state, subject to architecture/profile restrictions. Configuring the Secure register does not automatically guard Non-secure MSP.
  • Stack selection: MSPLIM protects MSP; PSPLIM protects PSP. If a scheduler changes PSP or thread stack, it must also handle the matching limit and context state.
  • Scope: These checks do not detect arbitrary out-of-bounds pointer writes, and an exception-entry limit violation can compromise fault-frame availability.

Why the Guard Reserve Margin is Critical

Do not put a 512-byte “guard reserve” below MSPLIM and assume the exception handler can use it. Access below the stack limit is precisely what the hardware prohibits. A fault while the stack is nearly exhausted may fail to create a complete exception frame, escalate to HardFault, or lock up during subsequent stacking.

A robust design reserves enough usable stack above the limit for normal worst-case nesting and plans how faults are handled. For example, choose a 16 KiB dedicated MSP region, keep the MSPLIM boundary at its low end, and budget exception and handler demand within that same 16 KiB. If faults must be diagnosed after MSP exhaustion, use a validated architecture-specific emergency-stack handler, debugger-side registers, or an intentional reset/reboot diagnostic path. A 256- or 512-byte margin is an application budgeting choice, not an architectural guarantee.

allocated_stack_bottom <= MSPLIM <= current_MSP <= stack_top
usable_stack_capacity = stack_top - MSPLIM

Arrange the linker so .data, .bss, .uninit, heap and per-core stacks cannot overlap the declared stack allocation. This is separate from programming the register.

Implementing MSPLIM Guard in Rust

The cortex-m crate exposes cortex_m::register::msplim::{read, write} on supported targets; writing the register is unsafe because a bad value can immediately make stack operations fault. Prefer configuring the cortex-m-rt startup feature set-msplim on ARMv8-M Mainline so the limit is installed before Rust application code uses deep stack frames.

For a runtime that does not already set it, the following helper is illustrative and checks alignment and bounds. Call it only after the correct stack region is reserved in the linker script, while running on the relevant core and security state.

// stack_guard.rs (ARMv8-M Mainline, MSP-based execution only)
use cortex_m::register::{msp, msplim};
/// # Safety
/// `stack_bottom` and `stack_top` must identify the actual reserved MSP
/// stack for this core/security state. The caller must prevent races with
/// stack switches or other runtime-owned configuration.
pub unsafe fn arm_stack_guard(stack_bottom: u32, stack_top: u32) -> Result<(), &'static str> {
let current = msp::read();
if stack_bottom == 0 || stack_bottom % 8 != 0 || stack_top % 8 != 0 {
return Err("invalid stack alignment/boundary");
}
if !(stack_bottom < current && current <= stack_top) {
return Err("MSP outside reserved stack region");
}
// SAFETY: The caller establishes and owns the active MSP stack region.
unsafe { msplim::write(stack_bottom) };
Ok(())
}
pub fn get_stack_limit() -> u32 { msplim::read() }
/// Snapshot only; the compiler's own stack use changes MSP during this call.
pub fn current_headroom() -> u32 {
msp::read().saturating_sub(msplim::read())
}

This helper is not an interrupt-safe stack switch and does not protect PSP-based tasks. Do not add an arbitrary offset to a linker-defined, already-reserved stack bottom.

Linker Script Configuration

cortex-m-rt names the initial stack pointer _stack_start and the optional lower limit _stack_end. With its set-msplim feature, supported ARMv8-M Mainline startup code programs MSPLIM from _stack_end. The following is a board-specific example of reserving an upper-RAM MSP stack; adapt its RAM address and memory requirements to your board.

/* memory.x example: 256 KiB SRAM, 16 KiB reserved for MSP */
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 256K
}
_stack_start = ORIGIN(RAM) + LENGTH(RAM);
_stack_end = _stack_start - 16K;

Important: Merely defining _stack_end does not prevent other sections/heap allocations from occupying the same RAM. Add a board-specific linker assertion against the actual end of the allocated writable sections and make the heap respect the reserved stack zone. Verify the final map file.

# Cargo.toml (only with a compatible cortex-m-rt 0.7.x version)
[dependencies]
cortex-m = "0.7"
cortex-m-rt = { version = "0.7.7", features = ["set-msplim"] }
panic-halt = "0.2"
// main.rs: the startup code has already installed MSPLIM.
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use panic_halt as _;
#[entry]
fn main() -> ! {
let _initial_limit = cortex_m::register::msplim::read();
// For a Mainline core, enable configurable UsageFault in init code
// if the application provides a suitable UsageFault handler.
let mut cp = cortex_m::Peripherals::take().unwrap();
cp.SCB.enable(cortex_m::peripheral::scb::Exception::UsageFault);
loop { cortex_m::asm::wfi(); }
}

Use a distinct application code path if startup, bootloader, or RTOS already owns MSPLIM. The feature does not apply to every ARMv8-M Baseline/non-secure configuration.

Integration with Embassy and RTIC

In Embassy applications, async futures and executor storage are usually static, but interrupt handlers and synchronous call chains still need an MSP guard. Configure set-msplim in the runtime and reserve the stack at link time, then enable UsageFault during early initialization. Avoid calling Peripherals::take().unwrap() inside an executor if the HAL or framework has already taken core peripherals.

// Embassy pattern (illustrative: runtime config and HAL setup are board-specific)
#[embassy_executor::main]
async fn main(spawner: embassy_executor::Spawner) {
// MSP limit was configured by cortex-m-rt before this entry point.
let msplim = cortex_m::register::msplim::read();
assert!(msplim != 0);
// Initialize the board's peripherals and enable UsageFault once.
spawner.spawn(telemetry_task()).unwrap();
}

For RTIC, configure the boot-time MSPLIM in the runtime/linker rather than waiting until a lower-priority task or an #[init] body is running. RTIC’s resource structures and #[init] signature differ between major versions, so a generic #[rtic::app] example with invented types would be misleading.

// RTIC-oriented guard check, called early in init after runtime startup
let limit = cortex_m::register::msplim::read();
assert!(limit != 0, "runtime did not configure MSP limit");
// Set per-task PSP limits separately if a different scheduler uses PSP.

The snippets are integration patterns, not complete standalone applications.

Trapping and Diagnosing the STKOF Fault

On ARMv8-M Mainline, a stack-pointer limit violation sets the STKOF UsageFault status bit when that status register is implemented. If UsageFault is disabled or cannot be serviced, the fault can escalate to HardFault; fault escalation and exception stacking may also lead to lockup. On ARMv8-M Baseline/Cortex-M23, do not assume the same UsageFault register and handler facilities exist.

A configured limit does not mean a high-level Rust handler always receives a trustworthy saved exception frame. For a genuine stack-exhaustion incident, a debugger or a carefully designed emergency fault stack is often the most dependable way to recover register context.

Decoding Fault Registers: CFSR and UFSR

For ARMv8-M Mainline, CFSR at 0xE000_ED28 includes UFSR in bits [31:16]. The STKOF flag is UFSR bit 4, therefore CFSR bit 20 (0x0010_0000). A status-bit snapshot establishes that a stack-limit violation was recorded, not that a valid PC, LR, or stack frame necessarily survived.

+----------------------------------------------------------------------+
| CFSR fields (ARMv8-M Mainline; schematic) |
| |
| CFSR[31:16] : UFSR (UsageFault status) |
| bit 20: STKOF = 0x00100000 |
| CFSR[15:8] : BFSR (BusFault status) |
| CFSR[7:0] : MMFSR (MemManage status) |
+----------------------------------------------------------------------+

Read the register only on a core/security state that implements it. Fault status bits are sticky and can report an earlier fault until cleared according to the processor documentation.

Implementing the Fault Handler

The standard cortex-m-rt #[exception] macro does not pass an ExceptionFrame to UsageFault. Only the optional HardFault trampoline supplies an &ExceptionFrame parameter. Furthermore, stack overflow can make frame access or defmt formatting unsafe. Use a minimal handler with little stack consumption, record only simple status, and let a debugger or startup code report details later.

// exceptions.rs; ARMv8-M Mainline, cortex-m-rt 0.7.7
use cortex_m_rt::exception;
use cortex_m::peripheral::SCB;
const CFSR_ADDR: *const u32 = 0xE000_ED28 as *const u32;
const STKOF: u32 = 1 << 20;
#[exception]
unsafe fn UsageFault() -> ! {
// SAFETY: CFSR exists on the selected ARMv8-M Mainline target.
let cfsr = unsafe { core::ptr::read_volatile(CFSR_ADDR) };
record_fault(cfsr); // Minimal fixed-size retained record (defined below).
// Do not allocate buffers, format logs, or dereference a possibly bad frame.
if (cfsr & STKOF) != 0 {
// A debugger can inspect CFSR/MSP/MSPLIM here.
}
SCB::sys_reset()
}
// No trampoline: does not assume a valid stacked ExceptionFrame.
#[exception(trampoline = false)]
unsafe fn HardFault() -> ! {
let cfsr = unsafe { core::ptr::read_volatile(CFSR_ADDR) };
record_fault(cfsr);
SCB::sys_reset()
}

Important limitation: Even these minimal Rust handlers may fail if exception entry cannot complete due to exhausted MSP, a stacking fault, or a lockup. The record_fault function and the .uninit section must be implemented and verified on the actual board. Do not treat this as a guarantee of crash recovery.

Exception Frame Architecture

For a successfully stacked basic exception frame, the hardware stores eight 32-bit words in the following order. The active stack used for saving the interrupted context can be MSP or PSP depending on execution mode. Additional floating-point context and 8-byte alignment padding alter the full frame layout.

Basic frame, only when exception stacking completed successfully:
SP + 0x00 R0
SP + 0x04 R1
SP + 0x08 R2
SP + 0x0C R3
SP + 0x10 R12
SP + 0x14 LR
SP + 0x18 PC
SP + 0x1C xPSR

The saved PC often identifies a useful location for instruction-related UsageFaults. However, for stack-limit faults arising during exception entry, the saved frame may be absent or incomplete; it must not be blindly dereferenced. The stacked LR is the interrupted context’s LR, not necessarily a conventional call-chain pointer.

For a validated address, use the ELF that matches the field firmware:

llvm-addr2line -e target/thumbv8m.main-none-eabihf/release/firmware -f -C 0x08001a42

Use the debugger’s register view and disassembly to determine whether this PC is truly associated with the fault.

Crash Telemetry Across System Resets

A crash record can be stored in a dedicated RAM section that the startup code intentionally does not initialize. Ordinary SRAM usually survives SYSRESETREQ on many chips but not power loss, brownout, or every reset mode; retention is chip-specific. Verify the linker mapping and startup zeroing rules. If a bus fault or exhausted stack prevents the handler from completing, the record can be incomplete.

// Retained crash-state example. One writer per core; board linker must KEEP
// the .uninit.crash_telemetry section outside startup zeroing.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct CrashTelemetry {
pub magic: u32,
pub cfsr: u32,
pub msp: u32,
pub msplim: u32,
}
const CRASH_MAGIC: u32 = 0xC45A_8E11;
#[unsafe(link_section = ".uninit.crash_telemetry")]
static mut CRASH_RECORD: CrashTelemetry = CrashTelemetry {
magic: 0, cfsr: 0, msp: 0, msplim: 0,
};
// Must remain extremely small; fault handling may still fail to execute.
fn record_fault(cfsr: u32) {
let record = &raw mut CRASH_RECORD;
unsafe {
core::ptr::write_volatile(&raw mut (*record).magic, 0);
core::ptr::write_volatile(&raw mut (*record).cfsr, cfsr);
core::ptr::write_volatile(
&raw mut (*record).msp, cortex_m::register::msp::read());
core::ptr::write_volatile(
&raw mut (*record).msplim, cortex_m::register::msplim::read());
// Commit marker last to distinguish partial records.
core::ptr::write_volatile(&raw mut (*record).magic, CRASH_MAGIC);
}
}
pub fn take_crash_record() -> Option<CrashTelemetry> {
let record = &raw mut CRASH_RECORD;
unsafe {
if core::ptr::read_volatile(&raw const (*record).magic) != CRASH_MAGIC {
return None;
}
let snapshot = core::ptr::read_volatile(record);
core::ptr::write_volatile(&raw mut (*record).magic, 0);
Some(snapshot)
}
}

The example does not record a PC: a trustworthy frame is not always available during a stack fault. Add PC/LR only if an architecture-aware assembly entry verifies valid exception stacking and switches to a known-good emergency stack first. Avoid writing to flash or running complex logging within the fault path.

Per-Core Guards on Dual-Core Architectures (RP2350, nRF5340)

Each Cortex-M33 core has its own MSP, PSP, MSPLIM, and PSPLIM. On RP2350, two Cortex-M33 cores can be enabled and share the SRAM address space; they still need non-overlapping stack allocations. The nRF5340 has distinct application and network cores with separate firmware images and memory arrangements, so one shared linker configuration does not cover both cores.

+----------------------------------------------------------------------+
| Per-core stack protection (schematic, addresses are separate) |
| |
| CORE 0: [ other data ][ MSP0 region, limit0 .. top0 ] |
| ^ limit0 checked by MSPLIM of core 0 |
| |
| CORE 1: [ other data ][ MSP1 region, limit1 .. top1 ] |
| ^ limit1 checked by MSPLIM of core 1 |
| |
| No register write on core 0 programs core 1 registers. |
+----------------------------------------------------------------------+

If TrustZone is enabled, repeat this analysis for Secure and Non-secure stack states. Multi-core retained crash records should be per-core or have explicit synchronization.

Memory Partitioning on RP2350

RP2350 offers 520 KiB SRAM in total: 512 KiB of main SRAM at 0x2000_0000 through 0x2007_FFFF, plus two separate 4 KiB scratch banks at 0x2008_0000 and 0x2008_1000. Do not treat 520 KiB as a single generic RAM region without verifying your runtime/linker mapping.

The following is an illustrative single-program allocation within the 512 KiB main SRAM, not an RP2350 SDK core-launch implementation:

/* memory.x example for a custom RP2350 linker/runtime */
MEMORY
{
FLASH (rx) : ORIGIN = 0x10000000, LENGTH = 2M
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 512K
}
/* Core 0 uses the highest 32 KiB of main SRAM. */
_stack_start = ORIGIN(RAM) + LENGTH(RAM);
_stack_end = _stack_start - 32K;
/* Core 1 has a distinct 16 KiB region immediately below core 0. */
_stack_start_core1 = _stack_end;
_stack_end_core1 = _stack_start_core1 - 16K;

For this layout, the normal writable sections and heap must end below _stack_end_core1, enforced by a board-specific linker assertion and allocator limits. The default cortex-m-rt _stack_start/_stack_end feature initializes only the core executing that reset handler. It does not launch core 1 or automatically load its MSP. Startup code running on core 1 must set its stack top and then MSPLIM correctly before executing Rust functions with significant stack demand.

// Called on core 1 *after* its correct MSP is installed by the launch stub.
unsafe fn configure_core1_limit(stack_bottom: u32) {
assert_eq!(stack_bottom & 7, 0);
// SAFETY: the core-1 launch code owns the allocated MSP stack.
unsafe { cortex_m::register::msplim::write(stack_bottom) };
}

RP2350 can also run its RISC-V Hazard3 cores instead of Arm cores; the ARMv8-M MSPLIM mechanism does not apply to that configuration. Validate the actual RP2350 boot and memory model before adapting this example.

ARMv7-M Fallbacks (STM32H7, Cortex-M7/M4)

[!IMPORTANT] ARMv7-M and ARMv6-M do not implement MSPLIM/PSPLIM. This includes STM32H7 Cortex-M7, STM32F4 Cortex-M4, and RP2040 Cortex-M0+. Use alternatives appropriate for the target and memory map:

  • MPU guard region: On cores with a Memory Protection Unit, block writes to a region adjacent to a stack boundary. Granularity and configuration differ between MPU architectures; not every core has an MPU.
  • flip-link: On supported bare-metal Rust layouts, arrange the stack below other static data so a downward overflow can reach a physical RAM boundary, provided an unmapped/faulting address follows it.
  • Software canaries / RTOS overflow checks: Use as supplementary detection; they are not equivalent to a hardware stack-limit comparator.

Neither an MPU guard nor flip-link is guaranteed to catch every stack overflow on every chip. Check memory aliasing, SRAM banks, fault routing, and the linker map.

On-Device Stack Telemetry

Measure instantaneous headroom during controlled execution and combine it with a stack high-water method. Instrumentation itself consumes stack, so snapshots are not a precise peak. For RTOS applications on PSP, reading MSP tells you about handler stack use, not the currently running task stack.

Mathematical Formulation of Stack Metrics

For a reserved descending main stack with stack_top >= MSP >= MSPLIM:

Instantaneous headroom (bytes) = MSP - MSPLIM
Instantaneous used (bytes) = stack_top - MSP
Configured capacity (bytes) = stack_top - MSPLIM
Utilization (%) = 100 * used / capacity

These are only valid for the correct core, security state, and active stack. If a handler runs on MSP while the interrupted thread used PSP, examine both stacks separately. MSPLIM is a bound, not the stack’s high-water mark.

Implementation

This function returns a point-in-time MSP estimate. Use the actual linker-defined top; validate that the limit has been initialized and the values are ordered.

// telemetry.rs, ARMv8-M Mainline, MSP-based execution
use cortex_m::register::{msp, msplim};
#[derive(Clone, Copy, Debug)]
pub struct StackStats {
pub used_bytes: u32,
pub headroom_bytes: u32,
pub total_capacity: u32,
pub utilization_pct: u8,
pub current_sp: u32,
pub limit: u32,
}
pub fn get_stack_statistics(stack_top: u32) -> Option<StackStats> {
let current_sp = msp::read();
let limit = msplim::read();
if limit == 0 || !(limit <= current_sp && current_sp <= stack_top) {
return None;
}
let total_capacity = stack_top - limit;
if total_capacity == 0 { return None; }
let used_bytes = stack_top - current_sp;
let headroom_bytes = current_sp - limit;
let utilization_pct = ((u64::from(used_bytes) * 100)
/ u64::from(total_capacity)) as u8;
Some(StackStats {
used_bytes, headroom_bytes, total_capacity,
utilization_pct, current_sp, limit,
})
}

Do not interpret this as proof that the stack has never fallen closer to its limit between observations.

Atomic High-Water Mark Tracking

A low-water sampler can record the minimum sampled MSP using AtomicU32 only when 32-bit atomics are supported by the selected target. It cannot reconstruct unobserved nested-interrupt depths and is not automatically a true high-water mark. Use distinct state for each core/stack and a separately validated memory-fill or instrumentation strategy if historical worst-case depth matters.

#[cfg(target_has_atomic = "32")]
mod main_stack_peak {
use core::sync::atomic::{AtomicU32, Ordering};
static MIN_SAMPLED_MSP: AtomicU32 = AtomicU32::new(u32::MAX);
pub fn sample() {
let sp = cortex_m::register::msp::read();
MIN_SAMPLED_MSP.fetch_min(sp, Ordering::Relaxed);
}
pub fn observed_headroom(stack_limit: u32) -> Option<u32> {
let minimum = MIN_SAMPLED_MSP.load(Ordering::Relaxed);
(minimum != u32::MAX).then(|| minimum.saturating_sub(stack_limit))
}
}

fetch_min is an atomic read-modify-write operation, so verify support, latency, and memory scope of the specific core and compiler. These measurements are sample-based lower bounds on observed stack usage, not full proofs of worst-case call depth.

MechanismWhat it detectsMain limitationApplicability
MSPLIM / PSPLIMDownward stack-pointer limit violationsA fault may prevent reliable exception stacking; does not guard arbitrary pointersSupported ARMv8-M configuration
flip-linkOut-of-RAM accesses after a downward overflow reaches the lower RAM boundaryRequires a compatible linker and an actually faulting RAM boundarySupported bare-metal Cortex-M layouts
MPU guardAccess to a configured prohibited memory regionRegion alignment/size, MPU availability, and fault stacking constraintsCores with a usable MPU
Stack canariesChanges to sentinels or compiler protection valuesDetection may be late and canaries can be bypassedSoftware/toolchain-dependent

Engineering recommendation: On ARMv8-M Mainline, reserve dedicated stack regions and configure the appropriate stack limit in the early startup path. Pair that with a debugger-verifiable fault strategy and stack measurement. On other Cortex-M cores, choose a verified memory-map protection strategy; combinations are useful but must be tested together.

Common Pitfalls and Failure Modes

The following problems commonly prevent a stack-limit design from providing the expected diagnostic protection. Fix the underlying linker and startup layout first; a register write alone is insufficient.

1. Forgetting to Enable UsageFault in SHCSR

On ARMv8-M Mainline, enable the configurable UsageFault exception when your firmware has an appropriate handler. Otherwise the violation may escalate to HardFault. It is not guaranteed that enabling UsageFault alone makes a stack-overflow report recoverable; stacking failure or fault-handler stack exhaustion can still cause escalation or lockup.

let mut cp = cortex_m::Peripherals::take().unwrap();
cp.SCB.enable(cortex_m::peripheral::scb::Exception::UsageFault);

Execute this once where ownership of the core peripherals is clear; frameworks may already own the SCB.

2. Omission of the Guard Reserve Margin

A reserve below MSPLIM cannot be used for normal stacking while the limit is enforced. The correct plan is to allocate sufficient usable stack above MSPLIM, including interrupt nesting and fault-handler needs, while protecting other allocations below it. If the application must report faults despite exhausted MSP, design and validate a separate fault stack or collect registers externally. Do not treat 512 bytes as a mandatory or sufficient architectural margin.

3. Conflating MSPLIM and PSPLIM

MSPLIM bounds MSP only. Code running with PSP needs a separately initialized PSPLIM on a supporting core and security state. An RTOS must save/restore or update each task’s PSP limit consistently with stack switching.

use cortex_m::register::psplim;
/// # Safety
/// `task_stack_bottom` is the actual aligned lower bound of the active PSP
/// task stack, and the scheduler has exclusive control of its context.
unsafe fn set_task_stack_limit(task_stack_bottom: u32) {
assert_eq!(task_stack_bottom & 7, 0);
unsafe { psplim::write(task_stack_bottom) };
}

Do not add an arbitrary reserve to a task’s allocated bottom unless the linker/task allocator has reserved that extra space accordingly.

4. Overlooking Core 1 on Dual-Core Chips

On dual-core chips such as RP2350, each core’s stack-limit registers are independent. Initialize both cores before their deep call paths begin; ensure allocated stacks cannot overlap, including during startup, resets, and interrupt nesting. For nRF5340, configure and build the application and network core images independently.

5. Inverted Headroom Calculations

For a descending stack, instantaneous headroom is SP - limit, not limit - SP. However, that formula is meaningful only after the proper limit is installed and for the correct active stack. Check MSP versus PSP, per-core and TrustZone banking, and the linker-defined stack top before computing percentages.

Verification and Diagnostics

Test the stack-limit implementation on a disposable board with a debugger attached. First confirm the linker region boundaries, the initial MSP, the active MSPLIM/PSPLIM, and exception enable state. Then test a controlled limit violation, inspect fault status, and verify whether the handler ran and any retained record survived reset. Never perform deliberate stack exhaustion in deployed firmware.

Inducing Deliberate Stack Exhaustion

Recursion is not a deterministic method of allocating exactly 1 KiB per frame: the compiler can inline, eliminate objects, or use tail-call optimization. Use a deliberately bounded test with observable local data and inspect its disassembly/stack use first. On the target, trigger a controlled limit violation only with debugger supervision.

// Illustrative: compiler and architecture may change stack usage.
#[inline(never)]
fn exercise_stack(depth: u32, seed: u8) -> u32 {
let mut frame = [0u8; 256];
for (i, b) in frame.iter_mut().enumerate() {
*b = seed.wrapping_add(i as u8);
}
let local = u32::from(frame[(depth as usize) & 255]);
if depth == 0 {
local
} else {
local.wrapping_add(exercise_stack(depth - 1, seed.wrapping_add(1)))
}
}

Call it from a controlled firmware test path at an explicitly bounded depth that you increase gradually. The Rust test harness #[test] is not normally available on a bare-metal #![no_std] Cortex-M target without special support. Do not assert that this example always overflows or prints a defmt log.

Inspecting Limit Registers in GDB

Debugger register aliases vary by GDB server and target. After halting on the fault, first inspect the core’s MSPLIM, MSP, PSPLIM and PSP; then read the CFSR address on ARMv8-M Mainline.

(gdb) info registers msp psp msplim psplim
(gdb) x/1wx 0xE000ED28

A representative readout might be:

0xe000ed28: 0x00100000

Bit 20 indicates that STKOF was latched on a target with this register. It does not prove that a complete exception frame exists or that the fault handler successfully recorded a precise PC. Compare the active register values against the linker symbols in the matching ELF.

Summary

Stack overflow is a plausible cause of an otherwise unexplained HardFault or corrupted state in embedded Rust, but it is not the only possible cause. On supported ARMv8-M Mainline devices, correctly configured stack-limit registers provide valuable hardware checking for downward stack-pointer movement.

  1. Reserve real stack space: Define non-overlapping, linker-verified regions for MSP (and PSP tasks where applicable).
  2. Install limits early: Use cortex-m-rt’s set-msplim feature with _stack_end where compatible, or carefully initialize registers in the correct reset path.
  3. Handle faults conservatively: STKOF is a useful status indicator; complete exception stacking, saved PC, and high-level logging are not guaranteed after overflow.
  4. Configure every execution context: Account for per-core limits, Secure/Non-secure banks, PSP tasks, and startup behavior.
  5. Measure and validate: Combine tool-assisted call-stack estimates, sampled stack observations, linker checks, and real target fault-injection tests.

MSPLIM complements careful memory layout, stack sizing, and fault-tolerant recovery. It does not itself guarantee memory safety or make an exhausted stack suitable for normal Rust logging.

References

  1. ARM Limited. ARMv8-M Architecture Reference Manual. DDI 0553. Section B3.3 “Stack Pointer Limit Registers (MSPLIM, PSPLIM)“. ARM Developer Documentation.
  2. ARM Limited. Arm Cortex-M33 Devices Generic User Guide. DUI 0902. Section 4.3.9 “Stack Pointer Limit Registers”. ARM User Guides.
  3. The Rust Embedded Working Group. The Embedded Rust Book: Exception Handling. Rust Embedded Resources.
  4. Raspberry Pi Ltd. RP2350 Datasheet: High-performance Microcontroller. Section 2.3.3 “Stack Limit Registers”. Raspberry Pi Documentation.
  5. docs.rs. Crate cortex-m: Low-level access to Cortex-M processors. Module cortex_m::register::msplim. docs.rs cortex-m documentation.
  6. LLVM Compiler Infrastructure. LLVM CodeGen Stack Coloring Pass Documentation. LLVM Code Generator.

Frequently Asked Questions

What causes a HardFault in embedded Rust when there's no panic message?

A HardFault without a Rust panic can arise from invalid memory accesses, corrupted pointers, stack exhaustion, or an escalated configurable fault. A missing panic log does not identify the root cause; inspect fault status and the active stack or use a debugger.

How does MSPLIM prevent stack overflow corruption on Cortex-M33?

On supported ARMv8-M Mainline cores, MSPLIM bounds downward MSP movement. A breach sets the STKOF UsageFault status flag; it can escalate or prevent valid exception stacking, so reliable PC capture and fault-handler execution are not guaranteed.

How do compiler optimization levels affect stack frame consumption in embedded Rust?

Rust optimization changes inlining, register spills, stack slots, and call paths. Neither debug nor size-optimized builds guarantee lower stack consumption; inspect the exact target ELF and measure worst-case stack depth.

How do you enable MSPLIM stack guarding in Rust?

Reserve a real MSP stack region in the linker script and configure its lower bound through the cortex-m-rt set-msplim feature with _stack_end, or write the aligned MSPLIM register safely during startup on a supported core. Plan exception handling separately.

What is the difference between flip-link and MSPLIM for stack overflow detection?

flip-link rearranges a compatible bare-metal memory layout so a downward overflow can hit a physical RAM boundary. MSPLIM checks stack-pointer limits in hardware on supported ARMv8-M cores. Neither method guarantees a complete saved fault frame or replaces correct stack sizing.

Tags

rustembeddedhardfaultstack-overflowcortex-mmsplimarmv8-m

Share


Previous Article
Fixing STM32H7 ADC Calibration Timeout Failures
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing Sporadic Hard Faults in FreeRTOS Heap Allocation
Fixing Sporadic Hard Faults in FreeRTOS Heap Allocation
September 09, 2026
8 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media