UsageFault is a configurable Cortex-M exception for invalid processor usage. It can signal an undefined instruction, a disallowed unaligned access, or division by zero when DIV_0_TRP is set. It can also report a stack-limit violation. section 6.4.6 section 7.4.5
On Armv7-M and Armv8-M mainline targets, UsageFault is disabled at reset. A UsageFault then escalates to HardFault, with the FORCED bit set in the HardFault Status Register (HFSR). Enabling UsageFault gives it a separate handler and makes the cause easier to classify. section 6.4.6
use cortex_m::peripheral::{scb::Exception, Peripherals};
let mut p = Peripherals::take().unwrap();
p.SCB.enable(Exception::MemoryManagement);
p.SCB.enable(Exception::BusFault);
p.SCB.enable(Exception::UsageFault);
Enable UsageFault through the cortex-m System Control Block API. This listing also enables the MemoryManagement and BusFault exceptions. section 6.4.6
use cortex_m_rt::exception;
#[exception]
unsafe fn MemoryManagement() -> ! {
panic!("MemoryManagement fault");
}
#[exception]
unsafe fn BusFault() -> ! {
panic!("BusFault");
}
#[exception]
unsafe fn UsageFault() -> ! {
panic!("UsageFault");
}
Install a dedicated handler with the cortex-m-rt exception attribute. This example panics when UsageFault occurs. section 6.4.6
Unlike a HardFault handler, a configurable-fault handler does not receive an ExceptionFrame from the cortex-m-rt macro. Read the UsageFault Status Register (UFSR) through the System Control Block for a more specific diagnosis. For example, its UNALIGNED bit identifies a disallowed unaligned access. section 6.4.6
Detecting a stack-limit violation
MSPLIM can mark the bottom of the main stack. A push that would take the stack pointer below that limit raises UsageFault with STKOF set in the Configurable Fault Status Register. Enable UsageFault to receive it directly; otherwise it escalates to HardFault. Program MSPLIM early in main, before code can push significant stack frames. section 7.4.5
use cortex_m::register;
extern "C" {
static _stack_bottom: u32; // lowest valid stack address, from memory.x
}
unsafe fn install_msplim() {
let limit = &raw const _stack_bottom as u32;
register::msplim::write(limit);
}
Set MSPLIM from the _stack_bottom linker symbol using the cortex-m register API. Register availability depends on the target. section 7.4.5
