Try Embedded

Code review for embedded C

What to look for in firmware changes, how to comment, and what to leave to tools.

Review is the cheapest place to catch a firmware bug

A bug found in review costs a comment. The same bug found on a test rig costs a day, and found in the field it can cost a recall. Firmware review is also how a team spreads knowledge: whoever reviews the UART driver can maintain it next year. Most teams require at least one approving review before anything merges to main.

Making a change easy to review

As the author, you control most of the review's quality:

  • Keep it small. Reviewers find far fewer defects per line in a 1000-line change than in a 200-line one. Split refactoring from behaviour changes.
  • Review it yourself first, in the diff view, as if someone else wrote it.
  • Write a description: what changed, why, how you tested it (on which board, with which measurements), and anything you are unsure about.
  • Let tools go first. Formatting (clang-format), compiler warnings, static analysis and unit tests should run in CI before a human looks, so the review is about what tools cannot judge.

What to look for in embedded code

Generic review advice (naming, duplication, structure) still applies. These are the areas where firmware bugs actually come from:

AreaQuestions to ask
Shared dataIs anything written in an ISR and read in a task (or two tasks)? Is it volatile? Is every read-modify-write protected by a critical section or an atomic operation?
Interrupt handlersIs the ISR short? Does it call anything that blocks, allocates, or takes a mutex? Is the interrupt flag cleared correctly, and before or after the work as the hardware requires?
TimeAre timeouts computed with unsigned subtraction (now - start >= timeout) so they survive the tick counter wrapping? Can any loop wait forever on hardware?
IntegersCan a multiplication overflow before it is widened? Signed and unsigned mixed in a comparison? Shifts by the width of the type or more? Units clear (timeout_ms, temp_dC)?
BuffersIs every length that comes from outside (a packet, a file, a register) checked before it is used as an index or a copy size?
Error pathsIs every return value checked? Does every early return release what was acquired (locks, buffers, chip selects)? What does the device do after an error: retry, report, reset?
HardwareIs the register sequence what the reference manual and errata require? Is a peripheral's clock enabled first? Are read-to-clear registers read only once?
ResourcesStack depth of new call chains, RAM and flash cost, power (is the peripheral or its clock switched off again?)

Timing bugs are the classic case a reviewer catches and testing misses, because they need days of uptime to show:

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

/* Two ways to write "has the timeout expired?" with a 32-bit millisecond tick. */
static bool expired_wrong(uint32_t now, uint32_t start, uint32_t timeout) {
  return now > start + timeout;          /* start + timeout can wrap past zero */
}
static bool expired_right(uint32_t now, uint32_t start, uint32_t timeout) {
  return now - start >= timeout;         /* elapsed time, correct across the wrap */
}

int main(void) {
  /* 49.7 days after boot the tick is about to wrap. A 100 ms timeout starts 50 ms before it does. */
  uint32_t start = 0xFFFFFFFFu - 50u;
  for (uint32_t elapsed = 0; elapsed <= 150; elapsed += 50) {
    uint32_t now = start + elapsed;
    printf("after %3u ms: wrong says %s, right says %s\n", (unsigned)elapsed,
           expired_wrong(now, start, 100) ? "expired" : "waiting",
           expired_right(now, start, 100) ? "expired" : "waiting");
  }
  return 0;
}

The wrong version reports the timeout expired at once, and then, at exactly 100 ms, that it is still waiting. On a device that is a retry storm or a skipped safety wait, once every 49.7 days.

Writing comments people can act on

  • Say what and why: "This read of rx_count can be torn by the UART ISR; read it with interrupts masked" is useful. "Race condition?" is not.
  • Mark how much it matters: a blocking issue (a bug, a safety or security problem) versus a suggestion or a nit. Many teams prefix nits so the author can skip them.
  • Ask when you are not sure: "What happens here if the sensor never answers?" often finds more than a statement.
  • Review the code, not the person; praise good solutions too.

As the author, answer every comment, either with a change or a reason. Disagreements about design go to a short conversation, not an endless thread.

Pitfall: Approving a large change after skimming it is worse than no review, because everyone then believes it was checked. If you cannot review it properly, say so and ask for it to be split.

Interview question: What do you look for when you review an interrupt handler?

Answer: That it is short and bounded: no blocking calls, no waiting on hardware in a loop, no heap allocation, no mutexes, no printf. That it clears its interrupt source correctly so it does not re-enter forever. That data it shares with tasks is volatile and accessed atomically or under a critical section on the task side, and that it hands longer work to a task through a queue, semaphore or flag. Also its priority relative to other interrupts and RTOS limits, such as only calling FromISR functions at priorities the kernel allows.

Build it: fix what the code review found

This is step 2 of the module project. A colleague's pull request adds the vibration calculation: the RMS of each block of accelerometer samples, the number the alarms depend on. It works on their desk. Your review found four problems; the comments are below. Fix them all.

Lab: Address four review comments

The function computes the root-mean-square (RMS) of a block of signed samples in milli-g: sqrt(sum of squares / n), rounded down. Its contract: n from 0 to 4096, and an empty block (n == 0) returns 0.

The review comments:

  1. Line int32_t sum: a sample can be ±16000 mg, and its square is up to 256,000,000. Two of them already overflow 32 bits. Use a 64-bit unsigned sum.
  2. Line for (uint16_t i = n - 1; i >= 0; i--): i is unsigned, so i >= 0 is always true, and i wraps from 0 to 65535. Loop forwards.
  3. Line return isqrt(sum / n);: with n == 0 this divides by zero. Handle the empty block first.
  4. isqrt: for big values the guess squared overflows, and the loop condition skips the exact root. Make it correct for every 64-bit value up to `4096 16000 * 16000: return the largest r with r * r <= x`.*

The rest of the code is fine: keep its interface.

Going deeper

Interview question: What would you look for first when reviewing a change to a pacemaker's firmware?

Answer: Whether it matches the requirement and is the smallest change that does, then safety: integer overflow and timing in pacing calculations, every error path, shared data between interrupts and tasks, volatile access, and resource use. Check the tests cover the change and its boundaries, and that traceability is updated. In medical code, a reviewer's job is to find the hazard before a patient does.

Interview question: How large should a pull request be, and why does it matter?

Answer: Small enough to review properly in one sitting, typically a few hundred lines of real change at most. Studies of code review find that defect detection drops sharply as change size and review speed grow, because reviewers start skimming. Small changes also merge faster, conflict less, are easier to revert and make git bisect more precise. Large work can still be delivered in a series of small, independently reviewable steps, with refactoring separated from behaviour changes.

Interview question: A reviewer insists on a design change you disagree with. What do you do?

Answer: First make sure I understand the concern, by asking what problem they see. Then explain my reasoning with evidence, such as measurements, constraints or the requirement, rather than opinion. If we still disagree, a short call usually resolves it faster than comments, and if not, a tech lead or the team's agreed conventions decide. The goal is the best result for the product, so I change my mind if the argument is better, and record the decision so it is not reopened in every review.

Explain it: In your own words, explain what a reviewer should focus on in a firmware change, and what should be left to tools.

Answer: Tools should handle formatting, compiler warnings, static analysis findings and running the tests, automatically in CI before review. The human reviewer focuses on what tools cannot judge well: data shared between interrupts and tasks and whether it is protected, timing and timeouts that must survive counter wraps, lengths from outside the device used as indexes, error paths that leak resources or leave hardware in a bad state, register sequences against the reference manual, and whether the design fits the requirement and the rest of the system.