Sub topic 8
Configuring Miri with MIRIFLAGS
This chapter assumes you can already run cargo miri test and read a basic Miri report. It also assumes you know what an aliasing violation is and that you can set an environment variable in your shell. The goal is to change how Miri behaves without editing your code.
How MIRIFLAGS works
Miri reads the MIRIFLAGS environment variable and passes its contents to the interpreter. Each Miri option starts with -Zmiri-. You separate several options with spaces, so quote the whole value.
MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri testThree things are easy to confuse here:
MIRIFLAGSconfigures the interpreter. It does not change how your code is compiled.RUSTFLAGSconfigures the compiler.cargo mirihas its own handling of it, so don't put-Zmiri-options there.- Arguments after
--on thecargo miri testcommand line go to the test harness (for example a test name filter). They never go to Miri.
On Windows PowerShell, set the variable first with $env:MIRIFLAGS="-Zmiri-tree-borrows" and then run the command.
# two flags, one quoted string
MIRIFLAGS="-Zmiri-tree-borrows -Zmiri-backtrace=full" cargo +nightly miri test
# test filter goes after --, not in MIRIFLAGS
cargo +nightly miri test -- my_unsafe_testThe set of flags changes between nightlies. If Miri rejects an option, check the README of the miri repository for your toolchain's version.
Choosing the aliasing model
The most common reason to set MIRIFLAGS is to pick the aliasing model. Stacked Borrows is the default. Tree Borrows is an alternative model that is more permissive in some patterns and stricter in others.
MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri testUse it when:
- You want to know whether a Stacked Borrows error also appears under the newer model. If your code passes under both, you can be more confident about it.
- Stacked Borrows rejects a pattern that you believe is reasonable. Check that the pattern also holds under Tree Borrows before you decide the code is fine.
- A dependency or the standard library is moving toward Tree Borrows semantics, and you want to test against it.
The model you choose affects which reports you see. A program can fail under one model and pass under the other, so a pass under one is not a pass under both. The related flag -Zmiri-disable-stacked-borrows turns aliasing checks off entirely. Use it only to confirm that an error comes from the aliasing rules and not from something else. Do not leave it on.
Controlling provenance checks
Pointer provenance records which allocation a pointer may access. Miri's default is lenient about pointer-to-integer casts. Two flags change that:
-Zmiri-strict-provenancerejects integer-to-pointer casts that would need Miri to guess which allocation you meant. Use it if your crate follows the strict provenance APIs such aswith_addrandmap_addr.-Zmiri-permissive-provenancesilences the warning that Miri prints when it sees an integer-to-pointer cast.
Strict mode is a useful CI check for code that claims not to depend on casting integers back to pointers. A related flag, -Zmiri-symbolic-alignment-check, makes Miri check alignment from the pointer's declared alignment instead of its concrete address. This catches code that is only correctly aligned by luck.
Seeds and concurrency
Miri makes random choices: how to schedule threads, and what addresses to give allocations. By default each run uses the same seed, so results repeat. A data race that depends on one specific interleaving may not show up under the default.
Take the race from the data-races chapter:
use std::thread;
static mut COUNTER: u32 = 0;
fn main() {
let h = thread::spawn(|| unsafe {
COUNTER += 1;
});
unsafe {
COUNTER += 1;
}
h.join().unwrap();
}Run it with different seeds:
MIRIFLAGS="-Zmiri-seed=1" cargo +nightly miri run
MIRIFLAGS="-Zmiri-seed=2" cargo +nightly miri runTyping seeds by hand is slow. -Zmiri-many-seeds runs the program once per seed in a range and stops at the first failure:
MIRIFLAGS="-Zmiri-many-seeds=0..32" cargo +nightly miri testThe failing run prints its seed, so you can reproduce it with -Zmiri-seed=N while you debug. Two related flags tune the scheduler. -Zmiri-preemption-rate=0.1 sets how often Miri switches threads, and -Zmiri-disable-data-race-detector turns the race checker off. Keep the detector on unless you are isolating a different problem.
Isolation
By default Miri runs your program in isolation. Code cannot read the host's files, environment variables, or real clock, and operations that need them fail with an "unsupported operation" error. Isolation makes runs repeatable and keeps the interpreter from touching your machine.
use std::fs;
fn main() {
let text = fs::read_to_string("Cargo.toml").unwrap();
println!("{}", text.len());
}Under default Miri this stops with an error saying the operation is not available when isolation is enabled. Pass -Zmiri-disable-isolation to allow it:
MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri runThere are gentler options:
-Zmiri-isolation-error=warnprints a warning and lets the call fail normally, instead of aborting. Use it when the test handles the failure.-Zmiri-env-forward=NAMEpasses one named environment variable into the interpreted program, so you don't need to open everything.
Disabling isolation lets the program see the host. It also makes results depend on that host, so prefer the narrower options when they are enough.
Leaks, backtraces and other useful flags
Miri reports memory that is still allocated and unreachable when the program ends. This catches real bugs, but it also fires on code that leaks on purpose.
fn main() {
std::mem::forget(Box::new(42));
}Miri reports a memory leak at exit. If the leak is intended, for example in a short test that deliberately forgets a value, add -Zmiri-ignore-leaks.
The following table lists options you will use most often.
| Flag | Effect | Typical use |
|---|---|---|
| `-Zmiri-tree-borrows` | Use Tree Borrows instead of Stacked Borrows | Compare aliasing models |
| `-Zmiri-seed=N` | Fix the random seed | Reproduce a failure |
| `-Zmiri-many-seeds=A..B` | Run once per seed in the range | Find schedule-dependent bugs |
| `-Zmiri-strict-provenance` | Reject ambiguous integer-to-pointer casts | Enforce provenance discipline |
| `-Zmiri-disable-isolation` | Allow host access | Tests using files, clock, env |
| `-Zmiri-ignore-leaks` | Do not report leaks | Intentional leaks |
| `-Zmiri-backtrace=full` | Print a fuller backtrace | Deep call stacks in reports |
Setting flags in a repeatable way
Typing the variable each time invites mistakes. Put the options in a script or in your CI configuration so everyone runs the same checks. A common setup runs two jobs: one with the defaults and one with extra checks.
#!/bin/sh
set -e
# default model
cargo +nightly miri test
# alternative aliasing model plus strict provenance
MIRIFLAGS="-Zmiri-tree-borrows -Zmiri-strict-provenance" cargo +nightly miri test
# many schedules for the threaded tests only
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri test threadedNote that setting MIRIFLAGS replaces any earlier value in that shell. If you want to extend an existing value, write MIRIFLAGS="$MIRIFLAGS -Zmiri-...".
Common mistakes
- Putting
-Zmiri-options inRUSTFLAGS. The compiler does not know them, and Miri does not read them from there. - Forgetting quotes around several flags. The shell then treats the second one as a command.
- Concluding that code is sound because it passed under one model or one seed. Each flag changes what is checked, and none of them proves the absence of undefined behavior.
- Leaving
-Zmiri-disable-isolation,-Zmiri-ignore-leaksor-Zmiri-disable-stacked-borrowson permanently. These reduce what Miri can tell you. Use them to answer a specific question, then remove them.
Exercise
A test that spawns two threads passes under cargo +nightly miri test, but a colleague suspects a data race that depends on thread scheduling. Which MIRIFLAGS value would you use to look for it, and how would you then reproduce a failure that it finds?
Show answer
Run with MIRIFLAGS="-Zmiri-many-seeds=0..32" cargo +nightly miri test to try many schedules. When one fails, Miri prints the seed. Rerun with MIRIFLAGS="-Zmiri-seed=N" using that seed to reproduce the same interleaving while you debug.
Exercise
Your program reads Cargo.toml with std::fs::read_to_string, and Miri stops with an unsupported-operation error. Name two ways to deal with it and say which is narrower.
Show answer
Pass -Zmiri-disable-isolation to allow host access, or use -Zmiri-isolation-error=warn so the call fails with a warning and the program continues. For environment variables, -Zmiri-env-forward=NAME is narrower still. Better yet, avoid host access in the code under test. -Zmiri-isolation-error=warn and -Zmiri-env-forward expose less of the host than disabling isolation completely.