Skip to content
Tech Interview Prep
Technical interview guide

Embedded Debugging & Toolchains

How embedded engineers actually find bugs when there's no stdout, no OS, and sometimes no working UART to print through.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Current GDB remote debugging and GCC debug guidance; current OpenOCD user guide; CMSIS 6 SVD/DAP/CoreDebug reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Walk me through the stages of a C/C++ cross-compilation toolchain from source files to final flashable images (.elf, .hex, .bin), explaining what each tool transforms and resolves.

Answer

The 90-second version

gcc is a driver, not a compiler. It runs four tools in sequence, passing the target flags (-mcpu=cortex-m4 -mthumb) down to each: cpp → cc1/cc1plus → as → ld. Each stage lowers the representation and resolves one class of unknown: text, then AST, then target assembly, then a relocatable object with symbolic references, then a fully addressed ELF. .hex and .bin are not stages: they are objcopy re-encodings of the ELF's loadable segments.

Assume bare-metal Cortex-M, arm-none-eabi-gcc, newlib-nano, flash at 0x08000000, RAM at 0x20000000.

StageToolIn → OutWhat it resolves
Preprocesscpp (-E).c/.h → .i#include, #define, #if; emits #line markers
Compilecc1/cc1plus (-S).i → .sParse, type-check, optimize, select target instructions
Assembleas (-c).s → .oMnemonics → opcodes; builds .text/.data/.rodata/.bss plus symbol and relocation tables
Linkld (-Wl,-T).o + .a + .ld → .elfSymbol resolution, VMA/LMA placement, relocation patching, CRT startup
Extractobjcopy.elf → .hex/.binNothing new: re-encodes loadable segments

Linker: the only stage that knows addresses. ld merges same-named sections from every .o, places them at addresses from the script's MEMORY/SECTIONS, and patches each relocation with the final address. It also pulls in CRT startup (crt0.o, or your startup_stm32.s), which copies .data from its flash LMA to its RAM VMA and zeroes .bss before main. -ffunction-sections -fdata-sections plus -Wl,--gc-sections drops unreferenced functions; without the first two flags, --gc-sections can only drop whole object files.

objcopy: re-encoding, not compiling. The .elf keeps section headers, the symbol table and DWARF. objcopy -O ihex writes ASCII Intel HEX records, each carrying its own address and checksum, so non-contiguous regions cost nothing. objcopy -O binary writes one flat stream from the lowest to the highest loadable LMA: addresses are gone, so the programmer needs a base address supplied separately.

Worked trace

C
// blink.c
volatile uint32_t ticks;
const char banner[] = "blink";
int main(void) { for (;;) ticks++; }
Shell
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O2 \
  -ffunction-sections -fdata-sections -c blink.c -o blink.o
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -T stm32.ld \
  -Wl,-Map=blink.map -Wl,--gc-sections -Wl,--print-memory-usage \
  blink.o -o blink.elf
arm-none-eabi-objcopy -O ihex   blink.elf blink.hex
arm-none-eabi-objcopy -O binary blink.elf blink.bin

ticks lands in .bss: no initialiser, so it occupies no image bytes. banner lands in .rodata and does occupy image bytes. arm-none-eabi-size blink.elf prints text/data/bss, but blink.bin's length is not text + data: it is the span from the lowest to the highest loadable LMA, because objcopy -O binary uses LMA. That is also why .data's initialisers appear in the image even though .data lives in RAM.

Now the gap arithmetic. If the script puts the bootloader at 0x08000000 and the app at 0x08040000, the binary spans 0x08040000 - 0x08000000 = 0x40000, i.e. 256 KiB of zeros in the middle. Flashing that writes over whatever lives in those sectors. The .hex does not have this problem: each record carries its address, so the programmer skips the hole. If you must ship a .bin, extract per region (objcopy -O binary -j .app blink.elf app.bin) or flash the hex.

Failure modes worth naming

  • undefined reference to 'foo' at link: declared but never defined. arm-none-eabi-nm the .a files to see what is actually there.
  • region FLASH overflowed by N bytes: the script's region is too small. -Wl,--print-memory-usage or the .map shows which section grew.
  • Globals read garbage at runtime: .data was never copied from flash, or .bss never zeroed. Check the startup code and the .map LMA/VMA columns.
  • Illegal instruction on target: object built for the wrong -mcpu/-mthumb. objdump -d shows the encoding.

Verification: readelf -S for sections, nm for symbols, objdump -d for disassembly, -Wl,-Map for placement.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How do MEMORY regions, sections (.text, .rodata, .data, .bss), and linker script symbols define the physical storage and runtime execution layout of embedded firmware across Flash and RAM?

Answer

The 90-second answer. MEMORY declares the physical address windows the part actually has (flash at 0x08000000, SRAM at 0x20000000 on an STM32) and SECTIONS decides which bytes land in them. One idea explains the whole layout: every output section has two addresses. The LMA is where the flasher writes the bytes; the VMA is where the CPU expects them at runtime. Code and constants are execute-in-place, so LMA == VMA in flash. Initialized variables need both: their bytes live in flash (LMA) but must be writable, so the VMA is in RAM and startup code copies them across. Zero-initialized variables have no bytes at all, so .bss has a VMA in RAM and no LMA. Symbols like _sdata and _edata are addresses the copy loop compares against: they hold no storage.

LD
MEMORY {
    FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 512K
    RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}

SECTIONS {
    .text : {
        KEEP(*(.isr_vector))
        *(.text*)
        *(.rodata*)
        . = ALIGN(4);
        _etext = .;
    } > FLASH

    _sidata = LOADADDR(.data);

    .data : {
        . = ALIGN(4);
        _sdata = .;
        *(.data*)
        . = ALIGN(4);
        _edata = .;
    } > RAM AT > FLASH

    .bss (NOLOAD) : {
        . = ALIGN(4);
        _sbss = .;
        *(.bss*)
        *(COMMON)
        . = ALIGN(4);
        _ebss = .;
    } > RAM
}

> RAM AT > FLASH is the whole trick: VMA in RAM, LMA in flash. (NOLOAD) makes the intent explicit: .bss is SHT_NOBITS, so it consumes no file space even without the keyword.

Tracing the startup copy. With _sidata = 0x08001234, _sdata = 0x20000000, _edata = 0x20000100:

C
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss;

void Reset_Handler(void) {
    uint32_t *src = &_sidata;   // 0x08001234
    uint32_t *dst = &_sdata;    // 0x20000000
    while (dst < &_edata) { *dst++ = *src++; }  // 64 iterations, 256 bytes

    dst = &_sbss;
    while (dst < &_ebss)  { *dst++ = 0; }

    SystemInit();
    main();
}

dst walks 0x20000000 → 0x20000100, so the loop runs 64 times and copies 256 bytes from flash to RAM. The ALIGN(4) calls are what make the word-at-a-time loop safe; without them the loop overruns _edata and clobbers whatever section follows.

Where the canonical layout is the wrong choice.

  • XIP vs copy-to-RAM for .text. Executing from flash costs wait states: an STM32F4 at 168 MHz needs 5 flash wait states (RM0090), mitigated by the ART accelerator/prefetch. Copying hot code to RAM gives deterministic zero-wait-state execution, and is required when flash is being erased or programmed: on most parts the flash controller stalls the bus, so any code running from flash halts mid-write. That is why flash-programming routines are placed in a RAM section. The cost is RAM and boot time.
  • .data in RAM vs flash-resident. A lookup table that is never written belongs in .rodata and stays in flash. Declaring it non-const silently doubles its cost: flash bytes plus a RAM copy plus boot time. Conversely, a table read on every interrupt may be worth copying to RAM deliberately.
  • Symbol loops vs copy tables. The crt0 loop is simple but O(size) every boot: 64 KB of .data is 16 384 words, roughly 0.4–0.6 ms at 168 MHz with flash wait states (approximate, depends on wait states and prefetch). Linker-generated copy tables (ARM scatter-loading, or multiple LOADADDR pairs) handle non-contiguous regions and let a bootloader decompress instead of copying raw.
  • When the map itself is wrong. A part with no internal flash (booting from external QSPI or RAM) has a MEMORY block describing RAM only. Multi-core parts need one script per core with shared RAM explicitly reserved, or both cores place .bss at the same address. On STM32F4, CCM RAM is not reachable by DMA, so DMA buffers must not land there: placement is a correctness constraint, not a sizing one. And MEMORY's rx/rw attributes are advisory to the linker; only the MPU enforces them at runtime.

Failure modes.

FailureMechanismSymptom
.data written > RAM without AT > FLASHLMA == VMA in RAM; no initial values in the imageVariables hold garbage on boot
uint32_t start = _sdata; instead of &_sdataReads the word stored at the boundary, not the boundary addressCopy loop starts from a data value
Missing ALIGN(4) between sectionsWord loop overruns _edataFirst words of the next section corrupted

Inspect with arm-none-eabi-objdump -h <elf> (shows VMA and LMA per section) or arm-none-eabi-readelf -S <elf>, then check total flash usage against LENGTH.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do JTAG and SWD hardware debug interfaces work at the physical and protocol levels, and how do on-chip units implement hardware breakpoints, watchpoints, and real-time instruction trace like SWO and ETM?

Answer

Hardware debugging operates on a layered architecture separating physical transport, memory-mapped system access, and dedicated execution-monitoring hardware.

1. Physical and Protocol Layer: JTAG vs. SWD

  • JTAG (IEEE 1149.1) uses a synchronous 4/5-wire bus: TCK (clock), TMS (test mode select), TDI (data in), TDO (data out), and optional nTRST (reset). It clocks state transitions across a 16-state TAP (Test Access Port) finite state machine. Operations shift instructions into an Instruction Register (IR) or data into a Data Register (DR), with devices cascaded in a scan chain where each chip adds shift delay.
  • SWD (Serial Wire Debug) reduces the pinout to 2 pins: SWCLK (clock, up to ~50 MHz) and SWDIO (bidirectional data line with turnaround cycles Trn). Each transaction consists of an 8-bit host request packet (start bit, APnDP selection, RnW bit, 2-bit register address, parity bit, stop bit, park bit), a 3-bit target ACK response (OK=001b, WAIT=010b, FAULT=100b), and a 32-bit data phase with parity.
Host -> Target: [START (1)][APnDP (1)][RnW (1)][A[2:3] (2)][PARITY (1)][STOP (0)][PARK (1)]
Turnaround:     [Trn (1)]
Target -> Host: [ACK (3)]
Data Phase:     [DATA (32)][PARITY (1)]
Turnaround:     [Trn (1)]

2. Debug Access Port (DAP) Architecture

The physical interface connects to an on-chip Debug Access Port (DAP) consisting of:

  • Debug Port (DP): Handles physical protocol deserialization (JTAG-DP or SW-DP).
  • Access Ports (AP): Bridge internal buses. An AHB-AP or AXI-AP acts as an on-chip bus master, allowing the external debug probe to read and write CoreDebug registers, peripheral registers, and SRAM without core execution overhead.

3. Hardware Breakpoints: Flash Patch and Breakpoint (FPB)

Software breakpoints rewrite the instruction opcode in flash/RAM with a breakpoint instruction (BKPT on ARM, opcode 0xBE00–0xBEFF), triggering a DebugFault/halt. In Flash memory, rewriting requires slow erase/program cycles.

