An interpreter for Rust's mid-level intermediate representation
An interpreter for Rust's mid-level intermediate representation
Miri is an Undefined Behavior detection tool for Rust. It can run binaries and test suites of cargo projects and detect unsafe code that fails to uphold its safety requirements. For instance:
unreachable_unchecked being
reached, calling copy_nonoverlapping with overlapping ranges, ...)bool that is not 0 or 1, for example,
or an invalid enum discriminant)On top of that, Miri will also tell you about memory leaks: when there is memory
still allocated at the end of the execution, and that memory is not reachable
from a global static, Miri will raise an error.
You can use Miri to emulate programs on other targets, e.g. to ensure that byte-level data manipulation works correctly both on little-endian and big-endian systems. See cross-interpretation below.
Miri has already discovered many real-world bugs. If you found a bug with Miri, we'd appreciate if you tell us and we'll add it to the list!
By default, Miri ensures a fully deterministic execution by isolating the
program from the host system. Some APIs that would usually access the host, such
as gathering entropy for random number generators, environment variables, and
clocks, are replaced by deterministic "fake" implementations. Set
MIRIFLAGS="-Zmiri-disable-isolation" to access the real system APIs instead.
(Note that this isolation is not a proper sandbox, and gaps in the isolation are considered
normal bugs, not security bugs. Also, the "fake" system RNG APIs make Miri not suited for
cryptographic use! Do not generate keys using Miri.)
All that said, be aware that Miri does not catch every violation of the Rust specification in your program, not least because there is no such specification. Miri uses its own approximation of what is and is not Undefined Behavior in Rust. To the best of our knowledge, all Undefined Behavior that has the potential to affect a program's correctness is being detected by Miri (modulo bugs), but you should consult the Reference for the official definition of Undefined Behavior. Miri will be updated with the Rust compiler to protect against UB as it is understood by the current compiler, but it makes no promises about future versions of rustc.
Further caveats that Miri users should be aware of:
-Zrandomize-layout
to detect some of these cases.)-Zmiri-seed, but that will still by far not explore all possible executions.--target x86_64-unknown-linux-gnu to get
better support.Moreover, Miri fundamentally cannot ensure that your code is sound. Soundness is the property of never causing undefined behavior when invoked from arbitrary safe code, even in combination with other sound code. In contrast, Miri can just tell you if a particular way of interacting with your code (e.g., a test suite) causes any undefined behavior in a particular execution (of which there may be many, e.g. when concurrency or other forms of non-determinism are involved). When Miri finds UB, your code is definitely unsound, but when Miri does not find UB, then you may just have to test more inputs or more possible non-deterministic choices.
Install Miri on Rust nightly via rustup:
rustup +nightly component add miriAll the following commands assume the nightly toolchain is pinned via rustup override set nightly.
Alternatively, use cargo +nightly for each of the following commands.
Now you can run your project in Miri:
cargo miri test.cargo miri run.The first time you run Miri, it will perform some extra setup and install some dependencies. It will ask you for confirmation before installing anything.
cargo miri run/test supports the exact same flags as cargo run/test. For
example, cargo miri test filter only runs the tests containing filter in
their name.
You can pass [flags][miri-flags] to Miri via MIRIFLAGS. For example,
MIRIFLAGS="-Zmiri-disable-stacked-borrows" cargo miri run runs the program
without checking the aliasing of references.
When compiling code via cargo miri, the cfg(miri) config flag is set for code
that will be interpreted under Miri. You can use this to ignore test cases that fail
under Miri because they do things Miri does not support:
#[test]
#[cfg_attr(miri, ignore)]
fn does_not_work_on_miri() {
tokio::run(futures::future::ok::<_, ()>(()));
}There is no way to list all the infinite things Miri cannot do, but the interpreter will explicitly tell you when it finds something unsupported:
error: unsupported operation: can't call foreign function: bind
...
= help: this is likely not a bug in the program; it indicates that the program \
performed an operation that Miri does not supportMiri can not only run a binary or test suite for your host target, it can also
perform cross-interpretation for arbitrary foreign targets: cargo miri run --target x86_64-unknown-linux-gnu will run your program as if it was a Linux
program, no matter your host OS. This is particularly useful if you are using
Windows, as the Linux target is much better supported than Windows targets.
You can also use this to test platforms with different properties than your host
platform. For example cargo miri test --target s390x-unknown-linux-gnu
will run your test suite on a big-endian target, which is useful for testing
endian-sensitive code.
Controlling target features works similar to regular rustc invocations:
RUSTFLAGS="-Ctarget-feature=+avx512f" cargo miri test runs the tests with AVX512 enabled. (Miri
only supports very few AVX512 intrinsics at the moment.) -Ctarget-cpu also works. If target
features are also relevant for doctests, you have to also set RUSTDOCFLAGS.
Unlike regular rustc, this flag has two effects: it builds the code with that target feature
available (which affects cfg(target_feature)), and it tells Miri to consider the "virtual CPU"
that the interpreted program runs on as having the feature available (meaning the code is allowed to
invoke the corresponding intrinsics).
Miri can be combined with cargo-nextest:
cargo install --locked cargo-nextest
cargo miri nextest runNextest spawns a separate instance of Miri for each test, which has several advantages:
However, there is also a big caveat: Miri will re-compile the test crate every time it is invoked, which means a crate with N tests will be compiled N+1 times. If the test crate takes a long time to build, this can outweigh the benefits of parallelization.
For more information about nextest, see the cargo-nextest Miri
documentation.
Note: Nextest's one-test-per-process model means that cargo miri test is able to detect data
races where two tests race on a shared resource, but cargo miri nextest run will not detect
such races.
Note: cargo-nextest does not support doctests.
Certain parts of the execution are picked randomly by Miri, such as the exact base address
allocations are stored at and the interleaving of concurrently executing threads. Sometimes, it can
be useful to explore multiple different execution, e.g. to make sure that your code does not depend
on incidental "super-alignment" of new allocations and to test different thread interleavings.
This can be done with the -Zmiri-many-seeds flag:
MIRIFLAGS="-Zmiri-many-seeds" cargo miri test # tries the seeds in 0..64
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo miri testMiri will test the given range of seeds with parallel interpreter instances. The default of 64 different seeds can be quite slow, so you often want to specify a smaller range.
When running Miri on CI, use the following snippet to install a nightly toolchain with the Miri component:
rustup toolchain install nightly --component miri
rustup override set nightly
cargo miri testHere is an example job for GitHub Actions:
miri:
name: "Miri"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Miri
run: |
rustup toolchain install nightly --component miri
rustup override set nightly
cargo miri setup
- name: Test with Miri
run: cargo miri testThe expl
`available_parallelism` misbehaves on FreeBSD
windows-fs test fails when run natively
dirfd support is racy
Get rid of Miri hack in DirEntry::metadata
Improve random scheduler to consider more "interesting" interleavings
Miri computes 2.0f64.powi(63) as 2^63 − 2048 instead of exactly 2^63, and thereby misses the float_to_int_unchecked UB
*ptr += 1 through a with_exposed_provenance_mut pointer is not reported as UB while *ptr = 1 is
Backtraces stop at thread boundaries
Casting `extern fn` to usize or fn pointer has changing address
ICE in Miri with `unsized_fn_params` and C-variadics