Sub topic 15
What a clean Miri run does and does not tell you
This chapter assumes you can run cargo +nightly miri test, read a Miri error report, and know the basic aliasing and provenance rules from earlier chapters. It covers how to interpret a run with no errors. A clean run is useful evidence. It is not a proof that your code is sound.
What "clean" means
When Miri finishes without an error, one statement is true: for the inputs, thread schedule, target, and Miri version used in that run, the executed code did not violate any rule Miri checks. Each part of that sentence limits the claim.
- Executed code: Miri only checks operations that actually run.
- Inputs and schedule: Different inputs or interleavings can take different paths.
- Rules Miri checks: Miri models many kinds of undefined behavior, but not all of them.
- Miri version: Its aliasing checks change between releases.
Unexecuted paths stay unchecked
Miri is a dynamic checker. It interprets the program and watches each operation as it happens. It does not analyze every possible path the way the compiler's borrow checker does.
This function has undefined behavior on exactly one input. Put it in src/lib.rs:
pub fn get(v: &[u32], i: usize) -> u32 {
if i == 7 {
// Bug: this branch skips the bounds check.
unsafe { *v.as_ptr().add(i) }
} else {
v[i]
}
}
#[test]
fn small_index() {
assert_eq!(get(&[1, 2, 3], 1), 2);
}cargo +nightly miri test passes. The test never takes the i == 7 branch, so Miri never sees the out-of-bounds read. A second test that calls get(&[1, 2, 3], 7) would make Miri report the access.
The consequence is that Miri's coverage is your test coverage. Branch and line coverage tell you which parts of your unsafe code Miri has looked at. Unsafe code that no test reaches gets no protection from Miri at all.
Choosing inputs that matter
Tests written for functional correctness often skip the inputs where unsafe code goes wrong. Add cases for:
- Empty collections and single-element collections.
- Capacity boundaries, such as pushing exactly to the point where a buffer grows.
- Zero-sized types.
- Drop paths, including a panic partway through an operation.
- Maximum and minimum values for index arithmetic.
Property-based tests and fuzzers can generate inputs you would not think of. Run them under Miri with small iteration counts, as the cfg(miri) pattern from the previous chapter showed.
Nondeterminism: schedules and addresses
Some behavior varies from run to run. Miri makes its own choices for those, and a single run explores one set of choices.
Thread schedules. Miri picks a schedule from a pseudo-random seed. A data race that needs a particular interleaving may not occur under the default seed. You can vary the seed to explore more schedules:
MIRIFLAGS="-Zmiri-seed=7" cargo +nightly miri test
MIRIFLAGS="-Zmiri-many-seeds=0..32" cargo +nightly miri testThe first command runs one specific seed. It is useful for reproducing a failure Miri reported. The second runs the program once for each seed from 0 up to but not including 32 and stops at the first failure. More seeds mean more schedules tried and a longer run. Even many seeds do not enumerate every interleaving, so a clean multi-seed run lowers the odds of a missed race without removing them.
Weak memory. Miri emulates some weak-memory behavior for atomics, so it can surface bugs from wrong memory orderings. The emulation is not complete. Treat it as a way to find bugs, not as a certificate that your orderings are right.
Addresses. When your code casts pointers to integers, the concrete address values Miri hands out are also pseudo-random. Code that relies on a particular address or alignment by luck can pass on one seed and fail on another. Running with several seeds helps here too.
Rules Miri enforces may not be the final rules
Rust does not yet have a complete, official specification of its aliasing rules. Stacked Borrows and Tree Borrows are experimental models. Miri implements them to find code that is likely to be undefined behavior, and each model has consequences in both directions.
- A Miri error may be stricter than the eventual rules. Code that Stacked Borrows rejects might be allowed under a later model. Tree Borrows accepts some patterns that Stacked Borrows rejects.
- A clean run under one model does not imply a clean run under the other. Run both if you need to be conservative:
cargo +nightly miri test
MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri test- A clean run today may fail on a future Miri. The checks get stricter, and the rules can change. Pin your nightly in CI and read release notes when you upgrade, so you can separate new findings from regressions in your own code.
A pattern that passes both models is the safest. A pattern that passes only one is relying on a rule that may not last.
What Miri cannot see
Foreign code
Miri interprets Rust MIR. It cannot run arbitrary native code. A call to a C function that Miri has no built-in replacement for stops the run with an unsupported-operation error. Miri provides replacements for many common libc functions, but not all. Inline assembly is also unsupported.
Even when a call is supported, Miri cannot check what the foreign code does to your memory. A C library that corrupts a buffer it was handed is invisible to Miri. A common workaround is to mock the foreign boundary in tests and skip the real FFI tests:
#[test]
#[cfg_attr(miri, ignore)]
fn talks_to_the_c_library() {
// Calls into native code that Miri cannot interpret.
}Ignoring a test under Miri also removes that test from Miri's coverage. Keep the Rust-side logic around the FFI call testable without the call.
Environment and isolation
By default Miri runs in isolation. It blocks or fakes access to the real clock, the host file system, and the environment. Tests that need them fail or behave differently. -Zmiri-disable-isolation allows access, at the cost of less reproducible runs.
Target and configuration
Miri checks the code compiled for one target and one set of cfg options. Code under #[cfg(windows)] is not checked on Linux. You can run Miri for another target:
cargo +nightly miri test --target i686-unknown-linux-gnuRunning a 32-bit or big-endian target can expose bugs in size, alignment, or byte-order assumptions that a 64-bit little-endian run hides.
Undefined behavior that is not a Miri check
Miri finds the Rust-level undefined behavior it models. Some bugs are outside its reach.
| Problem | Does Miri find it? |
|---|---|
| Out-of-bounds access on an executed path | Yes |
| Use-after-free on an executed path | Yes |
| Invalid values such as `bool` equal to 3 | Yes |
| Data race on an executed interleaving | Yes |
| Logic bugs with no undefined behavior | No |
| UB in C code called through FFI | No |
| UB on a path no test reaches | No |
| Violations of a library's documented safety contract that cause no immediate UB | Not unless the contract is encoded as a checked assertion |
The last row matters for library authors. If your unsafe fn has a safety contract, such as "the pointer must be aligned to 8 bytes", a caller can break it in a way that produces no visible failure in the tested path. Tests for the contract boundary are a way to make such violations reach a Miri check.
Deciding how much to trust a clean run
Use these questions to judge a result.
- Did the tests reach every unsafe block? Check coverage on the unsafe code.
- Do the inputs include the edge cases? Empty, full, zero-sized, and boundary values.
- For threaded code, did you try many seeds?
- Did you try both aliasing models?
- Is any unsafe path hidden behind
cfgorignore? - Does the code cross an FFI boundary Miri cannot see?
A run with good answers to these questions is strong evidence. Combine Miri with other tools for stronger confidence: fuzzing to widen the inputs, sanitizers for native code, and careful written safety arguments for each unsafe block. A passing Miri run is one input to that argument, not the argument itself.
Exercise
A test suite for a hand-written Vec-like type passes under cargo +nightly miri test with the default settings. The type has an unsafe grow method that reallocates the buffer, and the tests only push 4 elements into a type whose initial capacity is 8. Is the type free of undefined behavior? Name two concrete steps to improve your confidence.
Show answer
No. The tests never trigger grow, so Miri never checked that code, and a bug there (such as a stale pointer used after reallocation) would go unnoticed. First, add tests that push past the capacity so grow runs, including growth from empty and growth of zero-sized types, and run them under Miri. Second, run the suite under both models (-Zmiri-tree-borrows as well as the default) and, if the type is shared across threads, with -Zmiri-many-seeds. Measuring coverage on the unsafe blocks would confirm that every one of them executes.