Connect
GDB, the GNU debugger, runs on your laptop. OpenOCD passes its commands to an ST-LINK probe, which talks to the chip's debug port over SWD. Now GDB can halt the Cortex-M4 and read any register or memory.
Read the crash
We send the line "set led blink 50" and the board stops responding. Press Ctrl-C in GDB to halt it: the CPU is stuck in the default fault handler, an endless loop. Something went badly wrong.
On a fault the CPU pushes eight registers onto the stack, including PC, the address of the instruction being run. SP, the stack pointer, points to the stack's top. The pushed PC, at SP + 24, is where it failed: 0x0800030A.
Fault status registers record the cause. CFSR reads 0x00020000: INVSTATE, an invalid state. HFSR reads 0x40000000: FORCED, a usage fault turned into a hard fault because its own handler was off.
A Cortex-M4 only runs Thumb code, so a code pointer's lowest bit must be 1: it must be odd. 0x0800030A is even. main() called rx.cb, so check it: it holds that same broken address.
Catch the writer
Who broke rx.cb? Reset and type watch rx.cb. GDB loads that address into the chip's watch unit, which checks every write in hardware at full speed. Continue, and send the line again.
Each byte that arrives raises an interrupt. The ISR stores it at rx.buf[n] and adds 1 to n. After 16 bytes, "set led blink 50", the buffer is exactly full and n is 16.
The 17th byte, the newline 0x0A, goes to rx.buf[16]: past the end, onto the lowest byte of rx.cb. The watch unit fires, and GDB stops just after line 4, inside USART2_IRQHandler, with n = 17.
main() never calls USART2_IRQHandler: the hardware does, between two of main's instructions. LR, the link register, normally holds a return address, but p/x $lr shows 0xFFFFFFF9, a special return code. While halted here, bytes keep arriving.
Guard line 4 with "if (n < 16) rx.buf[n++] = c;". Now bytes past the end are dropped, and n stops at 16. Run again with the watchpoint set: it never fires, and rx.cb keeps 0x08000351.
What happens
;; step 1/10 · connect board STM32F4DISCOVERY (STM32F407VGT6, Cortex-M4) $ openocd -f board/stm32f4discovery.cfg $ arm-none-eabi-gdb app.elf (gdb) target extended-remote :3333 (gdb) monitor reset halt laptop -> USB -> ST-LINK -> SWD (SWDIO, SWCLK) -> chip
The card is an excerpt. The full ISR first reads the byte with char c = USART2->DR; main() calls rx.cb() when ready is set and then resets n. Writing rx.buf[16] is undefined behaviour in C; in practice, with this struct, it lands on the first byte of cb. The addresses come from one example build: flash starts at 0x08000000 on the STM32F407, so on_line() at 0x08000351 is plausible, but your linker may place it elsewhere. Thumb function pointers are odd, and the Cortex-M4 stores words little-endian here.