4G remote monitoring for compactors & critical equipment
Free 1-month trial
Technical & AI

Professional embedded debugging with JTAG, OpenOCD and GDB

10 août 202612 min readIOTINNOV Team

Debugging embedded systems has long been the poor relation of software engineering. In web or application development, graphical debuggers, structured logs and automated tests are part of the daily routine. On microcontrollers, many teams still make do with printf and spend days guessing why a firmware behaves poorly under real conditions. This is not inevitable: a toolchain composed of a JTAG/SWD probe, OpenOCD and GDB offers on a microcontroller a level of visibility close to that of a desktop environment. This article details the complete method, from hardware selection to hard fault analysis, all the way to integration into a continuous integration pipeline.

Why printf debugging reaches its limits

The reflex of using printf, or its equivalents UART_LOG, ESP_LOGx or Serial.print(), works as long as the bug is in pure application logic. It fails in four typical situations of industrial embedded systems:

  • Timing problems. Adding a printf modifies execution times, shifts interrupts and can make the bug disappear, or appear. Instrumentation modifies the observed behavior: this is the classic "it works in debug, it crashes in release".
  • Hard faults and other exceptions. When the processor jumps into the exception vector, printf no longer executes. You must inspect the registers, the stack and the PC to understand what happened.
  • Optimization-related bugs. With -O2, the compiler reorders, removes and transforms code. Observed variables may be optimized away, and the behavior may differ from that of the unoptimized version.
  • Resource consumption. A text output consumes flash (printf formatting can represent several kilobytes), CPU time, the UART and energy, which is prohibitive on a battery-powered IoT node.

Hardware probe debugging addresses these limits: it adds no code to the firmware, does not alter timings (except at breakpoints) and gives access to the complete processor state, including during an exception.

JTAG and SWD: the two debugging interfaces

Before choosing a probe, you need to understand the two protocols it speaks. They are not interchangeable: they respond to different constraints.

JTAG (IEEE 1149.1), the historical standard

JTAG (Joint Test Action Group) is standardized under IEEE 1149.1. Originally designed for board testing via boundary scan, that is, the ability to drive each pin of a circuit from the test chain, it has become the de facto standard for processor debug access. It requires four mandatory signals: TCK (clock), TMS (state selection), TDI (data input) and TDO (data output), to which TRST (TAP controller reset) is often added. Communication relies on a state machine, the TAP (Test Access Port), driven by TMS and TCK, which gives access to a chain of internal registers.

The main advantage of JTAG is its genericity: it works on ARM, RISC-V, embedded x86, FPGA and most architectures. It also allows chaining multiple chips on the same interface (daisy-chain), which is useful for programming multiple components on the same board. Its drawbacks: the number of pins and a speed often limited by the board topology.

SWD (Serial Wire Debug), the ARM alternative

Developed by ARM for its Cortex cores, SWD reduces the interface to two signals: SWDIO (bidirectional data) and SWCLK (clock). With comparable performance, it saves space on boards where every pin counts, and it has become the default interface for virtually all ARM Cortex-M microcontrollers. Common probes (ST-Link, J-Link, CMSIS-DAP, DAPLink) support it natively.

The practical choice is simple: on an ARM Cortex-M core, use SWD. JTAG remains relevant for non-ARM architectures (RISC-V, FPGA), for boundary scan in production, or when the test equipment on the manufacturing line requires it.

Choosing your debug probe

