Sub topic 12
Fixing what Miri finds
This chapter assumes you can run cargo miri test, read a Miri error report, and know the basics of raw pointers and unsafe. Miri tells you where undefined behavior (UB) happened. Fixing it means changing the code so the operation is valid, not silencing the report.
A fix workflow
- Read the first error. Later errors often follow from it.
- Find the rule that was broken: bounds, lifetime, validity, aliasing, or synchronization.
- Change the code so the rule holds. Do not add
unsafeblocks or casts to make the message go away. - Rerun Miri, and keep the failing case as a regression test.
Matching fixes to error kinds
| Miri reports | Typical cause | Fix |
|---|---|---|
| Out-of-bounds pointer use | Offset past the allocation | Check the length first, or use a slice with `get` |
| Use-after-free | Pointer outlives its `Box` or `Vec` | Keep the owner alive, or do not drop it early |
| Invalid value | `transmute` or zeroing into a type with restrictions | Convert with a checked method such as `u8` to `bool` by comparison |
| Uninitialized read | Reading memory before writing | Use `MaybeUninit` |
| Aliasing violation | Raw pointer used after a new `&mut` | Derive pointers from the reference you use |
| Data race | Unsynchronized shared writes | Use atomics or a `Mutex` |
Uninitialized memory with MaybeUninit
If you need a slot that is not yet filled, do not pretend it holds a value. MaybeUninit<T> is a wrapper that may hold uninitialized memory. Call assume_init only after you have written a valid value.
use std::mem::MaybeUninit;
fn main() {
let mut slot = MaybeUninit::<u32>::uninit();
slot.write(7);
let value = unsafe { slot.assume_init() };
println!("{value}");
}Miri accepts this because the write happens before assume_init. Swapping those two lines makes Miri report an uninitialized read.
Fixing an aliasing violation
The failing code creates a new &mut after taking a raw pointer, then uses the old pointer. The new reference invalidates it.
fn main() {
let mut x = 10;
let raw = &mut x as *mut i32;
let r = &mut x;
unsafe { *raw = 20; }
*r += 1;
}The fix is to use one source of access at a time. Here the raw pointer is derived from r, so it stays valid while r is the active path.
fn main() {
let mut x = 10;
let r = &mut x;
let raw = r as *mut i32;
unsafe { *raw = 20; }
*r += 1;
println!("{x}");
}The rule of thumb is to derive raw pointers from the reference you will keep using, and finish with them before you use the reference again.
Fixing a data race
Two threads writing a static mut race. Replace it with an atomic, which makes the operation synchronized.
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::SeqCst);
});
COUNTER.fetch_add(1, Ordering::SeqCst);
h.join().unwrap();
println!("{}", COUNTER.load(Ordering::SeqCst));
}This version needs no unsafe at all, which is the best outcome.
Exercise
A test reads *p after drop(Box::from_raw(p)) and Miri reports use-after-free. Name two ways to fix it.
Show answer
Move the read before the drop so the allocation is still alive, or copy the value out first (for example let b = Box::from_raw(p); let v = *b; drop(b);) and use v afterwards. Both keep every access inside the allocation's lifetime.