Rust for embedded
Ownership and borrowing, nostd, embedded-hal, RTIC and Embassy.
Why Rust is appearing in firmware
Most of the bugs this course warns about (buffer overflows, use-after-free, null dereferences, data races between interrupts and main code, uninitialised memory) are memory-safety bugs that C and C++ allow and only discipline, review and tools catch. Studies by Microsoft and Google have found that roughly 70% of serious security vulnerabilities in large C and C++ codebases are memory-safety issues. Rust prevents those bug classes at compile time while producing machine code as fast and small as C, with no garbage collector and no runtime. That combination is why it is now used in embedded products and in parts of the Linux and Android kernels, and why some job descriptions mention it.
You do not need Rust to get an embedded job today. Knowing what it offers, and being able to read it, is increasingly useful.
The ideas that make it safe
Ownership. Every value has exactly one owner. When the owner goes out of scope, the value is dropped (RAII, as in C++). Assigning or passing a value moves ownership; the old name can no longer be used.
Borrowing. Code can borrow a reference instead of taking ownership, under one rule checked by the compiler: at any time, either any number of shared references (&T, read-only) or exactly one mutable reference (&mut T), never both. That rule alone rules out iterator invalidation, aliasing bugs and data races.
Lifetimes. The compiler checks that no reference outlives the data it points to, so returning a pointer to a local variable is a compile error, not a crash.
No null, explicit errors. Optional values are Option<T> (Some(x) or None) and fallible operations return Result<T, E>; the compiler forces you to handle both cases.
unsafe is explicit. Raw pointer dereferences and register access are allowed only inside unsafe blocks, which are kept small and wrapped in safe APIs, so the code to audit is easy to find.
What embedded Rust looks like
#![no_std] // no operating system: only the core library
#![no_main]
use cortex_m_rt::entry;
use panic_halt as _; // what to do on panic: halt (or reset, or log)
use stm32f4xx_hal::{pac, prelude::*};
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap(); // singleton: peripherals can be taken once
let gpioa = dp.GPIOA.split();
let mut led = gpioa.pa5.into_push_pull_output(); // the pin's mode is part of its type
loop {
led.toggle();
cortex_m::asm::delay(8_000_000);
}
}
Things to notice:
no_std: no heap or OS by default; thecorelibrary still providesOption,Result, slices, iterators and formatting.- Peripheral singletons:
Peripherals::take()succeeds only once, so two parts of the program cannot both believe they own GPIOA, a bug that C cannot prevent. - Type-state: a pin configured as an input is a different type from an output pin, so calling
set_high()on an input does not compile. - The PAC and HAL layers: a Peripheral Access Crate is generated from the vendor's SVD file (typed register access); a HAL crate builds safe drivers on top, implementing the shared
embedded-haltraits, so a sensor driver written againstembedded-halworks on any MCU.
Concurrency without data races
Sharing data with an interrupt handler requires proving it is safe. Patterns include critical_section::Mutex<RefCell<T>> (access only inside a critical section), atomics, and frameworks:
| Framework | Model |
|---|---|
| RTIC | Real-time interrupt-driven concurrency: tasks are interrupt handlers with priorities; shared resources are locked using the priority ceiling protocol, checked at compile time, deadlock-free |
| Embassy | async/await executor: tasks are cooperative state machines generated by the compiler, with async drivers for timers, UART, USB, BLE and networking |
| Zephyr, FreeRTOS bindings, Tock OS | Rust on or with existing RTOSes |
The C comparison, honestly
| C | Rust | |
|---|---|---|
| Memory safety | By discipline and tools | Enforced by the compiler outside unsafe |
| Performance and size | Excellent | Comparable (optimised by LLVM) |
| Vendor support | Every MCU, every SDK, every certified toolchain | Growing; strong for Cortex-M, RISC-V, ESP32, nRF; vendor SDKs mostly C |
| Safety certification | Mature (MISRA, qualified compilers) | Emerging: qualified Rust compilers (Ferrocene) exist for ISO 26262 and IEC 61508 |
| Learning curve | Small language, hard to use safely | Steeper: the borrow checker takes time |
| Hiring pool and legacy code | Huge | Smaller |
| Interoperability | — | Calls C through FFI and can be called from C, so it can be adopted gradually |
A common path in companies is to write new, security-sensitive components in Rust (a protocol parser, a bootloader, a TLS-facing module) and link them with existing C.
The safety benefit, shown in C
The C program below has the classic bug Rust's lifetime rules reject at compile time; the simulator catches it at run time, which a real microcontroller would not:
#include <stdio.h>
#include <string.h>
static char *make_label(int id) {
char buf[16];
snprintf(buf, sizeof buf, "sensor-%d", id);
return buf; /* Rust: "returns a reference to data owned by the current function" */
}
int main(void) {
char *label = make_label(7);
printf("%s\n", label);
return 0;
}
Note: Rust prevents memory-safety bugs, not logic bugs. Wrong register values, timing errors, wrong units and bad protocol handling are still possible, and
unsafecode can still be wrong.
Interview question: What advantages and risks would you weigh before using Rust in a firmware product?
Answer: Advantages: compile-time prevention of memory-safety bugs and data races, which are the main source of security vulnerabilities and many crashes in C; type-state and ownership that catch API misuse such as two owners of a peripheral; performance and size comparable to C; and C interoperability for gradual adoption. Risks: the team's learning curve, smaller hiring pool, vendor SDKs, middleware and RTOSes that are mostly C, less mature safety-certification tooling and fewer qualified compilers, and the need to wrap C code with unsafe bindings. Starting with an isolated, security-sensitive component is a common low-risk approach.
Going deeper
Interview question: Would you write a hardware security key's firmware in Rust? What would you consider?
Answer: Rust's memory safety removes the bug classes behind most security vulnerabilities, which suits a device handling secrets. Consider the target's support (HALs, the vendor's crypto hardware), certification needs, the team's experience, and whether existing C libraries must be linked. A common path is new security-critical code in Rust with C at the edges.
Interview question: How does Rust make sharing data between an interrupt and main code safe?
Answer: Static mutable data cannot be accessed without unsafe, so shared state must be wrapped in a type that proves exclusive access, such as critical_section::Mutex<RefCell<T>>, which only hands out a reference inside a critical section token, or atomics for single values. Frameworks like RTIC go further: shared resources are declared, each task's priority is known, and the framework applies the priority ceiling protocol so the compiler ensures every access is properly locked and the system is deadlock-free.
Explain it: In your own words, explain how Rust's ownership and borrowing rules prevent a use-after-free bug.
Answer: Every value has exactly one owner, and when the owner goes out of scope the value is freed. Other code may only borrow references to it, and the compiler tracks how long each reference lives (its lifetime). If a reference could outlive the value it points to, for example returning a reference to a local variable or keeping a reference after the owner has been moved or dropped, the program does not compile. So the situation where code uses memory after it has been freed is rejected before the program ever runs.