The probe bridges the host (development workstation, continuous integration server) and the target. Its choice depends on the microcontroller family, budget and speed requirements.

  • ST-Link/V2 and V3: the probe integrated into STM32 evaluation boards. Excellent in the ST ecosystem, it handles SWD and JTAG (depending on the version) with sufficient throughput for the vast majority of use cases. The V3 reaches several tens of megahertz and adds a virtual COM port (VCP).
  • SEGGER J-Link: the reference in speed and features (RTT, accelerated flash programming, support for numerous ARM architectures and RISC-V on recent models). The EDU versions, inexpensive but reserved for non-commercial use, are suitable for learning; commercial versions are justified notably by their license and programming speed in production.
  • CMSIS-DAP / DAPLink: the open interface defined by ARM, implemented on low-cost boards (Raspberry Pi Pico with the debugprobe firmware, evaluation boards equipped with DAPLink, etc.). Ideal for economical debugging and large-scale deployment on continuous integration benches.
  • ESP-Prog and ESP32 probes: for the Espressif ecosystem, the official ESP-Prog probe provides JTAG, UART and programming; the ESP32-S3 and ESP32-C3 integrate a USB-Serial-JTAG controller directly, so a simple USB cable is enough to debug.
  • FTDI probes (FT2232H): these inexpensive generic adapters are OpenOCD-compatible and cover less common architectures.

For a team designing industrial IoT products, a pragmatic rule: one probe per engineer for development (J-Link or ST-Link depending on the architecture), and low-cost CMSIS-DAP probes for automated test benches, where throughput matters little and unit cost matters a lot.

OpenOCD: the universal software bridge

OpenOCD (Open On-Chip Debugger) is the free software that makes the probe and the target communicate. It supports dozens of probes and hundreds of targets, and exposes a GDB server (port 3333 by default), a Telnet server (4444) and a Tcl server (6666). It is the central tool of any non-proprietary debugging toolchain.

A typical launch for an STM32 target with an ST-Link probe:

openocd -f interface/stlink.cfg -f target/stm32f4x.cfg

For an ESP32-S3 with the integrated USB-Serial-JTAG controller:

openocd -f interface/esp_usb_jtag.cfg -f target/esp32s3.cfg

