Sub topic 10
Aliasing violations under Stacked Borrows and Tree Borrows
This chapter assumes you know Rust ownership and borrowing, raw pointers, and how to run cargo miri test with MIRIFLAGS. It covers the aliasing errors Miri reports most often, the two models that define them, and how to read and fix each one.
What aliasing rules protect
Rust lets the compiler assume that a &mut T is the only usable path to its target while the reference is live. A &T promises that nobody changes the target (outside UnsafeCell) while it is live. The optimizer uses these promises to reorder loads, cache values in registers, and delete stores.
Safe code cannot break these promises. Unsafe code can, because a raw pointer carries no such promise. Breaking the promise is undefined behavior (UB) even if the program prints the expected answer, because the optimizer is free to produce different machine code in a future compiler version.
Rust has no final, official aliasing model yet. Miri implements two experimental ones:
- Stacked Borrows is the original model and is Miri's default.
- Tree Borrows is a newer model designed to accept more real-world unsafe code while keeping most optimizations valid.
Both are about tags. Every reference or raw pointer that Miri tracks carries a tag naming where it was derived from. A tag decides whether an access through that pointer is still allowed.
The classic violation
This is the example from the topic plan. It looks harmless and usually works natively.
fn main() {
let mut x = 10;
let raw = &mut x as *mut i32;
let r = &mut x;
unsafe { *raw = 20; }
*r += 1;
}The sequence of events is:
rawis derived from a first mutable borrow ofx.&mut xcreatesr, a new unique borrow. This makesrawstale.- Writing through
rawuses a pointer that is no longer allowed to accessx.
Run it with cargo +nightly miri run. Under Stacked Borrows the report points at the write *raw = 20, and the message has this shape: attempting a write access using a tag, but that tag does not exist in the borrow stack for this location. Miri also prints help lines showing where the tag was created and where it was invalidated. The invalidation point is the &mut x line.
Stacked Borrows: a stack per memory location
Stacked Borrows keeps, for every byte of memory, a stack of permissions. Each entry is a tag plus a permission such as Unique, SharedReadWrite, or SharedReadOnly.
- Creating a reference pushes a new entry derived from the tag you borrowed from.
- Using a pointer is allowed only if its tag is on the stack with a sufficient permission.
- A write through a tag pops every entry above it. A read pops incompatible
Uniqueentries above it. - Once an entry is popped, any later use of that tag is UB.
In the example, &mut x pushes a new Unique entry above raw's entry. The write through raw is then rejected, because raw's tag is no longer on the stack once the new borrow takes over.
A second common case is writing through a pointer derived from a shared reference:
fn main() {
let x = 5;
let shared = &x;
let p = shared as *const i32 as *mut i32;
unsafe { *p = 6; }
println!("{x}");
}The pointer gets only SharedReadOnly permission. Casting it to *mut does not add write permission. Miri reports a write using a tag that lacks write permission. The same pattern is UB for plain Rust semantics reasons too, since x is not declared mutable.
Protectors
When you pass a reference as a function argument, Miri adds a protector to its tag for the duration of the call. While protected, the tag may not be popped or invalidated. Code like the following, where a function receives &mut i32 and something else invalidates it during the call, produces an error that mentions a protected tag. This models the noalias hint that rustc gives LLVM for reference arguments.
Tree Borrows: a tree of tags
Tree Borrows replaces each stack with a tree. Each tag is a node whose parent is the tag it was derived from. Every access is classified for each node as either:
- a child access, meaning it came through that node or one of its descendants, or
- a foreign access, meaning it came through any other node.
Each node has a state per location, and the state changes depending on whether an access is a child or foreign one. The states are:
| State | Meaning |
|---|---|
| Reserved | A fresh `&mut`. No write has happened yet. Reads and writes are allowed. |
| Active | A write through this tag has happened. Foreign accesses degrade it. |
| Frozen | Read-only. A foreign read of an Active node causes this. Child writes are UB. |
| Disabled | Any further use is UB. A foreign write causes this. |
Run the classic example again under Tree Borrows. Here the write through raw is a foreign write from the point of view of r, so r becomes Disabled. The write itself is allowed. The error arrives on the next line, *r += 1, which uses a disabled tag. This is the main practical difference when reading reports. Stacked Borrows tends to blame the first access made through a stale pointer. Tree Borrows blames the first use of a tag that an earlier access has disabled.
Switching models with MIRIFLAGS
Stacked Borrows is the default. To check with Tree Borrows, pass the flag through MIRIFLAGS:
MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri test| Aspect | Stacked Borrows | Tree Borrows |
|---|---|---|
| Data structure | A stack per location | A tree of tags per location |
| How to select | Default | `-Zmiri-tree-borrows` |
| Fresh `&mut` | Immediately unique | Starts as Reserved, becomes Active on first write |
| Where errors tend to appear | At the access through the stale tag | At the use of a tag disabled by earlier accesses |
| Strictness | Rejects more patterns | Accepts some code Stacked Borrows rejects |
Neither model is the official language rule. Code that passes one model can fail the other, so for a library the safest approach is to run both in CI and fix anything either one reports. If code passes only under Tree Borrows, treat it as fragile and prefer restructuring it.
Reading an aliasing report
An aliasing error has three parts you should find, in this order:
- The failing access. The headline names the operation (read or write), the tag, and the allocation. The source span points at the line that used the stale pointer.
- Where the tag was created. A help line says "this tag was created here" with a span. Check that this is the borrow you thought you were using.
- Where the tag was invalidated. A second help line shows the later access that popped or disabled it. This is usually the real bug: some other borrow of the same data happened in between.
The fix is almost always to change the second location, not the first.
Fixing aliasing errors
The reliable rule is to derive raw pointers from the reference you intend to keep using, and to stop using the raw pointer before you use the parent again.
fn main() {
let mut x = 10;
let r = &mut x;
let raw: *mut i32 = &mut *r;
unsafe { *raw = 20; }
*r += 1;
println!("{x}");
}Here raw is a child of r. The write through raw is a child write. The later use of r is a foreign access for raw, which is fine because raw is not used again. Miri accepts this under both models and prints 21.
Other practical fixes:
- Do not create a second
&mutto the same data while a raw pointer derived from the first is still in use. Use the raw pointer for all accesses instead, or re-derive it after the new borrow. - Never cast
&Tto*mut Tto write. UseCell,RefCell, orUnsafeCellso the type itself allows mutation behind a shared reference. - In data structures that hand out pointers (linked lists, arenas), store
*mut TorNonNull<T>rather than references, and create references only briefly at the point of use.
Exercise
In the classic example (raw derived from &mut x, then let r = &mut x;, then a write through raw, then *r += 1), why does reordering the last two statements (*r += 1; before unsafe { *raw = 20; }) still not fix the code?
Show answer
Creating r already invalidated raw. In Stacked Borrows, raw's entry is popped when &mut x creates r, so any later use of raw is UB regardless of statement order after that point. Using r first and then raw makes things worse: the write through raw now comes after r's use, and raw is still stale. The fix is to derive raw from r (&mut *r) and finish using raw before the next use of r.