Miri
An interpreter for Rust's mid-level intermediate representation
Install / Use
/learn @rust-lang/MiriREADME
Miri
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:
- Out-of-bounds memory accesses and use-after-free
- Invalid use of uninitialized data
- Violation of intrinsic preconditions (an
unreachable_uncheckedbeing reached, callingcopy_nonoverlappingwith overlapping ranges, ...) - Not sufficiently aligned memory accesses and references
- Violation of basic type invariants (a
boolthat is not 0 or 1, for example, or an invalid enum discriminant) - Data races and emulation of some weak memory effects, i.e., atomic reads can return outdated values
- Experimental: Violations of the Stacked Borrows rules governing aliasing for reference types
- Experimental: Violations of the Tree Borrows aliasing rules, as an optional alternative to Stacked Borrows
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 and isolates 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.
(In particular, 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:
- If the program relies on unspecified details of how data is laid out, it will
still run fine in Miri -- but might break (including causing UB) on different
compiler versions or different platforms. (You can use
-Zrandomize-layoutto detect some of these cases.) - Program execution is non-deterministic when it depends, for example, on where
exactly in memory allocations end up, or on the exact interleaving of
concurrent threads. Miri tests one of many possible executions of your
program, but it will miss bugs that only occur in a different possible execution.
You can alleviate this to some extent by running Miri with different
values for
-Zmiri-seed, but that will still by far not explore all possible executions. - Miri runs the program as a platform-independent interpreter, so the program
has no access to most platform-specific APIs or FFI. A few APIs have been
implemented (such as printing to stdout, accessing environment variables, and
basic file system access) but most have not: for example, Miri currently does
not support networking. System API support varies between targets; if you run
on Windows it is a good idea to use
--target x86_64-unknown-linux-gnuto get better support. - Weak memory emulation is not complete: there are legal behaviors that Miri will never produce. However, Miri produces many behaviors that are hard to observe on real hardware, so it can help quite a bit in finding weak memory concurrency bugs. To be really sure about complicated atomic code, use specialized tools such as loom.
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.
Using Miri
Install Miri on Rust nightly via rustup:
rustup +nightly component add miri
All 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:
- To run all tests in your project through Miri, use
cargo miri test. - If you have a binary project, you can run it through Miri using
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 support
Cross-interpretation: running for different targets
Miri 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
Controlling target features works similar to regular rustc invocations:
RUSTFLAGS="-Ctarget-features=+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).
Testing multiple different executions
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 test
The default of 64 different seeds can be quite slow, so you often want to specify a smaller range.
Running Miri on CI
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 test
Here is an example job for GitHub Actions:
miri:
name: "Miri"
runs-on: ubuntu-l
Related Skills
node-connect
337.4kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
83.2kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
337.4kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
83.2kCommit, push, and open a PR
