1
Fork 0

Don't allow transmuting ZSTs in dispatch_from_dyn impl

This commit is contained in:
Michael Goulet 2025-01-08 00:28:47 +00:00
parent ad211ced81
commit 3c3186148e
5 changed files with 66 additions and 7 deletions

View file

@ -135,7 +135,7 @@ hir_analysis_dispatch_from_dyn_multi = implementing the `DispatchFromDyn` trait
hir_analysis_dispatch_from_dyn_repr = structs implementing `DispatchFromDyn` may not have `#[repr(packed)]` or `#[repr(C)]`
hir_analysis_dispatch_from_dyn_zst = the trait `DispatchFromDyn` may only be implemented for structs containing the field being coerced, ZST fields with 1 byte alignment, and nothing else
hir_analysis_dispatch_from_dyn_zst = the trait `DispatchFromDyn` may only be implemented for structs containing the field being coerced, ZST fields with 1 byte alignment that don't mention type/const generics, and nothing else
.note = extra field `{$name}` of type `{$ty}` is not allowed
hir_analysis_drop_impl_negative = negative `Drop` impls are not supported

View file

@ -259,16 +259,25 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<()
let coerced_fields = fields
.iter()
.filter(|field| {
// Ignore PhantomData fields
if tcx.type_of(field.did).instantiate_identity().is_phantom_data() {
return false;
}
let ty_a = field.ty(tcx, args_a);
let ty_b = field.ty(tcx, args_b);
// Allow 1-ZSTs that don't mention type params.
//
// Allowing type params here would allow us to possibly transmute
// between ZSTs, which may be used to create library unsoundness.
if let Ok(layout) =
tcx.layout_of(infcx.typing_env(param_env).as_query_input(ty_a))
&& layout.is_1zst()
&& !ty_a.has_non_region_param()
{
if layout.is_1zst() {
// ignore 1-ZST fields
return false;
}
// ignore 1-ZST fields
return false;
}
if ty_a == ty_b {