Sub topic 2
Catching Out-of-Bounds Access and Use-After-Free
Assume you know Rust ownership, borrowing, lifetimes, Cargo, raw pointers, and unsafe. Miri is an interpreter for Rust’s Mid-level Intermediate Representation (MIR). It runs selected code and checks many rules that the compiler cannot check inside unsafe blocks.
Out-of-bounds access
A raw pointer does not automatically carry a valid range. Adding an index beyond an allocation and dereferencing the result is undefined behavior, even if the memory appears readable on your machine.
fn main() {
let values = vec![10, 20, 30];
let pointer = values.as_ptr();
let value = unsafe { *pointer.add(3) };
println!("{value}");
}Run this with Miri:
cargo +nightly miri runMiri reports the invalid pointer arithmetic or dereference, including the source location and a backtrace showing how execution reached it. The fix is to preserve the allocation’s bounds, usually by using a slice or checking the index before pointer arithmetic.
Use-after-free
A pointer becomes unusable after its allocation is released. Reconstructing a Box from a raw pointer transfers ownership back to the Box; dropping that Box frees the allocation.
fn main() {
let pointer = Box::into_raw(Box::new(5));
unsafe {
drop(Box::from_raw(pointer));
println!("{}", *pointer);
}
}Miri identifies the later read as a use-after-free. A pointer must remain tied to a live allocation. If ownership must continue, keep the Box alive or reconstruct it only once, at the point where ownership should end.
Invalid values and uninitialized memory
Rust types have valid-value rules. A bool, for example, must contain 0 or 1. MaybeUninit<T> is the safe container for storage that has not received a valid T yet. Call assume_init only after writing a valid value.
Flags, provenance, and aliasing
MIRIFLAGS configures Miri. Tree Borrows is an alternative aliasing model to the default Stacked Borrows model:
MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri testPointer provenance means a pointer carries the identity of the allocation from which it was derived. An integer with the same address does not necessarily recreate a valid pointer to that allocation.
Creating a new mutable reference can invalidate incompatible earlier accesses. Do not use raw pointers to bypass Rust’s aliasing rules. Derive pointers from the correct live reference and ensure mutable access is exclusive.
Exercise
What is the main difference between an out-of-bounds access and a use-after-free?
Show answer
An out-of-bounds access exceeds an allocation’s valid range. A use-after-free accesses an allocation after its storage has been released.