refactor: move exception handler to new module

This commit is contained in:
cscherr 2025-07-14 15:52:11 +02:00
parent 0f3a5f6b32
commit cb53f81662
Signed by: cscherrNT
GPG key ID: 8E2B45BC51A27EA7
2 changed files with 41 additions and 39 deletions

39
src/hardfaults.rs Normal file
View file

@ -0,0 +1,39 @@
use cortex_m_rt::ExceptionFrame;
fn display_ef(ef: &ExceptionFrame) {
struct Wrapper(ExceptionFrame);
impl defmt::Format for Wrapper {
fn format(&self, fmt: defmt::Formatter) {
defmt::write!(
fmt,
"ExceptionFrame(\n\tr0: {:08x}\n\tr1: {:08x}\n\tr2: {:08x}\n\tr3: {:08x}\n\tr12: {:08x}\n\tlr: {:08x}\n\tpc: {:08x}\n\txpsr: {:08x}\n)",
self.0.r0(),
self.0.r1(),
self.0.r2(),
self.0.r3(),
self.0.r12(),
self.0.lr(),
self.0.pc(),
self.0.xpsr()
);
}
}
error!("HardFault: Exception occured!");
error!("Exception occured at: {:08x}", ef.pc());
error!("XSPR: {:032b}", ef.xpsr());
error!("LR: {:08x}", ef.lr());
error!("HardFault: {:#?}", Wrapper(*ef))
}
#[allow(unreachable_code)]
#[cortex_m_rt::exception(trampoline = true)]
unsafe fn HardFault(ef: &ExceptionFrame) -> ! {
static mut EXCEPTION: Option<ExceptionFrame> = None;
unsafe { EXCEPTION = Some(*ef) };
display_ef(ef);
#[allow(clippy::empty_loop)]
loop {}
}

View file

@ -11,6 +11,8 @@ use defmt_rtt as _; // global logger
use cortex_m_rt::{ExceptionFrame, entry};
use hal::{pac, prelude::*, rcc::Config};
mod hardfaults; // defines a handler for evil hardfaults
// same panicking *behavior* as `panic-probe` but doesn't print a panic message
// this prevents the panic message being printed *twice* when `defmt::panic` is invoked
#[defmt::panic_handler]
@ -38,7 +40,6 @@ fn main() -> ! {
// Get the delay provider.
let mut delay = cp.SYST.delay(rcc.clocks);
// BUG: this program seems to completely halt whenever a C function is called.
debug!("Asserting that libalgorithms is correctly loaded");
assert!(algorithms::ffi_is_loaded(), "ffi is not loaded?");
@ -62,41 +63,3 @@ fn main() -> ! {
delay.delay_ms(500_u16);
}
}
fn display_ef(ef: &ExceptionFrame) {
struct Wrapper(ExceptionFrame);
impl defmt::Format for Wrapper {
fn format(&self, fmt: defmt::Formatter) {
defmt::write!(
fmt,
"ExceptionFrame(\n\tr0: {:08x}\n\tr1: {:08x}\n\tr2: {:08x}\n\tr3: {:08x}\n\tr12: {:08x}\n\tlr: {:08x}\n\tpc: {:08x}\n\txpsr: {:08x}\n)",
self.0.r0(),
self.0.r1(),
self.0.r2(),
self.0.r3(),
self.0.r12(),
self.0.lr(),
self.0.pc(),
self.0.xpsr()
);
}
}
error!("HardFault: Exception occured!");
error!("Exception occured at: {:08x}", ef.pc());
error!("XSPR: {:032b}", ef.xpsr());
error!("LR: {:08x}", ef.lr());
error!("HardFault: {:#?}", Wrapper(*ef))
}
#[allow(unreachable_code)]
#[cortex_m_rt::exception(trampoline = true)]
unsafe fn HardFault(ef: &ExceptionFrame) -> ! {
static mut EXCEPTION: Option<ExceptionFrame> = None;
unsafe { EXCEPTION = Some(*ef) };
display_ef(ef);
#[allow(clippy::empty_loop)]
loop {}
}