maybe_dangling

Summary

Declare that references and Box inside a new MaybeDangling type do not need to satisfy any memory-dependent validity properties (such as dereferenceable and noalias).

Motivation

Example 1

Sometimes one has to work with references or boxes that either are already deallocated, or might get deallocated too early. This comes up particularly often with ManuallyDrop. For example, the following code is UB at the time of writing this RFC:

fn id<T>(x: T) -> T { x }

fn unsound(x: Box<i32>) {
    let mut x = ManuallyDrop::new(x);
    unsafe { x.drop() };
    id(x); // or `let y = x;` or `mem::forget(x);`.
}

unsound(Box::new(42));

It is unsound because we are passing a dangling ManuallyDrop<Box<i32>> to id. In terms of invariants required by the language (“validity invariants”), ManuallyDrop is a regular struct, so all its fields have to be valid, but that means the Box needs to valid, so in particular it must point to allocated memory – but when id is invoked, the Box has already been deallocated. Given that ManuallyDrop is specifically designed to allow dropping the Box early, this is a big footgun (that people do run into in practice).

Example 2

There exist more complex versions of this problem, relating to a subtle aspect of the (currently poorly documented) aliasing requirements of Rust: when a reference is passed to a function as an argument (including nested in a struct), then that reference must remain live throughout the function. (In LLVM terms: we are annotating that reference with dereferenceable, which means “dereferenceable for the entire duration of this function call”). In issue #101983, this leads to a bug in scoped_thread. There we have a function that invokes a user-supplied impl FnOnce closure, roughly like this:

// Not showing all the `'lifetime` tracking, the point is that
// this closure might live shorter than `thread`.
fn thread(control: ..., closure: impl FnOnce() + 'lifetime) {
    closure();
    control.signal_done();
    // A lot of time can pass here.
}

The closure has a non-'static lifetime, meaning clients can capture references to on-stack data. The surrounding code ensure that 'lifetime lasts at least until signal_done is triggered, which ensures that the closure never accesses dangling data.

However, note that thread continues to run even after signal_done! Now consider what happens if the closure captures a reference of lifetime 'lifetime:

Example 3

As a third example, consider a type that wants to store a “pointer together with some data borrowed from that pointer”, like the owning_ref crate. This will usually boil down to something like this:

unsafe trait StableDeref: Deref {}

struct OwningRef<U, T: StableDeref<Target=U>> {
    buffer: T,
    ref_: NonNull<U>, // conceptually borrows from `buffer`.
}

Such a type is unsound when T is &mut U or Box<U> because those types are assumed by the compiler to be unique, so any time OwningRef is passed around, the compiler can assume that buffer is a unique pointer – an assumption that this code breaks because ref_ points to the same memory!

Goal of this RFC

The goal of this RFC is to

(Making the 2nd example UB-free without code changes would incur cost across the ecosystem, see the alternatives discussed below.)

The examples described above are far from artificial, here are some real-world crates that need MaybeDangling to ensure their soundness (some currently crudely work-around that problem with MaybeUninit but that is really not satisfying):

Guide-level explanation

To handle situations like this, Rust has a special type called MaybeDangling<P>: references and boxes in P do not have to be dereferenceable or follow aliasing guarantees. This applies inside nested references/boxes inside P as well. They still have to be non-null and aligned, and it has to at least be possible that there exists valid data behind that reference (i.e., MaybeDangling<&!> is still invalid). Also note that safe code can still generally assume that every MaybeDangling<P> it encounters is a valid P, but within unsafe code this makes it possible to store data of arbitrary type without making reference guarantees (this is similar to ManuallyDrop). In other words, MaybeDangling<P> is entirely like P, except that the rules that relate to the contents of memory that pointers in P point to (dereferencability and aliasing restrictions) are suspended when the pointers are not being actively used. You can think of the P as being “suspended” or “inert”.

The ManuallyDrop<T> type internally wraps T in a MaybeDangling.

