Sub topic 4
Installing Miri and running your code and tests
This chapter covers installing Miri, running a binary or test suite under it, and what to expect from the first runs. It assumes you know Rust ownership, borrowing and lifetimes, basic Cargo usage (cargo run, cargo test), raw pointers and the unsafe keyword, and how to install toolchains and components with rustup.
What you need before you start
Miri is not shipped with the stable toolchain. It is a rustup component that is available on the nightly toolchain, because it depends on compiler internals that change often. You can still develop on stable. You only use nightly to run Miri.
The pieces involved are:
rustup, which installs toolchains and components.- The nightly toolchain, which provides the compiler internals Miri needs.
- The
miricomponent, which provides thecargo mirisubcommand. - The
rust-srccomponent, which Miri needs to build a copy of the standard library that it can interpret.cargo mirisets this up for you on first use.
Installing Miri
Install the component on the nightly toolchain:
rustup +nightly component add miriThe +nightly prefix selects the toolchain for a single command. rustup installs nightly first if it is missing. You can check the result with cargo +nightly miri --version.
Miri is built from the same source as the nightly compiler, so the component is only available on nightly builds where it compiled successfully. If a given nightly lacks Miri, rustup reports that the component is unavailable. Installing an earlier nightly, for example rustup toolchain install nightly-2026-11-20 --component miri, resolves it. Substitute a date that exists.
Once Miri is installed, run this one-time setup:
cargo +nightly miri setupThis builds a special version of the standard library for Miri and caches it. It runs automatically the first time you use cargo miri run or cargo miri test, so the explicit command is optional. It is useful in CI and in containers, where you may want setup to happen in a separate, cacheable step.
Making nightly the default for a project
Typing +nightly each time is tedious. You can pin the toolchain for a directory with an override:
rustup override set nightlyYou can also add a rust-toolchain.toml file at the project root. Be careful with this. It changes the toolchain for everything in the project, including regular builds. Many projects prefer to keep stable as the project toolchain and use +nightly only for Miri.
Running a binary under Miri
The two commands you will use most are cargo miri run and cargo miri test:
cargo +nightly miri test
cargo +nightly miri runcargo miri run builds your binary for the interpreter and executes it. cargo miri test does the same for the test suite. Both accept the usual Cargo arguments. For example, cargo +nightly miri test my_test runs only tests whose names contain my_test, and cargo +nightly miri run -- --some-arg passes arguments to your program.
A first example: out-of-bounds access
Create a new binary crate with cargo new miri-demo and put the following in src/main.rs. It reads one element past the end of a three-element Vec:
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
let x = unsafe { *p.add(3) };
println!("{x}");
}Run it natively with cargo run. On most machines it prints some number and exits normally. The allocator usually has spare bytes after the Vec, so the read lands in memory your process owns, and nothing visibly fails. The program is still wrong. It has undefined behavior, and a different allocator, a different optimization level, or a later compiler release can change what it does.
Now run it under Miri:
cargo +nightly miri runMiri stops with an error. The first line of the report says Undefined Behavior and describes an out-of-bounds pointer use, with the allocation size and the offset you tried to read. It then points to the source line and shows a backtrace. The next chapter explains each part of that report in detail. For now, notice the difference. The native run succeeded and Miri did not, because Miri tracks the bounds of each allocation and checks every access against them.
What happens when you run `cargo miri`
It helps to know what the command does so you can predict its behavior.
- Cargo builds your crate and its dependencies, but
cargo mirireplacesrustcwith a wrapper. The wrapper compiles your code to MIR, the compiler's mid-level intermediate representation, and does not generate machine code. - The Miri interpreter runs that MIR one operation at a time. It keeps its own model of memory, with allocations, pointer provenance and borrow state, and checks each operation against Rust's rules.
- Build scripts and procedural macros run natively, since they are compile-time tools. Only the final program and its tests run in the interpreter.
- If the program executes undefined behavior, Miri prints an error and exits with a nonzero status. If the program finishes with no violation, it exits as the program itself would.
Two consequences follow. First, cargo miri test runs the test code itself in the interpreter, not just the code under test. Second, the interpreter works on a target you can choose, but by default it uses your host target. You can check other targets, such as a big-endian one, with --target:
cargo +nightly miri test --target s390x-unknown-linux-gnuThis is useful for finding code that assumes a particular byte order or pointer width, and it needs no cross-compilation toolchain or emulator, since Miri interprets the code itself.
Running the test suite
Running cargo +nightly miri test executes every unit test, integration test and doc test under the interpreter. Consider a small test that uses a raw pointer correctly:
use std::mem::MaybeUninit;
fn main() {
let mut slot = MaybeUninit::<u32>::uninit();
slot.write(7);
let value = unsafe { slot.assume_init() };
println!("{value}");
}Run as a binary, this passes under Miri with no output beyond 7, because the value is written before assume_init is called. A passing run is the normal outcome for correct code. Miri is quiet unless something is wrong.
Test output and failures
Miri reports undefined behavior as an error that aborts the interpreter. A test that triggers undefined behavior therefore does not fail like an ordinary assertion. The whole test process stops, and the remaining tests do not run in that invocation. This matters in practice. When you see an undefined-behavior error, fix it and rerun to find the next one. Ordinary assertion failures and panics behave as they do natively.
You can narrow a run to the code you are investigating:
cargo +nightly miri test --lib
cargo +nightly miri test my_unsafe_moduleDoc tests deserve a note. They are compiled and run as separate programs, so cargo miri test runs them too, and they are often slower than unit tests. Use --lib, --test <name> or --doc to select which kind you want.
Why Miri runs slowly
Interpreting each operation and checking it against a memory model is expensive. Expect Miri to run a program anywhere from tens to hundreds of times slower than native code. Heavy numeric loops and tests with large inputs are the usual problem.
Practical ways to cope:
- Run Miri on the crates and modules that contain
unsafe, not on every test in a large workspace. - Filter by test name while you debug.
- Reduce the workload under Miri with
cfg(miri), covered in a later chapter on Miri-friendly tests.
Common problems when starting out
| Symptom | Likely cause | What to do |
|---|---|---|
| `no such command: miri` | The component is not installed for the toolchain you ran | Run `rustup +nightly component add miri` and use `cargo +nightly miri` |
| Component unavailable on nightly | That nightly build did not include Miri | Install a slightly older nightly |
| Long delay on first run | Miri is building its standard library | Wait once, or run `cargo +nightly miri setup` ahead of time |
| Error about unsupported operation | The program calls something Miri cannot emulate, such as some system calls or FFI | Gate the code with `cfg(miri)` or skip that test under Miri |
| Program hangs or times out | Heavy computation is too slow under interpretation | Shrink the input or the iteration count |
The unsupported-operation error is different from an undefined-behavior error. It means Miri does not know how to execute something. It says nothing about whether your code is correct. Miri does not run foreign C code, for example, so tests that call into C libraries cannot run under it.
A second case: use after free
Try one more example before moving on. The pointer is read after the Box that owned the allocation was dropped:
fn main() {
let p = Box::into_raw(Box::new(5));
unsafe {
drop(Box::from_raw(p));
println!("{}", *p);
}
}Natively this often prints 5, because freed memory is rarely overwritten right away. Under cargo +nightly miri run, Miri reports that it tried to read memory that was already deallocated, and it names the line where the allocation was freed. Two different bugs, an out-of-bounds read and a use after free, show up through the same workflow. You run the command and read the report.
A diagram of the workflow
Summary of commands
| Task | Command |
|---|---|
| Install Miri | `rustup +nightly component add miri` |
| Build the Miri standard library | `cargo +nightly miri setup` |
| Run the binary | `cargo +nightly miri run` |
| Run all tests | `cargo +nightly miri test` |
| Run one test by name | `cargo +nightly miri test name` |
| Check another target | `cargo +nightly miri test --target <triple>` |
Exercise
You run cargo +nightly miri test on a crate. The first test that triggers undefined behavior stops the run, and three later tests never execute. A colleague says that means those three tests pass. Is that right, and what should you do next?
Show answer
No. Miri aborts the process at the first undefined-behavior error, so the later tests were not run and nothing is known about them. Fix the reported problem, then rerun. You can also run the remaining tests by name, for example cargo +nightly miri test test_name, to see their results before the fix is done.
Exercise
The out-of-bounds read of *p.add(3) prints a number natively but fails under Miri. Why can the native run succeed, and why does that not make the program correct?
Show answer
The read usually lands in memory the process owns, such as spare allocator space, so the hardware raises no fault. The program still violates Rust's rules, so its behavior is undefined and can change with the allocator, optimization level or compiler version. Miri tracks the bounds of each allocation and rejects any access outside them.