In embedded Rust, why does `cortex_m::Peripherals::take()` return an `Option`, and what does the `unsafe` `steal()` give up?
answer
- one value per piece of hardware
- a flag checked in a critical section
- the second call yields None
- zero-sized proxies moved into drivers
- steal sets the flag, skips the check
basics
~20 sPeripherals are singletons: the first take() returns Some and every later call returns None, so each piece of hardware has one owner. The unsafe steal() skips that check, making exclusive access your promise instead of the compiler's.
solid answer
~50 sHardware registers are global mutable state, so embedded Rust turns them into ordinary values the borrow checker can track. `cortex_m::Peripherals::take()` enters a critical section, checks a private `static mut TAKEN` flag, and on the first call sets it and returns `Some(Peripherals)`; after that it returns `None`. Each field, such as `SYST` or `NVIC`, is a zero-sized proxy that dereferences to the register block at a fixed address, so owning it is the permission to touch that hardware. Moving `cp.SYST` into `cortex_m::delay::Delay::new` hands the timer to the delay, and reusing it is `E0382`. An svd2rust PAC's `Peripherals::take()` does the same for the chip's own peripherals. `steal()` is `unsafe`: it sets the flag and returns a fresh instance anyway, so two owners can reconfigure the same peripheral, and a HAL that relied on being the only owner loses its guarantee.
code
rust · 26 lines#![no_std]
#![no_main]
use cortex_m::delay::Delay;
use cortex_m_rt::entry;
#[entry]
fn main() -> ! {
// First call: the core peripherals, handed out exactly once.
let cp = cortex_m::Peripherals::take().unwrap();
// Any later call sees the flag already set and gets None.
assert!(cortex_m::Peripherals::take().is_none());
// Delay::new takes SYST by value: the SysTick timer now belongs to `delay`.
let mut delay = Delay::new(cp.SYST, 64_000_000);
loop {
delay.delay_ms(500);
}
}
#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
loop {}
}go deeper
Recall that take() returns Some once and None afterwards, and that the idiom is take().unwrap() at the top of cortex-m-rt's entry function.
Explain the flag checked inside a critical section, the zero-sized peripheral fields, and how moving a field such as SYST into a driver transfers the right to use it.
Say exactly what steal() breaks, exclusivity the compiler can no longer check and HAL invariants, and name the narrow cases, such as a fault handler, where it is defensible.
Treat every steal() as a soundness review item and prefer passing ownership down from main, so the hardware ownership graph stays visible in function signatures.
## The problem: hardware is global mutable state A peripheral's registers live at fixed addresses and can be reached from anywhere in the program. If every function could write the SysTick reload register directly, nothing would stop two parts of the firmware from reprogramming the same timer. Rust's answer is to represent each peripheral as a **value** and let ownership decide who may touch it, the same aliasing-or-mutation rule the borrow checker applies to memory. ## How take() works in cortex-m 0.7 The `cortex-m` 0.7.10 source does four things: 1. A private `static mut TAKEN: bool` starts out `false`. 2. `Peripherals::take()` runs inside `cortex_m::interrupt::free`, a critical section, so no interrupt can interleave with the check. 3. If `TAKEN` is already `true`, it returns `None`. 4. Otherwise it calls `steal()`, which sets `TAKEN = true` and builds the struct, and returns it in `Some`. `Peripherals` has one public field per core peripheral: `SYST`, `NVIC`, `SCB`, `DWT`, `CPUID` and more. Each is a **zero-sized** struct holding only `PhantomData` that implements `Deref` to the register block at that peripheral's address. Owning a `SYST` costs nothing at run time; it is a compile-time token. The crate also defines a `#[unsafe(no_mangle)]` static named `CORE_PERIPHERALS`. Its source comment gives the reason: it prevents linking different minor versions of `cortex-m` into one program, which would give each version its own flag and let `take()` succeed once per version. ## Ownership after take() Once firmware holds the struct, ordinary Rust rules do the rest: - `cortex_m::delay::Delay::new(cp.SYST, 64_000_000)` takes `SYST` **by value**. The delay now owns the timer, and a second `Delay::new(cp.SYST, ...)` is rejected with `` error[E0382]: use of moved value: `cp.SYST` ``. - A function that only reads a peripheral can take `&SYST`; one that reconfigures it takes `&mut SYST` or the value, so signatures show which code may change the hardware. - A HAL constructor that takes a PAC peripheral by value gets the same guarantee: nothing else holds that peripheral. ## The PAC version An svd2rust-generated PAC emits the same pattern for the chip's own peripherals (GPIO ports, I2C controllers, timers): a `static mut DEVICE_PERIPHERALS: bool` flag marked `no_mangle` for the same minor-version reason, and a `Peripherals::take()` that runs inside `critical_section::with`. That `take()` exists only when the PAC's `critical-section` Cargo feature is enabled, and the program must link a critical-section implementation, such as the one `cortex-m` provides behind its `critical-section-single-core` feature. ## What steal() gives up `steal()` is an `unsafe fn` on both structs, and svd2rust also generates one on every individual peripheral type. The struct-level `steal()` returns a new instance without checking the flag, and it sets the flag, so a later `take()` returns `None`. What it gives up: - **Exclusivity.** Two `SYST` values can now reconfigure the same timer, and the compiler cannot see it. - **HAL invariants.** svd2rust's safety note on the per-peripheral `steal()` warns that HALs may rely on only one instance existing, so stolen instances must not be passed to them. - **The audit trail.** Every `steal()` is a place where a reviewer must show nothing races with the real owner. svd2rust documents narrow conditions for a sound per-peripheral `steal()`: the new instance must not be used in a way that races with existing ones, for example by touching only read-only or write-only registers, or by consuming the original and coordinating the copies with critical sections. Typical legitimate uses are a panic or fault handler that must reach a peripheral after `main` has given it away, and HAL internals that use the raw `ptr()` behind a safe API. ## The same idea for your own statics `cortex-m` applies the take-once idea to buffers too. `cortex_m::singleton!(: [u8; 1024] = [0; 1024])` returns `Option<&'static mut [u8; 1024]>`: `Some` the first time that line executes and `None` afterwards, so a DMA buffer or a queue can be handed out as a `&'static mut` without `unsafe` at the call site. Like `take()`, it needs a critical-section implementation, and its documentation tells the caller to use it only in code that runs at most once, such as the top of `main`, or the `unwrap()` will fail on the second call. ## The entry point around it `take()` is normally the first line of the `#[entry]` function. `cortex-m-rt` requires that function to have the signature `[unsafe] fn() -> !`; a plain `fn main()` is rejected by the macro with exactly that message, because firmware has nowhere to return to. Calling `take().unwrap()` once at the top of `main` is the idiom: `main` runs once, so the `unwrap` fails only if other code took the peripherals first.
- Why does cortex-m's Peripherals::take() run its check inside a critical section?The check and the set are two steps. Without a critical section, an interrupt arriving between reading `false` and writing `true` could call `take()` itself, and both callers would receive `Some`. `cortex-m` uses `cortex_m::interrupt::free`; svd2rust PACs use `critical_section::with`, which is why they need a critical-section implementation linked into the program.
- When is calling steal() on a Rust peripheral defensible?When the stealing code cannot race with the owner: a panic or fault handler that runs after normal execution has stopped and needs an LED or a UART, or access limited to read-only or write-only registers. svd2rust's note also allows consuming the original and coordinating the copies with critical sections. In normal code, restructure ownership instead of stealing.
- Why are the cortex-m and svd2rust peripheral statics marked no_mangle?Two semver-compatible minor versions of the same crate can be linked into one program, each with its own private flag, and `take()` would then succeed once per version. An unmangled static has the same symbol name in every version, so the linker rejects the duplicate instead. Both source files carry a comment saying exactly this.
A peripheral is like the only key to a plant room, kept in a lockbox: take() opens the box once and hands the key over, and anyone opening the box later finds it empty. steal() is cutting a duplicate and marking the box empty: it opens the door, but now two people can rewire the same room without knowing about each other.
- take() returns Option because the chip might not have that peripheral.
- A second take() call returns another handle to the same registers.
- steal() is safe on a single-core chip because nothing runs concurrently.
- After steal(), the first take() call still returns Some.
- Each peripheral field stores a copy of the register values read at startup.