Seeing Inside a Running Chip

A chip crashed and its screen is dark. Read two registers and one map, and the crash names the function that failed and the kind of mistake. Then we add the log, the clock and the trace.

Learn how a debug probe talks to a microcontroller, how to read a HardFault, and how to print, time and record a program that you cannot stop.

Pick a recorded crash, then press Next step three times: read the fault register, read the saved frame, look the address up in the map. Then we build, piece by piece, every tool underneath.

You need a little C and the idea that a program lives at numbered addresses in memory. We build the rest from zero.

Part of the course Firmware from Zero to Expertise. Built from primary sources: the Memfault Interrupt posts on HardFaults, profiling and debug interfaces, the SEGGER RTT page and the OpenOCD manual.

Replay a crash

Illustrative recordings. The register layout, the eight-word frame and the fault patterns follow the Memfault Interrupt HardFault post and the Arm manuals; the addresses and function names are invented for this lesson, on a Cortex-M4 part such as the STM32F407.

Chapter 0

A Chip With No Window

See why a running microcontroller hides its own state, and why every way of looking at it changes what you see

Picture a small sensor node in a weatherproof box on a fence post. It measures soil moisture and sends a number every minute. About once a night it restarts. Nobody sees it happen. There is no screen, no keyboard and no operating system to ask. The only clue is a counter that says “boots: 41”.

On your laptop you would add a print line and run again. A microcontroller offers no such comfort. Its program lives in flash memory. Its variables live in a few kilobytes of RAM. Nothing on the chip is built to tell you what it is doing. This lesson is about building the window.

Three questions you can ask a chip

Every debugging question about firmware is one of three. Where is it? Which function is running, and what do the registers hold right now? What happened? What did the program do in the last few milliseconds before it went wrong? How long did it take? How many clock cycles did this loop need?

Four families of tool answer these. You can stop and look: halt the processor and read it, as a debugger does. You can print: send text out while the program runs. You can count: let a hardware counter measure time for you. You can record: save a trace of events, or a snapshot of memory, to read later. The chapters follow that order.

Some words you need first

A register is a tiny storage cell inside the processor or inside a peripheral. A memory-mapped register has an address, just like a byte of RAM, so code can read it with a normal pointer. On an Arm Cortex-M chip such as the STM32F407, the registers that control debugging sit at fixed addresses near 0xE000ED00. You will meet them one by one.

A debug probe is a small USB box (or a part of the board, like the ST-Link on a Nucleo) that touches the chip through two or four thin wires. Through those wires the probe can read and write the chip’s memory and registers, even while the program runs. Your laptop never talks to the chip directly. It talks to the probe.

If any of this feels shaky, the embedded systems introduction builds it from zero, and from vector table to main shows where the program starts. This lesson builds on stack, heap and the MPU, on the fault chapter of interrupts and DMA, and it feeds the bench work in bench and root cause.

The catch: looking changes the thing you look at

Suppose the node runs a control loop every 1 ms. Each pass takes 0.2 ms of real work. You want to see a value, so you add a log line. Now the loop does its work and also pays for the log line. If the log line is slow, the loop is late. If it is very late, the whole behaviour you wanted to study disappears or turns into a different bug.

This is the probe effect: an instrument that changes the timing of the system it measures. A bug that vanishes when you add a print is called a heisenbug. The skill in this lesson is to choose a tool whose cost is small next to the thing you study. Try it below with the numbers of a real serial port.

Watch the loop while you watch it

Each tick is one 1 ms release of a control loop. Warm bars are the loop’s own work. Yellow is the cost of your instrument. A red cross is a release the chip had to skip. Pick an instrument, then lengthen the log line.

80 chars

Illustrative loop: 0.2 ms of work every 1 ms. The UART cost is exact arithmetic for 8N1 framing at 115200 baud: 10 bits per character. The RTT cost uses SEGGER’s figure of one microsecond or less for an average line. A breakpoint stops the core until you press continue.

With no log, all twelve releases run. With a UART printf of 80 characters, one log line holds the loop for almost 7 ms, so the next seven releases are skipped after every line. The log changed the system more than the bug did. RTT, which writes the line into a buffer in RAM, costs about one microsecond. The breakpoint is the extreme case: it is the best way to read state, and the worst way to watch a system that must keep time. A motor driver would keep spinning with nobody at the wheel.

The road

  1. The wire: how a probe reaches inside a running chip over two pins.
  2. Stopping the chip: GDB, OpenOCD and the few breakpoints you have.
  3. The crash frame: the eight words the chip saves when it faults.
  4. The fault registers: CFSR, HFSR and the address of the mistake.
  5. From address to line: turning a number into a function with the map.
  6. Printing without stopping: RTT against a serial port.
  7. Counting cycles: the DWT counter and a profile of a loop.
  8. Recording the run: ITM, SWO and ETM trace.
  9. Crashes in the field: coredumps for boxes on fence posts.
  10. Field guide: the numbers, the checklist and the code.
A 1 ms control loop starts missing deadlines only after you add a printf over a 115200 baud UART. What is the most direct explanation?

Chapter 1

The Wire: How a Probe Reaches Inside

Follow one memory read down a two-wire cable, bit by bit, and learn what a debug probe really does

You plug a small board into your laptop. You type one command. A moment later your computer shows you the value of a variable inside a chip that is still running. How did the number get from RAM on the chip to your screen?

The chip has no keyboard port and no screen port. What it has is a debug port: a small block of logic, built into every Cortex-M core, that listens on two pins and can read or write the chip’s memory on request. It works even when your program is busy. This chapter follows one request along that path.

Two wires instead of four

The older standard is JTAG (IEEE 1149.1, from 1990). It needs at least four pins, plus one optional reset pin. Arm added a slimmer option, SWD, for Serial Wire Debug. It needs two pins: SWDIO, one wire that carries data in both directions, and SWCLK, the clock. On many STM32F4 parts those are pins PA13 and PA14. Two pins matter on a small package where every pin is precious.

The clock is always driven by the host side. The data wire is shared: first the host drives it, then the target, then the host again. Whoever speaks, the other side listens. The moment of handing the wire over has a name, the turnaround, and costs one clock.

The probe is a translator

Your laptop speaks USB. The chip speaks SWD. A debug probe sits between them and translates. Memfault’s guide lists the usual kinds: FTDI-based adapters, CMSIS-DAP boards, SEGGER J-Link and ST-Link. On a Nucleo board the ST-Link is a second small chip on the same PCB. The software on your laptop (OpenOCD, in the next chapter) sends commands over USB, and the probe turns each one into SWD waveforms.

Two doors: the debug port and the access port

Inside the chip there are two layers. The Debug Port (DP) is the front door. It is what the two pins connect to. Per the same guide, the DP can configure transactions and talk to one or more Access Ports (AP). The AP most Cortex-M chips use is the AHB-AP, a port that acts like a second processor on the chip’s memory bus. Whatever it reads or writes lands in real RAM, flash or peripheral registers.