This means that the first example is actually fine: the dangling Box was passed inside a ManuallyDrop, so there is no UB.

The 2nd example can be fixed by passing the closure in a MaybeDangling:

// Argument is passed as `MaybeDangling` since we might actually keep
// it around after its lifetime ends (at which point the caller can
// start dropping memory it points to).
fn thread(control: ..., closure: MaybeDangling<impl FnOnce() + 'lifetime>) {
    closure.into_inner()();
    control.signal_done();
    // A lot of time can pass here.
}

The 3rd example can be fixed by storing the buffer inside a MaybeDangling, which disables its aliasing requirements:

struct OwningRef<U, T: StableDeref<Target=U>> {
    buffer: MaybeDangling<T>,
    ref_: NonNull<U>, // conceptually borrows from `buffer`.
}

As long as the buffer field is not used, the pointer stored in ref_ will remain valid.

Reference-level explanation

The standard library contains a type MaybeDangling<P> that is safely convertible with P (i.e., the safety invariant is the same), and that has all the same niches as P, but that does allow passing around dangling boxes and references within unsafe code. MaybeDangling<P> propagates auto traits, drops the P when it is dropped, and has (at least) derive(Copy, Clone, Debug).

“Behavior considered undefined” is adjusted as follows:

  * Breaking the [pointer aliasing rules]. `Box<T>`, `&mut T` and `&T` follow LLVM’s
    scoped noalias model, except if the `&T` contains an [`UnsafeCell<U>`].
    References must not be dangling while they are live. (The exact liveness
    duration is not specified, but it is certainly upper-bounded by the syntactic
    lifetime assigned by the borrow checker. When a reference is passed to a
    function, it is live at least as long as that function call, again except if
    the `&T` contains an [`UnsafeCell<U>`].) All this also applies when values of
    these types are passed in a (nested) field of a compound type, but not behind
-   pointer indirections.
+   pointer indirections and also not for values inside a `MaybeDangling<_>`.
[...]
   * Producing an invalid value, even in private fields and locals.
     "Producing" a value happens any time a value is assigned to or
     read from a place, passed to a function/primitive operation or
     returned from a function/primitive operation. The following
     values are invalid (at their respective type):
[...]
-  * A reference or Box<T> that is dangling, unaligned, or points to an
-    invalid value.
+  * A reference or `Box<T>` that is unaligned or null, or whose pointee
+    type `T` is uninhabited. Furthermore, except when this value occurs
+    inside a `MaybeDangling`, if the reference/`Box<T>` is dangling or points
+    to an invalid value, it is itself invalid.

Note: this diff is based on an updated version of the reference.

Another way to think about this is: most types only have “by-value” requirements for their validity, i.e., they only require that the bit pattern be of a certain shape. References and boxes are the sole exception, they also require some properties of the memory they point to (e.g., they need to be dereferenceable). MaybeDangling<T> is a way to “truncate” T to its by-value invariant, which changes nothing for most types, but means that references and boxes are allowed as long as their bit patterns are fine (aligned and non-null) and as long as there conceivably could be a state of memory that makes them valid (T is inhabited).

codegen is adjusted as follows:

Miri is adjusted as follows:

Comparison with some other types that affect aliasing

Drawbacks

Rationale and alternatives

Prior art

The author cannot think of prior art in other languages; the issue arises because of Rust’s unique combination of strong safety guarantees with low-level types such as ManuallyDrop that manage memory allocation in a very precise way.

Inside Rust, we do have precedent for wrapper types altering language semantics; most prominently, there are UnsafeCell and MaybeUninit. Notice that UnsafeCell acts “behind references” while MaybeDangling, like MaybeUninit, acts “around references”: MaybeDangling<&T> vs &UnsafeCell<T>.

There is a crate offering these semantics on stable Rust via MaybeUninit. (This is not “prior” art, it was published after this RFC came out. “Related work” would be more apt. Alas, the RFC template forces this structure on us.)

Unresolved questions

Future possibilities