Sub topic 8
Why moving a future can be unsafe: self-references
This chapter assumes you know ownership, borrowing, and lifetimes. It also assumes you know what async fn produces and that the compiler turns it into a state machine. Here you will see why that state machine can hold a reference to itself, and why moving it can then cause undefined behavior.
Moves are plain memory copies
In Rust, moving a value copies its bytes to a new address. The old location is treated as unused. For most types this is fine, because nothing else stores the value's address.
A value breaks this rule when one of its fields points at another field of the same value. This is a self-reference. After a move, the pointer still holds the old address, so it points at memory that no longer holds the data.
How async code creates self-references
Look at this async function:
async fn read_len() -> usize {
let buf = [0u8; 16];
let slice = &buf[..];
std::future::ready(()).await;
slice.len()
}Both buf and slice are alive across the .await. The compiler stores them as fields of the generated state machine. slice is a reference into buf, so one field points at another field of the same struct. Safe Rust lets you write this. The compiler must make sure the resulting future is never moved after it is first polled.
A hand-written example
The next struct shows the same problem with a raw pointer. It is built with PhantomPinned, which a later chapter covers. For now it only makes the type refuse to be moved once pinned.
use std::marker::PhantomPinned;
use std::pin::Pin;
struct SelfRef {
data: String,
ptr: *const String,
_pin: PhantomPinned,
}
impl SelfRef {
fn new(data: String) -> Pin<Box<Self>> {
let mut boxed = Box::pin(SelfRef {
data,
ptr: std::ptr::null(),
_pin: PhantomPinned,
});
let ptr: *const String = &boxed.data;
unsafe {
boxed.as_mut().get_unchecked_mut().ptr = ptr;
}
boxed
}
fn via_ptr(&self) -> &str {
unsafe { &*self.ptr }
}
}The constructor allocates the struct on the heap first. Only then does it record the address of data in ptr. The address stays valid because the heap allocation does not move.
Suppose the struct had been moved after ptr was set. ptr would still hold the old address, and via_ptr would read freed or reused memory.
What goes wrong
The moves that matter happen in ordinary code. Passing a future to a function, returning it, or storing it in a collection all move it. A future that is polled once and then moved is no longer safe to poll again.
The conclusion
The rule is that a future may move freely before its first poll, and must stay at one address after that. Rust needs a way to express "this value will not move again" in the type system. That tool is Pin, which the next chapter covers.
Exercise
In read_len above, which two variables become fields of the future, and why does that make the future unsafe to move after its first poll?
Show answer
buf and slice both live across the .await, so both are stored in the state machine. slice points into buf, so it holds the address of a field in the same struct. Moving the future changes where buf lives but not the address inside slice, which would then dangle.