Sub topic 13
Finding undefined behavior with Miri
This chapter assumes you know what undefined behavior (UB) is and how raw pointers and unsafe blocks work, as covered in earlier chapters. You also need Cargo and a nightly toolchain installed through rustup.
What Miri is
Miri is an interpreter for Rust's mid-level intermediate representation (MIR). It doesn't run your program as machine code. It executes it step by step and tracks every allocation, pointer, and borrow. When an operation breaks a rule of the language, Miri stops and reports it.
The compiler and tests can't do this. A program with UB often passes its tests, because the broken rule has no visible effect on your machine today. Miri turns many of those silent bugs into errors.
Miri reports these kinds of UB:
- Out-of-bounds and use-after-free memory accesses
- Misaligned pointer reads and writes
- Reads of uninitialized memory
- Values that break validity rules, such as a
boolthat isn't 0 or 1 - Aliasing violations, such as breaking the rules for
&mut - Data races
Installing and running Miri
Miri ships as a rustup component for the nightly toolchain.
rustup +nightly component add miri
cargo +nightly miri run
cargo +nightly miri testcargo miri test runs your existing test suite under the interpreter. This is the most common way to use it, since a good test suite already exercises your unsafe code.
A first catch
This program compiles without warnings and may print a number when you run it normally.
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
// SAFETY (wrong): index 3 is one past the end of the allocation.
let x = unsafe { *p.add(3) };
println!("{x}");
}Under cargo +nightly miri run, execution stops with an error that starts with Undefined Behavior. The message says the read goes beyond the end of the allocation and points at the line with *p.add(3). Miri also names the allocation and where it was created.
The fix is to respect the bounds. Here the code reads only inside the allocation.
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
// SAFETY: `v` has 3 elements, so index 2 is in bounds and initialized.
let x = unsafe { *p.add(2) };
println!("{x}");
}This version runs cleanly under Miri.
What Miri cannot promise
Miri checks only the paths that actually execute. If a branch with UB never runs in your tests, Miri won't see it. A clean run means "no UB found in these executions", not "no UB exists".
Other limits to know:
- It is much slower than native execution, so use small inputs.
- Calls to foreign C code generally don't work, because Miri can't interpret machine code. Some common libc functions are emulated.
- By default it isolates the program from the host, so some file and clock operations fail.
MIRIFLAGS="-Zmiri-disable-isolation"relaxes this. - The aliasing rules it enforces are still being specified. Stacked Borrows is the default model.
-Zmiri-tree-borrowsselects the newer Tree Borrows model. Code that one model rejects and the other accepts deserves a close look.
Using Miri in practice
- Write tests that cover each
unsafeblock, including edge cases such as empty slices and zero-length allocations. - Run
cargo +nightly miri testlocally while you develop. - Add the same command to continuous integration so regressions are caught.
Exercise
Your safe wrapper around an unsafe function passes all tests under cargo test, and cargo miri test also reports no errors. Does that prove the wrapper is sound? Explain.
Show answer
No. Miri only checks the executions your tests perform. An input that triggers UB but isn't in the tests goes unnoticed, and Miri's aliasing model may also differ from the final language rules. A clean run is strong evidence, not proof. You still need a written safety argument for why every call to the safe API upholds the unsafe code's contract.