skip to content

In Rust 2024 firmware, a `static mut PRESSES: u32` shared with a button interrupt compiles without warnings, yet the release build hangs; why, and what is the fix?

level: seniorimportance: must knowfreq 35%

answer

  1. the 2024 lint only sees references
  2. the optimiser assumes no concurrent writer
  3. one load, then a branch to itself
  4. read then store: a lost press
  5. swap on M3 and up, not on M0

basics

~20 s

Main and a preempting handler access it without synchronisation, a data race, so the optimiser loads PRESSES once and spins on that copy. Use a plain static PRESSES: AtomicU32: fetch_add in the handler, swap(0, ..) in main, or a critical section.

solid answer

~50 s

On the 2024 edition `static_mut_refs` is deny-by-default, but it fires only on references; `PRESSES += 1` and `let n = PRESSES` take none, so the code compiles cleanly. Main never calls the handler, the hardware does, so with plain loads rustc may assume nothing else writes `PRESSES`: the release build loads it once and turns `while PRESSES == 0 {}` into a branch to itself. Even where it reloads, `let n = PRESSES; PRESSES = 0;` is two steps, and a press handled between them is lost. Rust counts that unsynchronised access as a data race, undefined behaviour, which is what licenses the optimisation. The fix is a non-`mut` `static PRESSES: AtomicU32`: `fetch_add(1, Relaxed)` in the handler, `swap(0, Relaxed)` in main, which compile to LDREX/STREX loops on Armv7-M. Cortex-M0 has no such instructions, so there you use a critical section.

code

rust · 33 lines
rust
#![no_std]
#![no_main]

use cortex_m_rt::entry;
use pac::interrupt;

static mut PRESSES: u32 = 0; // shared with the handler: unsound

#[interrupt]
fn EXTI0() {
    unsafe { PRESSES += 1 };
}

#[entry]
fn main() -> ! {
    unsafe { cortex_m::peripheral::NVIC::unmask(pac::Interrupt::EXTI0) };
    while unsafe { PRESSES } == 0 {}
    loop {
        let n = unsafe { PRESSES }; // the handler can run here...
        unsafe { PRESSES = 0 };     // ...and this store erases its press
        report(n);
    }
}

#[inline(never)]
fn report(n: u32) {
    unsafe { core::ptr::write_volatile(0x2000_1000 as *mut u32, n) };
}

#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
    loop {}
}

go deeper

for a junior

Recall that a static mut shared with an interrupt handler is unsound, and that a plain static atomic or a critical section replaces it.

for a middle

Explain the lost update: reading and then storing zero are two steps, and the handler can run between them.

for a senior

Diagnose the release-only hang from the optimiser's view, explain why the 2024 lint is silent, and know which Cortex-M cores lack swap and fetch_add.

for a principal

Turn it into policy: forbid module-level static mut in firmware, review every shared static, and pick atomics or critical sections per core family.