To read a word, the probe uses three AP registers. It writes the address into TAR (transfer address). It reads the data from DRW (data read/write). A third register, CSW, sets the size of the access and whether the address steps forward by itself after each read. Because the AHB-AP is its own bus master, it can fetch a word from RAM while your program keeps running.

One transaction, field by field

Every SWD transaction has the same shape. First comes an 8-bit request from the host: a start bit (1), a bit saying DP or AP, a bit saying read or write, two address bits, an even parity bit, a stop bit (0) and a park bit (1). Then the turnaround. Then a 3-bit ACK from the target, sent least significant bit first: OK is 001, WAIT is 010, FAULT is 100. Then 32 data bits and one parity bit. Then, for a read, one more turnaround.

Count it: 8 + 1 + 3 + 32 + 1 + 1 = 46 clocks. That count is our own sum of the fields above, using the standard framing. Reading the AP register DRW sends the request byte 0x9F on the wire, least significant bit first. Reading the DP’s identification register sends 0xA5.

Walk down one SWD read

Each cell is one clock of SWCLK. Teal cells are driven by the probe, warm cells by the chip, grey cells are turnarounds. Drag the first slider through the 46 clocks, then change the clock speed.

12
500 kHz

The field layout is the Arm Debug Interface (ADIv5) SWD framing; the 46-clock total is our own count. The data value 0x0BADCAFE is a made-up memory word. Real probes pipeline and batch transactions, so treat the dump time as a rough estimate, not a benchmark.

A read is also a little odd. AP reads are posted: the value you ask for comes back on the next read, or from the DP’s read-buffer register. So one word costs a write to TAR, a read of DRW to start the fetch, and a read of the buffer to collect it: three transactions, 138 clocks, or 276 microseconds at 500 kHz. If the address steps itself, a block of words costs one transaction per word plus a small setup. A 1 KB dump is 256 words, about 259 transactions, near 24 ms at 500 kHz.

That is why probes feel instant for a few variables and slow for a full RAM dump. It is also why a faster SWCLK is the cheapest way to speed up flashing. The limit is the cable: long wires and fast clocks give bad bits, and parity will catch it.

On real hardware. On an STM32 Nucleo (for example the F446RE), put a logic analyser on the SWD header, sample at least four times faster than SWCLK, and decode SWD. Set the probe clock to 500 kHz and read one word. Count the clocks of one transaction and check for the 46, and look for the 0x9F request byte.
Why can a probe read a variable while the program is running?

Chapter 2

Stopping the Chip: GDB, OpenOCD and a Few Breakpoints

Connect a debugger, halt the core on a line, and learn why a chip gives you only a handful of breakpoints

The sensor node crashes again, but this time it sits on your desk with a probe attached. You want to stop it on the exact line where something goes wrong and look around. That needs three programs talking in a chain, and a chip willing to freeze on request.

The chain: GDB, OpenOCD, probe, chip

GDB is the GNU debugger. It knows your C code: line numbers, variable names, types. It does not know how to talk to a chip. OpenOCD, the Open On-Chip Debugger, does. It speaks to the probe over USB and offers GDB a network port. The OpenOCD manual’s examples use port 3333.

So the chain has four links. GDB asks, in its own protocol, for “the bytes at this address”. OpenOCD turns that into SWD transactions like the ones in Chapter 1. The probe puts them on the wire. The chip answers. Your laptop gets the bytes back and GDB shows them as a variable.

GDB needs the ELF file of your build: the compiled program plus a table that links every address to a function and a source line. Without it, GDB shows only raw numbers. The chip itself holds no names at all. Only your build folder does, and that matters for field crashes later in this lesson.

A first session

Start OpenOCD in one terminal with a probe file and a chip file. Start GDB in another. Then connect. These are real commands from the OpenOCD manual and the usual GNU tools; the config file names match an STM32F4 on an ST-Link.

shell# terminal 1: the gdb server on tcp port 3333
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg

# terminal 2: gdb, with the ELF so it knows names and lines
arm-none-eabi-gdb build/fw.elf
(gdb) target extended-remote :3333    # connect to OpenOCD
(gdb) monitor reset halt              # reset the chip, stop at the first instruction
(gdb) load                            # write the program into flash through the probe
(gdb) break control_step              # stop when this function starts
(gdb) continue
(gdb) info registers                  # r0..r12, sp, lr, pc, xPSR
(gdb) x/8wx $sp                       # 8 words of the stack, in hex
(gdb) print/x *(unsigned *)0xE000ED28  # read CFSR, the fault register

The word halt deserves care. A Cortex-M core has a debug control register, DHCSR, at 0xE000EDF0. Bit 0 enables debug. Setting the halt bit makes the core stop after its current instruction. Firmware can even read that debug-enable bit to know whether a debugger is attached; Memfault’s fault handler does exactly that, and if a debugger is there it runs a bkpt instruction so you land in GDB at the fault.

Why you only get a few breakpoints

Your program sits in flash, and flash cannot be rewritten each time you click a line. A software breakpoint swaps an instruction for a trap, which works only in RAM. For flash code, the chip has a few hardware breakpoint comparators: tiny circuits that watch the address bus and stop the core when the program counter matches. A watchpoint does the same for data: it stops the core when your code reads or writes a chosen address.

There are very few of them. OpenOCD’s startup text in its manual shows a typical part reporting “hardware has 6 breakpoints, 4 watchpoints”, and you can tell GDB the limits with set remote hardware-breakpoint-limit 6 and set remote hardware-watchpoint-limit 4. Your chip’s number may differ; the debugger prints it when it connects. Place a seventh breakpoint and the probe has nowhere to put it.

Spend your comparators

Press a line to put a hardware breakpoint on it. Press a variable to put a watchpoint on it. The chip in this model has 6 breakpoint slots and 4 watchpoint slots, as in the OpenOCD manual’s example.

Illustrative source lines and variable names. The 6 and 4 are the example counts printed in the OpenOCD manual; your part reports its own.

The cost of stopping

Halting freezes the core. It does not always freeze everything around it. A motor timer may keep generating pulses with no program to steer them. A watchdog timer (a timer that resets the chip if nobody feeds it) may keep counting and reset the board in the middle of your debug session. On STM32 parts a set of debug freeze bits chooses which peripherals stop when the core halts; read your reference manual for the names.

The symptom is a board that resets a few seconds after every breakpoint. The measurement is to look for the reset cause flag after the reset. The fix is to freeze the watchdog while the debugger is halted. Chapter 0 showed the same lesson in time: stopping is the strongest tool and the least polite one.

On real hardware. On a Nucleo, run the commands above on the blinking LED example. Set a breakpoint inside the blink loop, press continue ten times, and watch the LED. Then enable the independent watchdog and halt for ten seconds. See if the board resets, and check the reset flags.
You set a seventh breakpoint in flash code and the debugger refuses. What is the cause?

