Sub topic 3
Miri: an interpreter that checks as it executes
Prerequisites
This chapter assumes you know Rust ownership, borrowing and lifetimes. You should also be comfortable with cargo run and cargo test, and with raw pointers and the unsafe keyword at a basic level. The previous chapters explained why undefined behavior (UB) is dangerous and why ordinary tests often miss it. This chapter covers what Miri is and how it finds UB. Installing it is the next chapter's job.
What Miri is
Miri is an interpreter for Rust's mid-level intermediate representation, called MIR. An interpreter runs a program one small step at a time inside another program. It does not turn the program into machine code. Because Miri performs each step itself, it can look at every memory access and check it against the rules of the Rust abstract machine.
The abstract machine is the specification that defines what Rust code means, independent of any CPU. Real hardware lets many invalid programs "work". An out-of-bounds read may return whatever bytes sit next to your allocation, and a use of freed memory may still see the old value. The abstract machine says these programs have no defined behavior. Miri implements the abstract machine closely enough to stop at the first step that breaks its rules.
Miri is a dynamic checker. It runs your program, usually a binary or your test suite, and reports UB only on the code paths that actually execute with the inputs you gave it.
How it works
Miri reuses the Rust compiler's front end. Your crate is parsed, type-checked and borrow-checked as usual, then lowered to MIR. MIR is a simplified control-flow graph of basic blocks. Each block holds simple statements such as "assign this value to this place" or "call this function". Generics are instantiated with concrete types before interpretation. The same interpreter core also evaluates const items at compile time, so Miri's machinery is in daily use inside rustc.
The interpreter does not store memory as one flat array of bytes. It keeps a table of allocations. Each allocation records its size, its alignment, which bytes are initialized, and whether it is still live. A pointer is more than an address. It also carries provenance, which says which allocation it may access, plus a tag used by the aliasing checks. Later chapters cover provenance and the two aliasing models, Stacked Borrows and Tree Borrows. For now, the point is that Miri keeps extra metadata that real hardware has no room for.
What Miri tracks
Each kind of UB maps to a piece of state that Miri maintains and checks on every relevant step.
| Check | State Miri keeps | Example it catches |
|---|---|---|
| Bounds | Size of each allocation | Reading one element past a `Vec` |
| Liveness | Whether an allocation was freed | Dereferencing a pointer after `drop` |
| Initialization | A per-byte "initialized" flag | Reading a `MaybeUninit` before writing it |
| Validity | The type's valid value range | A `bool` holding 3 |
| Alignment | Required alignment of each access | Reading a `u32` through a pointer at an odd address |
| Aliasing | Borrow tags for every reference and pointer | Writing through a raw pointer after a newer `&mut` |
| Data races | Per-thread logical clocks | Two unsynchronized writes to a `static mut` |
| Leaks | Allocations still live at exit | `std::mem::forget(Box::new(1))` |
Leaks are not UB, but Miri reports them at exit because it can see every allocation. The alignment check is stricter than a typical CPU, where unaligned loads often succeed. Miri also randomizes some choices, such as the schedule of threads and where allocations land, to expose code that depends on a lucky layout.
A program that works natively and fails under Miri
Here is the out-of-bounds read from the earlier chapters.
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
let x = unsafe { *p.add(3) };
println!("{x}");
}Natively this usually prints some integer and exits normally. Nothing crashes, because the read lands in memory the process owns. Under Miri, the read is an access beyond the end of a 12-byte allocation, and the interpreter stops with an error. The message names the allocation, the size of the access and how far past the end it went. It also shows the source line and a backtrace. The next chapters cover how to read that report.
The important contrast is in where the check happens. The compiled program asks the CPU to read an address and the CPU does not object. The interpreter asks whether this pointer may access that many bytes and finds that it may not.
Only executed paths are checked
Miri does not analyze your code statically. It cannot warn about a line it never runs. Consider this program.
fn get(v: &[i32], i: usize) -> i32 {
unsafe { *v.as_ptr().add(i) }
}
fn main() {
let v = vec![1, 2, 3];
println!("{}", get(&v, 1));
if std::env::args().count() > 5 {
println!("{}", get(&v, 3));
}
}get is unsound, because any index at or beyond v.len() is UB. Run with no extra arguments, args().count() is 1, the if body never executes, and Miri reports nothing. Run with extra arguments, which you pass after --, the call with index 3 executes and Miri reports the out-of-bounds read.
cargo +nightly miri run -- a b c d eA clean Miri run therefore means "no UB on the paths this run took". To cover more paths, you need more tests, more inputs, or a fuzzer driving the code under Miri. The final chapter returns to this limit.
Costs and consequences
Interpreting is slow. Expect programs to run from tens to hundreds of times slower than native code, and the gap grows with heavy computation. Tests that loop 100,000 times natively may need a smaller workload under Miri. A later chapter covers cfg(miri) for this.
Other practical effects follow from the design.
- Nightly toolchain. Miri depends on compiler internals, so it ships as a component of the nightly toolchain.
- Isolation. By default Miri blocks access to the real environment, including the clock, most of the filesystem and random sources, so that runs are reproducible. A flag relaxes this, and a later chapter lists it with the other options.
- Foreign code. Miri interprets MIR, and it has no MIR for C libraries. Calls to arbitrary
extern "C"functions generally fail with an "unsupported operation" error. Some common system calls and the standard library's own platform calls are emulated. - Target emulation. Because Miri models the machine itself, it can interpret a program for a different target, such as a big-endian one, even on a little-endian host. This helps find code that assumes byte order.
- Standard library checks. Miri runs against a special build of the standard library that keeps the checks intact. That is why unsafe code inside
stdcan also be reported as UB.
Where Miri sits among your tools
Miri complements, and does not replace, other checks. The compiler and Clippy find problems statically, and they never run your code. Sanitizers such as AddressSanitizer run native code quickly, but they see only what the hardware layout reveals. They know nothing about validity or aliasing rules. Miri is the slowest of these but checks the most Rust-specific rules. A common workflow is to use fast native tests for everyday work and run the unsafe-heavy parts under Miri.
Exercise
The get function above is unsound, yet cargo +nightly miri run with no arguments reports no error. Does that show get is sound? Explain using how Miri works.
Show answer
No. Miri is an interpreter that checks only the steps it executes. With no arguments the if body never runs, so the out-of-bounds call never happens and no check fails. The run shows only that the executed path had no UB. Passing extra arguments makes the bad call execute, and Miri then reports the out-of-bounds read.
Exercise
Name two things Miri tracks that a native CPU does not, and say why each lets Miri catch bugs that run "fine" natively.
Show answer
Examples include per-byte initialization flags, allocation sizes and liveness, pointer provenance and borrow tags, and validity ranges for types. A native CPU holds only addresses and bytes. A read past the end of an allocation, a read from freed memory, or a bool holding 3 still produces some value. Miri compares each access against its metadata, so it sees that the access breaks an abstract machine rule and stops.