Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 132 ยท Testing and Tooling

Testing Unsafe Code with Miri and Sanitizers

Audit unsafe Rust: run tests under Miri, explore thread interleavings with loom, use AddressSanitizer and ThreadSanitizer, and add cheap debug assertions and leak counters.

A passing test only proves that one run did not visibly misbehave. For safe Rust that is usually enough, because the compiler has already ruled out whole classes of bugs. For unsafe code it is not: undefined behavior (UB) often produces the right answer today, on your machine, in a debug build, and then silently breaks in release mode or after a compiler upgrade. You need tools that check the rules, not just the results.

This lesson is a practical audit kit. You will meet Miri, which interprets your program and flags UB; loom, which explores thread interleavings; the compiler sanitizers (AddressSanitizer, ThreadSanitizer); and some cheap techniques you can run anywhere, including counters and debug assertions. Miri, loom and the sanitizers need a real Cargo project and a nightly toolchain, so their commands are shown read-only; the techniques we can run in the editor are runnable. It builds on Unsafe Rust, Building Data Structures with Unsafe and MaybeUninit and transmute.

Which tool finds which bug

flowchart LR
    A["unsafe code"] --> B["Unit tests<br/>behavior"]
    A --> C["Miri<br/>language-rule UB"]
    A --> D["AddressSanitizer<br/>real memory errors"]
    A --> E["ThreadSanitizer and loom<br/>data races, orderings"]
    A --> F["Fuzzing<br/>weird inputs"]

Each tool sees a different slice of the problem; serious unsafe code uses several.

Tool Finds Runs
Miri out-of-bounds, use after free, uninitialized reads, invalid values, misalignment, aliasing violations, leaks, data races in an interpreter on your tests (slow)
AddressSanitizer heap and stack overflows, use after free, double free natively, with instrumentation (fast)
ThreadSanitizer data races in real executions natively, with instrumentation
loom bugs that depend on a specific thread interleaving or memory ordering exhaustively explores a small model

Miri: an interpreter that knows the rules

Miri executes your program one MIR instruction at a time while tracking, for every byte, whether it is initialized and which pointers may legally access it. It does not run the final machine code; it runs the abstract machine that the language defines. That is why it can report UB that real hardware shrugs off.

Install and run it in your own project (a nightly toolchain component):

Terminal
# Read-only: run these on your own machine
rustup +nightly component add miri
cargo +nightly miri setup
cargo +nightly miri test            # run your test suite under Miri
cargo +nightly miri run             # run the binary under Miri

Typical problems it reports, with the kind of code that triggers them:

Rust
// Out-of-bounds read through a raw pointer (fine at run time, still UB)
let v = vec![1, 2, 3];
let p = v.as_ptr();
let x = unsafe { *p.add(3) };

// Use after free
let b = Box::new(5);
let p = &*b as *const i32;
drop(b);
let y = unsafe { *p };

// Invalid value: a bool must be 0 or 1
let z: bool = unsafe { std::mem::transmute(3_u8) };

// Misaligned read
let bytes = [0_u8; 8];
let q = unsafe { bytes.as_ptr().add(1).cast::<u32>().read() };

Each one makes Miri stop with an error: Undefined Behavior: ... message, a backtrace into your code and a note about what rule was broken. The message shape is always the same: it names the access, the allocation involved and the rule that failed. You read it like a compiler error.

Useful Miri options

Flags go in the MIRIFLAGS environment variable:

Terminal
# Read-only examples
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri test   # many random schedules
MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri test   # forbid int-to-pointer tricks
MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri test        # the newer aliasing model
MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test   # allow real clock, files, env

By default Miri isolates your program from the host, so tests that read the clock, environment variables or the file system need -Zmiri-disable-isolation. -Zmiri-many-seeds repeats the run with different thread schedules and allocation choices, which finds races a single run misses.

Limits to know

  • Miri is slow, often 10x to 100x slower than native. Run it on unit tests and small inputs, not on benchmarks.
  • It can only interpret what it can see: foreign (C) functions are mostly unsupported, though many libc calls are emulated.
  • A clean Miri run does not prove the absence of UB. It proves that the paths your tests took followed the rules. Test coverage still matters, and so does reasoning about the invariants.
  • Some tests need #[cfg_attr(miri, ignore)], or a smaller loop count under cfg!(miri), to finish in reasonable time.

Cheap checks that run everywhere

Before reaching for a nightly tool, use the techniques that work in any build. They catch behavior bugs and make UB far more likely to show up.

Debug assertions on every unsafe precondition

The standard library itself checks many unsafe fn preconditions in debug builds (for example slice::from_raw_parts checks alignment and size). Do the same in your own code. debug_assert! costs nothing in release builds.

Rust Checking a precondition with debug_assert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that the check lives in the unsafe fn, next to the # Safety section that documents the contract. Also enable the lints unsafe_op_in_unsafe_fn (an unsafe fn body must still wrap risky operations in unsafe {}) and, in Clippy, clippy::undocumented_unsafe_blocks to force a // SAFETY: comment on every block (see Clippy and rustfmt).

Counting live values to catch leaks and double drops

If your unsafe code manages ownership by hand, a counter of live objects is a very effective test. Make a type whose constructor increments a global counter and whose Drop decrements it. After the test, the counter must be zero: a leak leaves it positive and a double drop would push it negative.