Chapter 3

The Crash Frame: Eight Words the Chip Saves for You

Find the evidence that the processor itself leaves on the stack when a fault hits, and pick the right stack to read it from

Your board has just faulted. You halt it and look at the program counter. It points into HardFault_Handler, a few lines of startup code. That tells you nothing. The code that did the damage ran a moment ago, and the processor has already moved on. Where did the evidence go?

The answer is a kindness built into every Cortex-M core. Before it runs any exception handler, the hardware writes a small snapshot of the interrupted code onto the stack, with no software at all. A fault is an exception, so a crash gets a snapshot too.

What gets saved

On exception entry the core pushes eight 32-bit values. Memfault’s fault guide gives their order from the lowest address up: r0, r1, r2, r3, r12, LR, PC, xPSR. This is the exception stack frame. It is 32 bytes. The first four are the argument and scratch registers, so they often hold the arguments of the function that failed. LR is the link register: where the function would return to. PC is the program counter, the address of the instruction the core was about to execute. xPSR holds the flags; its bit 9 tells you if the core added 4 bytes of padding to keep the stack 8-byte aligned.

The PC in this frame is the clue you came for. For many faults it points straight at the instruction that went wrong. Chapter 5 turns that number into a function name.

If your chip has a floating-point unit and the code used it, the core saves more: the context-switching guide in the same blog says an extended frame adds 17 registers (68 bytes), and with lazy stacking enabled the hardware reserves the space but writes it only if a floating-point instruction runs inside the handler. The first eight words stay in the same place either way.

Two stacks, one choice

Here is the trap. A Cortex-M chip can have two stack pointers: the MSP, the main stack pointer used by interrupts (and by simple programs), and the PSP, the process stack pointer that an RTOS gives to each task. The frame is pushed on whichever stack was active when the fault happened. If your handler reads the wrong one, it reads a perfectly valid frame from some other moment in time.

The core tells you which stack to use in a special value placed in LR on entry, called EXC_RETURN. The values are: 0xFFFFFFF1 (back to handler mode, MSP), 0xFFFFFFF9 (thread mode, MSP), 0xFFFFFFFD (thread mode, PSP), and for a frame with floating-point state, 0xFFFFFFE1, E9 and ED. Bit 2 chooses the stack: 0 means MSP, 1 means PSP. Check 0xFFFFFFFD in binary: it ends in 1101, so bit 2 is 1 and the frame is on the PSP.

ctypedef struct { uint32_t r0, r1, r2, r3, r12, lr, pc, xpsr; } Frame;

/* naked: no prologue, so the stack is exactly as the core left it */
__attribute__((naked)) void HardFault_Handler(void) {
    __asm volatile(
        "tst lr, #4      \n"   /* test bit 2 of EXC_RETURN        */
        "ite eq         \n"
        "mrseq r0, msp  \n"   /* bit 2 = 0: frame is on the MSP   */
        "mrsne r0, psp  \n"   /* bit 2 = 1: frame is on the PSP   */
        "b fault_c      \n"   /* r0 = &frame is the first argument */
    );
}
void fault_c(Frame *f) {
    /* read-only evidence: save f->pc and CFSR, then log or reboot */
}

The five assembly lines are the pattern from the Memfault post: test bit 2 of LR, pick MSP or PSP, and pass the stack address to a C function as its first argument. The C function sees a normal pointer to a struct and can read f->pc.

Pick the stack the frame is on

Each column is eight words from one stack. The warm outline marks the stack that bit 2 of EXC_RETURN selects. Choose the EXC_RETURN value, then choose which stack your handler reads.

Illustrative addresses and values. The stale frame on the other stack stands for an earlier interrupt. The frame layout and the EXC_RETURN table are from the Memfault Interrupt posts on faults and context switching.

Try the naive handlers. A bare-metal program with no RTOS runs everything on MSP, so “always MSP” works there and seems fine. The day you add an RTOS, tasks run on PSP and the same handler starts reporting the wrong place. The symptom is a crash report that points at innocent code. The measurement is to print LR in the handler and check bit 2. The fix is to test the bit, as in the code above.

One more clue sits in this frame. If the stacked PC looks like 0xE0000000, the core was told to run from the system address range, which is not code. Memfault’s example reads the culprit from the stacked LR instead: it holds the return point in the caller. Always read both.

On real hardware. On a Nucleo, call a function through a null pointer on purpose. In GDB run info registers lr and read bit 2. Then x/8wx $sp or x/8wx $psp and find the PC word, the seventh value.
In a fault handler LR holds 0xFFFFFFFD. Where is the exception frame?

Chapter 4

The Fault Registers: Why It Died

Read the CFSR as a checklist of 19 named mistakes, and know when its address and its saved PC can be trusted

The frame told you where the core was. Now you want to know what kind of mistake it made. A wild pointer, a divide by zero, a jump into data and a stack that grew past its floor all end in the same HardFault, and each needs a different fix. The chip keeps a record of which one happened.

One 32-bit word, three small registers

The CFSR, the Configurable Fault Status Register at address 0xE000ED28, is really three byte-sized registers glued together. The low byte is MMFSR (memory management faults, bits 7:0). The next byte is BFSR (bus faults, bits 15:8). The top half is UFSR (usage faults, bits 31:16). Each bit means one specific mistake. A bit stays set until you write a 1 to it or the system resets, so the register shows the history since the last clear.

Two more registers carry addresses. MMFAR (0xE000ED34) holds the address a memory-protection fault touched. BFAR (0xE000ED38) holds the address a bus fault touched. Each is meaningful only when its valid bit is set: MMARVALID in the MMFSR, BFARVALID in the BFSR. Read the valid bit first, always. A stale address from last week looks exactly like a fresh one.

Why you see HardFault and not the finer fault

The three finer faults (MemManage, BusFault, UsageFault) are configurable: you can enable a dedicated handler for each in the system handler control register. By default none is enabled, so the core escalates every one of them to the HardFault. The HFSR register (0xE000ED2C) then has the FORCED bit set: it means “a configurable fault was forced up to HardFault”. It also has VECTTBL, a bad read of the vector table, and DEBUGEVT. So the habit is: halt in HardFault, read HFSR, and if FORCED is set, read CFSR for the real cause.

The bits worth knowing

