An interpreter for Rust MIR that detects undefined behavior
Miri is an experimental interpreter for Rust’s Mid-level Intermediate Representation (MIR) that detects undefined behavior, memory errors, and concurrency issues in Rust programs.
Miri executes Rust code at the MIR level and checks for various forms of undefined behavior that could lead to bugs or security vulnerabilities. It’s an essential tool for testing unsafe code and ensuring soundness.
Miri does not catch every violation of the Rust specification. It uses its own approximation of undefined behavior and tests one of many possible executions of your program.
# Run as Linux program (better support than Windows)cargo miri run --target x86_64-unknown-linux-gnu# Test on big-endian architecturecargo miri test --target s390x-unknown-linux-gnu# Test on different pointer widthcargo miri test --target i686-unknown-linux-gnu
Cross-interpretation is particularly useful for testing endian-sensitive code and platform-specific behavior without needing the actual hardware.
# Forward specific environment variableMIRIFLAGS="-Zmiri-env-forward=MY_VAR" cargo miri test# Set environment variable for the programMIRIFLAGS="-Zmiri-env-set=MY_VAR=value" cargo miri run
# Test with 64 different seeds (default)MIRIFLAGS="-Zmiri-many-seeds" cargo miri test# Test with specific range of seedsMIRIFLAGS="-Zmiri-many-seeds=0..16" cargo miri test# Continue even after finding failuresMIRIFLAGS="-Zmiri-many-seeds-keep-going" cargo miri test
Different seeds can reveal bugs that only occur under specific thread interleavings or memory layouts.
#[test]#[cfg_attr(miri, ignore)]fn test_requires_native_io() { // This test uses features Miri doesn't support std::fs::read("file.txt").unwrap();}// Or check at runtime#[test]fn conditional_test() { if cfg!(miri) { // Simplified version for Miri } else { // Full native test }}
# Make floating-point fully deterministicMIRIFLAGS="-Zmiri-deterministic-floats" cargo miri test# Disable extra rounding errorsMIRIFLAGS="-Zmiri-no-extra-rounding-error" cargo miri test