## The firmware that looks fine The code below counts button presses: the `EXTI0` handler increments a `static mut`, and `main` waits for the first press, then repeatedly reads the count, resets it and reports it. On Rust 1.99 with the **2024 edition** it compiles without a single warning, even though the 2024 edition made `static_mut_refs` a deny-by-default lint. That lint fires when code takes a **reference** to a `static mut` (`&PRESSES`, or a method call that borrows it). `PRESSES += 1`, `let n = PRESSES` and `PRESSES = 0` are by-value accesses, so the lint is silent; the general rules for `static mut` and that lint are covered with `unsafe` superpowers. ## Why the release build hangs The interrupt handler is never called from `main`; the hardware vectors to it. From the compiler's point of view `main` is ordinary straight-line code reading an ordinary memory location that nothing in `main` writes. Non-atomic, non-volatile loads carry no promise that another thread of execution may change the value, so the optimiser may keep it in a register. The release disassembly shows exactly that: 1. `ldr r0, [r1]` loads `PRESSES` once. 2. `cbz` jumps to an instruction that branches to itself if the value was zero: the wait loop is now an infinite loop that never looks at memory again. 3. If the first load was non-zero, `main` stores zero once, reports that first value, and then calls `report(0)` forever, again without reloading. The debug build reloads on every iteration and seems to work, which is how this bug survives testing. ## Why it is undefined behaviour, not just a missed optimisation Rust's list of undefined behaviour includes **data races**: two accesses to the same location from concurrent contexts, at least one a write, not ordered by synchronisation. A handler that preempts `main` is such a context; the Rust embedded book models it as a separate thread. The optimisation above is legal precisely because a racing program has no defined behaviour. Even on a build that does reload, the **lost update** remains: `let n = PRESSES;` and `PRESSES = 0;` are separate instructions, and if the button interrupt fires between them, its increment is overwritten by the zero. ## The fixes | Approach | Handler | Main loop | Works on | |---|---|---|---| | `static PRESSES: AtomicU32` | `fetch_add(1, Relaxed)` | `swap(0, Relaxed)` | Armv7-M, Armv7E-M and Armv8-M (`thumbv7m`, `thumbv7em`, `thumbv8m.*`) | | `critical_section::Mutex<Cell<u32>>` or `Mutex<RefCell<u32>>` | increment inside `critical_section::with` | `replace(cs, 0)` inside one section | every Cortex-M | | `portable_atomic::AtomicU32` | `fetch_add` | `swap` | cores without compare-and-swap, emulated with a critical section or by masking interrupts | The atomic version needs no `unsafe` and no `mut`: the static is an ordinary `static`, because atomics are `Sync`. On `thumbv7em-none-eabihf`, `fetch_add` and `swap` compile to **LDREX/STREX** retry loops, exclusive load and store instructions that restart if anything intervened. `Relaxed` is enough for a counter whose value is not used to publish other memory; ordering rules in general belong to the material on std atomics. Prefer the atomic when the shared state is a single integer or flag, because it never delays other interrupts; switch to a critical section as soon as two values must change together, such as a count and the timestamp of the last press, since two separate atomics can be observed half-updated. ## The Cortex-M0 trap Armv6-M (`thumbv6m-none-eabi`: Cortex-M0, M0+, M1) has atomic loads and stores but **no compare-and-swap**: its target specification sets `atomic-cas` to false, and `rustc --print cfg` reports no `target_has_atomic`. `core` compiles the read-modify-write methods (`swap`, `fetch_add`, `compare_exchange`) only under `cfg(target_has_atomic = "32")`, so on that target they simply do not exist and the call fails to compile. A plain `load` followed by `store(0)` would reintroduce the lost press. The choices are a critical section, or the `portable-atomic` crate with its `critical-section` feature or its `unsafe-assume-single-core` feature. ## What does not fix it - **Volatile access** (`read_volatile` / `write_volatile` through `&raw mut PRESSES`): it stops the hang, because every read goes to memory, but `core`'s documentation states that volatile accesses behave exactly like non-atomic ones for concurrency, and the read-then-store gap remains. - **Raw pointers to silence the lint**: `&raw mut` satisfies `static_mut_refs` and changes nothing about the race. - **Testing in debug only**: the hang appears only once the optimiser runs. One `static mut` remains fine: one declared **inside** an `#[interrupt]` or `#[exception]` handler's body. `cortex-m-rt` rewrites it into a `&mut` local that only that handler can reach, so it is never shared.

  • Would `read_volatile` and `write_volatile` on `&raw mut PRESSES` fix it?
    They fix the hang, since every volatile read really goes to memory, but not the race. `core` documents that volatile accesses behave exactly like non-atomic accesses for concurrency, and the read and the store of zero are still two separate operations the handler can run between. You still need an atomic `swap` or a critical section around read-and-reset.
  • On a Cortex-M0+ (`thumbv6m-none-eabi`), why does `PRESSES.swap(0, Ordering::Relaxed)` not compile?
    Armv6-M has no compare-and-swap or exclusive-access instructions, so the target has no `target_has_atomic` cfg and `core` leaves out every read-modify-write method: `swap`, `fetch_add`, `compare_exchange`. Only `load` and `store` exist. Use a critical section, or `portable-atomic` with its `critical-section` or `unsafe-assume-single-core` feature, which emulates those methods by masking interrupts.
  • Is `Ordering::Relaxed` enough for this counter on a single-core microcontroller?
    Yes. Each read-modify-write is indivisible whatever the ordering, and the count does not tell `main` that some other memory is ready. Stronger orderings matter when the atomic is a flag that publishes data the handler wrote, such as a filled buffer; then the handler stores with `Release` and `main` loads with `Acquire`.

  • The 2024 static_mut_refs lint catches every unsound use of a static mut.
  • A single-core microcontroller cannot have data races, so static mut is fine.
  • Making the accesses volatile makes the shared counter correct.
  • AtomicU32::fetch_add is available on every Cortex-M target.
  • The debug build works, so the release hang must be a compiler bug.
  • A static mut declared inside the interrupt handler's body is just as unsound.

Assumes Rust 1.99 on the 2024 edition (stable since 1.85), where static_mut_refs is deny-by-default but fires only on references, so by-value static mut accesses still compile silently.