BitNamePlain meaning, and what to look at
0IACCVIOLRan an instruction from a place that may not run code. Look at the stacked LR.
1DACCVIOLThe memory protection unit refused a data access. MMFAR if MMARVALID.
8IBUSERRBus error while fetching an instruction.
9PRECISERRA data bus error that points at one instruction. The stacked PC is exact. BFAR if BFARVALID.
10IMPRECISERRA bus error found late. The stacked PC is only nearby.
11, 12UNSTKERR, STKERRThe bus failed while taking the frame off, or putting it on, the stack. Suspect stack overflow.
15BFARVALIDBFAR holds a good address.
16UNDEFINSTRThe core met an instruction it cannot run, often after jumping into data.
17INVSTATEA jump to an address with bit 0 clear. Cortex-M runs only Thumb code.
19NOCPUsed a coprocessor that is off, usually the FPU. Check CPACR.
24, 25UNALIGNED, DIVBYZEROTrapped only if CCR bit 3 (UNALIGN_TRP) or bit 4 (DIV_0_TRP) is on.

The names are the ones Memfault’s post lists; the bit positions are the standard Arm v7-M layout. Memfault also gives the worked values. CFSR = 0x1 (IACCVIOL) came with a stacked PC of 0xE0000000. CFSR = 0x8200 came with BFAR = 0x0BADCAFE and PC 0x13A, and GDB’s info line *0x13a named line 123 of main.c. CFSR = 0x400 was an imprecise fault. CFSR = 0x1000 came with a frame pointer of 0x1FFFFFE0, below the start of RAM at 0x20000000.

Decode 0x8200 yourself. In binary it is 1000 0010 0000 0000. The set bits are bit 15 and bit 9. Bit 9 is PRECISERR and bit 15 is BFARVALID. Together they say: a data access hit a bad address, the PC is exact, and BFAR is good. Try more in the decoder below by tapping bits.

Decode a CFSR

Tap a bit to flip it, or press a preset. Set bits turn red and show their names. The read-out gives the diagnosis and tells you what you can trust.

The presets are the CFSR values in Memfault’s HardFault post, plus 0x02000000 for a divide by zero. The diagnosis text is a simple rule set written for this lesson, not a complete decoder.

When the PC lies

A precise fault is reported by the instruction that caused it, so the stacked PC points at it. An imprecise fault arrives later. Stores are the usual cause: the core hands a write to a write buffer and moves on, and the bus error returns after several more instructions have run. Memfault’s example shows a stacked PC in the general area of a call, not on the bad store. On Cortex-M3 and M4 you can set bit 1 (DISDEFWBUF) of ACTLR at 0xE000E008 to make stores wait. The same post says the PC then moved to the exact store, at a speed cost. On the Cortex-M7 the post says no such switch exists.

The symptom is a crash report that points at innocent code. The measurement is IMPRECISERR in the CFSR. The fix, while debugging, is DISDEFWBUF, and a careful look at the stores that came just before the stacked PC.

On real hardware. On a Nucleo, write through a pointer to 0x0BADCAFE (or any unmapped address). Halt in the handler and read CFSR and BFAR with x/wx 0xE000ED28 and x/wx 0xE000ED38. Then repeat after setting DISDEFWBUF and compare the stacked PC.
CFSR reads 0x8200. What do you know?

Chapter 5

From Address to Line: Symbolising a Crash

Turn a bare number like 0x08001A3A into a function, an offset and a source line, with the map or with addr2line

A customer sends you a crash report. It says: “PC = 0x08001A3A, CFSR = 0x8200”. You have no board and no debugger. All you have is a number. Is that enough to find the bug? Yes, if you kept one file from the build.

Why numbers can name code

When the linker builds your firmware it places every function at a fixed address in flash. Flash on an STM32F4 starts at 0x08000000. The linker writes down where it put each function and how big it is. That list is the symbol table inside the ELF file, and a human-readable copy is the map file (the toolchain lesson covers it in depth). Finding the function for an address is a lookup: take the function with the highest start address that is not above your number, and check that your number falls inside its size.

Take the lookup by hand. Say the sorted symbols include parse_packet starting at 0x08001A1C with size 0x5A, and the next one, crc16, starting at 0x08001A78. Is 0x08001A3A inside? Subtract: 0x08001A3A − 0x08001A1C = 0x1E, which is 30 bytes in. That is less than 0x5A, so yes: parse_packet + 0x1E. The offset also tells you roughly which instruction: Thumb instructions are 2 or 4 bytes, so offset 30 is around the tenth or fifteenth instruction.

Three tools that do the same lookup

shell# 1. keep the map: ask the linker to write it (add to LDFLAGS)
-Wl,-Map=build/fw.map  -Wl,--build-id

# 2. a sorted symbol list: the last start address at or below the PC wins
arm-none-eabi-nm -n --print-size build/fw.elf

# 3. one command: address in, function and file:line out (needs -g)
arm-none-eabi-addr2line -e build/fw.elf -f -p -C -i 0x08001A3A

# 4. or inside gdb, the form Memfault uses
(gdb) info line *0x08001A3A
(gdb) list *0x08001A3A

-f prints the function name, -p prints it on one line, -C undoes C++ name mangling and -i also shows functions that the compiler inlined at that address. Line numbers need debug information, so build with -g. It lives in the ELF on your disk and never needs to reach the chip.

The Thumb bit

One small detail catches everybody once. On a Cortex-M chip every instruction address is even, but a saved return address such as LR carries an extra 1 in bit 0 to say “stay in Thumb state”. So the LR in our crash frame, 0x080018C9, really means 0x080018C8. Clear bit 0 before the lookup. The stacked PC, in contrast, is already the true address. A jump to an address with bit 0 clear is what the INVSTATE bit of Chapter 4 reports.

Look up an address

The bar is the program in flash, one block per function. The list is the sorted map. Drag the address, or press a preset from the crashes. Rows whose start is at or below the address get a tick; the last tick is the answer.

0x08001A3A

Invented map for an invented image on a part with flash at 0x08000000. Sizes are shown to scale; the real tools do the same lookup on thousands of symbols with a binary search.

Drag into a gap: the address falls after a function’s end but before the next start. Then the tool should say “no function”. That can mean padding, a table of constants or a jump into data, so it is a clue by itself.

The core of a symbolizer

A fleet tool does exactly this lookup at scale. The core fits in a few lines of Python.

pythonimport bisect

# syms: [(start, size, name), ...] sorted by start; from arm-none-eabi-nm -n --print-size
def symbolize(syms, addr):
    addr &= ~1                                  # clear the Thumb bit
    i = bisect.bisect_right([s[0] for s in syms], addr) - 1   # last start <= addr
    if i < 0: return None
    start, size, name = syms[i]
    return (name, addr - start) if addr < start + size else None

The file you must keep

The lookup works only if the ELF matches the exact build that crashed. Rebuild with one changed line and every address after it moves. The symptom is a report that points at a function that cannot possibly fail. The measurement is the build ID: the linker flag --build-id stamps a unique value into the ELF, and you can print it with readelf -n. Log the same value from the device at boot. The fix is to archive the ELF of every release, named by its build ID.

Optimisation blurs the picture too. With -O2 the compiler merges and reorders code, so the line may belong to an inlined helper and the offset may jump around. That is why -i helps, and why a crash at -O0 may not reproduce at -O2.