Configuration files are the key element: interface/*.cfg describes the probe (pins, speed, protocol), target/*.cfg describes the processor (architecture, registers, memory, flash programming algorithms). OpenOCD natively supports most microcontrollers on the market; for recent chips, you may sometimes need to write or adapt a target file, an operation well documented by the project.

Essential commands:

  • reset halt: resets the target and immediately halts it, the starting state of any debugging session.
  • flash write_image erase: programs the flash after erasing.
  • program file.elf verify reset: programs, verifies and restarts in one command, very convenient in continuous integration.
  • mdw / mww: word-by-word memory read and write.
  • reg: displays the registers of the current core.
  • halt / resume: halts and resumes execution.

GDB in remote mode: complete debugging

Once OpenOCD is running, GDB connects to it as to a remote target:

arm-none-eabi-gdb firmware.elf
(gdb) target remote :3333
(gdb) monitor reset halt
(gdb) load
(gdb) continue

The OpenOCD and GDB pair offers all the functions expected from a debugger: breakpoints, step-by-step execution, variable and memory inspection, backtrace. Two points deserve particular attention in embedded systems.

Hardware and software breakpoints

On a Cortex-M, GDB uses hardware breakpoints when code runs from flash, because it cannot insert a breakpoint instruction (BKPT) there. Their number is limited, typically 4 to 8 depending on the core (FPB unit, Flash Patch and Breakpoint): beyond that, GDB can only use software breakpoints if the code is in RAM, otherwise it fails. Conditional breakpoints are valuable but costly: at each pass, the target is stopped and the condition is evaluated by GDB, which greatly slows down execution. On a heavily executed line, it is better to use ignore to skip a given number of passes, or temporarily place a test in the code that executes __asm volatile("bkpt 0") when the condition is met.

Watchpoints: monitoring a variable

The watchpoint interrupts the processor when a memory address is read or written. It is the reference tool for tracking memory corruption: a variable that changes value without explanation, a buffer overflow that overwrites a neighboring structure. On ARM, watchpoints are hardware-based (DWT unit) and limited to 2 to 4 depending on the cores: they must therefore be used sparingly. The command is simple:

(gdb) watch suspect_variable
(gdb) watch *(uint32_t*)0x20000100

When the watchpoint triggers, the backtrace immediately shows which code wrote to that address. For memory corruptions, this is the fastest method there is.

Inspecting memory and peripherals

Beyond C variables, GDB allows direct inspection of memory and peripheral registers:

(gdb) x/16wx 0x20000000      # 16 words in hexadecimal
(gdb) x/8bx 0x40021000       # registers of a peripheral
(gdb) p/x *(uint32_t*)0x40021000

This allows verifying the state of a peripheral register, the alignment of a DMA buffer or the exact content of a queue before it is consumed.

Debugging FreeRTOS: seeing tasks, not just the CPU

A FreeRTOS firmware is not debugged like a linear program: the code executing at the breakpoint is only one task among others, and the global state of the system is found in the task list, queues and semaphores. Without help, GDB only shows the current context.

OpenOCD integrates FreeRTOS support, to be activated in the target configuration ($_TARGETNAME configure -rtos FreeRTOS, or -rtos auto). It then relies on kernel symbols, such as pxCurrentTCB (recent versions of FreeRTOS also require uxTopUsedPriority to be retained at link time), to expose each task as a GDB thread. The info threads command lists all tasks, and thread N allows switching to one of them to inspect its stack. This is the difference between "the system is stuck" and "the sensor task is waiting for a semaphore that the network task never releases". The underlying architecture choices are detailed in our article FreeRTOS in industrial environments: architecture, pitfalls and best practices for embedded IoT.

Two checks are necessary in case of erratic behavior:

  • The high-water mark of each stack. The uxTaskGetStackHighWaterMark() function returns the minimum free space observed on a task's stack. Task stack overflow is one of the most common causes of random hard faults in production, and it remains invisible without this measurement.
  • The overflow detection hook. With configCHECK_FOR_STACK_OVERFLOW set to 1 or 2, FreeRTOS calls vApplicationStackOverflowHook() when an overflow is detected. In development, this hook can simply halt the system (__asm volatile("bkpt 0")) to analyze the stack with GDB.

Analyzing a hard fault: the method that saves days

The hard fault is the most dreaded event: the processor jumps into the exception handler and the program appears "dead". Without a probe, only manual decoding of fault registers remains, a tedious task. With GDB, the procedure is fast:

  1. monitor reset halt: put the target in a known state.
  2. Place a breakpoint on HardFault_Handler (break HardFault_Handler), then continue and reproduce the faulty scenario.
  3. When it triggers, examine the fault registers. On Cortex-M3/M4/M7, SCB->CFSR (0xE000ED28) indicates the cause: invalid memory access, bus fault, illegal instruction, or division by zero and unaligned access if their detection has been enabled. SCB->HFSR (0xE000ED2C) indicates whether the fault was escalated to a hard fault.
  4. Read SCB->BFAR (0xE000ED38) for the faulty address of a bus fault, and SCB->MMFAR (0xE000ED34) for that of a memory protection fault, checking in CFSR that the address is valid.
  5. Unstack the registers automatically saved by the hardware (R0-R3, R12, LR, PC, xPSR), on the MSP or PSP stack depending on bit 2 of the EXC_RETURN value contained in LR, to find the PC of the faulty instruction, then run bt for the complete backtrace.

In practice, the vast majority of hard faults are resolved by reading CFSR and the faulty PC: most often, it is a NULL or invalid pointer, a stack overflow, or an access to a peripheral whose clock is not enabled. With the probe, these three cases are diagnosed in a few minutes, instead of hours of guesswork with printf.

Semihosting, ITM and RTT: debug output without UART

When you need logs without tying up a UART, three mechanisms leverage the debug interface.

Semihosting: the target code calls a host function (printf, fopen...) via a special instruction (BKPT on Cortex-M, SVC on older ARM cores). The debugger intercepts the call and processes it on the host. No additional pin is needed, but execution is stopped at each call, and a firmware using semihosting faults if no debugger is connected: reserved for development.

ITM/SWO (Instrumentation Trace Macrocell): on Cortex-M3/M4/M7, the ITM sends trace data on the SWO pin, at high throughput and without stopping the processor. By redirecting printf (or better, ITM_SendChar) to the ITM, you get real-time logs with minimal overhead. Note: Cortex-M0 and M0+ do not have SWO.

SEGGER RTT (Real-Time Transfer): a small RAM area shared between the target and the host, read by the probe without stopping the processor. The microcontroller writes to RAM, the probe reads in the background: the method is very fast, requires no dedicated pin and works with J-Link as well as with OpenOCD. This has become the preferred solution for teams wanting high-frequency logs.

In an industrial IoT project, the recommended organization is as follows: RTT or ITM for development logs, a service UART for production logs (on-site diagnostics), and never blocking printf in an interrupt routine.

Integrating debugging into the continuous integration pipeline

The probe is not only for interactive debugging: it makes firmware validation automatable and reproducible. Driven by a script, OpenOCD allows:

  • programming the target after each build: openocd -f interface/... -f target/... -c "program build/firmware.elf verify reset exit";
  • running hardware tests: launch the firmware, wait for an RTT pattern or a memory value, verify that a GPIO switches to the expected state, then produce a test report;
  • capturing coredumps: when a test fails, halt the target and extract its complete state (registers, stack, memory) for offline analysis, like an application crash dump;
  • measuring metrics: boot time, CPU load per task (via the DWT cycle counter), latency between an interrupt and its handling, all objective data to validate real-time requirements.

GDB in batch mode (gdb -batch -ex "target remote :3333" -ex "..." firmware.elf) allows automating checks: read a variable, compare it to an expected value and exit with an error code usable by the continuous integration server. With inexpensive CMSIS-DAP probes connected to test benches, you get a distributed hardware test infrastructure for a fraction of the cost of dedicated test equipment.

Best practices from the field

A few reflexes that genuinely improve an embedded team's productivity:

  • Always compile with debug information (-g), including in release: it stays in ELF sections that are never programmed to flash, so it costs nothing on the target.
  • Disable optimization on suspicious areas: compiling a specific file in -O0, or a function with __attribute__((optimize("O0"))), allows debugging a module without losing the benefit of global optimization.
  • Archive the complete ELF of each build with its version number: it is the only way to analyze the crash of a deployed firmware. Finding the exact build and loading its ELF into GDB gives the backtrace of the failure.
  • Use assertions and fault hooks: FreeRTOS configASSERT, stack overflow hooks and a hard fault handler that halts the system and writes its state to a persistent memory area. In production, this area can be reported via the telemetry channel: it is a remote mini-coredump, to be protected like the rest of the firmware (see Security of industrial IoT firmwares: secure boot, flash encryption and secure OTA).
  • Centralize the project's OpenOCD and GDB commands in a Makefile (make debug, make flash, make test) so that each team member, as well as the continuous integration pipeline, uses exactly the same configuration.
  • Check voltage levels and link speed: a probe poorly matched to the target voltage (1.8 V or 3.3 V) produces intermittent errors that look like firmware bugs. The probe must read the target reference voltage (VTref), and a link frequency too high (adapter speed) for the wiring causes the same type of symptoms.

Conclusion

Professional embedded debugging is not a luxury reserved for large design offices: a probe costing a few dozen euros, OpenOCD and GDB form a complete toolchain. Days lost guessing the origin of a hard fault become analyses of a few minutes, production crashes become exploitable coredumps, and hardware validation enters continuous integration on the same footing as unit tests. For an industrial SME, it is often the difference between a project that slips by several weeks and a controlled time-to-market.

An embedded IoT project?

Our team designs the box, its firmware and the platform. Let's discuss your needs.