Module 9 · Lesson 64 of 112

Miri and the undefined-behavior catalog

Run Miri on Rust code, interpret its diagnostics, and classify common undefined behavior and compile-time overflow errors.

  • Beginner to advanced
  • 11 min read
  • 16 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, rustup, and network access to install the nightly toolchain and Miri

Your place in the module
By the end you can 4 objectives
  • Run a binary and a test suite under Miri.
  • Classify failures involving pointer lifetime, alignment, value validity, initialization, aliasing, and data races.
  • Distinguish a Miri diagnostic from a constant evaluation error.
  • Explain what a passing Miri run establishes about the code exercised.
Video coming soonMiri and the undefined-behavior catalog
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Code coverage and CI
  • Rust coverage instrumentation records execution counts that reporting tools map back to source.
  • A covered line can contain an expression that a test run never evaluated.
  • The stable coverage run and the ordinary Cargo test run can include different sets of tests.
01

Running Rust under Miri

4 min read

The testing lessons ended with coverage and CI. This lesson answers how to find undefined behavior with Miri and what UB looks like.

On Linux, mmap(2) gives a process a range of virtual addresses with specified access protections. An embedded program can use a mapping to access a device buffer. The mapping alone tells you very little about whether a particular Rust load is valid. Suppose a field starts one byte into that buffer. The bytes may be readable according to Linux, while a Rust load through a *const u32 still requires proper alignment. The process can continue after some invalid accesses, so a normal test can reach its final assertion and give you the expected answer.

is often shortened to UB. A panic from safe array indexing has defined behavior. An invalid access through a raw pointer can be UB even if the process continues. The compiler can assume that a Rust program follows the rules that exclude UB, so a successful access observed in one native build gives you little evidence about the next build.

Miri interprets Rust's mid-level intermediate representation, called MIR. It executes the operations represented there and maintains information that an ordinary native load lacks. For example, it can track which allocation a pointer refers to, whether that allocation is still live, and which bytes have been initialized. A read can therefore fail inside Miri even when the bytes at the corresponding address in a native execution happen to look reasonable. Miri also models threads and synchronization, which lets it detect data races in an interpreted execution.

Execution under MiriRust testor binaryInterpretMIRCheckprogramstateMemory,values, permissions,threadsContinueexecutionExit from step 3: Violation detectedReport diagnosticRust testor binaryInterpretMIRCheckprogramstateMemory,values, permissions,threadsContinueexecutionExit from step 3: ViolationdetectedReport diagnostic
Miri checks each operation it reaches against the state of the interpreted program.

In a Cargo project, install the nightly component and select it explicitly:

bash
rustup toolchain install nightly --component miri
cargo +nightly miri test
cargo +nightly miri run

Use cargo miri test when your selected toolchain has Miri and you want to execute tests. Use cargo miri run to execute the binary entry point. The explicit +nightly commands above leave the project's usual toolchain selection alone. A library crate without a binary target can use the test command. To investigate one test in a larger suite, put its name after test, as in cargo +nightly miri test reads_value.

When Miri reports UB, start at the operation it identifies and then read the call stack to find how your code reached it. For a stale pointer, the diagnostic may identify the read while the error in your reasoning occurred earlier, when the owner was dropped. For an invalid value, check where the program first produced the typed value. That may be a conversion several calls before the value would have influenced an assertion. Keep the input and the failing operation small enough that you can identify which precondition failed.

Interpretation is slow compared with running compiled machine code. Small tests for a pointer conversion, a buffer operation, or a thread interaction are good candidates. One run executes particular inputs, branches, and thread schedules. A clean result establishes that Miri found no violation in the execution it checked. A different input can reach a different unsafe operation, and another schedule can expose a conflict the observed schedule avoided.

Miri runs in isolation by default and emulates some external operations through shims. Arbitrary native FFI is unavailable in ordinary isolated runs. Disabling isolation permits more host interaction for operations Miri supports. A native library still needs specific support before Miri can use it, and the interpreter cannot check the internal memory operations of native code it does not interpret. If a test stops at an unsupported foreign function, its behavior beyond that call remains untested by that run. For a device-backed buffer, you can put the Rust decoding logic in a function that takes bytes and exercise it with a plain buffer under Miri.

02

The UB catalog

5 min read