Hardware breakpoints use the FPB unit:

  1. The debugger writes target addresses into FP_COMPn registers and sets FP_CTRL.ENABLE via the AHB-AP.
  2. The FPB comparator monitors the Instruction Fetch Address bus (I-Code/System bus).
  3. When the Program Counter matches an active comparator, the FPB either signals the core execution pipeline to halt into debug state (DHCSR.C_DEBUGEN enabled) before execution, or remaps the instruction fetch to an SRAM remap table containing patched instructions.
  4. Hardware breakpoint count is strictly bounded by physical comparators (typically 4 to 8 on Cortex-M).

4. Watchpoints: Data Watchpoint and Trace (DWT)

Watchpoints monitor data accesses rather than instruction fetches:

  1. Comparators in the DWT unit are configured via DWT_COMPn (target address), DWT_MASKn (address mask for ranges), and DWT_FUNCTIONn (access type: data read, data write, or read/write).
  2. DWT snoops the Data bus (D-Code/System bus). When a load/store matches the comparator criteria, DWT raises a debug halt or generates a trace packet.
  3. Unlike instruction breakpoints which halt before the matched instruction runs, data watchpoints halt after the memory transaction completes (or synchronously pipeline-halt on exact match).

5. Instruction & Event Trace: SWO vs. ETM

Trace provides execution visibility without halting the core:

  • ITM / SWO (Serial Wire Output): The Instrumentation Trace Macrocell emits software instrumentation packets and coarse DWT sampling (e.g., PC sample packets every N cycles). It outputs asynchronously over a single physical pin (SWO) using either Manchester encoding or UART (NRZ) protocol. Bandwidth is limited (~2–10 Mbps), making full instruction trace impossible.
  • ETM (Embedded Trace Macrocell): Streams non-intrusive, cycle-accurate instruction trace. The core cannot stream every 32-bit instruction at clock rate; instead, ETM outputs highly compressed delta packets (branch target addresses, direct branch outcome bits Atom P/E for Pass/Fail, exception arrivals). The stream is funneled through a high-speed parallel trace port (4-bit TRACECLK / TRACEDATA[3:0]) or captured into an on-chip circular buffer (Embedded Trace Buffer / ETB) to be read out post-mortem via the DAP.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Design and validate an embedded debugging workflow for memory-mapped reads.

Answer

Memory-mapped reads are bus transactions, not passive observation. A debugger read can clear a status flag, pop a FIFO, or latch a value. The workflow has three phases: classify each register from the reference manual, isolate read-sensitive registers behind a firmware-maintained shadow, and validate with a known workload that compares direct reads against shadow reads.

Assumptions: Cortex-M MCU, SWD or JTAG probe, CPU can be halted, firmware can be rebuilt. If the CPU cannot be halted, the same workflow applies but the debugger must use a non-intrusive path (trace) instead of memory reads.

Classify. From the reference manual, mark each register's read behavior. Look for "read clears", "rc_w0", "rc_w1", "reading this register clears". Concrete examples:

  • STM32F4 ADC_DR: reading clears EOC.
  • STM32F4 TIMx_CCR1: reading clears CC1IF.
  • STM32F7/G4/H7 USART_RDR with FIFO enabled: reading pops the RX FIFO. The F4 USART has no FIFO, so its DR read clears RXNE but does not pop.
  • Kinetis UART0_S1: RDRF is cleared only by reading S1 then reading D, not by reading S1 alone.
  • STM32F4 USART_SR: reading alone does not clear RXNE; RXNE is cleared by reading DR.

Isolate. For read-sensitive registers, firmware maintains a shadow copy in a reserved RAM region. The ISR updates the shadow. The debugger reads the shadow. For registers that cannot be shadowed (FIFO data), the debugger must not read them; use a firmware counter or trace buffer.

Validate. Run a known workload twice: once with the debugger reading the shadow, once reading the peripheral directly. Compare byte counts, interrupt counts, checksums. Hypothetical bench test: 1 kHz ADC sampling, debugger reads ADC1->DR every 100 ms. Direct reads cleared EOC before the ISR ran, so the ISR missed 3 conversions in 10 s. Shadow reads missed 0. Also check coherence: read status then data in the same order the firmware does. Use a logic analyzer or SWO to confirm no extra bus transactions.

RegisterRead behaviorDebugger read effectSafe strategy
STM32F4 USART_SRNormalNoneRead directly
STM32F4 ADC_DRRead-to-clear EOCClears EOC, ISR may not fireRead shadow
STM32F4 TIMx_CCR1Read-to-clear CC1IFClears capture flagRead shadow
STM32F7/G4/H7 USART_RDR (FIFO)Read-to-popPops RX FIFO, loses byteRead shadow
Kinetis UART0_S1Sequence-clearedRDRF cleared only by S1 then DRead shadow or avoid
Any 32-bit reg read as 2x16Split-widthFirst read may clear flag, second read not cleanUse 32-bit access
C
volatile struct {
    uint32_t adc_dr;
    uint32_t eoc_count;
} debug_mirror __attribute__((section(".debug_mirror")));

void ADC_IRQHandler(void) {
    debug_mirror.adc_dr = ADC1->DR; // read clears EOC
    debug_mirror.eoc_count++;
}

Trace: EOC set -> ISR fires -> read ADC1->DR returns the conversion result and clears EOC -> store result in mirror -> increment count. The debugger reads debug_mirror.adc_dr and debug_mirror.eoc_count; it never touches ADC1->DR, so EOC is not cleared by the debugger. Both fields are 32-bit aligned, so the debugger sees a consistent value.

Alternatives. Hardware trace (ETM/ETB on Cortex-M, or SWO) observes without bus reads; costs extra pins and a trace probe. A firmware ring buffer logs to RAM; costs RAM and code. Accept the side effect and re-arm; costs firmware complexity and races. There is no truly non-intrusive read of a memory-mapped register: the read is the bus transaction.

Failure modes:

  1. Read-to-clear status cleared before ISR: ISR never fires. Detection: ISR count stops, watchdog reset. Cost: missed deadline.
  2. FIFO pop: data loss. Detection: checksum mismatch, sequence gap. Cost: corrupted stream.
  3. Split-width access: reading a 32-bit register as two 16-bit reads can trigger the read side effect on the first read, so the second read is not a clean read. Detection: corrupted value. Cost: wrong control decision.
  4. Reserved bits: writing reserved bits is typically ignored by hardware, but reading them may return undefined values. Detection: unexpected values. Cost: misdiagnosis. Mask them.
  5. Registers that must be read periodically to refresh a value: debugger reads can disturb the timing. Detection: watchdog reset or stale value. Cost: reset.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate an embedded debugging workflow for SVD limits.

Answer

Assumptions: Cortex-M target, device described by a CMSIS-SVD 1.3 file, pyOCD or OpenOCD as the probe front end, firmware in C. "SVD limits" here means the limits of what a CMSIS-SVD description can express about the silicon.

Core answer. A CMSIS-SVD file is static XML. It describes register addresses, reset values, field offsets and widths, and access types: nothing about timing, write sequences, or read side effects unless the vendor filled in <readAction>/<writeAction>. So the workflow is: pin the description, validate it mechanically, cross-check the registers the firmware actually touches against the manual and errata, then prove the debugger's view against the running target. Never treat the generated view as evidence about silicon.

Mechanism. svdconv (CMSIS_5 5.9.0) parses the XML against the CMSIS-SVD 1.3 schema, resolves derivedFrom inheritance, expands dim/dimIncrement arrays, and emits headers. Reset values come from <resetValue>; field widths from <bitOffset>/<bitWidth>. pyOCD builds its register view from the same file (pyocd commander --svd STM32H743.svd -t stm32h743xx, then reg RCC_CR). Nothing on that path reads silicon, so a schema-clean SVD can still be wrong about the chip.

Alternatives. Generated-from-vendor-SVD is right when the vendor maintains the pack and the firmware touches many registers. Hand-written headers win when you touch a handful of registers and the vendor SVD is stale: you pay maintenance but you own the truth. Hand-editing the vendor SVD is the worst of both: it fixes the view but the fix is invisible to the next pack update, so record the edit as a patch against the pack version it applies to.

Workflow, in order.

  1. Pin: pack version plus SHA-256 of the .svd (e.g. Keil.STM32H7xx_DFP, sha256:...).
  2. Schema check: svdconv -b -o build STM32H743.svd; treat warnings as failures.
  3. Cross-check the touched registers against the reference manual and errata sheet.
  4. Prove against silicon: read each touched register via debugger and via firmware, compare.

Failure modes.

failuredetectcost
wrong variantread DBGMCU_IDCODE, compare to SVD device namewrite lands in another peripheral
stale reset valueread register before firmware runs, compare <resetValue>bring-up misread
field width / derivedFrom basewrite 0xFFFFFFFF, read back, maskset a reserved bit
missing sequence (unlock key)firmware write works, debugger write no-opssilent no-op
unsafe readread twice; value changes with no writedropped byte, cleared flag

Arithmetic. A 3-bit field at bit 5 is mask 0x7 << 5 = 0xE0. Writing 0xFF to the register also sets bits 0–4 and 6–7; if the SVD's bitWidth is 4, the debugger shows a field that does not exist and you write a reserved bit.

Trace. A 16-entry RX FIFO. The debugger reads the data register 16 times to "look at" the buffer; each read pops one entry. Firmware then sees an empty FIFO and drops 16 bytes. The SVD only warns you if it carries <readAction>clear</readAction>: most vendor files do not. Detection is the read-twice test: if the value changes without a write, the read has a side effect and the debugger must not touch it while the target runs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate an embedded debugging workflow for software breakpoints.

Answer

I'd start by clarifying where the code lives and what debug hardware the target has. On a Cortex-M4 with code in flash and SWD, I have six hardware instruction comparators in the FPB unit. That's the first decision: hardware breakpoints for flash-resident code, software breakpoints for RAM or when I need more than six.

Hardware breakpointSoftware breakpoint
MechanismComparator matches address; no code changeReplace instruction with BKPT (0xBE00) or INT3 (0xCC)
Resource6 instruction comparators on Cortex-M3/M4; 4 on Cortex-M0+One word of code space; flash sector erase
Flash wearNoneTwo sector erases per set/clear; STM32F4 rated 10k cycles
Read-only codeWorksFails unless flash is writable
CacheNo effectMust invalidate I-cache after patch

For a software breakpoint, I replace the instruction at the target address with a breakpoint instruction. On ARMv7-M that's BKPT #0, encoded as 0xBE00; on x86 it's INT3, 0xCC. In RAM, that's a single aligned store. In flash, it's not: NOR flash can only change bits from 1 to 0, so I must erase the whole sector first. On an STM32F4, the first sector is 16 KB, and the flash is rated for 10k erase cycles. So setting and clearing one breakpoint costs two sector erases. If I toggle it 50 times a day, that's 100 erase cycles a day, and the sector is worn out in 100 days. That's why hardware breakpoints are the default for flash.

After patching, I must invalidate the instruction cache. On a Cortex-M7, the I-cache line is 32 bytes. If I write BKPT to RAM and don't invalidate, the core may execute the stale original instruction and the breakpoint never hits. So the workflow is: patch, clean/invalidate D-cache if needed, invalidate I-cache, then run.

Validation has three parts. First, read back the patched address and compare to the original instruction. Second, after the debug session, restore the original instruction, erase and reprogram if in flash, and read back again. Third, track the flash erase count per sector; when it approaches the 10k limit, switch to hardware breakpoints or move the code to RAM.

