An MPU guard region marks a memory boundary as inaccessible. If a stack overflow reaches it, the offending access raises a memory-management fault or hard fault instead of silently corrupting memory. The fault status registers identify the access type and address, which a MemoryManagement exception handler can log for later analysis. section 7.4.5 section 7.4
A 32-byte guard requires a base address aligned to 32 bytes, so the linker must place the stack boundary accordingly. On Cortex-M3/M4 and M7, MPU regions are limited, so guards must be budgeted alongside other protections. MPU guards complement flip-link: both can be used, and MPU guards can protect individual task stacks. section 7.4.5 section 7.4
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 configures region 0 as an aligned, 32-byte no-access guard using raw MPU register encodings from the cortex-m crate. section 7.4.5
Armv8-M uses RBAR and RLAR with base-and-limit encoding rather than the RBAR and RASR base-and-size encoding; consult the Armv8-M Architecture Reference Manual for its register values. section 7.4.5