Rust A live-object counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Use this pattern in the tests of every container, arena or smart pointer you write. Miri reports leaks too, but this works with plain cargo test.

loom: testing every thread interleaving

Threads run in an order the OS chooses. A race may happen once in a million runs, so a normal stress test can pass for years. loom (a crate from the Tokio project) takes the opposite approach: you write your concurrent code against loom's drop-in replacements for std::sync and std::thread, and loom::model runs your test many times, trying every legal interleaving and every memory ordering the C++/Rust model permits.

A loom test looks like this (read-only, because it needs the crate):

Rust
#[cfg(loom)]
use loom::{sync::atomic::{AtomicUsize, Ordering}, sync::Arc, thread};

#[test]
fn counter_never_loses_updates() {
    loom::model(|| {
        let n = Arc::new(AtomicUsize::new(0));
        let n2 = Arc::clone(&n);
        let t = thread::spawn(move || { n2.fetch_add(1, Ordering::SeqCst); });
        n.fetch_add(1, Ordering::SeqCst);
        t.join().unwrap();
        assert_eq!(n.load(Ordering::SeqCst), 2);
    });
}
// cargo test --release   with   RUSTFLAGS="--cfg loom"

Loom explodes combinatorially, so keep models tiny: two or three threads and a handful of operations. To see why exhaustive exploration finds what a stress test misses, here is a hand-made miniature of the idea. Each "thread" is a list of steps; we run every way to interleave two threads and collect the possible results.

Rust Enumerating every interleaving by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first line shows that the lost-update bug exists in some schedules (the final value can be 1 as well as 2), even though many ordinary runs would give 2. The second shows that no schedule can lose an update. Real loom does the same exploration, but over your actual code and with a model of weak memory ordering as well.

AddressSanitizer and ThreadSanitizer

The compiler can instrument a native build to catch memory errors while the program runs at close to normal speed. These are unstable, nightly-only flags, and they only work on some targets (Linux x86-64 is the safest choice). Read-only commands:

Terminal
# Read-only: AddressSanitizer finds heap/stack overflow, use after free, double free
RUSTFLAGS="-Zsanitizer=address" cargo +nightly run --target x86_64-unknown-linux-gnu
RUSTFLAGS="-Zsanitizer=address" cargo +nightly test --target x86_64-unknown-linux-gnu

# Read-only: ThreadSanitizer finds data races; the standard library must be rebuilt
RUSTFLAGS="-Zsanitizer=thread" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu

Sanitizers shine in two places Miri cannot reach: programs that call into C through FFI, and workloads too heavy for an interpreter. They check what actually happened in the machine code, while Miri checks what the language allows. Use both.

A good CI recipe for a crate with unsafe: normal tests on stable, cargo +nightly miri test on a small test set, an AddressSanitizer run of the full suite, and a nightly fuzzing job (see Property Testing and Fuzzing).

An audit checklist

When you review unsafe code, yours or someone else's, walk through these questions:

  1. Is every unsafe block as small as possible, with a // SAFETY: comment naming the exact invariant?
  2. Does every unsafe fn have a # Safety doc section stating what the caller must guarantee?
  3. Can the safe API be used in a way that breaks those invariants? If yes, the abstraction is unsound and the function must be unsafe or checked.
  4. Who drops each value exactly once? (Test with a live-object counter.)
  5. What happens if a callback or Clone impl panics halfway through?
  6. Do the tests run clean under Miri, including multi-threaded ones with many seeds?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a test suite pass even though the code has undefined behavior?

    Undefined behavior means the language makes no promises. Wrong code can produce correct output for a long time, which is why you need tools that check the rules directly.
  2. 2. What does Miri do?

    Miri interprets MIR and tracks initialization, pointer validity and aliasing for every byte, so it reports UB even when real hardware would not crash.
  3. 3. Which tool is the best fit for finding a bug that appears only under one particular thread interleaving?

    loom runs your test under every permitted scheduling and ordering of a small model, so rare interleavings are found deterministically.
  4. 4. A live-object counter reads 1 after a test that should have freed everything. What does that suggest?

    The counter goes up in the constructor and down in Drop. A value that was never dropped, for example forgotten with mem::forget, leaves it positive.
  5. 5. Why are ThreadSanitizer and AddressSanitizer a useful complement to Miri?

    Sanitizers instrument real compiled code, so they handle FFI and large workloads. They still only see the paths that actually ran, so they complement rather than replace Miri.

Summary

  • Passing tests do not show the absence of undefined behavior; use tools that check the rules.
  • Miri (cargo +nightly miri test) interprets your tests and reports out-of-bounds, use-after-free, uninitialized reads, invalid values, misalignment, aliasing violations and leaks; add -Zmiri-many-seeds for thread races.
  • loom explores all interleavings of a small concurrent model; AddressSanitizer and ThreadSanitizer instrument native builds and cover FFI.
  • Cheap checks work everywhere: debug_assert! in every unsafe fn, SAFETY and Safety comments, unsafe_op_in_unsafe_fn, and live-object counters for leaks and double drops.
  • Treat the audit checklist as part of code review for any module that contains unsafe.

Next: Property Testing and Fuzzing