On real hardware. On a Nucleo, trigger the null-pointer crash, then compute the lookup three ways for the stacked PC: by hand from nm -n, with addr2line, and with GDB’s info line. All three must agree. Then change one line in main without flashing and see the answers drift.
A saved LR is 0x080018C9. Which address do you look up in the map?

Chapter 6

Printing Without Stopping: RTT Against a Serial Port

Send log lines out of a running chip at a cost of about one microsecond, and size the buffer that makes it work

A halted chip can tell you a lot, but a running chip tells you more. A motor controller, a radio stack or an audio loop cannot be paused to read its state. You want a stream of short messages while it runs: “sensor read 412”, “state: connecting”, “queue depth 7”. How do those lines leave the chip?

Three ways to print, and what each one costs

The oldest is a UART: the chip’s serial port. You wire two pins to a USB adapter and call printf. Chapter 0 gave the price. At 115200 baud, with 8 data bits, a start bit and a stop bit, each character takes 10 bit times. So the port moves at most 115200 / 10 = 11,520 characters per second. An 80 character line occupies the port for 6.94 ms.

The second is semihosting. The C library runs a special bkpt 0xAB instruction. The debugger sees it, halts the core, reads the text from target memory, prints it on your laptop and resumes. It needs no pin, but every call halts the core, and with no debugger attached the program gets stuck on that instruction. Forum reports of “debug stuck at BKPT 0xAB” are common. It is fine on the bench for a quick message, and wrong for anything that keeps time.

The third is RTT, SEGGER’s Real Time Transfer. It uses the debug connection you already have from Chapter 1, and no extra pin. It was built so that the target never waits for the probe.

How RTT works: a ring buffer in RAM

Your program owns a block of RAM called the RTT control block. It starts with an ID that the probe can find by scanning RAM, and it describes one or more channels. An up channel carries data from the chip to the host. A down channel carries keystrokes back. Each channel is a ring buffer: a fixed array of bytes with two numbers, a write pointer and a read pointer. Think of a conveyor belt in a loop. The chip puts items on at the write pointer. The probe takes them off at the read pointer. When the two pointers match, the buffer is empty.

Your printf becomes a memcpy into that array plus an update of the write pointer. SEGGER states that an average line can be output in a microsecond or less, basically the time of one memcpy. In the background, the probe reads the buffer over SWD, as it read RAM in Chapter 1, and advances the read pointer. The CPU never waits for the wire. Channel 0 is normally the terminal; channel 1 is commonly used for logging, for example performance data.

The footprint is small: about 500 bytes of code, 24 bytes of RAM for the block, and 24 bytes plus the buffer size for each channel. The throughput can be high: SEGGER quotes up to 2 MB/s with a 512 byte target buffer and a fast interface, and 0.5 MB/s with a regular J-Link.

What happens when the buffer is full

A ring buffer has a limit. If the chip writes faster than the probe reads, the belt fills. RTT then offers two modes. In non-blocking mode, which SEGGER states is the default, bytes that do not fit are thrown away and the program keeps its timing. In blocking mode the program waits until space appears: nothing is lost, but the loop stalls. Non-blocking also means the firmware keeps running when no debugger is attached at all, which is why RTT can stay in a production build.

How big must the buffer be? Enough for everything the chip writes between two probe reads. SEGGER publishes a table, measured with a J-Link Pro V7 at 50 MHz SWD on a 180 MHz NXP part. At 10,000 bytes per second it asks for 3 bytes when the probe polls at 10 kHz and 11 bytes at 1 kHz. At 1,000,000 bytes per second it asks for 301 and 1,001 bytes. The rule of thumb: bytes per second divided by polls per second, plus margin for bursts.

Size the RTT buffer

The warm line is how full the ring buffer is over 100 ms. The red line is the buffer size. When the fill touches it, bytes are lost (or the program stalls). Change the log rate, the buffer and how often the probe reads.

40 kB/s
512 B

Illustrative model: the chip writes in random bursts with the chosen average rate; the probe empties the whole buffer at each poll. The poll rates and the rule of thumb follow SEGGER’s buffer table; the UART limit is exact arithmetic for 115200 baud, 8N1.

Try the default: 40 kB/s into a 512 byte buffer polled at 1 kHz. The chip adds about 40 bytes per millisecond, bursts push it higher, and the probe clears it every millisecond. The fill stays far below the red line. Now drag the poll to 100 Hz. Each poll interval now brings about 400 bytes, which nearly fills the 512. Raise the rate to 60 kB/s and bytes are lost. The symptom is a log with holes in it. The measurement is the peak fill. The fix is a bigger buffer, a faster poll, or fewer bytes per message.

That last fix is the best one. Log numbers, not sentences: a binary log of an event ID and two values is 6 bytes instead of 60.

On real hardware. On an nRF52840 DK (J-Link on board) or a Nucleo with a J-Link, add SEGGER’s RTT files to a project, write one line per loop pass, and toggle a pin before and after the write. Measure the pin high time with a scope. Repeat with printf over a 115200 baud UART and compare.
An RTT log in non-blocking mode has gaps in it, while the loop timing is perfect. What is the most likely cause?

Chapter 7

Counting Cycles: The DWT and a Profile of a Loop

Time a piece of code to the clock cycle with a counter built into the core, and find where a loop spends its time

Your filter loop must finish every 100 microseconds, because the sensor delivers a new sample at 10 kHz. Is it fast enough? You could toggle a pin and look with a scope. You could print a timestamp, but Chapter 6 showed what printing costs. There is a better ruler, and it is already inside the chip.

A counter that ticks with the CPU

Cortex-M3, M4 and M7 cores include a block called the DWT, the Data Watchpoint and Trace unit. Among its parts is CYCCNT, a 32-bit register that counts up by one on every CPU clock cycle. It is free-running: nobody has to start a timer interrupt or service it. Read it before and after a piece of code, subtract, and the difference is the cost in cycles. (Cortex-M0 and M0+ do not have this counter; check the core in your part.)

Three registers switch it on, in this order: DEMCR at 0xE000EDFC, whose bit 24 (TRCENA) powers the debug and trace blocks; CYCCNT at 0xE0001004, which you reset to 0; and DWT_CTRL at 0xE0001000, whose bit 0 (CYCCNTENA) starts the count. The order matters. An ST community thread reports a counter that stayed dead without a debugger attached when DWT_CTRL was written before DEMCR, and swapping the writes fixed it. Also, SEGGER notes a J-Link may clear the debug enable bits, including TRCENA, when a session closes.

c/* Cortex-M3/M4/M7 cycle counter: DEMCR first, then CYCCNT, then DWT_CTRL */
#define DEMCR      (*(volatile uint32_t *)0xE000EDFC)
#define DWT_CTRL   (*(volatile uint32_t *)0xE0001000)
#define DWT_CYCCNT (*(volatile uint32_t *)0xE0001004)