For each access, ask what gives the program permission to use those bytes, whether the operation requires alignment, and whether the bytes can represent the promised type. Then ask what other pointers or threads can do to the same memory. These checks give you distinct diagnoses even when the same source line contains the final read.

Requirements in the UB catalogRequirementFailureexampleValid storagePointeridentifieslive storageNull ordanglingdereferenceAllocationlifetimeOwner keepsallocationliveRead afterfreeing a BoxAlignmentAddress meetstypealignmentOrdinarymisalignedu32 loadValue validityBytesrepresent thetypeProduce boolfrom byte 2InitializationValue byteswere writtenReadunwritten u32storageBorrowpermissionsAccessrespectsmutableborrowConflictingindependentpointer writeThreadsynchronizationConflictingaccesses areorderedUnsynchronized plaincounterwritesConstantevaluationRequiredconstantevaluatessuccessfullyOut-of-rangesum rejectedduringcompilation
The catalog groups failures by the requirement that the operation violates.

Null and dangling dereferences. A null raw pointer can serve as a sentinel. Reading a u32 through it is UB because it identifies no storage for that access. A dangling pointer also lacks valid storage for the access, even if its address is nonzero. For example, a raw pointer into a local variable can escape the variable's scope and then be dereferenced after that storage is gone. In both cases, obtaining or storing the raw pointer and reading through it are distinct operations. The read needs valid storage.

Use-after-free. This is a common way to get a dangling pointer. Take a raw pointer to the value owned by a Box<u32>, drop the box, then read through the pointer. The allocation's lifetime ended at the drop. The allocator might still leave the old bytes at the same address, or it might assign that address to a new allocation. Either outcome leaves the old pointer invalid for the read. In the interpreter, allocation identity and lifetime let Miri report the invalid access without waiting for the operating system to revoke access to the address.

Unaligned access. A u32 load through an ordinarily dereferenced raw pointer requires an address aligned for u32. Consider an array of two initialized u32 values. A pointer one byte past the start of that array can still identify enough bytes for a u32-sized read, yet it fails the alignment requirement. Some CPUs can execute certain unaligned instructions, but Rust's ordinary typed dereference still requires alignment. For a byte buffer with a specified layout, extract the bytes and use u32::from_le_bytes when the format is little-endian. For an intentionally unaligned typed read, std::ptr::read_unaligned relaxes alignment and still requires readable, initialized storage for a valid value. Creating a misaligned reference as an intermediate step already violates the reference's requirements.

Invalid bool. Rust represents false with zero and true with one. A byte containing 2 is a valid u8, but creating a bool from that bit pattern, for example with std::mem::transmute::<u8, bool>(2), is UB. The error arises when the invalid bool is produced. No later if statement is needed to make the value invalid. When parsing a format that permits exactly zero and one, match those bytes explicitly and return an error for other values.

Uninitialized reads. Reserving storage and initializing it are separate operations. MaybeUninit<T> can hold storage before it contains a T. Calling assume_init() promises that it already contains a valid T. Miri tracks initialization, so bits left behind in storage cannot be used as evidence that a value was written. In this example, every bit pattern of an initialized u32 is valid, yet the second field has never been initialized:

rust
use std::mem::MaybeUninit;

#[test]
fn reads_value() {
    let mut words = [MaybeUninit::<u32>::uninit(); 2];
    words[0].write(17);
    let value = unsafe { words[1].assume_init() };
    assert_eq!(value, 23);
}

The read of the second field violates the promise before the assertion can compare values. In a real run under a nightly Miri of December 2026, this test stopped with error: Undefined Behavior: constructing invalid value of type u32: encountered uninitialized memory, but expected an integer, pointing at the assume_init() call. Your Miri version may word it differently. Writing words[1].write(23); before the read fulfills that promise. When the intended operation was to read the first field, the correct repair is to read index zero and expect 17. The intended data layout determines the fix.

Aliasing through &mut. A mutable reference carries exclusive access requirements for the memory it covers. Raw pointers can retain an address that refers to the same memory, so an unsafe block can express conflicting accesses the borrow checker cannot rule out by examining the reference types alone. A write through an independent pointer can invalidate use of an existing mutable reference. The important facts are how each pointer was derived and the order in which the program used them. Equal numeric addresses by themselves do not diagnose an aliasing violation.

