DispatchFromDyn rules allowing non-PhantomData ZSTs in additional fields is unsound · Issue #135220 · rust-lang/rust (original) (raw)

DispatchFromDyn implementations are only allowed when all fields besides the main “pointer” contain ZSTs. Beyond this, those field’s types aren’t really restricted. Since actually dispatching from dyn then involves effectively transmuting the whole struct acting as receiving pointer, this can transmute between ZSTs that encode additional properties at the type level.

This isn't sound, as it breaks e.g. assumptions in the API of qcell::TCell, where the encoded assumption of the ZST TCellOwner<T: 'static> is that – for each type T: 'static – only one value of type TCellOwner<T> can ever be created.

#![feature(arbitrary_self_types)] #![feature(unsize)] #![feature(dispatch_from_dyn)]

use std:📑:PhantomData; use std:📑:Unsize; use std::ops::Deref; use std::ops::DispatchFromDyn; use std::ptr;

use qcell::TCell; use qcell::TCellOwner;

struct Dispatchable<T: ?Sized + 'static> { token: TCellOwner<PhantomData>, _ptr: *const T, }

impl<T, U> DispatchFromDyn<Dispatchable> for Dispatchable where T: Unsize + ?Sized, U: ?Sized, { }

trait Trait { fn get_owned(self: Dispatchable) -> TCellOwner<PhantomData>; } impl<S: 'static> Trait for S { fn get_owned(self: Dispatchable) -> TCellOwner<PhantomData> { self.token } }

impl<U: ?Sized> Deref for Dispatchable { type Target = U; fn deref(&self) -> &U { panic!() } }

fn owner_from_dyn<S: 'static>( x: TCellOwner<PhantomData<dyn Trait>>, ) -> TCellOwner<PhantomData> { let s = Dispatchable { token: x, _ptr: ptr::dangling::(), }; Trait::get_owned(s) }

fn main() { struct S; type T = PhantomData; type O = TCellOwner; let owner1: O = TCellOwner::new(); let mut owner2: O = owner_from_dyn(TCellOwner::new()); let c: TCell<T, Option> = TCell::new(Some("Hello World!".into())); let r: &str = c.ro(&owner1).as_deref().unwrap(); *c.rw(&mut owner2) = None; println!("{r}"); }

@rustbot label requires-nightly, I-unsound, F-dispatch_from_dyn, F-arbitrary_self_types, T-compiler

The rules should probably be changed to be like CoerceUnsized, requiring all fields besides the main “pointer” one to not only be zero-sized, but actually the type PhantomData.

Split from #135215 to track this issue independent of the question of its relevance to the stabilization of derive(CoercePointee).