static inline void cyc_enable(void) {
    DEMCR     |= (1u << 24);   /* TRCENA: power the DWT */
    DWT_CYCCNT = 0;
    DWT_CTRL  |= 1u;             /* CYCCNTENA: start counting */
}
uint32_t start = DWT_CYCCNT;
fir_filter(buf, 256);
uint32_t cycles = DWT_CYCCNT - start;   /* unsigned subtraction survives one wrap */

Wrap-around and units

A 32-bit counter holds 232 = 4,294,967,296 values. At 168 MHz that is 25.6 seconds before it wraps to 0. A wrap does no harm to short measurements, because unsigned subtraction wraps the same way. Work an example: start = 0xFFFFFF00, then the counter wraps, stop = 0x00000100. In 32-bit arithmetic, 0x00000100 − 0xFFFFFF00 = 0x200, which is 512 cycles, the right answer. The rule: it works for any interval shorter than one full wrap.

To get time, divide by the clock: seconds = cycles / fCPU. Memfault’s profiling post times a Mandelbrot function at 38,298,322 cycles on a 168 MHz part and calls it about 23 ms. Divide it yourself: 38,298,322 / 168,000,000 = 0.228 s, about 228 ms. Writing the division out every time is cheap protection against a unit slip.

A few cautions. Reading the counter takes a few cycles itself, so time an empty region first and subtract it. Interrupts that fire inside your region add their cycles to your count. The first pass runs slow if the caches and flash prefetch are cold, so time the second pass too.

Where does the time go? Sampling the PC

Timing one function works when you already know the suspect. To find the suspect, the DWT can sample the program counter. It watches a chosen bit of the cycle counter and, every time that bit toggles enough times, it emits the current PC through the trace pins (Chapter 8). In Memfault’s setup, CYCTAP (DWT_CTRL bit 9) picks bit 10 of the counter, POSTPRESET (bits 4:1) is 3, and PCSAMPLEENA (bit 12) turns it on. One sample then comes every 3 × 1024 = 3,072 cycles, about 54.7 kHz at 168 MHz. A host tool counts how often each address appears and looks each one up in the map, as in Chapter 5. A function that owns 60 percent of the samples owns about 60 percent of the time.

This costs the program nothing, because the hardware does the sampling. The alternative, halting the core from GDB again and again, the post calls a poor man’s profiler: roughly one sample per 50 ms.

Profile the filter loop

The top bar is one pass of the loop, measured exactly with CYCCNT. The marker is the 100 µs budget. The bars below compare each function’s true share with the share a PC sampler estimates. Change the compiler setting, the clock and how many passes the sampler sees.

8

Illustrative cycle counts for a made-up loop (functions adc_read, fir_filter, pid_update, uart_flush); the 3,072-cycle sample period is the one in the Memfault profiling post. The sampler here is a model with a random start point, not a real DWT.

At -O0 the loop takes 24,000 cycles, which is 143 µs at 168 MHz. It misses its 100 µs budget. The profile points at fir_filter. At -O2 the filter shrinks to 5,100 cycles and the pass takes 12,100 cycles, 72 µs: on time. Drop the clock to 84 MHz and the same 12,100 cycles take 144 µs: late again. Cycles are the stable number. Time depends on the clock.

Notice what -O2 did not change: uart_flush still costs 5,400 cycles, because it waits for a slow port. After optimising the filter, that wait is now the biggest line of the profile. The symptom of a misleading profile is one that blames the wrong function. The measurement is to compare the sampled share against the exact cycles, as the device does. The fix is more samples before you act.

On real hardware. On an STM32 Nucleo-F446RE or a similar Cortex-M4 board, enable the counter, time a 256 sample FIR loop at -O0 and -O2, and print the cycles after the loop. Compute microseconds from the clock you set. Then change the system clock and check that cycles stay the same while time moves.
start = 0xFFFFFFF0 and stop = 0x00000010 are two CYCCNT reads around one function. What does stop - start give in 32-bit unsigned arithmetic?

Chapter 8

Recording the Run: Trace

Capture what the chip did in order, with timestamps, and read a missed deadline back as a timeline

The control loop glitches about once every few minutes. The output jumps for one cycle and recovers. A breakpoint is useless, because by the time you stop the chip the moment is gone. A log line cannot say why the loop was late, only that it was. What you need is a trace: a recording of events with timestamps, in order, that you can read after the glitch.

Three kinds of hardware trace

Cortex-M cores can stream out events with no help from your program. The first is ITM, the Instrumentation Trace Macrocell. It gives your code numbered stimulus ports: write a byte to port 0 and the byte leaves the chip as a trace packet. This is the trace-based printf: the NXP SDK notes that a _write function can forward each character with ITM_SendChar. The packets travel out of one pin called SWO (Serial Wire Output), which is why SWO needs only the two SWD pins plus one more.

The second is the DWT of Chapter 7. Besides counting cycles it can emit PC samples through the same ITM and SWO path. Memfault’s profiling post sets it up with OpenOCD commands: monitor tpiu config internal itm.fifo uart off 168000000 to route trace to a file, and monitor itm port 0 on to enable port 0. Host tools (itm-decode and pcsampl from itm-tools, in that post) turn the stream into text and a sample histogram. If the host reports too many Overflow packets, the SWO pin cannot carry the stream; the post advises raising POSTPRESET to take fewer samples.

The third is ETM, the Embedded Trace Macrocell, found on larger cores. Memfault’s guide describes it as a subsystem that streams out data and instruction accesses while the system runs. It records every instruction executed, so it can replay the last few thousand steps before a crash. It needs a wider trace port and a probe that supports it, so it is a bench tool for bigger chips, not a field tool.

Trace you build yourself

The most useful trace on a small chip is often a handful of lines of your own code. Each event is a small record: when it happened (the DWT cycle counter, from Chapter 7), what happened (an ID), and one piece of data. Write records into a ring buffer in RAM. Read the buffer out through RTT (Chapter 6), or save it in a coredump (Chapter 9).

ctypedef struct { uint32_t cyc; uint16_t id; uint16_t arg; } Ev;   /* 8 bytes per event */
enum { EV_ISR_ENTER = 1, EV_ISR_EXIT, EV_TASK_START, EV_TASK_END, EV_DEADLINE_MISS };

static Ev ring[256]; static volatile uint32_t head;

static inline void ev(uint16_t id, uint16_t arg) {
    uint32_t i = head++ & 255;                 /* wrap: newest overwrites oldest */
    ring[i] = (Ev){ DWT_CYCCNT, id, arg };       /* a few cycles, no waiting       */
}
/* in the handler: ev(EV_ISR_ENTER, IRQ_UART); ...work...; ev(EV_ISR_EXIT, IRQ_UART); */

