Skip to content

Instantly share code, notes, and snippets.

@ryankurte
Last active October 8, 2017 16:00
Show Gist options
  • Save ryankurte/f2bab6e7e23bb915b7734d4e1780d89f to your computer and use it in GitHub Desktop.
Save ryankurte/f2bab6e7e23bb915b7734d4e1780d89f to your computer and use it in GitHub Desktop.
Cortex M Hardfault Handler
// A HardFault handler to make life easier when debugging
// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/Cihcfefj.html
// The smol version
void HardFault_Handler(void) {
SCB_Type* scb = SCB;
(void*)scb;
__asm("BKPT #0");
while(1);
}
// The overly helpful version
void HardFault_Handler(void) {
// Grab an instance of the SCB so we can `p/x *scb` from the debugger
SCB_Type* scb = SCB;
(void*)scb;
// Identify hardfault type
if (SCB->HFSR & SCB_HFSR_FORCED_Msk) {
// Forced hardfault
// Copy faults for easy debugging
size_t mmu_fault = (SCB->CFSR >> 0) & 0xFF;
size_t bus_fault = (SCB->CFSR >> 8) & 0xFF;
size_t usage_fault = (SCB->CFSR >> 16) & 0xFFFF;
// Check for memory manger faults
if(SCB->CFSR & SCB_CFSR_MMARVALID_Msk) __asm("BKPT #0");
if(SCB->CFSR & SCB_CFSR_MLSPERR_Msk) __asm("BKPT #0");
if(SCB->CFSR & SCB_CFSR_MSTKERR_Msk) __asm("BKPT #0");
if(SCB->CFSR & SCB_CFSR_MUNSTKERR_Msk) __asm("BKPT #0");
if(SCB->CFSR & SCB_CFSR_DACCVIOL_Msk) __asm("BKPT #0");
if(SCB->CFSR & SCB_CFSR_IACCVIOL_Msk) __asm("BKPT #0");
// Check for bus faults
if (SCB->CFSR & SCB_CFSR_BFARVALID_Msk) __asm("BKPT #0");
if (SCB->CFSR & SCB_CFSR_LSPERR_Msk) __asm("BKPT #0");
if (SCB->CFSR & SCB_CFSR_STKERR_Msk) __asm("BKPT #0");
if (SCB->CFSR & SCB_CFSR_UNSTKERR_Msk) __asm("BKPT #0");
if (SCB->CFSR & SCB_CFSR_IMPRECISERR_Msk) __asm("BKPT #0");
if (SCB->CFSR & SCB_CFSR_PRECISERR_Msk) __asm("BKPT #0");
if (SCB->CFSR & SCB_CFSR_IBUSERR_Msk) __asm("BKPT #0");
// Check for usage faults
if (SCB->CFSR & SCB_CFSR_DIVBYZERO_Msk) __asm("BKPT 0");
if (SCB->CFSR & SCB_CFSR_UNALIGNED_Msk) __asm("BKPT 0");
if (SCB->CFSR & SCB_CFSR_NOCP_Msk) __asm("BKPT 0");
if (SCB->CFSR & SCB_CFSR_INVPC_Msk) __asm("BKPT 0");
if (SCB->CFSR & SCB_CFSR_INVSTATE_Msk) __asm("BKPT 0");
if (SCB->CFSR & SCB_CFSR_UNDEFINSTR_Msk) __asm("BKPT 0");
__asm("BKPT #0");
} else if (SCB->HFSR & SCB_HFSR_VECTTBL_Msk) {
// Vector table bus fault
__asm("BKPT #0");
}
__asm("BKPT #0");
while(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment