©Code by Samnoon
Blog
← All posts

c

Moving legacy C/C++ to new hardware without a rewrite

Find the seams, pin today's behavior with characterization tests, and put a thin interface between the code and the board.

4 min read

A new hardware revision is the perfect excuse for a rewrite. The old code is hard to read, the people who wrote it have moved on, and the new board is different enough that "we might as well start fresh" sounds reasonable in a meeting.

It usually isn't. Code that's been in the field for years encodes hundreds of small decisions about timing, retries and odd hardware behavior, and most of them aren't written down anywhere except in that code. A rewrite throws them all away and then rediscovers them, one bug report at a time.

What tends to work better is changing as little as possible, in a particular order.

1. Find every place the code touches hardware

Before changing anything, work out exactly where the code and the hardware meet. In older C and C++ it's rarely one place. Start with the obvious system calls:

grep -rnE '\b(open|ioctl|mmap|tcsetattr|cfsetispeed)\s*\(' src/ | grep -v test
grep -rn '/dev/' src/

Then look for hard-coded register addresses, hex constants that are suspiciously specific, and #ifdefs named after boards. Write the list down. It's always longer than anyone expects, and it's the map for everything that follows.

2. Pin down what the code does today

Michael Feathers calls these characterization tests: tests that don't check what the code should do, only what it does. Feed the existing code recorded inputs, save its outputs, and assert that later versions produce the same thing.

For code that talks to a device over a serial port, socat can create a pair of linked virtual serial ports, so the code under test talks to a script instead of a board:

socat -d -d pty,raw,echo=0,link=/tmp/ttyV0 pty,raw,echo=0,link=/tmp/ttyV1

The application opens /tmp/ttyV0 as if it were the real device. A test script on /tmp/ttyV1 replays recorded device traffic and records what the application sends back. Run that against the untouched code first and keep the result as your golden copy.

These tests will be ugly, and that's fine. Their only job is to fail when behavior changes, so you find out at your desk instead of in the field.

3. Put a seam between the code and the board

Now move every direct hardware call behind a single interface, without changing behavior. In C, a struct of function pointers does the job, the same pattern the Linux kernel uses for its drivers:

board.h
#include <stddef.h>
#include <sys/types.h>
 
struct board_ops {
    int     (*open)(void *ctx, const char *device);
    ssize_t (*read)(void *ctx, void *buf, size_t len, int timeout_ms);
    ssize_t (*write)(void *ctx, const void *buf, size_t len);
    int     (*reset)(void *ctx);
    void    (*close)(void *ctx);
};
 
struct board {
    const struct board_ops *ops;
    void *ctx;
};
 
extern const struct board_ops board_rev_a_ops;
extern const struct board_ops board_rev_b_ops;
extern const struct board_ops board_fake_ops;

The first implementation, board_rev_a_ops, is just the existing code moved behind the interface. Nothing else. Run the characterization tests: they should pass without a single change to the golden files. If they don't, the refactor changed behavior, and that's far easier to track down now than once the new board is in the picture.

In C++ the seam would be an abstract base class instead, but the idea doesn't change. One narrow interface, and the rest of the code has no idea which board it's talking to.

4. Add a fake, then the new board

With the seam in place, two more implementations become possible. A fake that lives entirely in memory makes unit tests fast and lets you simulate faults real hardware rarely gives you on demand: timeouts, short reads, garbage bytes. Then the new board's implementation goes in alongside the old one, chosen at startup:

const struct board_ops *board_ops_for(const char *revision)
{
    if (strcmp(revision, "B") == 0)
        return &board_rev_b_ops;
    if (strcmp(revision, "fake") == 0)
        return &board_fake_ops;
    return &board_rev_a_ops;
}

Keep both real implementations until the old hardware is actually retired. Being able to run the same build against either board is the quickest way to answer the question that comes up every week: is this a new bug, or an old one?

The bugs that turn up anyway

Even with all that, some problems only appear on the new hardware. These are the first places to look.

Framing assumptions. Old code often assumes one read() returns exactly one message, because on the old device it always did. A new interface that delivers bytes in different-sized chunks breaks that without any error. Read until you have the whole frame:

/* The old driver returned whole frames from one read(). The new link can split them anywhere. */
static int read_exact(struct board *b, unsigned char *buf, size_t len, int timeout_ms)
{
    size_t got = 0;
    while (got < len) {
        ssize_t n = b->ops->read(b->ctx, buf + got, len - got, timeout_ms);
        if (n <= 0)
            return -1;
        got += (size_t)n;
    }
    return 0;
}

Timing. A faster interface can expose race conditions the old one's slowness was hiding. A slower one breaks timeouts that somebody tuned by trial and error a decade ago and never wrote down.

Byte order and struct layout. If the new board brings a different CPU or compiler, any code that casts buffers to structs is suspect. There's more on why in the Q.931 decoder post.

References

  • Michael Feathers, Working Effectively with Legacy Code (Prentice Hall, 2004): the source of the terms "characterization test" and "seam".
  • Legacy Seam, Martin Fowler's bliki: a short, free introduction to seams.
  • Characterization test, Wikipedia.
  • socat manual: the pty address type and its raw, echo and link options.
  • Overview of the Linux Virtual File System, Linux kernel documentation: struct file_operations, the function-pointer table pattern.
  • read(2): a successful read() may return fewer bytes than requested.

#c #cpp #legacy-code