Evidence-Driven Debugging for C and C++ Firmware and Tools

A practical debugging workflow for C and C++ firmware, drivers, Linux utilities, and test tools: capture failures, replay inputs, instrument boundaries, protect timing, and verify fixes.

Advertisement

Imagine a board that looked fine on the bench and then fails a few minutes into normal operation, after several hundred UART or CAN messages have already gone through. No line of code is obviously wrong. Your first reflex is to open the editor and change the part you suspect. This is where many debugging sessions go wrong, because the edit changes the timing, the memory layout or the exact sequence that triggered the bug, and afterwards you do not know whether you fixed the problem or only moved it. The same thing happens when a serial parser rejects one frame out of a long capture, when a Linux tool fails for one input file, or when a C++ lifetime bug shows up only with optimization switched on.

This article describes the order of work that I use in such cases: collect evidence first, narrow the fault down to one layer, and change code last. The examples are C and C++ for firmware and for host tools.

Capture the exact failure before editing code

While a failure is still vague, your first job is to describe it so that another engineer could reproduce it. For firmware, write down the board revision, the firmware build, the power condition, the communication sequence, the last reset reason and the state you observed. For a host tool, write down the command line, the input file, the operating system, the compiler flags and the last log lines. It takes five minutes, and it stops the symptom from changing its description every time somebody talks about it.

A captured symptom also tells you when you are finished. Say the original failure was a CRC error counter that went up after a USB reconnect. A cleaner parser or a longer timeout does not close this bug. You have to run the same reconnect sequence again, and the counters or the trace have to show that the path that failed before now works. The diagram below shows the workflow that the rest of this article follows.

Evidence Driven Debugging Workflow Each step should narrow the fault domain and leave a checkable result behind. Capture exact symptom Reproduce same input Instrument one boundary Isolate cause or layer Verify original failure is gone
A useful investigation loop captures the symptom, reproduces the input, instruments one boundary, isolates the failing layer, and verifies against the original failure.

Freeze the input that triggers the bug

A debugger is much more useful when the input stays the same. If your parser fails on one packet, keep that packet. If a production tester fails after a certain button sequence, save the sequence. If a string parser fails for one input, make a small replay case from it. Otherwise you try to understand a failure while the stimulus changes under you. Most tools can record the input for you: a logic analyzer exports the bytes, candump -l writes CAN traffic to a file, and Wireshark saves a TCP session.

The next snippet stores a failing frame as an array of bytes. The first two bytes use the protocol constants for the start byte and for the command under test, so that somebody who reads the test later can see whether it is about framing, command decoding, length handling or the checksum, without decoding raw numbers.

The stored packet does not tell you where the defect is. It gives you and your team something fixed that can be replayed after every parser change, after a compiler update, or during a discussion about the bug.

Build a timeline from cheap trace records

Some failures are about order, and you can look at the final value for a long time without finding them, because the value is not wrong. Imagine a DMA callback that fires before the buffer has changed its owner, a timeout that expires at the moment the retry starts, or a worker thread that posts its result after the receiving object is already destroyed. In all three cases you need to know which event came first.

A short trace records enough to answer that question. In firmware it has to be cheap enough to run close to the failure without moving it. On a host tool you can afford richer logs or timestamps from a test harness, but the goal is the same: a short ordered list of events, which is more useful than a large unstructured log.

You read the trace with the debugger. Stop at a breakpoint in the fault handler or at the place where the error is detected, and print trace_entries in GDB shows the last 32 events with their times. A small ring has one clear limit: old entries are overwritten. That is fine when the failure happens shortly after its trigger. For faults that take hours to appear, use a larger buffer or stop recording when a fault flag is set, so that the interesting entries survive.

The example also depends on the execution context. volatile stops the compiler from caching the write index, but it does not make the update of the index atomic. If an interrupt handler and a task can both write trace entries, let only one of them write, disable interrupts around the index update, or use an atomic operation that your target supports. On Cortex-M parts with the right debug hardware, ITM/SWO or ETM trace through the debug probe can give better timing data than more software trace records.

Instrument the boundary where the state changes

Every time data changes its form, the kind of possible fault changes too. Bytes become frames, frames become commands, commands change a state, and the state produces outputs. Linux utilities and Qt tools have the same structure: files become records, records become model objects, and model objects drive a display or a report. If you put your counters and trace points at these crossings, you learn much more than from print statements in every function along the call path.

It helps to draw a map of these crossings before you add instrumentation. The blocks differ from project to project, but the useful counters are almost always at the places where the owner of the data, the timing, the format or the level of trust changes.