Failure modes I'd watch for:

  • Flash wear: detection is the erase counter and flash controller error flags.
  • Instruction not restored: if the debugger crashes or the target resets mid-session, the BKPT remains. Next boot executes it and faults. Detection: boot-time CRC over the code region; mismatch means a leftover patch.
  • Breakpoint in boot verifier: if you patch the secure boot ROM or verifier, the signature check fails. Detection: boot log shows signature failure.
  • Cache stale: breakpoint doesn't hit; single-step shows the original instruction. Detection: invalidate I-cache after every patch.
  • Self-check detects patch: a runtime CRC sees the modified byte and resets. Detection: CRC error flag.

The trade-off is clear: hardware breakpoints cost comparators but don't touch code. Software breakpoints cost flash wear and cache maintenance but are unlimited in number and work on any writable memory. For a production debug workflow, I'd use hardware breakpoints on flash, software breakpoints in RAM, and always validate by read-back and erase-count tracking.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate an embedded debugging workflow for flash verification.

Answer

What I'd say first. I'd split this into three stages: a deterministic program step, a verify that reads through the same path the bootloader will use, and a boot-time self-check. The trap is that a host-side verify over SWD proves the debug path, not the boot path: those diverge whenever there's a read cache, an address alias, or a remap.

Assumptions. Cortex-M target, OpenOCD over SWD, internal flash plus an optional external QSPI device, single or dual-bank.

Program step. One command does erase, write, verify, reset:

openocd -f interface/cmsis-dap.cfg -f target/stm32l4x.cfg \
  -c "init; reset halt; flash probe 0; flash info 0" \
  -c "program build/app.elf verify reset exit"

flash info 0 prints the bank base, sector map and protection state: capture that in the log, because it's the evidence that the bank you programmed is the bank you think.

Verify step. program ... verify reads back over the debug path. That's necessary but not sufficient. Two stronger checks: read the region through the boot alias with the cache disabled, or have the target compute a CRC32 over the region and compare it to the host's CRC of the artifact. The CRC peripheral runs 32 bits per cycle, so 1 MB at 80 MHz is ~3 ms; a full SWD read-back of the same 1 MB at a typical 100 kB/s is ~10 s. The CRC is roughly three orders of magnitude cheaper and, more importantly, it reads the array the CPU actually fetches from.

Failure modes and how I'd catch them.

failuremechanismdetection
wrong addresslinker LMA ≠ flash bank base; write and verify both hit the same wrong offset, so verify passescompare flash info bank base to the ELF LMA; check the reset vector at the bank base points into the image
stale secondary slotdual-bank A/B: you program slot B, the bootloader still boots slot Aread the bootloader's image header (magic + version) in the active slot and match it to the artifact
wrong flash algorithmOpenOCD loads a RAM algorithm whose sector map doesn't match the part; erase no-ops or hits the wrong sectorerase one sector, read it back, expect 0xFF across the whole sector
protected sectorwrite-protection option bytes reject the erase; the write may still report successread the WRP option bytes; erase and confirm the sector reads 0xFF
verify reads cache/aliasthe flash controller read cache or an XIP alias returns the just-written buffer, not the arrayverify through the boot alias with cache off, or use the target CRC

Trade-off. Full read-back is simple and needs no target code, but it's slow and only proves the debug path. Target-side CRC is fast and proves the boot path, but needs a small routine in the image and a matching host CRC. Deciding criterion: if the boot path and the debug path read the same physical array, host verify is enough; if there's a cache, alias, or remap, use the target CRC.

Boot-time self-check. Have the bootloader CRC the active slot before jumping. That catches the stale-slot and protected-sector cases at every boot, not just on the bench.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate an embedded debugging workflow for reset types.

Answer

Core answer

Assume a Cortex-M target (STM32F4 here), OpenOCD driving an ST-Link, and firmware that must behave correctly after every reset source. The workflow has three parts: declare the reset wiring once, drive each reset type with a distinct command, and validate by reading the MCU's reset-cause register instead of trusting the debugger.

Declare the wiring in openocd.cfg:

source [find interface/stlink.cfg]
source [find target/stm32f4x.cfg]
reset_config srst_only srst_nogate
$_TARGETNAME configure -event reset-init {
    # board bring-up only: PLL, SDRAM controller, flash wait states
    mww 0x40023808 0x00001440   ;# RCC_PLLCFGR (illustrative)
}

reset_config tells OpenOCD which physical lines exist; get it wrong and reset silently does nothing or resets the wrong domain. srst_nogate keeps JTAG alive across the reset so the debugger stays attached.

Why the types differ

A reset is not one signal. On Cortex-M the domains are: the core (VECTRESET), the core plus most peripherals (SYSRESETREQ via AIRCR), the whole chip including debug logic (POR / NRST), and the watchdog. SYSRESETREQ leaves the debug domain powered, so the debugger stays connected; POR does not, so the adapter must re-attach. That single fact decides which reset you can debug live.

Table

reset typedrive it withSTM32F4 RCC_CSR bitresets
power-oncycle the supplyPORRSTF (27)everything, incl. debug
pin / NRSTreset with srstPINRSTF (26)chip, not debug domain
softwaremww 0xE000ED0C 0x05FA0004SFTRSTF (28)core + most peripherals
watchdoglet the WDT expireIWDGRSTF (29)chip; WDT config may survive

Trace

> reset halt
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x08000188 msp: 0x20020000
> mdw 0x40023874 1
0x40023874: 04000000        # bit 26 = PINRSTF -> pin reset, as expected

If the cause bit doesn't match the reset you just issued, the wiring or the reset path is wrong: that is the validation.

Trade-offs

reset halt stops at the reset vector so you can set breakpoints before boot code runs, but it changes boot timing and on some targets halts after the first instruction. reset run preserves timing but you cannot break before the bootloader. reset init runs the reset-init handler so clocks and SDRAM are up, at the cost of masking bugs in the firmware's own clock init. Pick reset halt for debugging the reset path, reset run for timing, reset init only for board bring-up.

Failure modes

  • Halt after first instruction: read PC after reset halt; if it is not the reset vector, you halted late and missed the first instructions.
  • Watchdog not reset: read the WDT control register right after a WDT reset; if it is still enabled, the target resets again immediately.
  • reset-init changes clocks: boot once with reset run and once with reset init; a difference means the handler is hiding a firmware clock bug.
  • Peripheral reset scope: read a peripheral that SYSRESETREQ should clear (e.g. a timer) and confirm it is at its reset value.
  • Bootloader skipped: if you halt at the vector and jump, the bootloader's init never runs; detect by comparing the cause register and clock state against a cold boot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate an embedded debugging workflow for reset fidelity.

Answer

To validate reset fidelity, you must reproduce each reset cause and capture the raw reset status before any code clears it. The workflow: instrument the firmware to log reset cause and retained state, script the debugger to issue each reset type, then compare captured values against expected. Assume an ARM Cortex-M target (e.g., STM32F4) with a J-Link or ST-Link probe, OpenOCD or GDB, and a programmable power supply for brownout tests.

The mechanism matters because reset domains differ. On Cortex-M, a debugger's system reset request (AIRCR.SYSRESETREQ) resets the core and VDD-domain peripherals, but not the backup domain (VBAT) or always-on domain. A power-on reset (POR) resets everything, including the backup domain if VBAT is absent. A pin reset (NRST) resets the VDD domain but not VBAT. So a bug that depends on backup-domain retention will vanish under SYSRESETREQ but appear on POR. Similarly, a debugger may hold NRST low (SRST) or write memory on connect, changing the boot state.

Workflow:

  1. Instrument: at boot, read the reset cause register (e.g., STM32 RCC_CSR bits 31..24: LPWRRSTF, WWDGRSTF, IWDGRSTF, SFTRSTF, PORRSTF, PINRSTF, BORRSTF). Store the value in a no-init RAM section or a backup register, then clear the flags by writing RMVF. Also log a known pattern to backup registers (e.g., RTC backup registers) to test retention.
C
uint32_t csr = RCC->CSR;
uint32_t cause = csr & 0xFE000000; // bits 31..25
RCC->CSR |= RCC_CSR_RMVF; // clear flags
  1. Script: use OpenOCD commands reset halt, reset run, reset init to issue debugger resets. For POR, use a programmable supply to ramp VDD down and up. For brownout, ramp VDD below the BOR threshold and back. For pin reset, toggle NRST. For watchdog, trigger IWDG.
  2. Capture: after each reset, halt the core and read the stored reset cause and backup registers via GDB or OpenOCD mdw. Compare against expected.
  3. Validate: the captured cause must match the issued reset. Backup registers must retain the pattern. External peripherals that are not reset (e.g., an I2C GPIO expander) must keep their state. Boot straps must be sampled correctly. No debugger-induced memory writes should be present.

Alternatives: you can use a debugger reset for speed, but it cannot test POR or brownout. You can use a power cycle for POR, but it is slower and may not be scriptable. The deciding criterion is which reset cause you need to reproduce. For retention, you must keep VBAT powered and use a reset that does not reset the backup domain.

Failure modes: debugger holds SRST, so the target sees a pin reset instead of the intended cause. Debugger writes memory on connect, corrupting the no-init RAM section. Probe connects under reset, changing boot mode. Backup domain is reset by a POR if VBAT is not present. External peripheral is reset by a shared reset line. Strap pins are driven differently by the debugger.

Table: reset cause vs what it resets.

Reset causeCore/VDDBackup (VBAT)Always-onTypical tool
PORYesYes if VBAT absentYesProgrammable supply
Pin reset (NRST)YesNoNoToggle NRST
BrownoutYesNoNoRamp VDD
WatchdogYesNoNoTrigger IWDG
SYSRESETREQYesNoNoOpenOCD reset
Software resetYesNoNoNVIC_SystemReset

OpenOCD reset may use SRST or SYSRESETREQ depending on config; check your interface. This table is a guide; check your specific MCU's reference manual.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate an embedded debugging workflow for peripheral debugging.

Answer

Assumptions: a Cortex-M4 at 166 MHz, an SPI sensor that intermittently returns 0x00 at cold boot, a logic analyzer on the bus, and SWO available. The workflow is three stages: instrument without perturbing, align the two timebases, then validate the workflow itself by injecting a known failure.

Instrument. Emit a marker at every state transition: CS assert, first clock edge, DMA complete, ISR entry. Two options:

C
// Cortex-M4, CMSIS. DWT->CYCCNT is the firmware timebase.
#define MARK(id)     do { ITM->PORT[0].u32 = (id); } while (0)
#define MARK_PIN(p)  do { GPIOD->BSRR = (1u << (p)) | (1u << ((p) + 16)); } while (0)

ITM carries a 32-bit payload but costs roughly 10 cycles per write and silently drops words when the SWO FIFO fills. A GPIO toggle costs one cycle and one pin, carries no payload, and needs no SWO. Use GPIO when the question is sub-microsecond timing, ITM when it is which code path ran, ETM when it is why the CPU stalled.

Align. The analyzer and the DWT cycle counter are independent oscillators. Toggle a sync pin at the start and end of the capture and record the same instant in the marker stream:

analyzer tDWT cyclesevent
0.000 ms0sync pulse
0.412 ms68,400CS asserted
0.421 ms69,900MISO sampled 0x00, expected 0x6B
10.000 ms1,660,083sync pulse

10 ms at 166 MHz is 1,660,000 cycles; the second sync reads 1,660,083, so the two clocks differ by 83 cycles = 0.5 µs over 10 ms, i.e. 50 ppm. At 10 MHz SPI one bit is 100 ns, so 0.5 µs is five bit times: enough to say "MISO was already low when CS asserted", not enough to correlate a specific clock edge. That is the deciding criterion for whether you need a shared clock.