Count the cost. Eight bytes per event. A system that makes 2,000 events per second produces 16,000 bytes per second, more than a 115200 baud UART can carry (11,520 B/s) and easy for RTT. The ring is 256 × 8 = 2,048 bytes of RAM and holds the last 256 events. When something goes wrong, you stop writing and read the last 256 events as a timeline. That is a flight recorder. SEGGER’s SystemView tool uses the same idea and sends its events over RTT.

Read the timeline

Five milliseconds of a model system. A 1 kHz control task must respond within 500 µs of its release (triangle). A UART interrupt arrives at 1.1 ms and 3.2 ms. Lengthen it, then try deferring its work.

400 µs

Illustrative model: fixed priorities, interrupts above the control task above the UART worker. The sensor interrupt runs 40 µs every 500 µs; the control task needs 200 µs. Each recorded switch is one 8 byte event, as in the code above.

With the default setting, the UART interrupt at 1.1 ms runs for 400 µs. The control task, released at 1.0 ms, has run only 100 µs when the interrupt starts, so it finishes late. The timeline shows the interrupt directly above the gap. A log line could never have shown this, because the late loop does not know why it was late. Turn on deferral: the interrupt only copies a byte into a queue (30 µs) and a low priority task does the rest after the control task is done. The deadlines hold.

Trace has its own failure modes. The ring can fill and overwrite the very event you wanted, so keep the newest events and stop writing at the fault. The cycle counter wraps after 25.6 seconds at 168 MHz, so store a wrap count or a coarse time as well. On some parts the counter may stop while the core sleeps, so timestamps jump across low-power periods; read your reference manual.

On real hardware. On a Nucleo with SWO wired (check the board’s solder bridge for the SWO pin), enable ITM port 0 with the two OpenOCD commands above and send a character from a loop. For a no-extra-pin version, add the 8 byte ring buffer and print it from GDB with x/64wx ring after a pin toggle shows the glitch.
A control task misses its deadline once in a while. Why is a trace better than a log line here?

Chapter 9

Crashes in the Field: Coredumps

Save the evidence at the moment of the crash, carry it home, and debug a chip you will never touch

The sensor node on the fence post crashes at 3 a.m. There is no probe on it and nobody near it. The watchdog resets it and it carries on, with “boots: 42” on its counter. A week later you have 40 devices in 40 fields and a crash on one of them every few days. You cannot visit them all. What can the chip tell you after the fact?

What a coredump is

On a laptop, a crashing program leaves a core dump: a file with its memory and registers at the moment of death. You open it in a debugger and look around as if you had stopped the program yourself. The Cortex-M version works the same way, but the chip must write the file itself, with very little time, memory and trust in its own state. The tool CrashDebug describes the reason for it: GDB supports core dump debugging on other targets such as Linux, but not on Cortex-M.

Everything you learned in this lesson goes into the dump. The registers and the exception frame of Chapter 3. The fault registers of Chapter 4. A slice of the stack to rebuild the call chain. And the ELF on your disk from Chapter 5, which supplies all the names.

What CrashCatcher saves

CrashCatcher is an open-source library that does this for Cortex-M. Its dump has a small header, then the integer registers R0 to R12, SP, LR, PC, PSR, MSP, PSP and the exception PSR, then the floating-point registers if the chip has them, then any memory regions your code asks for, then the five fault status registers starting at 0xE000ED28. By our count the fixed part is about 116 bytes: a 4 byte header, a 4 byte flag word, 20 register words (80 bytes) and the 5 fault registers with an 8 byte region header (28 bytes). Flash is not saved. The host reads the code from the ELF.

The rest is your choice, and it is the real design problem. RAM is big and the place you keep the dump is small. You choose regions: the used part of each task stack, the globals, the heap bookkeeping, your event ring from Chapter 8. CrashCatcher’s own notes suggest limiting the dump to the currently used stack, using the SP value, which makes a smaller dump at the price of losing the globals.

Doing it safely

Remember the third crash in the hero: the stack overflow. The fault handler tried to run on a stack that was already gone. A fault inside a HardFault handler leaves the core locked up until a reset, with no dump at all. So CrashCatcher’s assembly handler first switches to its own dedicated stack, g_crashCatcherStack, so it works even if the crash came from stack corruption. Then it pushes the remaining registers and calls a C function.

Where does the dump go? Memfault’s talk on coredumps says it is typically saved in noinit RAM, or written straight to external flash with a very minimal driver. Noinit RAM is a section that start-up code does not clear, so its bytes survive a software reset. The common pattern has two phases. In the handler, do the least: copy registers and the stack top into noinit RAM, set a magic number, and reset. On the next boot, in a healthy chip, see the magic, move the dump to flash and later upload it. Noinit RAM does not survive a power loss, so a brownout may still erase the evidence.

ctypedef struct { uint32_t magic, build_id, regs[20], cfsr, hfsr, mmfar, bfar; uint8_t stack[512]; } Dump;
__attribute__((section(".noinit"))) static Dump g_dump;     /* survives a soft reset */

void fault_c(Frame *f) {                      /* phase 1: do the least, on a safe stack */
    g_dump.cfsr = *(volatile uint32_t *)0xE000ED28;
    g_dump.hfsr = *(volatile uint32_t *)0xE000ED2C;
    memcpy(g_dump.stack, f, sizeof g_dump.stack);
    g_dump.build_id = BUILD_ID;  g_dump.magic = 0xC0DEDEAD;
    NVIC_SystemReset();
}
void boot_check(void) {                       /* phase 2: a healthy chip ships it */
    if (g_dump.magic == 0xC0DEDEAD) { save_to_flash(&g_dump); g_dump.magic = 0; }
}

Reading it at home

On your laptop CrashDebug plays the part of OpenOCD. It acts as a remote debugging stub for GDB, but reads the dump instead of a chip. The command from its page:

shellarm-none-eabi-gdb main.elf -ex "set target-charset ASCII" \
    -ex "target remote | CrashDebug --elf main.elf --dump MainCrashDump.txt"
(gdb) bt            # the call chain at the crash, with names from the ELF
(gdb) info registers

Check the build ID first, as in Chapter 5, or the names will lie. Also remember that a dump of RAM may contain keys and user data. Decide what you are allowed to collect before you collect it.

Budget a coredump

Press a region to add it to the dump. The bar shows the bytes against the slot. Below it, the questions your dump can answer. Then set the speed of your uplink.

0.5 kB/s

Illustrative sizes for a made-up 128 KB RAM part. The fixed 116 bytes is our count of CrashCatcher’s registers and fault registers; every region adds an 8 byte header. Link speeds are examples, not a measured radio.

Start with only the fixed part and the used stack of the failing task: 116 bytes, an 8 byte header and 1,800 bytes of stack, near 1.9 KB. It answers where, why and who called it. It cannot tell you what a global flag held. Add the globals and you can. Add the heap and the dump no longer fits a 4 KB slot. That is the symptom of an over-ambitious dump: the write is cut short, or never finishes before the watchdog fires. The measurement is the byte count. The fix is to dump the smallest set that answers your top three questions, and keep the rest for a debugger.