Data races. A data race involves conflicting accesses to overlapping memory from different threads, with at least one write and at least one non-atomic access, where synchronization does not order the accesses. Two unsynchronized plain writes to the same counter are enough. One thread reading a plain value while another writes it can also race. A mutex can order accesses when every thread uses the same lock for the protected state. This is the mutual exclusion described by pthread_mutex_lock(3p). Miri tracks relevant synchronization in its interpreter and can report a data race even though it executes individual operations in some order. That interpreter order alone does not establish the synchronization the program needs.

Overflow in a const context. Include this case when classifying failures, because it is caught at a different stage. A required constant such as const LIMIT: u8 = u8::MAX + 1; must be evaluated by the compiler. The sum is outside the range of u8, so compilation fails before Miri can run the program. Ordinary Rust integer addition at runtime follows the applicable overflow-checking rules. When wrapping is intended, u8::MAX.wrapping_add(1) states that operation explicitly and evaluates to zero even in a constant expression.

03

What Miri models for aliasing

3 min read
Going deeperExplore the mechanism

Two pointers can have the same address and different permissions to access the allocation. A raw pointer derived from a mutable reference can be used within the rules for that borrow. A pointer derived independently can conflict with it. To see the difference, consider this sequence:

rust
fn main() {
    let mut value = 0_u32;
    let raw = &raw mut value;
    let unique = &mut value;

    *unique = 1;
    unsafe { raw.write(2) };
    assert_eq!(*unique, 2);
}

The storage stays live throughout. The address is aligned and the writes use valid u32 values. The reference is used for a write, the earlier raw pointer is used for a write, and the program then reads through the reference again. The raw pointer was obtained directly from value before unique was created. Its write conflicts with the permissions needed for those uses of unique. A Miri diagnostic can identify the conflicting access or a later use of an invalidated permission, depending on the model and sequence. In a real run with the default Stacked Borrows model, Miri stopped at the raw.write(2) line with attempting a write access using <tag> at alloc[0x0], but that tag does not exist in the borrow stack for this location. With MIRIFLAGS=-Zmiri-tree-borrows it also reported undefined behavior, worded as reborrow through <tag> ... is forbidden. The tag numbers and the exact line it blames differ between models and versions.

Conflicting accesses to one valueDerive rawpointerFrom theoriginalvariableCreatemutablereferenceSeparatelyfrom thesamevariableWritethroughreferenceWritethroughpointerAttemptreferencereadDerive rawpointerFrom theoriginalvariableCreatemutablereferenceSeparatelyfrom thesamevariableWritethroughreferenceWritethroughpointerAttemptreferenceread
The example uses a mutable reference, writes through an independently derived pointer, then attempts to use the reference again.

Stacked Borrows tracks access permissions using tags and a stack of borrow permissions for memory. Creating or using a pointer can affect what other tags may do at that location. An access that conflicts with the stack can invalidate permissions or fail immediately. Tree Borrows tracks derivation as a tree and tracks permission states for accesses. A new mutable borrow can begin reserved, with a write through it activating its stronger permissions. The models can therefore disagree on when a particular sequence becomes invalid. They are operational models used by Miri, and Rust's complete aliasing rules are still being specified.

When you read an aliasing diagnostic, reconstruct the operations in order. Find the allocation, then find where each pointer or reference came from. Identify the access Miri rejected and any earlier access that changed its permission. If the code needs a raw pointer temporarily, keep its derivation tied to the reference that authorizes that use and make sure the access sequence respects that borrow. In the example, all three operations can use unique, which expresses the intended order with a single reference.

A useful interpretation of any report is a sentence that names the operation and its failed requirement. For example, “This load used a pointer after its allocation was freed” identifies both the load and the earlier lifetime event to look for. “This conversion produced a bool from byte 2” identifies the conversion and the input to validate. Apply the same reasoning when a failure happens before Miri starts. Constant evaluation errors and unsupported interpreter operations tell you where execution stopped and what evidence you still need.

The next lesson, Sanitizers, asks what errors a compiled program can report during a native run. It follows from the limits of interpretation when your test needs to execute through a native library or exercise a larger workload.

Key takeaways

  • Miri interprets Rust and checks operations against tracked memory and thread state.
  • An address can refer to mapped memory while a Rust access through it is invalid.
  • An overflowing required constant expression fails during compilation.
  • Miri checks executed paths and supported operations under its execution model.
Reflect
  1. Explain to a colleague, in two sentences: run a binary and a test suite under Miri.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close