Validate the workflow, not just the device. Three checks:

  1. Inject a known fault, jumper MISO to ground, and confirm the workflow reports "MISO stuck low" rather than "device NACK". If it cannot separate those two, it is not a workflow.
  2. Put a sequence number in each marker payload and assert it is contiguous. A gap means the ITM FIFO overflowed and the trace is incomplete.
  3. A/B the probe: 1000 cold boots with the probe attached and 1000 without. If the failure rate moves (3/1000 vs 0/1000), the probe is part of the system under test.

Failure modes and how you catch them.

  • Reading a status register clears its flag, so the ISR's own read hides the cause. Log the raw value into a shadow before any other access, or use the peripheral's raw register variant.
  • Probe loading: a 10 pF probe on a 4.7 kΩ I2C pull-up adds 47 ns to the edge's RC, which can turn a marginal setup violation into a pass. Detect it with the A/B above.
  • Wrong decoder mode: a CPOL/CPHA mismatch shifts every decoded byte by one bit. Decode a known WHO_AM_I value (0x6B on the LSM6DS3) and compare against the datasheet before trusting any capture.
  • Timestamp drift: as above, 50 ppm is 0.5 µs over 10 ms. Measure it with two sync pulses; if the slope exceeds one bit time, stop correlating edges.
  • Recovery destroys evidence: a reset clears the error latch and the peripheral FIFO. Latch the error into a no-init RAM section and dump it in the fault handler before the reset path runs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do compiler optimization levels (-O0, -O2, -Og) affect GDB debugging fidelity, and what specific techniques and DWARF structures allow you to inspect optimized-out variables and inlined functions?

Answer

The 90-second answer. Optimization level decides how much of the source-to-machine mapping DWARF can still express. At -O0 each variable has one location for its whole lifetime and each statement maps to a contiguous instruction range, so GDB is exact. At -O2 a value may live in a register for a few instructions, be folded into a constant, or vanish, and GDB prints <optimized out>. -Og is GCC's middle setting: it runs optimizations that don't break the mapping, and because -O0 disables the var-tracking passes that build location lists, -Og can give better variable info than -O0 in places. Recovery comes from three places: the location list and the register it names, entry values for clobbered parameters, and the DW_TAG_inlined_subroutine DIE for inlined frames.

What each level does to DWARF

  • -O0: one DW_AT_location per variable, usually DW_OP_fbreg (frame-base relative). No location lists, no inlining unless always_inline, statement boundaries map to contiguous instruction ranges. Exact, but unrepresentative of production.
  • -Og: enables optimizations that don't interfere with debugging (dead-code elimination, constant propagation, register allocation) and keeps var-tracking on. Inlining is limited. PC-to-line mapping stays dense.
  • -O2: full register allocation, CSE, loop unrolling, scheduling, aggressive inlining, sibling-call (tail-call) optimization. Variables get location lists, get folded to DW_AT_const_value, or disappear.
LevelVariable locationInliningBacktrace
-O0single DW_OP_fbregnonephysical frames
-Oglocation list, stack or registerlimitedphysical frames
-O2location list / const / goneaggressivesynthetic inline frames

Inlined functions. GCC emits a DW_TAG_inlined_subroutine DIE inside the caller's DW_TAG_subprogram. DW_AT_abstract_origin points at the out-of-line definition; DW_AT_low_pc/DW_AT_high_pc (or DW_AT_ranges) give the PC range where the inlined body is live; DW_AT_call_file/DW_AT_call_line give the call site.

$ readelf --debug-dump=info a.out
 <2><1a3>: Abbrev Number: 12 (DW_TAG_inlined_subroutine)
    <1a4>   DW_AT_abstract_origin: <0x2c1>
    <1a8>   DW_AT_low_pc  : 0x401126
    <1b0>   DW_AT_high_pc : 0x1a
    <1b4>   DW_AT_call_file : 1
    <1b8>   DW_AT_call_line : 42

GDB turns each DIE into a virtual frame, so bt shows the inlined call stacked on one physical frame:

(gdb) bt
#0  calculate_crc (data=0x20001000, len=64) at crc.c:18
#1  packet_process (pkt=0x20000ff0) at net.c:104
#2  main () at main.c:42

frame/up/down walk those virtual frames; info registers reports the one physical frame underneath.

<optimized out> variables. At -O2 GCC emits DW_AT_location as a location list in .debug_loc (DWARF ≤4) or .debug_loclists (DWARF 5): PC ranges each mapped to a register or stack expression.

$ readelf --debug-dump=loc a.out
00000000 0000000000401130 0000000000401145 (DW_OP_reg5 (rdi))
0000000c 0000000000401145 0000000000401152 (DW_OP_fbreg: -20)

When GDB prints <optimized out>, the current PC is outside every range, or the named register has been reused. Recovery:

  1. Read the location list and the register. disassemble /m around $pc, then info registers for the register the list names, and trace back to where the value was computed.
