CocoIsBuggy A small flapping bug

Embedded Rust

Is Rust really appropriate in embedded environments?

The Rust Book is one of the best programming books I have ever read. It reads partially as a guide to rust, but also as an insight into the design of the language itself. It really does help you get into the heads of the programmers who conceived the language in the first place.

In some of its paragraphs you can tell from the sheer enthusiasm that the author has spent plenty of time tracking down memory-related bugs in other languages.

Running out of memory

Rust doesn’t really stop you from writing a program that allocates more memory than the device has, which will cause the program to panic. However, you aren’t more at risk of this happening than you would be with C/C++. The same code in both languages will allocate the same amount of memory to do the same things. Rust still mandates that you think about how much memory your data requires, and rust will never copy heap data silently. It’s actually really easy to reason about how much memory your program requires, and the management strategy is enforced by the borrow checker.

In theory, your program will never leak memory. The borrow checker is very mature, though obviously it could still happen if there is a bug in the checker itself.

Rust also has access to some language features that improve the ergonomics surrounding slices which help prevent needless copying of sequences.

Heap Fragmentation

Like in C and C++, if you have a long-running program and you are not careful with how you use the heap, your rust program may end up unable to allocate the necessary memory even if the space technically exists.

You can make various configurations to the allocator and even specify exactly what memory hardware you’d like the ESP32 to use, but by default the rust language has no compiler constructs that protect your heap from fragmentation.

The good news is that even though rust does not represent an advantage in this area, it’s also not really any worse than C/C++. I would also make the argument that since rust error handling is so good it makes it easier for devs to implement robust fallible allocation.

Depending on your application needs, you might also be using an RTOS like embassy, in which case there is an operating system that will perform some heap management for you without you even needing to think about it. It’s not zero-cost by any means, but my word if your objective is just to quickly write some piece of shit IOT sensor device this kind of thing bootstraps the exercise to a ridiculous extent. You really do just write the code, the compiler validates it, and off you go.

Here’s a neat article about TLS implementations for ESP/STM microcontrollers.

Sales Pitch

If we were to assume that Rust can be just as good - practically speaking - as C/C++ in embedded contexts, what would be the compelling reason to consider using it when C and C++ are battle tested?

The true answer to this is that there is no single concrete reason why C and C++ should not be used for new projects since they are both excellent languages that provide the core abstraction methods that any developer needs to write functional software. That said, if I were to give the main reason why rust is appealing it would be that rust is a very beautiful language with a compiler that will blow your fucking mind if you have become used to C/C++ toolchains

Syntax

The C syntax is often beautiful, it strongly resembles many languages to this day because it’s hard to improve on a good thing. Nevertheless, I want to point out a couple of mistakes that were made in its conception. Because we have identified these mistakes, we are able to design new languages with foreknowledge of these challenges.

Language Ambiguity

We’re deep into the territory that I know David likes, but I wanna touch on the pumping lemma.

LAW: You can’t check code you can’t parse

~ article

The essential measurement for this aspect of a particular programming grammar is when we talk about how easy it is for a machine (or human) to understand a given expression.

for example

1 * 1

Is easy to parse, and therefore is easy to evaluate. When the C toolchain runs, it has no trouble parsing and lexing code of this kind. But take a look at this:

AA *bb;

This is tricky but with context the compiler can resolve it. It needs to know if AA is bound to an int, or if AA is a custom type that the user has defined. Based on this context the compiler will know if the code expresses math multiplication or variable declaration. C gets around this by making the parser and lexer mutually recursive and introducing extra global state in the form of a ‘Symbol Table’.

This was almost certainly not done intentionally by the language designers, C was once a trailblazer and these kinds of things only emerge as formal theory once the theorists have a chance to write their papers, but we now know that there are ways to express this concretely such that the parser does not need any additional help to understand the expression.

AA *bb

Rust will always resolve this as AA multiplied by bb. Rust will know that this case is not a variable declaration since that would be expressed as

let bb: AA = ?;

This makes the parsing stage more straightforward, since the program needs to resolve far fewer ambiguities. Rust is not actually fully context-free, but it comes quite close.

Another C example that is legal but quite unclear without context is

foo(bar);

which is either a function call passing bar, or is a declaration of a variable named bar of type foo (Because C allows for var declarations within parentheses).

The classic horror for this grammar being

foo(*bar(baz))[5]

which is either a function declaration or an expression containing two function calls.

Then, because C can have named or unnamed function args you can also do

int MyFunc(foo (bar));

where it is unclear if MyFunc takes bar as type foo, or if it takes a pointer to an anonymous function that itself takes bar and returns type foo.

Because of these lexical quirks, the C preprocessor is an extremely powerful hand-written piece of software. Because of just how powerful it needs to be to resolve all of these ambiguities, people often struggle to write tools that check or introspect C-style code. Because we’ve had some time to generalize these problems in the field of language design, languages like zig and rust spend a lot of time in the initial phase of language development trying to design a syntax that resist these kinds of uncertainty.

Some people argue this can be taken too far. Zig has been in alpha (pre V1.0) for over a decade, and to this day those clever folks occasionally change the syntax in ways that break existing code. I could easily write another article on zig and its design process.

Zig has managed to get its language definition beautifully small (580 lines)

Type System

Rust has a beautiful type system. I’m not sure really how to quantify it in concrete terms but the zero-cost abstraction of data and its traits is extremely pleasing to me. Some people really bang up against the strictness of the compiler in these regards but I have to say that for me it is part of the central beauty of any language.

