Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ptr::metadata: avoid references to extern types #127859

Merged
merged 2 commits into from
Jul 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions library/core/src/ptr/metadata.rs
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@ use crate::hash::{Hash, Hasher};
use crate::intrinsics::aggregate_raw_ptr;
use crate::intrinsics::ptr_metadata;
use crate::marker::Freeze;
use crate::ptr::NonNull;

/// Provides the pointer metadata type of any pointed-to type.
///
@@ -153,7 +154,7 @@ pub const fn from_raw_parts_mut<T: ?Sized>(
/// compare equal (since identical vtables can be deduplicated within a codegen unit).
#[lang = "dyn_metadata"]
pub struct DynMetadata<Dyn: ?Sized> {
_vtable_ptr: &'static VTable,
_vtable_ptr: NonNull<VTable>,
_phantom: crate::marker::PhantomData<Dyn>,
}

@@ -166,15 +167,18 @@ extern "C" {
}

impl<Dyn: ?Sized> DynMetadata<Dyn> {
/// One of the things that rustc_middle does with this being a lang item is
/// give it `FieldsShape::Primitive`, which means that as far as codegen can
/// tell, it *is* a reference, and thus doesn't have any fields.
/// That means we can't use field access, and have to transmute it instead.
/// When `DynMetadata` appears as the metadata field of a wide pointer, the rustc_middle layout
/// computation does magic and the resulting layout is *not* a `FieldsShape::Aggregate`, instead
/// it is a `FieldsShape::Primitive`. This means that the same type can have different layout
/// depending on whether it appears as the metadata field of a wide pointer or as a stand-alone
/// type, which understandably confuses codegen and leads to ICEs when trying to project to a
/// field of `DynMetadata`. To work around that issue, we use `transmute` instead of using a
/// field projection.
#[inline]
fn vtable_ptr(self) -> *const VTable {
// SAFETY: this layout assumption is hard-coded into the compiler.
// If it's somehow not a size match, the transmute will error.
unsafe { crate::mem::transmute::<Self, &'static VTable>(self) }
unsafe { crate::mem::transmute::<Self, *const VTable>(self) }
}

/// Returns the size of the type associated with this vtable.
Loading