A Memory Protection Unit (MPU) enforces access permissions for configured memory regions in hardware. On Cortex-M, a no-access region below a stack can catch overflow when an offending read or write occurs. section 7.4.5
A stack guard depends on careful configuration:
- Align the guard address to the region size; the example uses a 32-byte region and requires 32-byte alignment. section 7.4.5
- The cortex-m crate exposes raw MPU registers, so configuration writes directly to CTRL, RNR, RBAR, and RASR. section 7.4.5
- A violation raises a memory management fault or hard fault; fault status registers identify the access type and address for post-mortem logging. section 7.4.5
- Plan the limited region budget across stack guards and other protections. The MPU complements flip-link, which catches overflow at the bottom of RAM. section 7.4.5 section 7.5
Figure 7.6 MPU stack guard: hardware-enforced overflow detection
The diagram shows how a no-access region below the valid stack catches overflow. section 7.4.5
use cortex_m::peripheral::MPU;
/// Configure region 0 as a 32-byte no-access guard at `guard_addr`.
/// `guard_addr` must be 32-byte aligned.
fn install_stack_guard(mpu: &MPU, guard_addr: u32) {
// RASR encoding for a 32-byte no-access execute-never region:
// bit 0 ENABLE = 1
// bits 5:1 SIZE = 4 -> region size = 2^(SIZE+1) = 32 bytes
// bits 26:24 AP = 0b000 -> no access from any privilege
// bit 28 XN = 1 -> execute never
const RASR_ENABLE: u32 = 1 << 0;
const RASR_SIZE_32: u32 = 4 << 1;
const RASR_AP_NONE: u32 = 0b000 << 24;
const RASR_XN: u32 = 1 << 28;
// RBAR encoding:
// bits 31:5 ADDR = base address (must be aligned to size)
// bit 4 VALID = 1 -> use REGION field below
// bits 3:0 REGION = 0 -> configuring region 0
const RBAR_VALID: u32 = 1 << 4;
const RBAR_REGION_0: u32 = 0;
// CTRL encoding:
// bit 0 ENABLE = 1
// bit 2 PRIVDEFENA = 1 -> default memory map active as background
const CTRL_ENABLE: u32 = 1 << 0;
const CTRL_PRIVDEFENA: u32 = 1 << 2;
unsafe {
// Disable the MPU while reconfiguring.
mpu.ctrl.write(0);
// Select region 0 and program its base and attributes.
mpu.rbar.write(guard_addr | RBAR_VALID | RBAR_REGION_0);
mpu.rasr.write(RASR_ENABLE | RASR_SIZE_32 | RASR_AP_NONE | RASR_XN);
// Re-enable the MPU with the default memory map as background,
// so unrelated regions keep their normal access rules.
mpu.ctrl.write(CTRL_ENABLE | CTRL_PRIVDEFENA);
// Ensure the MPU configuration is observed before any subsequent
// memory access (covered in chapter 5).
cortex_m::asm::dsb();
cortex_m::asm::isb();
}
}
The listing encodes a 32-byte no-access region through MPU registers. section 7.4.5
