HardFault Handler that Captures the Stack Frame
When a Cortex-M HardFault occurs, the hardware has pushed R0, R1, R2, R3, R12, LR, PC, xPSR (in that order) onto whichever stack was in use. Bit 2 of the EXC_RETURN value in LR tells you which: 0 means MSP, 1 means PSP.
Write the C part of the handler, void fault_decode(uint32_t exc_return, uint32_t *msp, uint32_t *psp, fault_info_t *out), that selects the right stack and copies the stacked pc, lr and xpsr into out. Then sketch the naked assembly entry that would call it.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
exc_return & 4 selects the stack. In the frame, PC is at index 6, LR at 5 and xPSR at 7.
#include <stdio.h>
#include <stdint.h>
typedef struct { uint32_t pc, lr, xpsr, r0; } fault_info_t;
enum { F_R0, F_R1, F_R2, F_R3, F_R12, F_LR, F_PC, F_XPSR };
void fault_decode(uint32_t exc_return, uint32_t *msp, uint32_t *psp, fault_info_t *out)
{
const uint32_t *frame = (exc_return & 4u) ? psp : msp;
out->r0 = frame[F_R0];
out->lr = frame[F_LR];
out->pc = frame[F_PC];
out->xpsr = frame[F_XPSR];
}
/*
* On target, the entry point is a naked function so the compiler
* does not push anything before we read the stack pointers:
*
* __attribute__((naked)) void HardFault_Handler(void)
* {
* __asm volatile(
* "mov r0, lr \n" // EXC_RETURN
* "mrs r1, msp \n"
* "mrs r2, psp \n"
* "ldr r3, =g_fault\n"
* "b fault_decode_and_halt \n");
* }
*/
The stacked PC is the address of the faulting instruction (for precise faults), so addr2line -e firmware.elf 0x08000200 points straight at the line of code. The stacked LR shows the caller. Together with SCB->CFSR, HFSR, MMFAR and BFAR, this usually identifies the bug without a debugger attached.
Production handlers save this data to a no-init RAM region, trigger a reset, and report it on the next boot. If the FPU was active, bit 4 of EXC_RETURN is 0 and the frame is 26 words long, but the first 8 words are laid out the same way.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
uint32_t main_stack[8] = { 1, 2, 3, 4, 12, 0x08000101u, 0x08000200u, 0x01000000u };
uint32_t process_stack[8] = { 9, 0, 0, 0, 0, 0x08000301u, 0x08000400u, 0x21000000u };
fault_info_t f;
fault_decode(0xFFFFFFF9u, main_stack, process_stack, &f); /* thread mode, MSP */
CHECK(f.pc == 0x08000200u && f.lr == 0x08000101u && f.r0 == 1);
fault_decode(0xFFFFFFFDu, main_stack, process_stack, &f); /* thread mode, PSP */
CHECK(f.pc == 0x08000400u && f.xpsr == 0x21000000u && f.r0 == 9);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}