(gdb) disassemble /m
17        r1 = sensor->raw_reading;
   0x08000214 <+4>:  ldr   r1, [r0, #4]
18        r2 = r1 << 2;
   0x08000216 <+6>:  lsls  r2, r1, #2
19        sensor->scaled = r2;
=> 0x08000218 <+8>:  str   r2, [r0, #8]
(gdb) info registers r1 r2
r1             0x2a   42
r2             0xa8   168
  1. Entry values. With -g -O2 GCC emits DW_OP_entry_value (DWARF 5; DW_OP_GNU_entry_value in DWARF 4) so a parameter clobbered inside the callee can still be recovered from its value at entry. GDB uses these to print the parameter instead of <optimized out> when the entry value is available.

  2. Force materialization. When you can rebuild, pin the value:

C
volatile uint32_t snapshot = sensor_reading;   /* forces a stack slot */
asm volatile("" : "+r"(sensor_reading));       /* forces a register */

Two flags matter here: -fvar-tracking (on by default at -O1+ with -g) is what builds the location lists, and -fno-omit-frame-pointer keeps backtraces walkable. -g3 adds macro info.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and validate an embedded debugging workflow for call stacks.

Answer

Assumptions: Cortex-M4, bare-metal or RTOS (FreeRTOS/Zephyr), release build with symbols, GDB + OpenOCD/J-Link. Core answer: capture fault context, reconstruct with three independent methods, validate by cross-checking, automate.

Workflow

  1. Build: -g -gdwarf-4 -funwind-tables -fstack-protector-strong; debug also -fno-omit-frame-pointer. Keep .elf with build-id.
  2. On crash: halt, read MSP, PSP, LR, PC, xPSR, CFSR (0xE000ED28), HFSR (0xE000ED2C), BFAR (0xE000ED38), MMFAR (0xE000ED34). Dump stack: x/64wx $sp.
  3. Reconstruct: bt full. If it fails, manual: info frame, x/16wx $sp, find saved LR/PC. Use arm-none-eabi-addr2line -e firmware.elf <pc>.
  4. Validate: cross-check three methods: unwind tables (readelf --debug-dump=frames), frame-pointer walk, stack scan (find /w $sp, $sp+1024, 0x08000000, 0x08100000). Compare.
  5. Automate: CI batch GDB on coredump; HIL pyOCD/OpenOCD; field CrashCatcher/Memfault.

Mechanism

  • SP bounds: task stack region from linker/RTOS. SP must be within [base, limit) and 8-byte aligned. Example: task stack 1024 bytes at 0x20001000-0x200013FF; SP=0x20000F00 -> below base, overflow. SP=0x20001400 -> above limit. Misalignment -> corruption.
  • Saved PC: Cortex-M exception frame pushes PC, LR, xPSR, R0-R3, R12. PC must be in .text and Thumb bit set. If PC=0xFFFFFFFE or in RAM, corrupt.
  • Unwind data: DWARF CFI or ARM EHABI. GDB uses it. If missing, backtrace stops. Validate by comparing with manual frame-pointer walk.
  • Disassembly: objdump -d -S around PC and LR. Check call sites match expected call graph. LR in middle of instruction -> corruption.
  • Crash chronology: CFSR bits: STKOF -> stack overflow; INVPC -> invalid PC; PRECISERR -> precise bus fault. Read via GDB p/x *(uint32_t*)0xE000ED28.

Tradeoffs

  • Frame pointer: simple, reliable, costs r7/r11 and code size. Fails if asm/lib omits it.
  • Unwind tables: no runtime cost, works with optimized code, but flash cost and toolchain support. Fails if stripped.
  • Stack scan: no compiler support, but false positives. Use only as corroboration.
  • When wrong: relying on stack scan alone; trusting GDB backtrace with stale symbols; assuming basic exception frame when FPU active.

Failure modes

  • Stack scan false positive: data looks like PC. Detection: cross-check with unwind data and disassembly; reject if no call site. Cost: false blame.
  • Exception frame variant: FPU active -> 26-word frame instead of 8. Detection: check CONTROL.FPCA or frame size. Cost: misread all registers.
  • Inline frame confusion: -O2 inlines. Detection: info frame shows inlined into; disassemble /m. Cost: wrong function.
  • Stale symbols: build ID mismatch. Detection: info files build-id vs .elf. Cost: wrong line numbers.
  • Overwritten return address: buffer overflow. Detection: stack canary, MPU guard, LR check. Cost: silent corruption.
MethodHowCostDetectsFails when
Frame pointerr7/r11 chain1 reg, code sizeOptimized code if compiled with FPOmitted in asm/lib
Unwind tablesDWARF CFI / ARM EHABIFlashOptimized code, asyncStripped/missing
Stack scanSearch stack for PC-like valuesCPU, false positivesNo compiler supportData looks like PC

Validation: if two methods agree, confidence. If all three disagree, dump full stack, check memory map, set hardware watchpoint on return address.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate an embedded debugging workflow for thread awareness.

Answer

Assumptions. Cortex-M target, FreeRTOS V11.x (or ThreadX 6.x), OpenOCD 0.12.0 driving GDB 13 over SWD, and a build with configUSE_TRACE_FACILITY 1. If you're on SMP, Cortex-A, or a vendor fork, step 1 changes; the rest holds.

Core answer. Thread awareness is a two-source problem. The debugger's RTOS plugin reconstructs task state by walking kernel structures over the debug link; the kernel can report the same state from inside the target. Design the workflow so those two sources are always compared, and so the halt is taken where the structures are quiescent. Four steps:

  1. Halt deterministically. On SMP, halt every core before reading anything: OpenOCD's -rtos hwthread exposes each core as a thread. Halt one core of a dual-core Cortex-M and the other keeps running, mutating shared lists under you. Then check IPSR: if the halt landed in an exception handler (IPSR != 0), pxCurrentTCB may name a task that was preempted, not one that is running.

  2. Match plugin to kernel. OpenOCD's -rtos FreeRTOS walks pxReadyTasksLists and pxCurrentTCB using the TCB_t and List_t layout of the kernel it was written against. FreeRTOS V11 replaced configNUM_CORES with configNUMBER_OF_CORES and changed the SMP fields, so a plugin built for V10 reads the wrong offsets and prints plausible fiction. Verify by reading one known symbol, pxCurrentTCB, and confirming it points into the TCB pool you allocated.

  3. Corroborate. Compare the plugin's info threads against an in-target snapshot from uxTaskGetSystemState() (needs configUSE_TRACE_FACILITY), dumped over UART or into a RAM buffer. If the plugin says task A is Ready and the snapshot says Blocked, the plugin's list walk is torn.

  4. Validate integrity. Walk each list and check uxNumberOfItems against the count you actually traverse. Check TCB identity: ThreadX stamps tx_thread_id with TX_THREAD_ID (0x54485244); FreeRTOS has no magic field by default, so add one in a debug build.

Failure modes and detection.

failuremechanismdetection
torn listhalt lands inside vTaskDelay, between ready-list removal and delayed-list insertuxNumberOfItems mismatch; task in neither list
ISR preempted schedulerhalt in an ISR, pxCurrentTCB staleIPSR != 0
SMP core not haltedother core mutates lists mid-readinfo threads shows one core only
stale stack watermarkuxTaskGetStackHighWaterMark() reports worst case so far, not current usetask hasn't run its deep path yet

Trade-offs. Plugin-only is fast but unverifiable: good for interactive triage, not for a bug report. Snapshot-only is authoritative but needs a UART and a cooperative target, and it perturbs timing. Run the plugin first, then confirm anything you intend to write down against the snapshot. If the two disagree, trust the snapshot and treat the plugin's kernel-version match as the suspect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How do you diagnose and debug an ARM Cortex-M HardFault or crash using stack unwinding, fault status registers, and GDB?

Answer

To diagnose a Cortex-M HardFault, you isolate the active stack pointer at the moment of exception entry, extract the hardware-pushed exception stack frame to locate the offending Program Counter (PC), and decode the System Control Block (SCB) fault registers: HFSR (HardFault Status Register) and CFSR (Configurable Fault Status Register).

1. Determining the Exception Frame

When an exception triggers, the Cortex-M core pushes eight 32-bit words onto the active stack (MSP or PSP) before vectoring to HardFault_Handler: R0, R1, R2, R3, R12, LR (Return Address), PC (Faulting Address), and xPSR (plus FPU S0-S15 and FPSCR if lazy stacking was active).

Inside the naked HardFault_Handler, test bit 2 of the incoming LR (EXC_RETURN):

  • Bit 2 == 0: Frame was stacked on the Main Stack Pointer (MSP).
  • Bit 2 == 1: Frame was stacked on the Process Stack Pointer (PSP).
C
__attribute__((naked)) void HardFault_Handler(void) {
    __asm volatile (
        "tst lr, #4            \n"
        "ite eq                \n"
        "mrseq r0, msp         \n"
        "mrsne r0, psp         \n"
        "mov r1, lr            \n"
        "b hard_fault_decoder  \n"
    );
}

2. Reading SCB Fault Status Registers

In hard_fault_decoder(uint32_t *stack_frame, uint32_t exc_return) or live over GDB via OpenOCD:

GDB
(gdb) # Read CFSR (0xE000ED28) and HFSR (0xE000ED2C)
(gdb) x/1wx 0xE000ED28
(gdb) x/1wx 0xE000ED2C
(gdb) # Read MMAR (0xE000ED34) and BFAR (0xE000ED38)
(gdb) x/1wx 0xE000ED34
(gdb) x/1wx 0xE000ED38
RegisterOffset / AddressBit / FieldDiagnostic Interpretation
HFSR0xE000ED2CFORCED (bit 30)Configurable fault escalated to HardFault because handler was disabled or priority escalated.
VECTTBL (bit 1)Fault occurred on vector table read during exception processing.
CFSR0xE000ED28UFSR (0xE000ED2A)Bits: UNDEFINSTR (bit 16), INVSTATE (bit 17, e.g., BX to even address without Thumb bit set), UNALIGNED (bit 24), DIVBYZERO (bit 25).
BFSR (0xE000ED29)Bits: PRECISERR (bit 9, exact PC in stack frame), IMPRECISERR (bit 10, delayed write buffer error, PC has moved past fault), BFARVALID (bit 15, address in BFAR is valid).
MMFSR (0xE000ED28)Bits: IACCVIOL (bit 0), DACCVIOL (bit 1), MMARVALID (bit 7, address in MMFAR is valid).
BFAR0xE000ED38AddressFaulting bus address when BFSR.BFARVALID (bit 7 of BFSR / bit 15 of CFSR) is 1.
MMFAR0xE000ED34AddressFaulting MPU memory address when MMFSR.MMARVALID (bit 7 of CFSR) is 1.

3. GDB Unwinding and Traps

If CFSR.BFSR shows IMPRECISERR (0x0400 in CFSR), the stacked PC points to an instruction executed after the write buffer flushed, not the instruction that initiated the bad transaction. To isolate it, disable imprecise write buffering temporarily by setting the DISDEFWBUF bit (bit 1) in ACTLR (0xE000E008), turning write faults into synchronous PRECISERR.

In GDB, target the stack frame directly:

GDB
(gdb) set $sp_fault = (uint32_t*) $r0  # Stack pointer passed to decoder
(gdb) printf "PC = 0x%08x, LR = 0x%08x\n", $sp_fault[6], $sp_fault[5]
(gdb) list *$sp_fault[6]
(gdb) disassemble $sp_fault[6]-16, $sp_fault[6]+16

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate an embedded debugging workflow for fault context.

Answer

Assume a Cortex-M4F (ARMv7-M) running FreeRTOS, shipping to the field with no debugger attached. The workflow has four steps: capture in a naked handler, validate the frame before dereferencing it, persist to a noinit RAM block, reset, and decode on the next boot.

Capture. The handler must be naked (no prologue, no locals, no printf) because the fault may have come from a stack overflow or a corrupted stack, and any C prologue writes to that stack. On exception entry the hardware has already pushed a frame. EXC_RETURN in LR tells you which stack and how big:

C
// Cortex-M4F, arm-none-eabi-gcc 13.2, -O2
__attribute__((naked)) void HardFault_Handler(void) {
    __asm volatile(
        "tst   lr, #4        \n"   // EXC_RETURN bit 2: 0 = MSP, 1 = PSP
        "ite   eq            \n"
        "mrseq r0, msp       \n"
        "mrsne r0, psp       \n"
        "mov   r1, lr        \n"
        "b     fault_capture \n");
}

fault_capture reads CFSR (0xE000ED28), HFSR (0xE000ED2C), MMFAR (0xE000ED34) and BFAR (0xE000ED38), copies the frame, writes a magic and CRC, and resets.

Validate before dereference. The stacked SP is not trustworthy. Check three things: the pointer lies inside the stack's known bounds (linker _estack down to the task's stack base from its TCB); it is 8-byte aligned; and if xPSR bit 9 is set, the frame is offset by 4 bytes because CCR.STKALIGN was 0 and the SP was only 4-byte aligned. Fail any check and you record the raw SP and fault registers and stop: a bad dereference turns a recoverable fault into a lockup.

wordbasic (32 B)extended (104 B)
0–3R0–R3R0–R3
4–5R12, LRR12, LR
6–7PC, xPSRPC, xPSR
8–23—S0–S15
24–25—FPSCR, reserved

EXC_RETURN bit 4 (FP) says which layout you have. Copy 32 bytes when the frame is 104 and you lose the FP context silently.

Alternatives. A rich handler that walks the RTOS TCB list gives you the task name and its stack high-water mark, but it faults again if the corruption is in the scheduler. Writing the dump straight to flash survives a power cut, but a page erase is milliseconds: long enough for a second fault. A debugger post-mortem (SWD, arm-none-eabi-gdb, info registers) is the fastest path on the bench and useless in the field. Pick by whether the fault is reproducible and whether a probe is attached: bench → debugger, field → noinit RAM plus reset.

Failure modes. A nested fault re-enters the handler and overwrites the buffer: guard with the magic and a "captured" flag, and keep the handler on MSP so a PSP fault doesn't corrupt it. Lazy FPU stacking (FPCCR.LSPEN=1) means the FP registers are only written if the handler itself uses FP, so read the frame before any float arithmetic. On Cortex-M33 with TrustZone, CFSR is banked: read CFSR_S or CFSR_NS according to EXC_RETURN bit 6, or you get zeros. A warm reset that doesn't clear noinit leaves a stale record: CRC it.

Validation. Inject each fault deliberately in CI: a write to an unmapped address, an undefined instruction, a divide by zero, an unaligned access, and an MPU violation. A precise bus fault gives CFSR = 0x00008200, BFARVALID (bit 15) plus PRECISERR (bit 9), and BFAR = 0x20001FFC, four bytes past a 4 KB stack ending at 0x20002000: a stack overflow. If the decoded output doesn't name that, the workflow isn't done.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and validate an embedded debugging workflow for watchpoint perturbation.

Answer

Assumptions: Cortex-M4/M7 with CoreSight (DWT, ITM, ETM), SWD via ST-Link or J-Link, bare-metal or RTOS, one or two cores. The question is how to observe a watchpoint hit without the observation itself changing the system.

Core answer (first 90 seconds). Watchpoint perturbation is the change the debug mechanism makes to the system it observes. The workflow has four steps and one rule: never let the halt-based observation be the only evidence.

  1. Pick the least intrusive trigger that answers the question.
  2. Configure it exactly: address, mask, read/write direction, cycle counter.
  3. Capture two independent records: the halt snapshot and a non-halting trace.
  4. Validate by comparing them under load, and check the freeze bits that keep peripherals from running away.

Mechanism. When a DWT watchpoint matches and the core halts, the core clock domain stops retiring instructions. DMA, timers and the watchdog do not stop unless you freeze them. A buffer the watchpoint fired on can be overwritten by DMA while the core is halted, so the value you read at halt is a torn snapshot of the trigger, not the value at the trigger. That gap is the perturbation you are validating against.

Configure (Cortex-M4, CMSIS):

C
DEMCR |= DEMCR_TRCENA;            // bit 24: enable trace block
DWT->COMP0 = (uint32_t)&buf;      // watched address
DWT->MASK0 = 0;                   // exact match
DWT->FUNCTION0 = 0x6;             // data-address watchpoint, write (0x4 r/w, 0x5 read)
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;   // cycle stamps
CoreDebug->DHCSR |= CoreDebug_DHCSR_C_DEBUGEN_Msk;  // halt on match

On STM32, also set DBGMCU_APB1_FZ DBG_IWDG_STOP and DBG_WWDG_STOP so the watchdog does not reset the halted core.

Trade-offs.

mechanismintrusionwhat it seescost
halt watchpointstops coreexact value at trigger, stale aftersimplest; perturbs timing
DWT data tracenon-haltingaddress+data per matchSWO bandwidth
ISR countercode changecount onlyshifts timing
ETMnon-haltingfull instruction flowparallel trace port, big buffer

Failure modes and detection.

  • DMA continues: buffer overwritten during halt → torn read. Detect by comparing halt value against trace value at the same CYCCNT.
  • Watchdog resets: IWDG keeps counting → core resets mid-session. Detect via RCC_CSR IWDGRSTF.
  • FIFO overrun: ITM/SWO FIFO overflows at high packet rate → dropped packets. Detect as gaps in CYCCNT.
  • Multicore: only the halted core stops; the other keeps mutating shared state. Detect with cross-core sequence counters.
  • Wrong trigger direction: DWT_FUNCTION0 set to read when the write is what matters → zero hits on a known write.

Worked arithmetic (example figures). SWO at 2 Mbaud, 8N1 = 10 bits/byte → 200 kB/s. A DWT data-trace packet for a 32-bit address and 32-bit data is 1 header + 4 + 4 = 9 bytes, so the link carries ~22,000 packets/s. A word written at 100 kHz demands 900 kB/s: 4.5× the link, so the FIFO overruns. Narrow the trigger (data-value match instead of address match) or move to ETM.

Validation trace.

runvalue at halttrace value at same CYCCNTDMA writes while haltedverdict
10x000000000x000000000agree
20x000012340x000012340agree
30x000012340x000056783perturbed

Run N iterations; if any row is perturbed, the halt-based watchpoint is not a valid measurement for that variable and the trace record is the one you keep.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

A fault reproduces only on the production board and vanishes when you halt the core. Walk me through how you'd use the Cortex-M's on-chip debug hardware (DWT comparators, breakpoints, ITM/SWO) to catch it, and how you choose which to reach for first.

Answer

What I'd say first. A fault that vanishes when you halt is telling you the halt is the perturbation: the core stops, the DMA, ISR or timer racing it doesn't. So I stop halting. Put a DWT watchpoint on the address I suspect, let the core run at full speed, and read the captured state afterwards. If I don't know the address yet, ITM/SWO trace gives me a timeline without a UART. Halting breakpoints are the last tool, not the first.

Assumptions. Cortex-M4 at 168 MHz, SWD through a CMSIS-DAP probe, OpenOCD + GDB, code in flash, SWO pin routed. If SWO isn't routed, everything below still works except the trace part.

Watchpoints. The DWT has four comparators: DWT_COMP0–3 at 0xE0001020 + 0x10*n, DWT_MASK0–3 at +0x4, DWT_FUNCTION0–3 at +0x8. Don't assume four: read DWT_CTRL (0xE0001000) bits [31:28], NUMCOMP, which holds the comparator count. DEMCR.TRCENA (CoreDebug, 0xE000EDFC, bit 24) has to be set or nothing triggers.

The low nibble of FUNCTION selects what the comparator matches and which access fires it. 0b0010/0b0011/0b0100 are the read / write / read-or-write selectors when the comparator matches the PC; 0b0101/0b0110/0b0111 are the same three selectors when it matches a data address:

FUNCTION[3:0]Meaning
0b0000disabled
0b0001EMIT: PC sample
0b0010 / 0b0011 / 0b0100PC watchpoint, data read / write / either
0b0101 / 0b0110 / 0b0111data watchpoint, data read / write / either
0b1000–0b1010data watchpoint with data value match

So a write watchpoint on a global is COMP = &g_state, MASK = 0, FUNCTION = 0b0110. MASK widens the match to 2^MASK bytes, which is how you cover a struct field or a small array without burning comparators.

C
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->COMP0     = (uint32_t)&g_state;
DWT->MASK0     = 0;
DWT->FUNCTION0 = 0b0110;   // data watchpoint, write

A match raises a debug event. With the debugger halting, the core stops; with DEMCR.MON_EN (bit 16) set and no halt, you get the DebugMonitor exception (exception 12) and can record PC, LR and the address from the handler while the core keeps running. That's the mode I want here. DWT_CYCCNT (0xE0001004, enabled by DWT_CTRL bit 0) gives cycle timestamps that wrap every 25.6 s at 168 MHz, enough to bracket a race.

Breakpoints. Hardware instruction breakpoints come from the FPB, not the DWT: six instruction comparators on Cortex-M3/M4, and (FP_CTRL >> 12) & 0x7 reads NUM_CODE from FP_CTRL (0xE0002000). They don't modify code, so they work on flash. A software breakpoint is BKPT #0 (0xBE00) written over the instruction: one store in RAM, a sector erase in flash, and a HardFault if no debugger is attached when it executes. The two pools are separate, so six hardware breakpoints and four watchpoints can be live at once.

ITM/SWO instead of printf. A 40-character printf line at 115200 8N1 costs 400 bits / 115200 ≈ 3.5 ms and blocks the caller, if the fault is a deadline miss, that's the bug. ITM is a store to a stimulus port at 0xE0000000 + 4*n, a few cycles, and non-blocking if you check the FIFO-ready bit:

C
if (ITM->PORT[0].u32 & 1u) ITM->PORT[0].u8 = c;   // drop instead of stall

SWO carries it out at trace_clock/(ACPR+1): 2 Mbaud from an 8 MHz trace clock is ~200 kB/s, about 17x a 115200 UART. The trade is that it's lossy under load and needs the pin.

Order. Watchpoint on the suspected address first: no halt, no code change. If the address is unknown, ITM trace to find the window, then a watchpoint inside it. A hardware breakpoint only when I need to stop at one instruction and can pay the halt. A software breakpoint only in RAM, or in flash once I've accepted the erase cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate an embedded debugging workflow for trace versus halt.

Answer

Core answer (first 90 seconds)

Assume an ARM Cortex-M or Cortex-A with CoreSight: SWD/JTAG for halt, ETM/ITM/SWO for trace, and either an on-chip ETB or an off-chip probe (Segger J-Trace, Lauterbach TRACE32, or OpenOCD with a trace-capable probe). The decision is not which is better: it's whether halting changes the bug.

Halt stops the core at a breakpoint or watchpoint. It's deterministic and cheap: registers, memory, stack backtrace. But it stops only the core you halted. DMA, timers, and other cores keep running, so system state diverges from the moment you halt. A race, a timeout, or a missed deadline either hides or moves.

Trace records program flow without stopping the core. ETM emits compressed branch packets; ITM/SWO carries printf-style instrumentation. You get causality and timing, at the cost of bandwidth and buffer. Use halt for deterministic, single-threaded, non-timing bugs; use trace when the bug is timing-, ordering-, or concurrency-dependent, or when halt makes it disappear.

symptomhalttrace
deterministic, single-threadedyesoverkill
race / timeout / missed deadlinehides ityes
registers at a pointyesneeds decode
ordering across coresnoyes

Workflow

  1. Reproduce under halt first if it's cheap. Cortex-M3/M4 typically give 6 instruction breakpoints and 4 data watchpoints; Cortex-M7 gives 8 and 4. If it reproduces, stop.
  2. If it doesn't reproduce, or halting perturbs it, switch to trace. Choose the capture target: on-chip ETB (small, no pins, wraps) or off-chip via TPIU to a probe (large, needs pins, no wrap).
  3. Size the budget. A 4 KB ETB at a plausible 20 MB/s of ETM output holds 4096 / 20e6 ≈ 205 µs. Longer windows need off-chip trace or a trigger that arms just before the event.
  4. Set a bounded trigger: a DWT watchpoint or a CoreSight CTI cross-trigger that starts or stops the ETB on the event, so you capture the window around the bug, not the whole run.
  5. Capture, decode, correlate. Check the decoder for overflow and sync packets before trusting the timeline.

ITM instrumentation costs a few cycles per write:

C
// CMSIS: reading an ITM port returns status; bit 0 set = FIFO ready
if (ITM->PORT[0].u32 & 1u) ITM->PORT[0].u32 = value;

Failure modes and detection

  • ETB wrap: the buffer is circular; a late trigger gives you the tail, not the event. Detect by reading the ETB status register's wrap bit and the decoder's first sync packet.
  • Trace overflow: ETM output exceeds TPIU bandwidth; the ETM emits an overflow packet and the decoder reports a discontinuity. Detect by checking for that packet, not by eyeballing the timeline.
  • Missing timestamps: if the global timestamp counter isn't enabled, packets carry no time and you can't order events across cores. Detect by looking for timestamp packets in the decode.
  • SWO saturation: an ITM write when the FIFO is full sets the busy bit and drops the packet. Detect by polling the busy flag or counting stimulus packets against expected.
  • Trace changes power: enabling the trace clock and toggling trace pins adds dynamic current, so you cannot measure sleep current with trace on. Detect by measuring current with trace enabled and disabled.
  • Filtered branches: branch-broadcast mode traces only taken branches, so the not-taken path is missing. Detect by comparing the decoded path against a known-good run.

Validation

Validate the workflow itself, not just the bug. Toggle a GPIO at a known point and check the trace timestamp against a scope. Run a known instruction-count loop and check the decoder's count. Inject a deliberate overflow and confirm the tool reports it. Then run the same bug under halt and trace and confirm they agree where they overlap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate an embedded debugging workflow for semihosting.

Answer

I'd treat semihosting as a debug-only transport, not a logging API. The workflow has four gates: toolchain, probe, runtime, release validation. Assume Cortex-M, newlib, SWD, OpenOCD or J-Link.

Mechanism: the target executes BKPT 0xAB (Cortex-M) or SVC 0x123456 (older ARM). The debugger sees the halt, reads r0 = operation and r1 = pointer to a parameter block, reads that block from target memory, performs the host operation, writes the result to r0, and resumes. For printf, newlib's _write issues SYS_WRITE (0x05) with a block {handle, buffer, length}. If no debugger is attached, BKPT escalates to HardFault. That is why a release image with a hidden semihosting call hangs or faults when the probe is disconnected.

Design:

  1. Toolchain. Debug: link with --specs=rdimon.specs and call initialise_monitor_handles() before first I/O. Release: link with --specs=nosys.specs and provide explicit stubs for _write, _read, _open, _close, _lseek, _fstat, _isatty, _exit, _kill, _getpid. Never link rdimon into release.
  2. Probe. OpenOCD: arm semihosting enable. Leave arm semihosting_fileio disabled unless you need host file I/O. J-Link GDB Server and pyOCD also implement the protocol; check the probe's documentation for the enable switch.
  3. Runtime. Keep semihosting out of ISRs. A semihosting call from an ISR blocks in interrupt context and can deadlock if the debugger needs the target halted. Do not print secrets; semihosting file I/O can read and write host files.
  4. Validation. Build release, then:
    • arm-none-eabi-objdump -d release.elf | grep -n "bkpt": expect no output.
    • arm-none-eabi-nm release.elf | grep rdimon: expect no output.
    • Power cycle with the probe disconnected. The image must run to completion.
    • Connect the probe but disable semihosting in the debugger. The image must not halt on a BKPT.
    • Call the logging path from an ISR in a debug build and confirm no deadlock.
    • Check that no secret is passed to printf or file I/O.

Worked trace: printf("hi\n") -> newlib _write -> BKPT 0xAB, r0=0x05, r1=&block{1, buf, 3} -> debugger halts, reads block, writes 3 bytes to host stdout, sets r0=0 -> target resumes. If the probe is absent, the same instruction becomes a HardFault.

Latency: at 115200 8N1, 3 bytes take 3*10/115200 = 260 µs. A semihosting SYS_WRITE is a debug halt plus host syscall; on a 4 MHz SWD link it is commonly in the millisecond range per call. A 1 kHz control loop that logs one line per iteration will miss deadlines. Measure yours by toggling a GPIO around a SYS_WRITE and scoping it.

Trade-offs:

transportcosthalt?production?
semihostingms per callyesno
RTTµs per callno (background memory access)debug only
ITMlow, SWO pinnodebug only
UARTdeterministic, pinsnoyes

Use semihosting for early bring-up when no UART exists, or for host file I/O. Use RTT for high-rate logging during debug. Use ITM for low-overhead instrumentation. Use UART for production.

Failure modes and detection:

  • Hidden libc syscall: a library calls _write or _sbrk. Detect by disassembling release for BKPT and checking the map for rdimon.
  • Enormous latency: a semihosting call in a hot loop. Detect by GPIO toggle around the call.
  • Debugger absent: release image faults. Detect by power cycling with no probe.
  • ISR invokes output: deadlock or priority inversion. Detect by calling the logging path from an ISR.
  • Secrets sent to host: printf of keys or file I/O. Detect by code review and by leaving semihosting file I/O disabled.

The pass condition is a release image that runs to completion with no probe attached and no BKPT in the disassembly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate an embedded debugging workflow for logging.

Answer

Assumptions. Cortex-M4 at 168 MHz (STM32F4-class), 128 KB SRAM, FreeRTOS 10.5, arm-none-eabi-gcc 12.2. Figures are for that part; re-measure on yours.

Core answer (first 90 seconds). A logging workflow is three decisions made before any code: what must survive a reset, what may be dropped, and what an ISR is allowed to do.

Classify. Fault and assert records must survive reset and are never dropped. State transitions are droppable but must be counted. Debug traces are droppable and uncounted.

Transport per class. Fault records go to retained RAM: a .noinit linker section the startup code does not zero. Bench debug goes to SEGGER RTT or ITM/SWO. Field telemetry goes to UART + DMA.

Non-blocking ISR path. Copy into a ring buffer, publish an index, return. No formatting, no mutex, no malloc.

Validate by measurement. ISR latency, drop counts, retention across reset, fault injection.

Why the ISR path matters. A blocking UART write of a 64-character line at 115200 8N1 costs 64 × 10 / 115200 = 5.6 ms. A 1 kHz control loop has a 1 ms period, so one log line inside the ISR misses five deadlines. The ring-buffer path is a 52-byte memcpy plus a few stores: roughly 80 cycles, ≈ 0.5 µs at 168 MHz.

C
/* Cortex-M4, FreeRTOS 10.5, arm-none-eabi-gcc 12.2 -O2 */
#define LOG_SLOTS 64
typedef struct { uint32_t seq, cyc; uint16_t id; uint8_t sev, n; uint8_t d[52]; } log_rec_t;
static log_rec_t ring[LOG_SLOTS];
static volatile uint32_t head, tail, dropped, seq_ctr;

bool log_isr(uint16_t id, uint8_t sev, const void *d, uint8_t n) {
    uint32_t h = head, next = (h + 1u) & (LOG_SLOTS - 1u);
    if (next == tail) { dropped++; return false; }   /* full: drop, count, return */
    log_rec_t *r = &ring[h];
    r->seq = ++seq_ctr; r->cyc = DWT->CYCCNT; r->id = id; r->sev = sev;
    r->n = n > 52u ? 52u : n;
    memcpy(r->d, d, r->n);
    head = next;                                     /* publish last */
    return true;
}

Trace: head=tail=0 → next=1 ≠ tail → write ring[0], head=1. The ring holds 63 records (one slot distinguishes full from empty), 4032 of 4096 bytes. When head=63 and tail=0, next=0 == tail → dropped++ and return false. A low-priority task drains to RTT or UART.

Transport trade-offs.

transportpaththroughputwhen not to use
retained RAM (.noinit)CPU writes; survives resetbounded by section sizeno host visibility until next boot
SEGGER RTTCPU writes RAM ring; probe reads via AHB-APvendor-documented up to ~1 MB/s on Cortex-M; measure yoursno probe attached (field units)
ITM/SWOCPU writes ITM stimulus porthundreds of kB/s practicalSWO pin or trace clock unavailable; overruns drop silently
UART + DMACPU fills DMA buffer92160 B/s at 921600 8N1no free UART/DMA channel

Deciding criterion: does the record have to survive a reset, and is a host attached? Fault class → retained RAM. Bench → RTT. Field → UART DMA.

Failure modes and detection.

  • Recursive fault logging. The fault handler logs, the log path itself faults, the handler re-enters: a reset loop with nothing retained. Detect with a re-entrancy counter in the handler: on entry > 1, write one minimal record to .noinit and reset. The fault path must also never take the log mutex; a fault taken while the mutex is held deadlocks.
  • Silent ring overwrite. Producer outruns consumer, oldest records vanish, and the trace still looks complete. Detect with dropped plus the per-record seq: a gap in seq is a lost record.
  • Clock discontinuity. DWT->CYCCNT is 32-bit and wraps every 2^32/168e6 ≈ 25.6 s; sleep modes gate it. Detect with a 64-bit extension carrying a wrap counter, and flag any backwards jump.
  • Formatter stack overflow. printf with %f pulls newlib float formatting and roughly 1 KB of stack; in a 512-byte ISR stack it corrupts. Detect with stack painting (high-water mark) and an MPU guard region; format integers only in ISRs.
  • Secret leakage. Keys in retained RAM are readable over SWD after a field return. Detect by redacting at the format-string level, scanning the image for key material, and setting RDP level 1 on production parts.

Validation.

whatmethodpass criterion
ISR latencyDWT->CYCCNT delta around log_isr, 10k samplesp99 < 2 µs
drop rate10 kHz synthetic stream for 60 s, read dropped0 for fault class; < 0.1% for debug
retentionwrite a record, NVIC_SystemReset(), read .noinit on bootrecord intact, seq monotonic
re-entrancyforce a HardFault inside the fault handlerexactly one retained record, then reset
secretsscan firmware image and log stringsno key material

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate an embedded debugging workflow for multicore halt.

Answer

Assumptions I'd state first

Heterogeneous SoC: a 4-core Cortex-A53 cluster running Linux or an RTOS, plus a Cortex-M7 safety core feeding a 1 s watchdog. CoreSight CTI/CTM cross-trigger fabric, one probe (J-Link Ultra+ or Lauterbach) on the A53 cluster. The bug is a suspected lock-ordering hang, not a crash.

The workflow

1. Pick the stop policy from the bug class, not from habit. Race, lock inversion, corrupted shared state → all-stop via a CTI halt group, so no peer mutates memory while you read it. Live-lock, watchdog reset, anything timing-sensitive → non-stop, halt only the suspect core.

2. Attach without resetting. TRACE32: SYStem.Mode Attach. OpenOCD: declare the cluster as an SMP group (target smp $_TARGETNAME0 ... $_TARGETNAME3) so GDB sees one target with four threads, then set non-stop on and set scheduler-locking on so a step on one core doesn't release the others. J-Link needs a script file to bring the second core under debug; without it you only ever halt core 0.

3. Halt, then read state before resuming. Confirm who actually stopped by reading EDPRSR.Halted on each A53 and DHCSR.C_HALT on the M7.

4. Choose the memory path deliberately. AXI-AP reads go straight to the bus and bypass the halted core's L1: you get DDR contents, not what the core sees. APB-AP reads go through the core's MMU and caches, which is what a stack walk needs, but they hang if the core is in a low-power state.

5. Resume in a defined order and re-arm the watchdog.

All-stop vs non-stop

all-stop (CTI halt group)non-stop (halt one core)
state consistencyfrozen, safe to readpeers keep mutating
timing fidelitydestroyedpreserved
watchdogmust be in the group or extendedkeeps running, may reset
use whenlock inversion, corrupted queuelive-lock, latency bug

Worked trace

4× A53 at 1.2 GHz, spinlock in DDR, M7 watchdog at 1 s.

All-stop: t=0 core 2 takes the lock. t=2 µs core 3 enters the LDXR/STXR spin loop. t=50 µs the probe asserts the CTI halt group; cores 0–3 stop within a few debug-clock cycles. Core 2's PC sits in the critical section, core 3's in the spin loop: the inversion is now stable and readable. The M7 is not in the group, keeps running, and resets the SoC at t=1 s. You lose the session unless you add the M7 to the group or extend its timeout.

Non-stop: halt only core 2. Core 3 spins forever, the lock never releases, and if core 3 is the watchdog feeder the SoC resets at t=1 s anyway. Non-stop turned a 50 µs window into a permanent hang.

Validating the workflow

Fault injection: a test build where core 2 takes the lock and then spins on a GPIO-triggered flag. Run 20 iterations.

  • All four A53 cores report Halted in EDPRSR before any of them advances a shared counter: proves the halt group is atomic.
  • Ten 5 s halts with the M7 in the group: zero resets, reset-cause register clear.
  • Control run: attach, no halt, 100 iterations, zero resets. Proves the probe itself isn't the cause.

Failure modes and detection

  • Watchdog reset mid-session: reset-cause register reads WDOG. Fix: put the M7 in the halt group.
  • Stale read: an AXI-AP read of a stack disagrees with the core's own view. Re-read via APB-AP.
  • IPI storm: the halted core's GIC redistributor keeps pending SGIs and peers spin in the handler. Detect by reading the redistributor's pending registers.
  • Peripheral continues: DMA keeps writing a buffer the halted core owns. Detect via DMA channel status.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate an embedded debugging workflow for memory corruption.

Answer

Assume a Cortex-M target with SWD, no ETM trace, and a crash that happens minutes after boot. The workflow has four phases: reproduce, instrument, bisect, validate.

First, reproduce and capture. Get a reliable repro. On the fault, read CFSR and HFSR to distinguish a precise bus fault from an imprecise one. If you have a core dump, save it. Otherwise, snapshot the suspect memory region.

Second, instrument. The goal is to turn silent corruption into an immediate fault. On target, use the MPU to set a guard region: mark the memory immediately after a heap block or stack as no-access. Any write past the boundary triggers a MemManage fault at the corrupting instruction. Hardware watchpoints are more precise: set a watchpoint on the variable that ends up corrupted. Cortex-M typically has 2-4 watchpoints, so choose the most likely victim. Add stack canaries (fill with 0xDEADBEEF and check on context switch) and heap canaries (write a known pattern after each allocation). If you can run on host or QEMU, build with AddressSanitizer (-fsanitize=address) and UndefinedBehaviorSanitizer. ASan adds redzones around allocations and catches out-of-bounds and use-after-free with a full stack trace.

Third, bisect the causal time window. The crash site is often far downstream. Heap corruption propagates because a write past the end of a buffer overwrites adjacent metadata or a function pointer; the crash occurs when that corrupted pointer is later dereferenced. To find the first invalid write, use the watchpoint to stop at the exact instruction. If watchpoints are exhausted, bisect in time: take periodic checksums of the suspect region, and binary search the interval where the checksum first changes. With ETM trace, you can replay the last N instructions.

Fourth, validate. After fixing, run the same repro with instrumentation to confirm the fault is gone. Then run without instrumentation under stress: a 24-hour soak, fault injection, and worst-case timing. Finally, enforce the fix in production with the MPU: set the buffer's boundary as read-only or no-access, and verify the fault handler logs and resets cleanly.

Tradeoffs: hardware watchpoints are precise but scarce (2-4 on Cortex-M). MPU is cheap but has alignment and granularity limits (e.g., 32-byte minimum on some parts). ASan is powerful but adds roughly 2x memory and 2x slowdown, often too heavy for target. So use ASan on host/QEMU for early detection, MPU+watchpoints on target for final validation.

Failure modes to check: guard itself overwritten (detect by periodic guard checks; cost: extra memory and CPU), DMA writer omitted (DMA can bypass MPU on some MCUs; detect via DMA error interrupts or an IOMMU if present; cost: complexity), use-after-free (detect by poisoning freed memory with 0xDEADBEEF and checking on alloc; cost: overhead), stack collision (detect via stack canaries and an MPU guard region below the stack; cost: stack usage), and instrumentation masks race (detect by running with and without instrumentation and comparing timing; cost: time).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate an embedded debugging workflow for fault injection.

Answer

Assume a Cortex-M or Cortex-A target, a debug probe (J-Link or OpenOCD), a build I can rebuild with instrumentation, and a release image that must ship without injection code. The workflow has three layers (inject, observe, assert) and its purpose is not to prove the absence of bugs. It is to prove the diagnostic system detects the fault, retains evidence, recovers, and fails safe.

Inject. Pick the mechanism that matches where the bug lives. For software error handling, a linker wrap is the cheapest deterministic hook:

C
/* gcc -Wl,--wrap=read_sensor */
ssize_t __real_read_sensor(int fd, void *buf, size_t n);
ssize_t __wrap_read_sensor(int fd, void *buf, size_t n)
{
    static int calls;
    if (__atomic_fetch_add(&calls, 1, __ATOMIC_RELAXED) == 3)
        return -ETIMEDOUT;      /* 4th call fails */
    return __real_read_sensor(fd, buf, n);
}

Trace it: calls starts at 0, so the first three calls return 0, 1, 2 and pass through to the real function; the fourth returns 3 and yields -ETIMEDOUT. Deterministic, and the driver itself is untouched.

For kernel allocation failure, build with CONFIG_FAULT_INJECTION_DEBUG_FS and CONFIG_FAILSLAB, then write probability=100 and times=1 into /sys/kernel/debug/failslab/ to fail exactly the next allocation. For function-level errors, fail_function plus ALLOW_ERROR_INJECTION() on the target. For bus faults, go below software: hold I2C SDA low, short CANH to CANL to force error frames, or use a DWT watchpoint (Cortex-M typically exposes four comparators) to corrupt a register mid-transfer.

Observe. ETM/CoreSight trace, a ring buffer, dmesg, the reset-cause register, and a bus-analyzer capture. The evidence has to survive the fault, so the buffer must be in retained RAM or flushed before the reset.

Assert. Three separate checks, not one: the fault fired (an injection counter), the detector fired (log line or errno at the caller), and recovery completed (a post-condition such as the device re-enumerating within 500 ms).

Trade-offs. Compile-time injection costs nothing at runtime but needs a rebuild and cannot run on a customer unit. Runtime injection (debugfs, or bpf_override_return with CONFIG_BPF_KPROBE_OVERRIDE) runs against the shipping binary but installs a kprobe and perturbs timing. Hardware injection is the most realistic and the least deterministic. The deciding rule is to match the layer to the bug: software error handling gets software injection, driver/bus interaction gets hardware, and races get hardware or trace, because software hooks change timing.

Fault classInjectionExpected detectorEvidence
Timeout--wrap returning -ETIMEDOUTdriver timeout patherrno at caller + ring buffer
Allocationfailslab, probability=100, times=1-ENOMEM handled, no NULL derefdmesg + fault counter
Bus errorSDA held low / CAN error frameNAK or timeout, bus recoveryETM trace + analyzer capture
Resetsuppress the watchdog kickboot reason = WDTreset-cause register
Exhaustionfill queue to depth, then one morebackpressure or drop counterqueue high-water mark
Concurrencytwo threads on one handlelock assertion or TSanTSan report

Failure modes and how to catch them. A hook that changes timing can create or mask the very race under test: compare ETM timestamps with the hook compiled out and the fault forced in hardware; if the failure only reproduces with the hook present, the test is invalid. An injection that bypasses the real layer means you tested a stub: require non-zero gcov/llvm-cov hits on the production function during the run. Recovery that is never asserted lets a hang pass as success: require the explicit post-condition rather than absence of a crash. Destructive tests leak state into flash or EEPROM and poison the next run: use a fresh image per test and read the persistent state back in teardown. And a hook that ships is caught mechanically: nm -C release.elf | grep -E 'should_fail|__wrap_' must be empty, gated in CI, with CONFIG_FAULT_INJECTION off in the release defconfig.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate an embedded debugging workflow for debug security.

Answer

Assumptions. A Cortex-M33 SoC with an SWD/JTAG debug port, ARM CoreSight debug, a lifecycle word in OTP sampled at reset, an OEM debug-signing key held in an HSM, and a factory that needs debug on the line but not in the field. If your part has no OTP lifecycle word, the design still holds but the enforcement point moves to whatever fuse or ROM the SoC provides.

The 90-second answer. Debug is not a read-only convenience: it halts the core, reads and writes memory, patches the program counter, and dumps flash. Treat it as a full-control interface and gate it on lifecycle: open in fab and provisioning, locked in production, unlockable only by an authenticated challenge-response for RMA. Enforce the lock in hardware at reset, not in software, because an attacker with debug halts before your software runs. Then validate with tests that fail closed.

Design.

LifecycleDebug portEnforcement
Fab / chip manufacturingOpenDBGEN/NIDEN/SPIDEN asserted from OTP
ProvisioningOpen, keys being writtensame
ProductionLockedOTP debug-disable bit; DBGEN deasserted at reset
RMATime-limited unlockSigned challenge-response; re-lock on reset

Mechanism: on ARM CoreSight, invasive debug is gated by the authentication signals DBGEN (non-secure invasive), NIDEN (non-secure non-invasive, i.e. trace), SPIDEN (secure invasive) and SPNIDEN (secure non-invasive). Tie them to an OTP bit sampled at reset and the debugger cannot halt the core or touch memory. Depending on the SoC the DAP may still enumerate with an empty ROM table, or not respond at all: either is fine; what matters is that no memory read succeeds. A software "debug disabled" flag is not enforcement, because the attacker halts before it executes.

Unlock: the host requests a nonce, the SoC returns a random one, the host signs it with the OEM debug key, the SoC verifies against a public-key hash in OTP and asserts DBGEN for the session. The certificate carries an expiry and a device ID so a leaked certificate is bounded in time and scope. ARM's CoreSight SDC-600 Secure Debug Channel is one implementation of this.

Transport: GDB's manual warns that the remote protocol provides no authentication or encryption, and OpenOCD's telnet/TCL ports give arbitrary command execution. Never expose them on a network: bind to loopback and tunnel over SSH, or use the authenticated debug channel.

Validation. Each test has a pass criterion:

  1. Locked part: attach SWD, attempt halt and flash read. Both must fail.
  2. Unlock: correct key works; wrong key refused; replayed nonce refused.
  3. Irreversibility: blow the production lock on a sample, then confirm the RMA unlock still works and the lock cannot be reversed. Do this before committing the fuse policy to the line: blow it first and discover the unlock is broken, and you have bricked fleet serviceability. STM32's RDP Level 2 is the canonical irreversible lock.
  4. Debug vs secure boot: with debug unlocked, halt at the secure-boot signature check and patch the branch. The part must not boot.
  5. Audit: every unlock attempt, success and failure, logged with device ID, nonce, result and time, surviving reset and readable without debug.

Failure modes and detection. Debug left enabled in production: scan the OTP lifecycle word on the line and in periodic field audits; a part that halts under SWD in the field is a finding. Shared unlock secret across a fleet: one leak unlocks everything; require per-device certificates and check the device ID. Public debug port: port-scan the lab and factory networks for OpenOCD/gdbserver. Debug bypassing secure boot: the test above. Lock irreversible before recovery test: the sample test above.

Trade-off. An irreversible lock maximizes field security but destroys RMA and failure analysis. An authenticated unlock keeps serviceability but adds a signing service that must be available when a field unit fails. Decide by whether you can replace rather than repair a failed unit: if yes, irreversible; if no, authenticated unlock with short-lived certificates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate an embedded debugging workflow for debug evidence.

Answer

Assumptions. Bare-metal or lightly-RTOS'd Cortex-M, SWD probe (J-Link/ST-Link) driven by GDB + OpenOCD or a vendor IDE, ELF with DWARF, CMSIS-SVD for the peripheral view. On Cortex-M0/M0+ there is no ITM/SWO, so the trace channel below has to be a RAM ring buffer instead.

Core answer (first 90 seconds). A debug workflow is a loop that turns an observation into a claim you can defend, and what makes it defensible is that every claim is pinned to one binary, one reset path, and one observation channel. Five steps. (1) Write the claim and its falsifier before touching the probe: "the UART drops bytes when the DMA buffer wraps," not "UART is broken." (2) Pin the artifact: ELF GNU build ID, compiler and probe-firmware versions, target silicon revision, SVD version. (3) Record the reset path and read the reset-cause flags at boot. (4) Capture raw evidence on the least intrusive channel that still sees the bug. (5) Reproduce from the same reset path N times and record the pass/fail count. Validation is not "it worked once": it is corroboration from a second channel plus a deliberate attempt to falsify.

Why each step exists. The build ID is the only cheap way to prove the symbols GDB is using match the image in flash; without it, a wrong binary produces plausible-looking line numbers that are simply off. The reset path matters because power-on, NRST pin, SYSRESETREQ, and watchdog reset leave different peripheral state: on STM32 the RCC_CSR flags (PINRSTF, PORRSTF, SFTRSTF, IWDGRSTF) tell you which one happened, and if you don't log them you will attribute a watchdog reset to a software bug.

The central trade-off: intrusion versus visibility. Breakpoints halt the core. Peripherals keep running, and on parts that offer debug freeze bits (STM32's DBGMCU) the watchdog and timers keep counting unless you set them, so a timing bug disappears under a breakpoint and returns in free run. SWO/ITM or a RAM ring buffer costs RAM and cycles but doesn't halt anything. Deciding criterion: if the bug is timing- or interrupt-order-sensitive, use the non-intrusive channel; if it's a logic error on a cold path, breakpoints are cheaper and fine. Don't pay trace overhead for a bug that reproduces under a halt.

A ring buffer you can trust from an ISR.

C
#define TRACE_N 64
static volatile uint32_t head, tail;
static volatile uint32_t ev[TRACE_N];

void trace_push(uint32_t code) {      /* single writer: ISR only */
    uint32_t h = head;
    ev[h & (TRACE_N - 1)] = code;
    head = h + 1;
}

int trace_pop(uint32_t *out) {        /* single reader: main loop */
    uint32_t t = tail;
    if (t == head) return 0;
    *out = ev[t & (TRACE_N - 1)];
    tail = t + 1;
    return 1;
}

Trace it: trace_push(0x11) sets ev[0]=0x11, head=1; trace_push(0x22) sets ev[1]=0x22, head=2. trace_pop(&v) sees t=0 != head=2, returns v=0x11, tail=1. Next pop returns v=0x22, tail=2. Third pop sees t==head and returns 0. Push 65 events without popping and head-tail = 65 > TRACE_N: the 65th push wrote ev[64 & 63] = ev[0], silently overwriting the oldest entry. The reader detects that gap by checking head - tail > TRACE_N, if you don't check it, you will read a truncated trace as a complete one.

Failure modes, how each is detected, what it costs.

failuredetectioncost if missed
wrong binarycompare ELF build ID (readelf -n) against the image read back from flashevery conclusion invalid; hours on a phantom
observer effectrun the same scenario with breakpoints vs SWO trace and comparefalse "fixed"
stale SVDSVD version vs silicon revision; cross-check one known register against the reference manualmisread field, wrong fix
unrecorded memory patchlog every debugger memory write; diff RAM against the ELF init imagenon-reproducible session
ambiguous resetlog reset-cause flags at bootwrong root cause
screenshot without timestamprequire a monotonic timestamp in every captureevidence uncorrelatable with logs

Validation. Two independent channels must agree: e.g. the ring buffer and a GPIO toggled at the same point, read on a scope. Then try to break the claim: change one variable, rerun from the same reset path, and record the count. A claim that survives ten runs and one falsification attempt is worth writing down; one that survives a single run is a hypothesis.

Curated: · Written: · Reviewed:

Difficulty: Hard