fn execute<E: HasHead>(entity: E, guillotine: impl Chop) {
  guillotine.chop(entity)
}

This kind of type expression allows for plenty of pondering about whether you are interested in combining data, or combining behaviors. This kind of programming is extremely fun to me and can solve certain kinds of problems in an absolutely beautiful way.

In Embedded rust in particular, this can provide incredible feedback to the programmer because the type system is powerful enough to describe the hardware with which you are interfacing.

for example, look at this code

let pin = Input::new(peripherals.GPIO2, InputConfig::default());
let i2c = match I2c::new(peripherals.I2C0, esp_hal::i2c::master::Config::default()) {
    Ok(i2c) => i2c.with_sda(pin).with_scl(peripherals.GPIO22),
    Err(err) => panic!("Failed to set up i2c {:?}", err),
};

It might not be immediately obvious what the error is here, but the compiler can tell that you are setting up the sda line for i2c with an Input pin rather than an IO pin.

error[E0277]: the trait bound `Input<'_>: PeripheralOutput<'_>` is not satisfied
    --> src/bin/main.rs:55:33
     |
  55 |         Ok(i2c) => i2c.with_sda(pin).with_scl(peripherals.GPIO22),
     |                        -------- ^^^ the trait `OutputPin` is not implemented for `Input<'_>`
     |                        |
     |                        required by a bound introduced by this call
     |
     = help: the following other types implement trait `OutputPin`:
               AnyPin<'_>
               GPIO0<'_>
               GPIO10<'_>
               GPIO11<'_>
               GPIO12<'_>
               GPIO13<'_>
               GPIO14<'_>
               GPIO15<'_>
             and 22 others
     = note: required for `Input<'_>` to implement `PeripheralOutput<'_>`
note: required by a bound in `esp_hal::i2c::master::I2c::<'d, Dm>::with_sda`
    --> /home/coco/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/esp-hal-1.1.2/src/i2c/master/mod.rs:1193:63
     |
1193 | ...> + PeripheralOutput<'d>) -> Self {
     |        ^^^^^^^^^^^^^^^^^^^^ required by this bound in `I2c::<'d, Dm>::with_sda`

It tells you exactly what is wrong with this code and refuses to compile.

Here’s another example:

let btn = Input::new(peripherals.GPIO4, InputConfig::default());
let buzzer = Output::new(peripherals.GPIO5, Level::Low, OutputConfig::default());
let buzzer2 = Output::new(peripherals.GPIO4);

This one is more obvious, and the compiler catches it easily

error[E0382]: use of moved value: `peripherals.GPIO4`
  --> src/bin/main.rs:52:31
   |
50 |     let btn = Input::new(peripherals.GPIO4, InputConfig::default());
   |                          ----------------- value moved here
51 |     let buzzer = Output::new(peripherals.GPIO5, Level::Low, OutputConfig::default());
52 |     let buzzer2 = Output::new(peripherals.GPIO4, Level::Low, OutputConfig::default());
   |                               ^^^^^^^^^^^^^^^^^ value used here after move

We configured the pin twice. A trivial mistake, trivially caught by the compiler as an illegal state for the program to be in. GPIO4 would need to be released to be reconfigured. This error would throw even if you were to make the conflicting configuration deep within a function callstack, or even in another thread context. The borrow checker is very thorough.

I can’t enumerate all of these, but the rich and expressive type system means that you are usually always quite aware of what data may be ascociated with which functions. You can usually write your programs without needing to reference documentation too frequently, and if the type system has been properly used you will usually expect that if your code compiles it will run (It will still have the bugs that you write, but it will run). This means you spend more time reasoning about the actual behavior of your code rather than trying to tease out irrational behaviours.

Proper Modular Code

A genuine pain point with C/C++ is that the language does not define a system for dealing with namespaces. Using include can introduce errors that feel pointless to address when you come from a language that defines a module system. Being able to keep code concretely separate and having namespaces is a convenience that is annoying to forego. It obviously doesn’t affect the actual function of the language, but the process of writing the code is definitely affected.

Crates

An extension of the modular code point is that rust has a built-in dependency management system that just works. This is undeniably just a nice thing to have, and makes it much easier to keep a handle on your dependencies. It also makes it easy and desirable to write your own modules since they will integrate easily.

Code Formatting

This is a complete aside, but the rust foundation write a formatter for rust code and there are NO others. I quite like this strategy because all rust code everywhere adheres to the same formatting rules, it doesn’t differ project to project.

Unsafe Rust

There is a book with a certain dry humor to it that is maintained by the rust community called the rustonomicon. I quite enjoyed reading it and it essentially covers all the ways in which you might eject from the rust borrow-checker to write code in a standard C-style way.

THE KNOWLEDGE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF UNLEASHING INDESCRIBABLE HORRORS THAT SHATTER YOUR PSYCHE AND SET YOUR MIND ADRIFT IN THE UNKNOWABLY INFINITE COSMOS.

~ The opening of the Rustonomicon

Unsafe rust is not ’true’ rust code, but it exists because sometimes a rust program may need to interface with a program written in C.

Conclusion

I will typically reach for rust if it’s my own project that I’m starting out on because I like the tools and I enjoy the rigid constraints of rust. If there is existing C/C++ code you can usually get 90% of the way to this goal by choosing your tools well and making sure that the project uses well-structured code. My usual feeling is that if you are using C you will need to try harder to make the code as expressive as rust, but for the most part you should still be able to have fun with it.