Try Embedded

Debugging embedded systems

JTAG and SWD, GDB, hard faults and a method for finding bugs.

Debugging is a method, not luck

Embedded bugs are harder than desktop bugs: limited visibility, timing that changes when you observe it, hardware that may itself be at fault, and failures that appear once a week in the field. Good embedded debuggers rely on a method and the right tools.

The method

  1. Reproduce. Find the shortest, most reliable way to trigger the failure. A bug that happens "sometimes" needs a stress test, a loop or a fault-injection rig until it happens on demand.
  2. Observe before changing. Gather facts: logs, fault registers, a logic analyser trace, the reset cause. Do not guess and patch.
  3. Form one hypothesis that explains all the observations.
  4. Test it with the smallest experiment that could prove it wrong.
  5. Bisect when stuck: between a working and a failing version (git bisect), between working and failing inputs, or by removing half the system.
  6. Fix the cause, not the symptom, and add a test or assertion that would have caught it.
  7. Write it down. The same bug class will come back.

Debug probes: JTAG and SWD

A debug probe connects the PC to the chip's debug port:

JTAGSWD (Serial Wire Debug)
PinsTCK, TMS, TDI, TDO (+ TRST)SWCLK, SWDIO
ChainsSeveral chips in a daisy chainOne target (multi-drop in SWD v2)
Also used forBoundary scan (testing board connections)—
On Cortex-MSupportedThe usual choice: two pins

Plus SWO (serial wire output), a third pin for trace data and fast printf-style output via the ITM.

Probes: SEGGER J-Link, ST-LINK, CMSIS-DAP / DAPLink, Black Magic Probe, Lauterbach TRACE32 (high end). Host software: OpenOCD, pyOCD or J-Link GDB Server, which speak the GDB remote protocol.

What the debug hardware gives you: halt and step, read and write memory and registers while running, hardware breakpoints (a limited number, typically 4 to 8 on Cortex-M, required for code in flash), and data watchpoints (stop when an address is written: the best tool for "who is corrupting this variable?").

GDB remotely

# terminal 1: the probe server
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg

# terminal 2
arm-none-eabi-gdb build/firmware.elf
(gdb) target extended-remote :3333
(gdb) monitor reset halt
(gdb) load                          # flash the image
(gdb) break uart_rx_irq
(gdb) watch rx_count                # stop when it changes
(gdb) continue
(gdb) bt                            # backtrace
(gdb) info registers
(gdb) x/16xw 0x20000000             # examine memory
(gdb) p/x *GPIOA                    # print a peripheral struct

IDEs (VS Code with Cortex-Debug, STM32CubeIDE, Segger Ozone) wrap the same mechanisms and add peripheral register views from SVD files.

HardFault analysis

On Cortex-M, an illegal operation (bad memory access, undefined instruction, unaligned access where not allowed, divide by zero if trapping is enabled, executing from a non-executable address) raises a fault that escalates to HardFault. The CPU has already stacked R0 to R3, R12, LR, PC and xPSR, so the faulting instruction's address is recoverable. The fault status registers explain why:

RegisterTells you
CFSR (UFSR, BFSR, MMFSR)Which fault: usage, bus or memory-management, and the specific cause bits
HFSRWhether a fault escalated (FORCED) or came from a vector-table read
BFAR, MMFARThe faulting data address, when the valid bits are set
Stacked PCThe instruction that faulted (or the next one, for imprecise bus faults)
Stacked LRThe caller, and EXC_RETURN tells which stack (MSP or PSP) was in use
#include <stdio.h>
#include <stdint.h>

/* Decode the Configurable Fault Status Register (CFSR) as a fault handler would. */
static void decode_cfsr(uint32_t cfsr) {
  static const struct { uint32_t bit; const char *meaning; } bits[] = {
    { 1u << 0,  "MMFSR IACCVIOL: instruction access violation (execute from XN region)" },
    { 1u << 1,  "MMFSR DACCVIOL: data access violation (MPU)" },
    { 1u << 7,  "MMFSR MMARVALID: MMFAR holds the faulting address" },
    { 1u << 8,  "BFSR IBUSERR: instruction bus error" },
    { 1u << 9,  "BFSR PRECISERR: precise data bus error, BFAR valid if BFARVALID" },
    { 1u << 10, "BFSR IMPRECISERR: imprecise data bus error (PC is not exact)" },
    { 1u << 15, "BFSR BFARVALID: BFAR holds the faulting address" },
    { 1u << 16, "UFSR UNDEFINSTR: undefined instruction" },
    { 1u << 17, "UFSR INVSTATE: invalid state (e.g. Thumb bit clear in a branch target)" },
    { 1u << 18, "UFSR INVPC: invalid EXC_RETURN" },
    { 1u << 24, "UFSR UNALIGNED: unaligned access" },
    { 1u << 25, "UFSR DIVBYZERO: divide by zero" },
  };
  printf("CFSR = 0x%08X\n", cfsr);
  for (unsigned i = 0; i < sizeof bits / sizeof bits[0]; i++)
    if (cfsr & bits[i].bit) printf("  %s\n", bits[i].meaning);
}