Instrument the Boundary, Not the Whole System Most useful counters sit where ownership, format, timing, or trust changes. Input packet, file, IRQ Driver bytes, DMA, fd Parser frames, CRC State mode, owner Output UI, motor, log Transport counters overrun, timeout, bytes Format counters short, sync, CRC State counters invalid transition
Useful counters usually live where data changes form or ownership, because that is where the next debugging decision becomes clearer.

Change one condition at a time

Imagine you increase a timeout, add a delay and enlarge a buffer in the same test run, and the symptom disappears. You still do not know which of the three changes mattered, or whether the combination only hides the failure. When several experiments are mixed, you lose the connection between cause and effect.

A temporary compile-time switch lets you test one theory without mixing it with other edits. It should look temporary, and after the experiment you either remove it or turn it into a real configuration option with a reason. In the snippet only the sensor timeout changes, and the production value stays visible next to it.

Testing one condition at a time feels slow when everybody has three ideas they want to try at once, but each result then means something. If the failure appeared between two known builds, git bisect does the same thing for you automatically: it tests one commit at a time until the change that introduced the failure is found.

Use one counter for each kind of failure

One error counter is rarely enough in firmware or protocol code. A frame that is too short, a wrong start byte, a bad CRC and a rejection by the application all look like “receive failed” from outside, but they have different causes. If you add them into one number, you can no longer see in which layer the first thing went wrong.

In the example, 0xA5u is the sync byte of the protocol. The check uses the constant FRAME_START_BYTE from the earlier snippet, so the failure path contains no bare number.

Do not let the counters grow into a second interface that has to be maintained. Start with the crossings that decide your next debugging step: transport, framing, validation, state transition and rejection by the application.

Make invalid states report themselves

C and C++ systems often fail long after the first invalid state appeared. Suppose a state machine accepts a transition that it should reject, or a driver accepts a command although the shutdown has already started. If the code accepts such a state without any record, the symptom you finally see can look unrelated to the cause.

The state machine below has only a few legal transitions. The helper counts every unexpected one, so the state cannot break its rules without leaving a trace.

In safety-related or production firmware, an invalid transition may need more than a counter: a fault state, a diagnostic record or a controlled reset. During bring-up a counter is often enough, because it shows that the state model was violated before the visible failure happened.

The counter is only diagnostic, but it has to follow the same concurrency rules as all other shared data. If all transition requests go through one control task, a normal counter is enough. If requests can come from an interrupt handler, from several tasks or from several cores, the counter needs an atomic increment or a short critical section. Without it, the diagnostic code can lose counts while it tries to report the bug.

Keep logging out of timing-critical paths

More logging has a price in embedded systems. A log statement changes the timing, uses stack, can block on a UART and can allocate memory. At 115200 baud one character takes about 87 µs, so a blocking print of a 30-character line holds the code for 2.6 ms. That is enough to hide the race condition you are looking for, or to create a new one. On a desktop the costs are different, but a log line can still move a concurrency bug, because it changes the scheduling of the threads.

For timing-sensitive code, decide first which information must be recorded in the fast path and which work can wait. Event counters, compact trace records, a GPIO pin that you toggle and watch on an oscilloscope, and status snapshots are all much cheaper than formatted text inside an interrupt handler, a control loop or a fast receive callback.

The counter example below uses two wrapper functions for a critical section. In a real project they save and restore the interrupt state, enter an RTOS critical section, or are replaced by an atomic operation. The reason is the same as before: volatile only makes the variable visible, and ++counter is still a read, an add and a write that an interrupt, another task or a second core can interrupt.

Keep Fast-Path Evidence Cheap Record compact facts near timing-sensitive code, then format or transmit them later. ISR or control loop increment counter store compact record Deferred context snapshot buffer format strings External evidence UART, file, GUI or logic analyzer Avoid blocking I/O, allocation, printf formatting, and unbounded loops in the path being measured.
Timing-sensitive code should record small facts first, then leave formatting, transport, and heavier analysis to a context that can afford it.

Such small records give you less context than a full log. Accept that at first, because the behavior of the system stays the same. When you know the suspicious crossing, add richer output in a slower task, in a replay on the host or in a test harness.

In host-side C++, std::atomic<unsigned> is the clearest way to write a shared debug counter. In C firmware you can use C11 atomics or compiler builtins such as __atomic_fetch_add, but check what your MCU, compiler and runtime make of them. On small MCUs a short critical section is often more predictable than the hope that the compiler produced a lock-free instruction.