On real hardware. On a Nucleo or an nRF52840 DK, add CrashCatcher to a project, crash on purpose with a null write, and save the hex dump over the UART. Run the CrashDebug command above on your laptop and confirm that bt shows the function that crashed, without the board attached.
Why does CrashCatcher switch to its own stack before it does anything else?

Chapter 10

Field Guide: Seeing Inside a Running Chip

Keep the numbers, the checklist and the code, and know where to go next

You started with a dark screen and a rebooting box. You now have a ladder of tools. Each one answers a different question and costs a different amount. This chapter puts the whole ladder on one page.

The one-paragraph summary

A debug probe reaches a running chip over SWD, two wires, through the debug port and the AHB-AP, which reads memory beside the CPU. GDB and OpenOCD let you halt the core, but halting is costly and breakpoints are few. When the core faults it saves an eight-word frame; the CFSR, HFSR, BFAR and MMFAR say what kind of mistake; the map or addr2line turns the saved PC into a function. To watch without stopping, use RTT, which costs about a microsecond, the DWT cycle counter for time, and trace for order. For chips you cannot touch, save a coredump and read it at home.

The numbers that matter

WhatNumberSource or note
SWD against JTAG pins2 (SWDIO, SWCLK) against at least 4, plus 1 optionalMemfault, debug interfaces post
One SWD transaction46 clocks: 8 request, 1 turnaround, 3 ACK, 33 data and parity, 1 turnaroundADIv5 framing; the total is our own sum
Hardware breakpoints and watchpoints6 and 4 in the OpenOCD exampleOpenOCD manual; your part reports its own
GDB to OpenOCDtarget extended-remote :3333OpenOCD manual
Exception frame8 words (32 bytes): r0, r1, r2, r3, r12, LR, PC, xPSR; the FPU adds 17 registers (68 bytes)Memfault, faults and context switching posts
EXC_RETURN bit 20 = MSP (0xFFFFFFF9), 1 = PSP (0xFFFFFFFD)Memfault
Fault registersCFSR 0xE000ED28, HFSR 0xE000ED2C, MMFAR 0xE000ED34, BFAR 0xE000ED38Memfault; bit layout is Arm v7-M
Worked CFSR values0x1, 0x8200, 0x400, 0x1000Memfault HardFault post
Serial port, 115200 baud, 8N111,520 B/s; an 80 character line takes 6.94 msArithmetic
RTT per lineabout 1 µs; up to 2 MB/s with a 512 B buffer; 0.5 MB/s with a regular J-LinkSEGGER RTT page
RTT memoryabout 500 B code; RAM 24 B plus (24 B + buffer) per channelSEGGER RTT page
RTT minimum buffer10,000 B/s: 3 B (10 kHz poll), 11 B (1 kHz). 1,000,000 B/s: 301 B, 1,001 BSEGGER table, J-Link Pro V7
Cycle counterDEMCR 0xE000EDFC bit 24; DWT_CTRL 0xE0001000 bit 0; CYCCNT 0xE0001004; wraps in 25.6 s at 168 MHzMemfault; community threads
PC sample period3 × 1,024 = 3,072 cycles, about 54.7 kHz at 168 MHzMemfault profiling post (it rounds to 50 kHz)
Profiling example38,298,322 cycles at 168 MHz = 228 msMemfault example; the post’s “23 ms” is a unit slip
CrashCatcher fixed dumpabout 116 bytes before any memory regionOur count from the CrashCatcher page

The checklist for a dead chip

  1. Halt in the fault handler. Read LR bit 2 to pick MSP or PSP.
  2. Read HFSR. If FORCED is set, read CFSR.
  3. Check BFARVALID and MMARVALID before you trust BFAR or MMFAR.
  4. Read the saved PC and LR from the frame. Clear bit 0 of LR.
  5. Look both up with addr2line on the ELF of that exact build.
  6. If IMPRECISERR is set, set DISDEFWBUF (M3, M4) and reproduce.
  7. If STKERR is set, measure the stack high-water mark.
  8. If the bug is about timing, stop halting. Use RTT, DWT cycles or a trace.
  9. If the board is in the field, ship a coredump with the build ID.

The core in a few lines

gdb# triage after a HardFault, halted in the handler
(gdb) printf "CFSR=%08x HFSR=%08x\n", *(unsigned *)0xE000ED28, *(unsigned *)0xE000ED2C
(gdb) printf "BFAR=%08x MMFAR=%08x\n", *(unsigned *)0xE000ED38, *(unsigned *)0xE000ED34
(gdb) info registers lr           # bit 2 of EXC_RETURN picks the stack
(gdb) x/8wx $psp                  # or $msp: r0 r1 r2 r3 r12 lr pc xpsr
(gdb) info line *0x08001A3A       # the saved pc, in source terms

Where this sits

This lesson is the debugging layer of the firmware course. It leans on stack, heap and the MPU for the stack overflow case, on interrupts and DMA for fault decoding and interrupt design, and on the toolchain and map file for the ELF. It hands off to bench and root cause, where the scope and the logic analyser join the debugger, and to testing firmware, where a crash becomes a regression test. The coredump pattern pairs with bootloaders and OTA, since a build ID decides which ELF reads a dump.

Keep going

Sources and credit

This lesson has no course slides. We built it from public primary sources and checked every number against them: the Memfault Interrupt posts How to debug a HardFault, Profiling firmware on Cortex-M, A deep dive into Arm Cortex-M debug interfaces and Arm Cortex-M RTOS context switching; the SEGGER Real Time Transfer page; the OpenOCD manual chapter GDB and OpenOCD; the open-source CrashCatcher and CrashDebug repositories; and the Memfault webinar slides on coredumps. The SWD frame layout follows the Arm Debug Interface framing as described in the Zephyr and ST reference texts. Fault bit positions follow the Arm v7-M layout. Thanks to the Memfault authors and to SEGGER for writing this knowledge down in the open. Addresses, functions and loop cycle counts in the devices are invented for teaching and labelled as such.

The takeaway. You cannot look inside a chip without touching it, so pick the tool whose cost is small next to the thing you study: a halt for state, RTT for words, the cycle counter for time, a trace for order, and a coredump for the places you cannot go.
A deployed device crashes once a week with no probe attached. Which set of choices follows this lesson?

Now press Present or Teach and explain one crash out loud, from memory: where the frame is, what the CFSR said, how the map named the function, and what you would turn on so the next crash costs you one command. Then go back to the replay at the top, pick the stack overflow, and explain why that one has no PC to look up.

Seeing Inside a Running Chip
Back to the course · Interrupt: HardFaults · SEGGER RTT