int main(void) {
  decode_cfsr(0x00008200u);   /* PRECISERR + BFARVALID: e.g. a NULL-ish or unmapped pointer */
  decode_cfsr(0x02000000u);   /* DIVBYZERO */
  return 0;
}

A production fault handler should save these registers plus the stacked frame to a no-init RAM area, reset, then report them on the next boot, where addr2line turns the PC and LR into source lines.

Common causes: NULL or dangling pointers, stack overflow (the MPU or a stack canary catches it), calling through an uninitialised function pointer, a peripheral accessed before its clock is enabled (bus fault), and the FPU used before being enabled.

Logging and tracing without breaking timing

Breakpoints stop the world, which breaks anything time-dependent (motor control, communication protocols). Alternatives:

  • printf over UART: simple, but slow (about 87 µs per character at 115200 baud) and blocking; use a buffered, interrupt- or DMA-driven logger.
  • SEGGER RTT / semihosting-free ring buffers in RAM read by the probe in the background: microseconds per message.
  • ITM/SWO trace output.
  • GPIO toggles viewed on a logic analyser or scope: the lowest-overhead way to measure timing and see interrupt order.
  • Instruction trace (ETM) with a trace probe: a complete record of executed instructions, for the hardest bugs.
  • Event recorders (Percepio Tracealyzer, SEGGER SystemView) for RTOS behaviour: task switches, queue operations, timing.

Classes of bug and the first thing to try

SymptomFirst suspect
Works in debug build, fails in releaseMissing volatile, undefined behaviour exposed by optimisation, timing
Works under the debugger, fails aloneTiming, watchdog (frozen in debug), uninitialised memory
Random corruption of a variableBuffer overrun next to it, stack overflow, DMA into the wrong buffer: set a watchpoint
Fails after hours or daysLeak, counter or timer overflow, heap fragmentation, rare race
Fails only on some boardsHardware tolerance, clock accuracy, power supply, uninitialised RAM content
Peripheral does nothingClock not enabled, pin mux, wrong mode, wrong instance

Pitfall: Adding a printf that makes a bug disappear does not fix it. It changed the timing or the stack layout, which is a strong hint that the bug is a race, an uninitialised variable or a buffer overflow.

Interview question: Your firmware occasionally HardFaults in the field. How do you find the cause?

Answer: Make the HardFault handler capture the evidence: the stacked exception frame (PC, LR, xPSR and registers) from the correct stack (MSP or PSP per EXC_RETURN), and the CFSR, HFSR, BFAR and MMFAR registers, saved to a no-init RAM section with a checksum, then reset. On the next boot, report the record. Decode the fault bits to know the type (bus error, MPU violation, undefined instruction, unaligned, divide by zero), and map PC and LR to source with addr2line on the exact release ELF. Then reproduce under the debugger with stress tests, stack-overflow detection and watchpoints.

Interview question: How do you debug a timing-sensitive problem where breakpoints change the behaviour?

Answer: Use non-intrusive observation: toggle GPIOs at points of interest and capture them with a logic analyser or scope alongside the external signals; log into a RAM ring buffer read by the probe in the background (RTT) or via ITM/SWO; use an RTOS trace tool to see task switches and interrupt timing; use the DWT cycle counter to timestamp events; and if available, ETM instruction trace. Then analyse after the fact instead of halting the system.

Exercises: read the GDB session

Each exercise is a bug report and the GDB session an engineer ran on an STM32F4 board through a debug probe. Read the session and decide what it proves before you look at the options.

1. A variable that changes by itself. motor_speed jumps to random values while the motor runs.

(gdb) watch motor_speed
Hardware watchpoint 2: motor_speed
(gdb) continue
Hardware watchpoint 2: motor_speed

Old value = 1200
New value = 1074
uart_rx_irq () at src/uart.c:48
48	    rx_buf[rx_head++] = USART2->DR;
(gdb) p &motor_speed
$1 = (uint16_t *) 0x20000440 <motor_speed>
(gdb) p &rx_buf[64]
$2 = (uint8_t *) 0x20000440 <motor_speed>
(gdb) ptype rx_buf
type = uint8_t [64]

2. A HardFault a few milliseconds after reset.

(gdb) bt
#0  HardFault_Handler () at src/fault.c:12
#1  <signal handler called>
#2  0x00000000 in ?? ()
#3  0x08000a52 in timer_tick () at src/timer.c:22
#4  <signal handler called>
#5  main () at src/main.c:40
(gdb) frame 3
#3  0x08000a52 in timer_tick () at src/timer.c:22
22	  on_tick();
(gdb) p on_tick
$1 = (void (*)(void)) 0x0
(gdb) x/xw 0xE000ED28
0xe000ed28:	0x00020000

3. An LED that never lights.

