Sub topic 13
Finding undefined behavior with Miri
This chapter assumes you have read the earlier chapters on undefined behavior, raw pointers, safety contracts, and safe abstractions. You should also be comfortable running cargo run and cargo test. By the end you will be able to install Miri, run programs and tests under it, read its error reports, and judge what a clean run does and does not prove.
What Miri is
Miri is an interpreter for Rust's mid-level intermediate representation (MIR). The normal compiler turns your code into machine instructions and trusts that you followed the rules. Miri runs the program step by step on a virtual machine. It tracks every allocation, every pointer's origin, and every initialized byte, and it stops at the first operation that breaks a rule of the language.
This makes it the main tool for checking that unsafe code upholds its safety contracts. Undefined behavior (UB) often produces no visible symptom on your machine. Miri turns that silent corruption into a precise error message.
The kinds of UB Miri detects include:
- Out-of-bounds and use-after-free memory accesses.
- Misaligned pointer reads and writes.
- Reads of uninitialized memory.
- Invalid values, such as a
boolthat holds 2. - Violations of the aliasing rules for references.
- Data races between threads.
- Memory leaks, reported when the program ends.
Installing and running Miri
Miri ships as a rustup component for the nightly toolchain. Your project can stay on stable. You only need nightly to run the checker.
rustup +nightly component add miri
cargo +nightly miri run
cargo +nightly miri testcargo miri run interprets your binary. cargo miri test interprets your test suite, which is usually the better habit. Tests exercise a library's API the way callers do, and each test is a small, fast Miri run.
The first run builds a special copy of the standard library, which takes a while. Later runs reuse it.
Reading a Miri report
Start with a program that has a bug. It reads one element past the end of a vector through a raw pointer.
fn main() {
let v = vec![1u32, 2, 3];
let p = v.as_ptr();
// BUG: index 3 is one past the end of a 3-element vector.
let x = unsafe { *p.add(3) };
println!("{x}");
}Normally this program runs and prints some number. Under Miri it stops with an error that begins error: Undefined Behavior. The message says the access was out of bounds, gives the size of the allocation (12 bytes) and the offset that was read. It also points at the source line and shows where the allocation was created.
Read these parts in order:
- The first line names the category of UB.
- The arrow and source snippet show the operation that was executed.
- The notes below it show where the memory or pointer came from.
Miri stops at the first error. Fix it and run again, because later bugs may be hidden behind it.
Common categories and what they look like
| Bug | Typical cause | What Miri reports |
|---|---|---|
| Out-of-bounds access | `ptr.add(n)` past the end | Access beyond the end of the allocation |
| Use after free | Pointer kept after `drop` or after a `Vec` reallocates | Pointer to a deallocated allocation |
| Invalid value | `transmute` or `assume_init` producing a bad `bool`, `char`, or enum | Constructing an invalid value |
| Uninitialized read | `assume_init` before writing | Using uninitialized data |
| Misalignment | Casting `*const u8` to `*const u32` | Accessing memory with insufficient alignment |
| Aliasing violation | Using a raw pointer after a conflicting `&mut` | A borrow-model error naming the tag that was invalidated |
| Data race | Unsynchronized access from two threads | Data race detected |
The exact wording changes between nightly versions, so search for the category and not the full string.
An invalid value
fn main() {
// BUG: only 0 and 1 are valid bit patterns for bool.
let b: bool = unsafe { std::mem::transmute::<u8, bool>(2) };
println!("{}", b);
}Miri reports that it encountered 0x02 but expected a boolean. This example shows that UB is about the value you construct, not about when you use it. The error appears at the transmute, before the println!.
An aliasing violation
Aliasing bugs are the hardest to find by reading code. Here a raw pointer is created, then a new &mut borrow of the same variable invalidates it.
fn main() {
let mut x = 0u32;
let p = &mut x as *mut u32;
let r = &mut x; // new unique borrow: p is no longer allowed to access x
*r += 1;
// BUG: p's permission was taken away by the borrow above.
unsafe { *p += 1 };
println!("{x}");
}This compiles without a warning and probably prints 2. Miri rejects it, because the write through p happens after p lost its right to access x. The report names the pointer's tag (a label Miri attaches to each borrow) and shows where it was created and where it was invalidated. The rule to take away is that a raw pointer derived from a reference stays usable only while that reference's borrow is still the active one for the memory.
Testing a safe abstraction
The real benefit comes from testing the safe wrappers you wrote in earlier chapters. This version of split_at_mut has an off-by-one error in the second slice and no assert!:
use std::slice;
fn split_at_mut_buggy(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = values.len();
let ptr = values.as_mut_ptr();
// BUG: the second slice is one element too long.
unsafe {
(
slice::from_raw_parts_mut(ptr, mid),
slice::from_raw_parts_mut(ptr.add(mid), len - mid + 1),
)
}
}
fn main() {
let mut data = [1, 2, 3, 4, 5];
let (left, right) = split_at_mut_buggy(&mut data, 2);
left[0] = 10;
right[0] = 30;
println!("{:?} {:?}", left, right);
}On a normal build this prints plausible output. Miri reports that the second slice reaches beyond the 20-byte array. The mistake is in the unsafe block, but the safe signature lets any caller trigger it. That makes the function unsound, and a test run under Miri finds it quickly.
Write tests that cover the boundaries of every safe API built on unsafe code: mid = 0, mid = len, empty slices, and zero-sized types. Edge values are where pointer arithmetic goes wrong.
Useful flags
Pass flags through the MIRIFLAGS environment variable:
MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri test
MIRIFLAGS="-Zmiri-symbolic-alignment-check -Zmiri-strict-provenance" cargo +nightly miri test
MIRIFLAGS="-Zmiri-many-seeds=0..32" cargo +nightly miri test-Zmiri-tree-borrowsswitches from the default aliasing model (Stacked Borrows) to Tree Borrows. Tree Borrows accepts some patterns the default rejects. If your code passes only under one model, treat that as a warning sign, since the rules are still being finalized.-Zmiri-symbolic-alignment-checkchecks alignment from the pointer's declared type and allocation. Without it, Miri checks the real address, so a misaligned access can pass by luck.-Zmiri-strict-provenancerejects integer-to-pointer casts that lose track of which allocation a pointer belongs to.-Zmiri-many-seedsrepeats the run with different seeds for thread scheduling and allocation addresses. This helps find races and address-dependent bugs.-Zmiri-disable-isolationallows access to the real clock, environment, and file system. By default Miri blocks these.
What a clean run does not prove
Keep these limits in mind:
- Speed. Interpretation is often tens to hundreds of times slower than native code. Keep Miri tests small. You can skip heavy tests with
#[cfg_attr(miri, ignore)]. - Foreign code. Miri cannot execute arbitrary C functions, so code that calls into C libraries cannot be fully checked. It does emulate some common system functions.
- Model changes. The aliasing rules are still being specified. A pattern that passes today could be ruled out later.
- Platform. It interprets one target. Bugs that depend on another platform's layout need
--targetruns. - Hardware behavior. It does not model every real-world behavior, such as weak memory ordering on specific CPUs.
Combine Miri with the review practices from the next chapter. Miri finds bugs in what you ran, and review covers what you did not run.
Exercise
A colleague runs cargo +nightly miri test on a crate that casts a *const u8 into a *const u32 and reads it. The tests pass. Give two reasons the code might still be unsound, and name one Miri flag that could change the result.
Show answer
First, Miri only checks executed paths, so an input or schedule not covered by the tests may still cause UB. Second, by default Miri checks alignment against the actual address of the allocation, so a misaligned read can pass by luck when the buffer happens to land on a 4-byte boundary. Running with -Zmiri-symbolic-alignment-check checks alignment from the declared type and would catch it. Using ptr.read_unaligned() is the fix when alignment cannot be guaranteed.
Exercise
In the aliasing example, the program creates p from &mut x, then creates r = &mut x and uses it, then writes through p. Which single reordering of the statements makes the program free of UB?
Show answer
Finish all uses of r before touching p and never use r afterward, or do the write through p before creating r. For example, moving unsafe { *p += 1 }; above let r = &mut x; removes the conflict, because p still has its access when it is used. Miri would then accept the program.