Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

miri

> 编程语言
Open source

An interpreter for Rust's mid-level intermediate representation

6.5K stars0 likes3 views
WebsiteGitHub

About

An interpreter for Rust's mid-level intermediate representation

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_unchecked being reached, calling copy_nonoverlapping with overlapping ranges, ...)
  • Not sufficiently aligned memory accesses and references
  • Violation of basic type invariants (a bool that 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 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:

  • 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-layout to 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-gnu to 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:

bash
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:

rust
#[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:

bash
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-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).

Nextest integration

Miri can be combined with cargo-nextest:

cargo install --locked cargo-nextest
cargo miri nextest run

Nextest spawns a separate instance of Miri for each test, which has several advantages:

  • Tests can run in parallel. Miri itself only uses a single thread per interpreter so this can give a massive speedup (but see the caveat below).
  • Tests do not stop when a single problem is found. Miri aborts execution when it encounters Undefined Behavior or an unsupported operation (there is often not really any way to continue), so once a single test fails, the remaining tests cannot be executed. Nextest's process-per-test model means that you end up with a full list of which tests worked in Miri and which tests had a problem.

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.

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

Miri 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.

Running Miri on CI

When running Miri on CI, use the following snippet to install a nightly toolchain with the Miri component:

bash
rustup toolchain install nightly --component miri
rustup override set nightly

cargo miri test

Here is an example job for GitHub Actions:

yaml
  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 test

The expl

Issues· 192 open

View all issuesOpen on GitHub
  • #5344

    `available_parallelism` misbehaves on FreeBSD

    C-bugA-shimsA-freebsdUpdated Sep 24, 2026
  • #5335

    windows-fs test fails when run natively

    C-bugA-testsA-windowsUpdated Sep 20, 2026
  • #5326

    dirfd support is racy

    C-bugA-shimsUpdated Sep 19, 2026
  • #5327

    Get rid of Miri hack in DirEntry::metadata

    Updated Sep 19, 2026
  • #5323

    Improve random scheduler to consider more "interesting" interleavings

    C-proposalA-concurrencyUpdated Sep 19, 2026
  • #5320

    Miri computes 2.0f64.powi(63) as 2^63 − 2048 instead of exactly 2^63, and thereby misses the float_to_int_unchecked UB

    Updated Sep 19, 2026
  • #5321

    *ptr += 1 through a with_exposed_provenance_mut pointer is not reported as UB while *ptr = 1 is

    Updated Sep 18, 2026
  • #4066

    Backtraces stop at thread boundaries

    C-enhancementE-good-first-issueA-diagnosticsUpdated Sep 11, 2026
  • #5314

    Casting `extern fn` to usize or fn pointer has changing address

    Updated Sep 10, 2026
  • #5310

    ICE in Miri with `unsized_fn_params` and C-variadics

    C-bugS-blocked-on-rustA-interpreterI-ICEUpdated Sep 6, 2026

> Tags

Rust

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 24, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言