Check lifetime and ownership before rewriting logic

In C++ a value can be logically right and still be invalid. Imagine a failure that changes when you switch the optimization level, add a log line or change an allocation. This behavior is typical for lifetime bugs: a view of a string that no longer exists, a reference to a temporary object, an iterator that was invalidated, a callback that lives longer than its owner, or a span that was kept after its buffer was freed. Check the lifetimes early in such a case, before you rewrite any logic.

The example uses a status string. Returning a view of a local string is wrong, because the string is destroyed when the function returns. Returning a view of static storage is safe here, because that storage exists for the whole program run.

Which fix is right depends on the interface. Static storage works for fixed text and is no solution for dynamic data. In the other cases the caller should own a std::string, or the function should write into a buffer that the caller provides, or the interface should say clearly who owns the data.

Sanitizer builds on the host find this class of bug quickly. AddressSanitizer (ASan) catches many use-after-free errors and stack lifetime errors, and UndefinedBehaviorSanitizer (UBSan) reports several kinds of undefined behavior. With GCC or Clang, compile and link with -fsanitize=address,undefined -g and run your tests. The sanitizers do not replace tests on the target and usually cannot run on bare-metal firmware, but for parser logic, protocol code, libraries and simulation builds that run on a PC they are very effective.

Use assertions for broken assumptions

Some checks are about assumptions of the design and have nothing to do with errors that can happen in normal operation. An assertion is right when a violation means that the surrounding code is wrong, and it is most useful in debug builds, test tools, simulation builds and during firmware bring-up. The question to ask is whether the system can recover. Bad input from outside should be handled. An internal condition that can never be false in correct code should stop loudly when it is false.

In the example, the capacity of the ring buffer must be a power of two, because the wrap uses a bit mask. The static assertion puts this requirement into the code, where the compiler checks it, and it no longer lives only in a design note. The runtime assert covers the second kind of assumption, one that exists only while the code runs: the index must already be wrapped when it reaches the store function.

The standard assert() disappears when NDEBUG is defined, which is the default of most release builds. On small targets, decide which assertions stay in production and what they do when they fire. Some products can stop in a fault state, some need a diagnostic record and a reset, and some must continue with reduced function. This decision should follow the risk of the system.

Reduce the failing path to one test

When the frozen input and the counters point to a small area, make a test from it. The test does not have to model the whole product. It only has to keep the properties that make the bug appear, so that you can check the fix again after the next edit.

The next test checks that a short frame is counted as short and is not counted as a wrong start byte. The difference matters because each counter points to a different layer of the receive path.

A small test does not replace the check on hardware. It removes one source of uncertainty before you go back to the board, the test fixture or the customer capture. For firmware the usual way is to replay the parser or the state logic on the host first, and then to run the original hardware sequence again with the changed code.

Verify the fix against the original symptom

A fix is finished when the original symptom is gone and your evidence shows that the intended path is now used. Cleaner code or a passing test nearby is not enough. Keep the original packet, the test sequence, the input file or the hardware setup until you have done this check.

The table sums up the habits from this article, together with the evidence each one produces. If a debugging step produces no new evidence, it is probably not bringing you closer to the cause.

Debugging habits that leave useful evidence behind.
Habit Evidence it creates Failure it prevents
Capture the exact symptom Known start and end condition Debugging a changing story
Freeze failing input Repeatable stimulus Chasing a moving packet, file, or state
Build a timeline Ordered events Confusing order bugs with value bugs
Instrument boundaries Layer-specific evidence Scattering logs without narrowing the fault
Change one condition Experiment with causality Lucky fixes with unknown mechanism
Count failure classes Transport, format, or state distinction One vague error counter
Use bounded instrumentation Timing-safe clues Measurement changing the failure
Check lifetime early Ownership and validity evidence Rewriting logic around a dangling object
Add a focused test Regression protection A fix that only works once

Practical takeaways

In C and C++ systems, most of the useful debugging work happens before the first code change: capture the failure, freeze the input, find the crossing where correct state becomes incorrect, and choose instrumentation that does not change the timing or the lifetimes you are measuring. When the cause is isolated, reduce it to a small test if you can, and then check the fix with the original symptom on the real target or the real input. In the first ten minutes this feels slower than guessing. It pays off as soon as the failure involves firmware timing, protocol layers, object lifetime or production hardware, where trial and error does not get you far.

Comments and corrections

Would you like to leave a comment, report a technical error, or flag an outdated detail? Use the form below.

Required fields are marked *. Comments are moderated. Email addresses are not published. Privacy Policy