skip to content

What does running `cargo miri test` catch in a Rust crate's unsafe code, and what can Miri not tell you?

level: middleimportance: should knowfreq 40%

answer

  1. an interpreter, not a linter
  2. nightly toolchain component
  3. only the paths that run
  4. foreign calls stop it
  5. Stacked or Tree Borrows

basics

~20 s

Miri interprets the crate's tests and stops at undefined behaviour it observes: invalid or uninitialised values, out-of-bounds or misaligned accesses, aliasing violations, data races, leaks. It sees only executed paths and cannot run most foreign calls.

solid answer

~40 s

Miri is an interpreter for rustc's mid-level IR that ships on the nightly toolchain and runs with `cargo +nightly miri test` or `cargo +nightly miri run`. While interpreting, it tracks which bytes are initialised, which allocation and offset every pointer belongs to, alignment, and the permissions of each reference under an aliasing model, Stacked Borrows by default or Tree Borrows with `-Zmiri-tree-borrows`. It stops with "Undefined Behavior:" on invalid values, uninitialised reads, use-after-free, out-of-bounds and misaligned accesses, aliasing violations and data races it observes, and it reports memory leaks at exit. Its limits: it only checks the paths and thread interleavings the tests actually execute, it reports "unsupported operation" on most foreign functions, it is slow, and a clean run under an experimental aliasing model is evidence, not proof.

code

rust · 9 lines
rust
use std::ffi::c_int;

unsafe extern "C" {
    safe fn abs(x: c_int) -> c_int;
}

fn main() {
    println!("{}", abs(-3));
}

go deeper

for a junior

Know that Miri runs your tests in an interpreter and stops at undefined behaviour, and that it is launched with cargo +nightly miri test.

for a middle

List what Miri detects (invalid values, uninitialised reads, out-of-bounds, aliasing, races, leaks) and its blind spots: unexecuted paths and foreign calls.

for a senior

Explain Stacked versus Tree Borrows, why Miri calls them experimental, and how you design tests so the unsafe code's edge cases actually execute under Miri.

for a principal

Position Miri as one layer of evidence beside written safety arguments and review, and decide how often its slow runs belong in CI.

## What Miri is **Miri** is an interpreter for **MIR**, the mid-level intermediate representation rustc produces from your code. Instead of compiling to machine code and running it, Miri executes the program step by step in a virtual machine that keeps far more information than real hardware does. It is distributed as a rustup component on the **nightly** toolchain and driven through Cargo: - `cargo +nightly miri test` runs the crate's tests under Miri; - `cargo +nightly miri run` runs a binary; - extra options go in the `MIRIFLAGS` environment variable. Miri itself is a tool, not a language feature: the code it checks is ordinary stable Rust. ## What it tracks and catches Because Miri remembers the provenance and state of every byte, it can detect operations on the Rust Reference's list of undefined behaviour as they happen: - **invalid values**: a `bool` holding 2, a null reference from `mem::zeroed`, an enum with an impossible discriminant; - **uninitialised memory** read as an integer, for example `MaybeUninit::uninit().assume_init()` for a `u8`; - **out-of-bounds, dangling and use-after-free** accesses through raw pointers; - **misaligned** accesses; - **aliasing violations** under its aliasing model: using a `&mut` after another reference invalidated it, or writing through a pointer derived from a `&T`; - **data races** between threads it runs, for example two threads incrementing through a shared raw pointer; - **memory leaks**, reported at exit as "memory leaked" unless you pass `-Zmiri-ignore-leaks`. Each report begins with `error: Undefined Behavior:` (or `error: memory leaked:`), names the offending line, and for aliasing errors points to where the reference was created and where it was invalidated. ## The aliasing model is a choice Rust's exact aliasing rules are not settled; the Reference gives an outline. Miri implements two candidate models: | Model | How to select | Character | |---|---|---| | **Stacked Borrows** | the default | stricter; retagging a new `&mut` invalidates older ones over the whole range | | **Tree Borrows** | `MIRIFLAGS=-Zmiri-tree-borrows` | more permissive in several patterns; tracks permissions per byte | Miri's own messages say the rules it enforces *are still experimental*. Code that one model flags and the other accepts sits in an unsettled area; a cautious crate makes it pass both. ## What Miri cannot tell you 1. **Paths that did not run.** Miri checks one execution. A bug behind an untested branch, or behind a length your tests never use, is invisible. Thread interleavings are explored one schedule per run; `-Zmiri-many-seeds` tries several, but none of this is exhaustive. 2. **Foreign code.** A call into a C library that Miri does not emulate stops with `unsupported operation: can't call foreign function`. Miri implements a set of common platform functions itself, so some calls do run, but your own C dependency will not. 3. **Soundness of the API.** Miri tests what your callers did, not every misuse a safe caller could write. An unsound safe function passes Miri until someone writes the test that misuses it. 4. **Platform behaviour.** Miri emulates a target; it does not run your binary on real hardware, so timing and real system calls are outside its scope. 5. **Speed.** Interpretation is orders of magnitude slower than native code, so large tests are often trimmed or gated with `cfg(miri)`. ## Reading a report - The first line names the kind of violation, after `error: Undefined Behavior:` or `error: unsupported operation:`. - For aliasing errors, `help:` lines show where the offending reference was created and which later access or retag invalidated it. - A short stack backtrace follows; `MIRIFLAGS=-Zmiri-backtrace=full` prints the complete one. ## Using it well - Run the unit tests of every module that contains `unsafe` under `cargo +nightly miri test` in CI, on a schedule if not on every push. - Write tests that hit the edge cases of the unsafe code: empty inputs, full buffers, the last element, reallocation. - Try both aliasing models for code that juggles references and raw pointers. - Keep the safety argument in a `// SAFETY:` comment anyway; Miri checks executions, the comment covers the rest.

  • Why might a test pass under Tree Borrows but fail under Miri's default model?
    Stacked Borrows, the default, is stricter: creating a new `&mut` from a raw pointer invalidates older references over the whole range, while Tree Borrows tracks permissions per byte and tolerates some patterns, such as two mutable references touching disjoint bytes. Since neither model is the official rule yet, code accepted only by the looser one relies on an unsettled question and is worth rewriting.
  • How do you keep a slow test out of a Miri run?
    Miri sets `cfg(miri)` while it interprets, so a test can be skipped with `#[cfg_attr(miri, ignore)]`, or its input shrunk with `if cfg!(miri) { .. }`. That keeps the unsafe-heavy tests under Miri while large integration workloads run only natively.

  • Says a clean Miri run proves the crate has no undefined behaviour.
  • Expects Miri to check C code reached through FFI calls.
  • Thinks Miri is a static analyser that inspects every branch.
  • Believes Miri flags only crashes, not invalid values or aliasing errors.
  • Treats Miri as a stable-toolchain command like cargo test.