Sub topic 8
Why moving a future can be unsafe: self-references
This chapter assumes you know ownership and borrowing, what a move does to a value's memory address, and the basics of Future and poll from earlier chapters. It explains why Future::poll takes Pin<&mut Self> and not &mut Self. The next chapter introduces Pin itself.
What a move really does
In Rust, moving a value copies its bytes to a new location and treats the old location as unused. That is cheap and almost always harmless, because nothing else knows the value's address. The borrow checker enforces this: you cannot move a value while a reference to it is alive.
Safe Rust gives no way to write a struct that holds a reference to one of its own fields. A lifetime on the struct would have to name a borrow of self, and the language has no syntax for that. Raw pointers do allow it, and so does compiler-generated code. Async blocks are the case that matters here.
A self-reference built by hand
The following struct stores a String and a raw pointer to that same String. The pointer is set in a separate init step because it needs the struct's final address.
struct SelfRef {
data: String,
ptr: *const String,
}
impl SelfRef {
fn new(data: String) -> Self {
SelfRef { data, ptr: std::ptr::null() }
}
fn init(&mut self) {
self.ptr = &self.data;
}
fn data_via_ptr(&self) -> &str {
unsafe { &*self.ptr }
}
}
fn main() {
let mut a = SelfRef::new("first".to_string());
a.init();
let mut b = SelfRef::new("second".to_string());
b.init();
println!("a.data = {}, via ptr = {}", a.data, a.data_via_ptr());
std::mem::swap(&mut a, &mut b);
println!("a.data = {}, via ptr = {}", a.data, a.data_via_ptr());
}The first line prints first twice. After the swap, a.data is "second", but a.data_via_ptr() returns "first". swap copied the bytes of each struct into the other, including the pointer values. a.ptr still holds the address of the field inside b, and b now holds the string "first".
In this program the stale pointer still points at live memory, so the symptom is a wrong value. If the old location had been freed or reused, reading it would be undefined behavior.
Only the String struct (pointer, length, capacity) lives inside SelfRef. Its heap buffer does not move when the struct moves. A pointer to the buffer would survive the move. The pointer here targets the String itself, which is why it breaks.
Where async code creates self-references
An async fn is compiled into a state machine, a struct whose fields hold every local variable that is alive across an .await. If one of those locals borrows another, the state machine contains a reference into itself.
async fn tick() {}
async fn sum_after_tick() -> usize {
let numbers = [1usize, 2, 3];
let first = &numbers[0];
tick().await;
*first + numbers.len()
}Both numbers and first are used after the .await, so both are saved in the future. numbers is an inline array, so it sits inside the future's own memory. first points into that memory. The compiler's generated struct looks roughly like this sketch:
// Illustrative only. The real generated type is hidden and more detailed.
enum SumAfterTickState {
Start,
Suspended {
numbers: [usize; 3],
first: *const usize, // points into `numbers` above
// plus the inner `tick()` future
},
Done,
}This is the same shape as SelfRef. If the future is moved after it suspends, first points at the old location.
Why safe code could move it
You might expect the type system to stop the move, since moving a borrowed value is an error. It does not stop it here, for two reasons:
- The references inside the state machine are compiler-managed. They do not appear in the future's type as lifetimes, so the borrow checker has nothing to track.
Future::pollcould have been declared asfn poll(&mut self, ...). A&mut Selflets safe code callstd::mem::swap,std::mem::replace, orOption::takeon the future. That is exactly the operation that brokeSelfRef.
Without a change to the signature, every self-referential future would be a soundness hole reachable from safe code. The fix is to make the poll receiver a type that does not let safe code move the target. That type is Pin<&mut Self>, covered in the next chapter.
What moves and what does not
The danger is limited to data that the future itself owns inline and that something else points to. These cases are safe:
- A reference to data that lives outside the future, such as a
&strargument. The future moves, but the referent does not. - A pointer into a heap allocation owned by the future, such as
&vec[0]on aVec. TheVecheader moves, but the buffer stays put. - A future that has completed, or one that is dropped and never polled again.
These cases are dangerous:
- A reference to an inline local (an array, a struct, an integer) that stays alive across an
.await. - A reference to one inline local stored in another inline local, for example a slice held next to the array it borrows.
The compiler does not tell you which case you have, and in general you do not want to reason about it by hand. The contract is simple: once a future has been polled, it must stay at the same address until it is dropped.
Why not forbid the references instead
Other designs were possible, and each has a cost:
| Option | Cost |
|---|---|
| Forbid borrows across `.await` | Most useful async code holds a borrow across an `.await`, such as reading into a buffer. |
| Always allocate the future on the heap | Adds an allocation for every async call, which is not zero-cost. |
| Make futures movable with offset-based references | Needs new reference types and a different unsafe model throughout the language. |
| Change `poll` to take a pinned receiver | Adds a type, `Pin`, that you must learn, but costs nothing at run time. |
Rust chose the last option. The price is paid in signatures, not in performance.
Summary of the problem
- A move changes a value's address.
- An
async fnstores locals across an.await, and some of them borrow each other. - This creates references from inside the future into itself.
- Moving the future after it is polled leaves those references pointing at the old address.
- A
&mut Selfreceiver would let safe code do that move, sopollneeds a receiver that forbids it.
Exercise
In the SelfRef program, after std::mem::swap(&mut a, &mut b), why does a.data_via_ptr() return "first" even though a.data is "second"? Would the result change if ptr pointed to the heap buffer of the string, for example through a *const u8, instead of to the String struct?
Show answer
swap copies the bytes of each struct into the other, including the ptr field. So a.ptr now holds the address of the data field inside b, and that location holds "first" after the swap. If the pointer targeted the string's heap buffer, the result would change: the buffer does not move when the String struct moves, so the pointer would stay valid and a.ptr would read from the buffer that a.data now owns, which holds "second". Only pointers into inline data break on a move.
Exercise
A future is created by calling an async fn and is then returned from a function and pushed into a Vec without being polled. Is this a problem for self-references? Explain.
Show answer
No. Before the first poll, the state machine has not run any of the async body, so it holds only its arguments and no references into itself. Moving it is safe. The restriction starts at the first poll that reaches a suspension point with a live borrow.