What causes a HardFault and how do you debug one?
Short answer: A HardFault is the catch-all fault on Cortex-M. Common causes: accessing an invalid address (NULL or wild pointer, freed memory), stack overflow, executing from a non-executable or invalid address, branching to an address without the Thumb bit, unaligned multi-word accesses, divide by zero (if trapping is enabled), undefined instructions, and MemManage/BusFault/UsageFault faults escalated because their handlers are disabled. Debug it by capturing the stacked registers to find the faulting PC, then reading the fault status registers.
Debugging steps
- Capture the stack frame in a handler (assembly wrapper chooses MSP or PSP from bit 2 of
LR, as shown in the MSP/PSP question).
void hard_fault_c(uint32_t *frame)
{
volatile uint32_t pc = frame[6]; /* faulting instruction (or next, if imprecise) */
volatile uint32_t lr = frame[5]; /* caller */
volatile uint32_t cfsr = SCB->CFSR; /* which fault and why */
volatile uint32_t hfsr = SCB->HFSR;
volatile uint32_t mmfar = SCB->MMFAR, bfar = SCB->BFAR;
(void)pc; (void)lr; (void)cfsr; (void)hfsr; (void)mmfar; (void)bfar;
__BKPT(0); /* stop here in the debugger */
for (;;) { }
}
- Find the code:
arm-none-eabi-addr2line -e fw.elf 0x08001234or look up PC and LR in the map file/disassembly. - Decode
CFSR(Configurable Fault Status Register): - MMFSR (MemManage):IACCVIOL,DACCVIOL,MSTKERR(stacking error, often stack overflow),MMARVALID→ address inMMFAR. - BFSR (BusFault):PRECISERR(address inBFAR),IMPRECISERR(write buffered, PC is later than the fault),STKERR,IBUSERR. - UFSR (UsageFault):UNDEFINSTR,INVSTATE(Thumb bit clear: bad function pointer),INVPC,NOCP(FPU used but not enabled),UNALIGNED,DIVBYZERO,STKOF(Armv8-M stack limit). HFSR.FORCED= 1 means a configurable fault was escalated to HardFault (enable the separate handlers inSCB->SHCSRto get more specific faults).- Imprecise BusFault: the stacked PC is after the real culprit, because the write was buffered. Temporarily set
DISDEFWBUFinSCnSCB->ACTLR(Cortex-M3/M4) to make bus faults precise while debugging.
Recognisable patterns
- PC =
0xFFFFFFFEor a RAM address equal to the initial stack pointer: a NULL or erased-flash function pointer was called. INVSTATE: function pointer without bit 0 set.NOCP: floating point used beforeSCB->CPACRenabled the FPU (often in start-up code or an earlyprintf("%f")).MSTKERR/STKERRor random faults that change with code changes: stack overflow.
In production: save the frame and status registers into a .noinit area, reset, and report them on the next boot. Tools like SEGGER Ozone, STM32CubeIDE's fault analyser and Memfault automate the decoding.