(gdb) break led_init
(gdb) continue
Breakpoint 1, led_init () at src/led.c:14
14	  GPIOA->MODER |= 1u << 10;      /* PA5 as an output */
(gdb) next
15	  GPIOA->ODR |= 1u << 5;
(gdb) p/x GPIOA->MODER
$1 = 0x0
(gdb) p/x RCC->AHB1ENR
$2 = 0x100000

4. A loop that never ends. The main loop waits for a flag that a DMA-complete interrupt sets, and hangs in release builds only.

(gdb) interrupt
main () at src/main.c:28
28	  while (!data_ready) { }
(gdb) p data_ready
$1 = 1
(gdb) x/3i 0x8000410
   0x8000410 <main+16>:	cbnz	r2, 0x8000414 <main+20>
=> 0x8000412 <main+18>:	b.n	0x8000412 <main+18>
   0x8000414 <main+20>:	bl	0x8000600 <process>

Build it: turn a crash into a bug report

This is step 1 of the module project, a wrist-worn heart-rate monitor. Watches in the field crash about once a week and reboot. Nobody can attach a debugger to a customer's wrist, so the firmware saves the Cortex-M fault registers and the stacked registers before rebooting, and uploads them. Your code turns those numbers into a diagnosis.

Lab: Decode a Cortex-M HardFault

On a fault the core pushes 8 registers onto the stack, in this order: R0, R1, R2, R3, R12, LR, PC, xPSR. The Configurable Fault Status Register (CFSR) says what went wrong; MMFAR and BFAR may hold the faulting address.

CFSR bitNameMeaning
0 / 1IACCVIOL / DACCVIOLMPU violation on an instruction fetch / data access
4MSTKERRthe MPU stopped the stacking on exception entry
7MMARVALIDMMFAR holds the address of the data access violation
9PRECISERRa bus fault on a data access, at an exact instruction
10IMPRECISERRa bus fault on a buffered write: the PC is already past the culprit
12STKERRa bus fault while stacking on exception entry
15BFARVALIDBFAR holds the address of the precise bus fault
16UNDEFINSTRan undefined instruction
17INVSTATEthe Thumb bit was clear: a call through a bad function pointer
24 / 25UNALIGNED / DIVBYZEROan unaligned access / an integer division by zero (when trapping is on)

Write fault_cause(cfsr, mmfar, bfar, addr), which returns one of the provided cause strings, checking in this order (the first that matches wins):

  1. STKERR or MSTKERR: CAUSE_STACK (the stacked registers cannot be trusted).
  2. INVSTATE: CAUSE_BAD_FPTR. 3. UNDEFINSTR: CAUSE_UNDEF. 4. DIVBYZERO: CAUSE_DIV0. 5. UNALIGNED: CAUSE_UNALIGNED.
  3. PRECISERR: CAUSE_NULL if BFARVALID is set and BFAR is below 0x1000, otherwise CAUSE_BUS.
  4. IMPRECISERR: CAUSE_IMPRECISE. 8. DACCVIOL or IACCVIOL: CAUSE_MPU. 9. Otherwise CAUSE_UNKNOWN.

It stores the faulting address in *addr when one is known (BFAR with BFARVALID for a precise bus fault, MMFAR with MMARVALID for an MPU data violation), and NO_ADDR otherwise.

Also write fault_pc(frame) and fault_lr(frame), which return the stacked PC and LR.

Going deeper

Interview question: One thermostat in a thousand freezes every few days in the field. How do you find it?

Answer: Get data first: a watchdog with the reset reason and a crash record saved across resets, telemetry of uptime and resets per unit, and logs around the event. Look for what is common to the failing units (hardware revision, network, configuration). Reproduce by stressing that condition, then confirm the root cause with the debugger or extra instrumentation before fixing.

Interview question: How do you debug a bug that only appears after days of running?

Answer: Log continuously and cheaply (event counters, timestamps, a RAM ring buffer saved on fault), capture crash records with fault handlers, and watch resource trends such as heap, stack high-water marks, queue depths and counters for leaks or overflow. Accelerate time where possible (shorter timer periods, simulated rollover by starting counters near their limit) and stress test. Bugs that appear after 49.7 days point at a 32-bit millisecond counter wrapping.

Interview question: What is the difference between a hardware and a software breakpoint?

Answer: A software breakpoint replaces an instruction with a breakpoint instruction, which works only in writable memory such as RAM. A hardware breakpoint uses comparators in the debug unit that match the program counter, so it works in flash; Cortex-M cores provide only a few (typically 4 to 8). Debuggers use hardware breakpoints for flash automatically, which is why setting too many fails.

Explain it: In your own words, describe a systematic method for debugging an intermittent firmware bug.

Answer: First find a way to reproduce it reliably, using stress tests, loops or fault injection, because a bug you cannot trigger cannot be confirmed fixed. Gather evidence before changing anything: logs, fault registers, reset causes, logic analyser captures. Form one hypothesis that explains all the evidence and design the smallest experiment that could disprove it. If stuck, bisect, between versions with git bisect, between inputs, or by removing parts of the system. Fix the root cause, add a test or assertion that would have caught it, and record what you learned.