The Zeno Book Zeno 0.1 zeno-lang.org

31 Firmware

Firmware is a program that runs on a board with no operating system under it: it starts when the power comes on and runs until it goes off. It is held to rules a desktop program is not, and often to a written coding standard such as MISRA C. zeno build --firmware writes C for that world. This chapter is about what it changes, how to put a real board under the program, and what it does not yet claim.

31.1 Errors as values

An ordinary build compiles try with C’s setjmp and longjmp: a raise jumps straight back to the try, out of however many functions are in between. That is cheap, and it is exactly what standards for safety-critical firmware forbid. MISRA C bans <setjmp.h> outright, because the jump skips what the functions in between still meant to do, can leave local variables with no defined value, and hides paths from the tools that measure stack depth and test coverage.

A firmware build carries errors as ordinary return values instead. The Zeno does not change:

speed.zeno

function parse_speed(text: str) -> int raises ValueError {
    let n = int(text)
    if n < 0 or n > 100 {
        raise ValueError(f"a speed is 0 to 100, and {n} is not")
    }
    return n
}

for text in ["40", "fast", "250"] {
    try {
        print("speed", parse_speed(text))
    } except ValueError as e {
        print("refused:", e.message)
    }
}
$ zeno build --firmware speed.zeno
Wrote speed.c
Built speed. Run it with ./speed
$ ./speed
speed 40
refused: cannot turn "fast" into an int
refused: a speed is 0 to 100, and 250 is not
$ grep setjmp speed.c | wc -l
0

It prints what zeno run prints, and there is no setjmp in the C (grep found 0 lines). Here is what parse_speed became:

$ zeno build --firmware speed.zeno > /dev/null
$ grep -A11 "^static bool z_parse_speed.*{$" speed.c
static bool z_parse_speed(const char *z2_text, int64_t *zeno_result) {
    int64_t t4;
    if (!zeno_parse_int(z2_text, 2, 13, &t4)) return false;
    int64_t z_n = t4;
    if ((z_n < 0) || (z_n > 100)) {
        zeno_note(zeno_error_new("ValueError", zeno_join(3, "a speed is 0 to 100, and ", zeno_str_int(z_n), " is not"), NULL), 4, 9);
        return false;
    }
    *zeno_result = z_n;
    return true;
}

Three things changed. The function returns true when it worked and false when it raised, and its answer goes out through one more parameter. A raise notes the error, with its line and column, and returns false. And a call to something that can raise, int(text) here, is followed at once by a test. Only the functions that say raises are compiled this way; the rest are plain C, with no tests after calls to them. That is why raises must be written in a build (When Things Go Wrong).

31.2 Faults

Zeno has two sorts of error that zeno run can catch:

  • errors the program raises itself: raise, and int or float of text;

  • errors the runtime finds: a division by zero, a position past the end, a key that is not there, an overflow, pop on an empty list.

A firmware build carries the first sort as values. The second sort is a fault: the program stops there, with the message zeno run gives for an uncaught error, and no except sees it. To carry a division by zero as a value, every function would have to be one that can fail, and nearly every line would need a test after it. The firmware answer is to test first:

if divisor != 0 {
    rate = total // divisor
}

The compiler does not leave this to be found when the board resets. A try that hopes to catch a fault is refused before anything is built:

divide.zeno

let readings = [4, 0]
for n in readings {
    try {
        print(100 // n)
    } except ZeroDivisionError {
        print("no reading")
    }
}
$ zeno build --firmware divide.zeno
error: nothing in this `try` can be caught. In a firmware build, an error the program raises itself (and `int` or `float` of text) travels as a value and can be caught. A division by zero, a bad index, a key that is not in a dict or an overflow stops the program. Test for it before it happens, or build without `--firmware`
 --> divide.zeno:3:5
  |
3 |     try {
  |     ^

A FileError is the exception to the exception: no check the program could make rules out a missing file, so it is always a value, and can always be caught.

The line between the two sorts is the line between what the program can check beforehand and what it cannot. A bad index can be ruled out by testing the length; a missing file cannot. Firmware held to a standard is expected to test, and the build makes the cases it did not test visible. (Decisions 4.1 and 5.5l.)

31.3 A real board underneath

The board module meets the hardware in four C functions (The Board). For a real board, write them in a header over the vendor’s library, and tell the C compiler where it is with -DZENO_BOARD:

$ zeno build --firmware --no-collector blink.zeno
$ cc -O2 -DZENO_BOARD='"my_board.h"' -o blink blink.c -lm

With ST’s HAL for an STM32, where the LED of a Nucleo board is on port A pin 5, the header would look like this. It is a sketch, and has not been run on hardware:

#define ZENO_PINS 16

static void zeno_board_write(int pin, bool level) {
    if (pin == ZENO_LED) pin = 5;
    HAL_GPIO_WritePin(GPIOA, (uint16_t)(1u << pin),
                      level ? GPIO_PIN_SET : GPIO_PIN_RESET);
}
static bool zeno_board_read(int pin) {
    if (pin == ZENO_LED) pin = 5;
    return HAL_GPIO_ReadPin(GPIOA, (uint16_t)(1u << pin)) == GPIO_PIN_SET;
}
static void zeno_board_sleep(double seconds) {
    HAL_Delay((uint32_t)(seconds * 1000.0));
}
static double zeno_board_now(void) { return (double)HAL_GetTick(); }

To the Zeno program the LED is always pin 13, and the board is free to wire that number to wherever its LED really is. The same flag works for an LLVM build, on the clang line.

A board whose clock moves only when the program sleeps makes a program that waits run in no time. That is how firmware is tested on a desk, and Zeno’s own tests do exactly that.

All of blink’s program, in a firmware build with no collector, is three lines of C:

while (true) {
    zeno_pin_toggle(ZENO_LED);
    zeno_sleep((500.0 / 1000.0));
}

A pin is a number, 500 ms has become seconds, and nothing in it takes memory or can raise.

31.5 What this does not claim

Removing setjmp removes one obstacle to MISRA, not all of them. The C that a firmware build writes in version 0.1 still uses variable argument lists in the runtime, calls printf and exit, and uses GCC and Clang built-ins for checked arithmetic. Taking memory from the heap, which MISRA also bans, is answered by --no-collector, in the next chapter. None of these is hidden, and each is a later piece of work. A function that can raise cannot yet be passed around as a value in a firmware build, because a function type does not say whether it raises.

zeno build --firmware carries errors the program raises as return values, tested after each call, with no setjmp. Errors the runtime finds are faults that stop the program, and a try that hopes to catch one is refused. A real board goes under the program as a header of four functions, named with -DZENO_BOARD.

  1. Build speed.zeno with and without --firmware, and compare the C of parse_speed in the two.

  2. Rewrite the divide.zeno example so that a firmware build accepts it.

  3. Write a board header of your own for the simulated board that prints HIGH and LOW, and build blink with it.