Sub topic 9
Pointer provenance: why a pointer's origin matters
This chapter assumes you can read basic unsafe Rust (raw pointers, *const T, *mut T, add, dereferencing). It also assumes you can run cargo +nightly miri run as shown earlier in the tutorial. You do not need to know Stacked Borrows or Tree Borrows yet. The next chapter covers them.
A pointer is more than a number
On most hardware, a pointer is an address, an integer that names a byte in memory. Rust's abstract machine, the model that defines what your program means, treats a pointer as more than that. A pointer value has two parts:
- an address, which is the number
- provenance, which records which allocation the pointer may access, and which part of it
Provenance is not stored in the compiled program. It exists only in the abstract machine, and the optimizer reasons about it. Miri is an implementation of the abstract machine, so it tracks provenance explicitly for every pointer. That tracking is why Miri can catch bugs that native execution hides.
Two pointers can have the same address and still not be interchangeable. The standard example is a one-past-the-end pointer. If a and b are two arrays that happen to sit next to each other, a.as_ptr().add(a.len()) and b.as_ptr() may hold the same address. The first pointer has provenance for a, so it must not be dereferenced, even though the address would land inside b.
How provenance is created and passed on
A pointer gets provenance when it is created from an allocation or a reference. Derived pointers inherit it, and they can never gain access to more than their parent had.
Arithmetic such as add, offset, and wrapping_add changes the address and keeps the provenance. Deriving from a reference is the usual way to lose range by accident, as the next section shows.
Narrow provenance from a reference
This program looks harmless, and it usually works natively:
fn main() {
let arr = [1u32, 2, 3];
let first = &arr[0];
let p = first as *const u32;
let second = unsafe { *p.add(1) };
println!("{second}");
}The reference first points at one u32. Reborrowing it as a raw pointer gives p permission for those four bytes only. Reading element 1 is outside that range. Miri reports undefined behavior, saying that the read at an offset into the allocation is not permitted by the pointer's tag (the label Miri attaches to each reference or derived pointer). The exact wording differs between Miri versions and between Stacked Borrows and Tree Borrows. Both models reject this program.
The fix is to derive the pointer from something that covers the whole array:
fn main() {
let arr = [1u32, 2, 3];
let p = arr.as_ptr();
let second = unsafe { *p.add(1) };
println!("{second}");
}as_ptr is called on the whole array, so p carries provenance for all three elements. The rule to keep: a pointer can reach exactly what the thing it was derived from could reach. Derive from the widest valid source.
Integers have no provenance
An integer is just a number. If you cast a pointer to usize and back, the question is where the provenance comes from the second time.
fn main() {
let x = 5u32;
let addr = &x as *const u32 as usize;
let p = addr as *const u32;
println!("{}", unsafe { *p });
}Rust's rules for this are layered:
- Pointer to integer cast (
as usize): the pointer's provenance is exposed. The abstract machine remembers that this allocation's address has been leaked into an integer. - Integer to pointer cast (
as *const T): the new pointer gets some exposed provenance that matches the address. Which one is picked depends on the address. - Strict provenance: a stricter discipline in which integers never regain provenance. Pointer values are only ever derived from other pointers.
By default Miri implements the permissive model. It tracks exposed allocations and lets the program above run. It is an approximation of how the real optimizer reasons, so a round trip that Miri accepts can still be fragile.
You can ask Miri to enforce the strict discipline:
MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri runWith this flag, the program above fails. The pointer made from addr has no provenance, so Miri reports that the access is through a dangling pointer. Treat that failure as a signal to change the code, not as a Miri quirk.
Doing address tricks the strict way
Sometimes you need to manipulate address bits, for example to store a flag in the low bit of an aligned pointer. The strict provenance methods on raw pointers let you do that without leaving the pointer world. They are stable from Rust 1.84.
| Method | What it does |
|---|---|
| `addr()` | Returns the address as `usize`. It does not expose provenance. |
| `with_addr(a)` | Returns a pointer with address `a` and the provenance of `self`. |
| `map_addr(f)` | Applies `f` to the address and keeps the provenance. |
| `expose_provenance()` | Returns the address and marks the provenance as exposed. This is the explicit form of `ptr as usize`. |
| `std::ptr::with_exposed_provenance(a)` | The explicit form of `a as *const T`. It picks up exposed provenance. |
Here is a tagged pointer that passes -Zmiri-strict-provenance:
fn main() {
let p = Box::into_raw(Box::new(42u32));
// A Box<u32> is 4-byte aligned, so the low bit is free for a flag.
let tagged = p.map_addr(|a| a | 1);
let flag = tagged.addr() & 1;
let clean = tagged.map_addr(|a| a & !1);
let value = unsafe { Box::from_raw(clean) };
println!("flag={flag} value={value}");
}At no point does an integer turn back into a pointer. map_addr changes the number and keeps the origin, so Miri can verify that clean still owns the allocation that Box::into_raw produced. Do not dereference tagged. Its address is misaligned for u32, and a misaligned read is undefined behavior on its own.
Common provenance mistakes Miri finds
- Deriving from a narrow reference. Taking
&v[0]and then walking past it, as in the first example. Usev.as_ptr()orv.as_mut_ptr(). - Assuming equal addresses mean equal access. Walking off the end of one allocation into a neighbor is never valid, even if the addresses match. Miri chooses its own allocation layout, so adjacency you see natively may not exist under Miri. A program that relies on it may fail only there.
- Integer round trips. The permissive model can accept code that strict mode rejects. Running once with
-Zmiri-strict-provenanceshows which casts you depend on. - Using a pointer after its allocation changed.
realloc,Vecgrowth, andBox::from_rawfollowed by drop all end the old allocation. A pointer saved from before the change keeps its old provenance, and using it is use-after-free. The earlier chapter on memory errors covers this case. - Mixing
*mutfrom&T. A pointer derived from a shared reference is read-only, even if you cast it to*mut T. Writing through it is undefined behavior. The aliasing chapter explains why.
Reading a provenance error
When a provenance rule is broken, the report usually names one of these situations:
- The pointer has no provenance, which means it came from an integer in strict mode.
- The pointer's provenance covers a different allocation than the address it is accessing.
- The access is outside the range that the pointer's tag allows.
- The allocation no longer exists.
Reading the help: lines in the report, and the allocation and tag creation notes that Miri prints, tells you where the pointer was derived. Work backwards from the faulting access to the place where the pointer was made, then ask whether a wider source was available there.
Exercise
The program below runs natively and prints 3, but Miri reports undefined behavior. Explain why, and give a one-line change that fixes it. fn main() { let mut data = [1u8, 2, 3, 4]; let p = &mut data[1] as mut u8; let last = unsafe { p.add(2) }; println!("{last}"); }
Show answer
&mut data[1] is a reference to one byte, so the raw pointer p derived from it has provenance for index 1 only. p.add(2) has the right address for data[3], but a pointer cannot reach outside the range it was derived from, so the read is undefined behavior. Deriving from the whole array fixes it: let p = data.as_mut_ptr();. The pointer then has provenance for all four bytes, and the read of data[3] is valid. The program prints 4.