Sub topic 1
Finding Undefined Behavior in Unsafe Rust with Miri
Prerequisites
This chapter assumes Rust ownership, borrowing, and lifetimes; basic Cargo commands; raw pointers; unsafe; and installing toolchains with rustup.
What Unsafe Rust Lets You Do
An unsafe block permits operations that the compiler cannot fully verify. These include dereferencing raw pointers, calling unsafe functions, accessing mutable statics, using union fields, and calling foreign functions.
unsafe does not make an operation safe. It moves responsibility to the programmer. You must maintain the rules that safe Rust normally checks, such as valid pointer alignment, initialized values, correct lifetimes, and non-conflicting access.
Undefined Behavior and Why Tests Can Miss It
Undefined behavior (UB) means the Rust program breaks requirements that the language depends on. The compiler may then assume the impossible never happens. Results can include incorrect output, crashes, or behavior that changes after an unrelated optimization.
A test can miss UB because it runs only one path, input, or thread schedule. An invalid pointer might happen to point into readable memory during a particular run.
Miri: An Interpreter That Checks as It Executes
Miri runs Rust's intermediate representation (MIR) in an interpreter. As executed code performs operations, Miri checks many rules involving memory, values, pointers, aliasing, and data races.
Installing Miri and Running Code and Tests
Miri is distributed as a component for the nightly Rust toolchain:
rustup +nightly component add miri
cargo +nightly miri test
cargo +nightly miri runFor example, this reads one element beyond a three-element vector:
fn main() {
let values = vec![10, 20, 30];
let pointer = values.as_ptr();
let value = unsafe { *pointer.add(3) };
println!("{value}");
}Native execution may appear to work. Miri reports the out-of-bounds access when that line executes.
> warning > Miri checks executed paths. A successful run does not prove that every input and schedule is free from UB.
Reading a Miri Error Report
Start at the error kind, such as “out-of-bounds pointer arithmetic” or “use-after-free.” Then find the source location where the invalid operation occurred. The backtrace shows the calls that led there. Finally, inspect the allocation and pointer details to determine which lifetime or bounds assumption failed.
The fix usually belongs at the point where the pointer is created or derived, not where the diagnostic becomes visible.
Exercise
Why can a native test pass while Miri reports undefined behavior?
Show answer
The test may execute an invalid operation whose effects happen to look harmless for that run. Miri checks the violated rule directly.