</>EmbeddedInterview

What causes a HardFault and how do you debug one?

MediumMicrocontrollers & ARM Cortex-M

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

  1. 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 (;;) { }
}
  1. Find the code: arm-none-eabi-addr2line -e fw.elf 0x08001234 or look up PC and LR in the map file/disassembly.
  2. Decode CFSR (Configurable Fault Status Register): - MMFSR (MemManage): IACCVIOL, DACCVIOL, MSTKERR (stacking error, often stack overflow), MMARVALID → address in MMFAR. - BFSR (BusFault): PRECISERR (address in BFAR), 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).
  3. HFSR.FORCED = 1 means a configurable fault was escalated to HardFault (enable the separate handlers in SCB->SHCSR to get more specific faults).
  4. Imprecise BusFault: the stacked PC is after the real culprit, because the write was buffered. Temporarily set DISDEFWBUF in SCnSCB->ACTLR (Cortex-M3/M4) to make bus faults precise while debugging.

Recognisable patterns

  • PC = 0xFFFFFFFE or 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 before SCB->CPACR enabled the FPU (often in start-up code or an early printf("%f")).
  • MSTKERR/STKERR or 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.