Sub topic 12
Fixing what Miri finds
This chapter assumes you can already run cargo miri test and read a Miri report. It covers what to do next. It maps each kind of error to a fix, shows corrected versions of the earlier failing programs, and ends with habits that stop the same bug coming back.
A fix-first workflow
A Miri error means your code broke a rule of the language. It does not mean Miri is being strict. The goal is to make the code obey the rule, not to make the message disappear.
- Reproduce the failure with the smallest test that triggers it.
- Read the error line and the backtrace. Find the first frame in your own code.
- Decide which rule was broken: bounds, lifetime, validity, aliasing, or synchronization.
- Prefer removing the
unsafeblock. If it must stay, change the code so the rule holds. - Re-run under the default model and under
-Zmiri-tree-borrows. Add a regression test.
Out-of-bounds access
The failing program read *p.add(3) from a three-element Vec. Native runs often print a stale value, so the bug stays hidden. The safe fix is to let the standard library check the index.
fn main() {
let v = vec![1, 2, 3];
match v.get(3) {
Some(x) => println!("{x}"),
None => println!("index 3 is out of range"),
}
}If you really need a pointer, for example when implementing your own container, keep the length next to it and check before every add. A pointer may point one past the end of an allocation, but you must not read through it there.
fn read_at(v: &[i32], index: usize) -> Option<i32> {
if index < v.len() {
// SAFETY: index is below len, so the element is inside the allocation.
Some(unsafe { *v.as_ptr().add(index) })
} else {
None
}
}
fn main() {
let v = vec![1, 2, 3];
println!("{:?} {:?}", read_at(&v, 2), read_at(&v, 3));
}In this particular case v.get(index).copied() does the same job with no unsafe. Use the unsafe form only when you can show the safe one costs something you cannot afford.
Use-after-free
Miri reported a read through a pointer after drop(Box::from_raw(p)). The allocation had been freed, so the pointer dangled. The fix is to end the pointer's use before the owner is dropped, which here means reading first.
fn main() {
let p = Box::into_raw(Box::new(5));
unsafe {
println!("{}", *p);
drop(Box::from_raw(p));
}
}Real programs rarely have the drop and the read next to each other. When they are far apart, check these causes:
- Two owners. Two
Box::from_rawcalls on the same pointer free it twice. Make exactly one place responsible for freeing. - A pointer that outlives a
Vecreallocation. Pushing to aVeccan move its buffer. Re-derive pointers after any call that might grow it. - A pointer to a local. Returning
&x as *const _from a function leaves a pointer to a dead stack slot. Return the value, or put it in aBox.
If the data must live for the whole program, Box::leak gives you a &'static mut T and removes the question.
Invalid values and uninitialized memory
The transmute(3u8) program created a bool that is neither 0 nor 1. Miri flags the creation, not a later use. Convert with a check instead of reinterpreting bits.
fn byte_to_bool(b: u8) -> Option<bool> {
match b {
0 => Some(false),
1 => Some(true),
_ => None,
}
}
fn main() {
println!("{:?} {:?}", byte_to_bool(1), byte_to_bool(3));
}For types with restricted valid values, such as bool, char, enums, references, and NonZero*, look for a checked constructor first: char::from_u32, NonZeroU32::new, or a TryFrom implementation.
For uninitialized memory, MaybeUninit<T> is the type that may hold bytes that are not yet a valid T. Write first, then call assume_init.
use std::mem::MaybeUninit;
fn main() {
let mut slot = MaybeUninit::<u32>::uninit();
slot.write(7);
// SAFETY: slot was fully written on the line above.
let value = unsafe { slot.assume_init() };
println!("{value}");
}Two common mistakes remain even with MaybeUninit. First, calling assume_init after only part of a struct was written is still undefined behavior. Second, std::mem::uninitialized and mem::zeroed for types like references or Box create invalid values at once. Replace both with MaybeUninit.
Aliasing violations
The aliasing program created a new &mut x while an older raw pointer was still going to be used. Under Stacked Borrows, the new reference invalidates the raw pointer. Tree Borrows reports the same program for a similar reason. The rule to apply is: derive a pointer from the reference you intend to keep using, and stop using it once a newer reference takes over.
fn main() {
let mut x = 10;
let r = &mut x;
let raw = r as *mut i32;
unsafe {
*raw = 20;
}
*r += 1;
println!("{x}");
}Here raw is derived from r, so it sits above r in the permission stack. Writing through raw and then using r is a valid ordering. Using raw again after *r += 1 would be an error, because r's use removes the permissions of pointers derived from it.
Other fixes, roughly from best to worst:
- Remove the raw pointer and use the reference.
- Use
Cell,RefCell, orUnsafeCellwhen you need mutation through shared access. Plain&Tto&mut Tcasts are never allowed. - Pass the raw pointer around instead of converting back and forth between references and pointers. Each conversion adds a retag that Miri checks.
Data races
Two threads doing COUNTER += 1 on a static mut race. Miri reports a conflicting access from each thread. Replace the shared variable with a type that is safe to share.
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn main() {
let h = thread::spawn(|| {
COUNTER.fetch_add(1, Ordering::Relaxed);
});
COUNTER.fetch_add(1, Ordering::Relaxed);
h.join().unwrap();
assert_eq!(COUNTER.load(Ordering::Relaxed), 2);
}Choose the tool by what the data is:
| Situation | Fix |
|---|---|
| One counter or flag | An atomic such as `AtomicU32` |
| Several fields that change together | `Mutex<T>` or `RwLock<T>` |
| Data handed from one thread to another | A channel, or `join` before reading |
| Custom lock-free structure | Atomics with explicit `Acquire` and `Release` ordering, tested under many seeds |
Ordering bugs can hide. A Relaxed ordering where you needed Release/Acquire may pass one schedule and fail another. Run the test with several seeds, for example MIRIFLAGS="-Zmiri-many-seeds=0..32" cargo +nightly miri test, before trusting it.
Make the fix last
After the fix compiles and Miri is quiet, three habits keep it fixed.
- Add a regression test that reproduces the original input. If the bug needed a specific index or schedule, encode it.
- Write a
// SAFETY:comment above every remainingunsafeblock that says which condition makes it valid. Writing the sentence often reveals a missing check. - Wrap unsafe code in a safe function whose signature makes misuse impossible, and put
debug_assert!checks on its preconditions. Miri then tests the safe API, and callers cannot reach the unsafe parts.
Exercise
This test fails under Miri with an aliasing error. What is the problem, and how do you fix it without removing the raw pointer? fn main() { let mut v = 1; let p = &mut v as mut i32; let r = &mut v; r += 1; unsafe { *p += 1; } }
Show answer
The program makes p, then creates a second &mut v and uses it. Using r invalidates p, so the later write through p is an aliasing violation. To keep a raw pointer, derive it from the reference you keep using: write let r = &mut v; let p = r as *mut i32;, use p first, and then use r. Do not touch p after the last use of r. Alternatively, finish all work through r before creating p.
Exercise
A test uses MaybeUninit::<[u8; 4]>::uninit(), writes only the first two bytes, and calls assume_init. Why does Miri complain, and what are two valid fixes?
Show answer
assume_init asserts that all four bytes are initialized, but two bytes were never written, so reading the array is undefined behavior. One fix is to write all four bytes before calling assume_init. Another is to start from [0u8; 4] and skip MaybeUninit, since a zeroed array is a valid value.