Skip to content
Draft
Show file tree
Hide file tree
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
56 changes: 35 additions & 21 deletions compiler/rustc_const_eval/src/interpret/validity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use std::borrow::Cow;
use std::fmt::Write;
use std::hash::Hash;
use std::mem;
use std::num::NonZero;

use either::{Left, Right};
Expand Down Expand Up @@ -288,6 +289,7 @@ struct ValidityVisitor<'rt, 'tcx, M: Machine<'tcx>> {
/// If this is `Some`, then `reset_provenance_and_padding` must be true (but not vice versa:
/// we might not track data vs padding bytes if the operand isn't stored in memory anyway).
data_bytes: Option<RangeSet>,
may_dangle: bool,
}

impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
Expand Down Expand Up @@ -503,27 +505,29 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
// alignment and size determined by the layout (size will be 0,
// alignment should take attributes into account).
.unwrap_or_else(|| (place.layout.size, place.layout.align.abi));
// Direct call to `check_ptr_access_align` checks alignment even on CTFE machines.
try_validation!(
self.ecx.check_ptr_access(
place.ptr(),
size,
CheckInAllocMsg::Dereferenceable, // will anyway be replaced by validity message
),
self.path,
Ub(DanglingIntPointer { addr: 0, .. }) => NullPtr { ptr_kind, maybe: false },
Ub(DanglingIntPointer { addr: i, .. }) => DanglingPtrNoProvenance {
ptr_kind,
// FIXME this says "null pointer" when null but we need translate
pointer: format!("{}", Pointer::<Option<AllocId>>::without_provenance(i))
},
Ub(PointerOutOfBounds { .. }) => DanglingPtrOutOfBounds {
ptr_kind
},
Ub(PointerUseAfterFree(..)) => DanglingPtrUseAfterFree {
ptr_kind,
},
);
if !self.may_dangle {
// Direct call to `check_ptr_access_align` checks alignment even on CTFE machines.
try_validation!(
self.ecx.check_ptr_access(
place.ptr(),
size,
CheckInAllocMsg::Dereferenceable, // will anyway be replaced by validity message
),
self.path,
Ub(DanglingIntPointer { addr: 0, .. }) => NullPtr { ptr_kind, maybe: false },
Ub(DanglingIntPointer { addr: i, .. }) => DanglingPtrNoProvenance {
ptr_kind,
// FIXME this says "null pointer" when null but we need translate
pointer: format!("{}", Pointer::<Option<AllocId>>::without_provenance(i))
},
Ub(PointerOutOfBounds { .. }) => DanglingPtrOutOfBounds {
ptr_kind
},
Ub(PointerUseAfterFree(..)) => DanglingPtrUseAfterFree {
ptr_kind,
},
);
}
try_validation!(
self.ecx.check_ptr_align(
place.ptr(),
Expand All @@ -536,6 +540,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
found_bytes: has.bytes()
},
);

// Make sure this is non-null. We checked dereferenceability above, but if `size` is zero
// that does not imply non-null.
let scalar = Scalar::from_maybe_pointer(place.ptr(), self.ecx);
Expand Down Expand Up @@ -1269,6 +1274,14 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt,
ty::PatternKind::Or(_patterns) => {}
}
}
ty::Adt(adt, _) if adt.is_maybe_dangling() => {
let could_dangle = mem::replace(&mut self.may_dangle, true);

let inner = self.ecx.project_field(val, FieldIdx::ZERO)?;
self.visit_value(&inner)?;

self.may_dangle = could_dangle;
}
_ => {
// default handler
try_validation!(
Expand Down Expand Up @@ -1354,6 +1367,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
ecx,
reset_provenance_and_padding,
data_bytes: reset_padding.then_some(RangeSet(Vec::new())),
may_dangle: false,
};
v.visit_value(val)?;
v.reset_padding(val)?;
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,8 @@ language_item_table! {

PhantomData, sym::phantom_data, phantom_data, Target::Struct, GenericRequirement::Exact(1);

ManuallyDrop, sym::manually_drop, manually_drop, Target::Struct, GenericRequirement::None;
ManuallyDrop, sym::manually_drop, manually_drop, Target::Struct, GenericRequirement::Exact(1);
MaybeDangling, sym::maybe_dangling, maybe_dangling, Target::Struct, GenericRequirement::Exact(1);
BikeshedGuaranteedNoDrop, sym::bikeshed_guaranteed_no_drop, bikeshed_guaranteed_no_drop, Target::Trait, GenericRequirement::Exact(0);

MaybeUninit, sym::maybe_uninit, maybe_uninit, Target::Union, GenericRequirement::None;
Expand Down
11 changes: 11 additions & 0 deletions compiler/rustc_middle/src/ty/adt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ bitflags::bitflags! {
const IS_PIN = 1 << 11;
/// Indicates whether the type is `#[pin_project]`.
const IS_PIN_PROJECT = 1 << 12;
/// Indicates whether the type is `MaybeDangling<_>`.
const IS_MAYBE_DANGLING = 1 << 13;
}
}
rustc_data_structures::external_bitflags_debug! { AdtFlags }
Expand Down Expand Up @@ -315,6 +317,9 @@ impl AdtDefData {
if tcx.is_lang_item(did, LangItem::ManuallyDrop) {
flags |= AdtFlags::IS_MANUALLY_DROP;
}
if tcx.is_lang_item(did, LangItem::MaybeDangling) {
flags |= AdtFlags::IS_MAYBE_DANGLING;
}
if tcx.is_lang_item(did, LangItem::UnsafeCell) {
flags |= AdtFlags::IS_UNSAFE_CELL;
}
Expand Down Expand Up @@ -439,6 +444,12 @@ impl<'tcx> AdtDef<'tcx> {
self.flags().contains(AdtFlags::IS_MANUALLY_DROP)
}

/// Returns `true` if this is `MaybeDangling<T>`.
#[inline]
pub fn is_maybe_dangling(self) -> bool {
self.flags().contains(AdtFlags::IS_MAYBE_DANGLING)
}

/// Returns `true` if this is `Pin<T>`.
#[inline]
pub fn is_pin(self) -> bool {
Expand Down
8 changes: 7 additions & 1 deletion compiler/rustc_middle/src/ty/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1053,6 +1053,12 @@ where
})
}

ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
// FIXME: what is the exact effect of maybe dangling?
Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset)
.map(|info| PointeeInfo { safe: None, ..info })
}

_ => {
let mut data_variant = match &this.variants {
// Within the discriminant field, only the niche itself is
Expand Down Expand Up @@ -1091,7 +1097,7 @@ where
}
}
Variants::Multiple { .. } => None,
_ => Some(this),
Variants::Empty | Variants::Single { .. } => Some(this),
};

if let Some(variant) = data_variant
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1403,6 +1403,7 @@ symbols! {
maxnumf128,
may_dangle,
may_unwind,
maybe_dangling,
maybe_uninit,
maybe_uninit_uninit,
maybe_uninit_zeroed,
Expand Down
55 changes: 46 additions & 9 deletions library/core/src/mem/manually_drop.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::marker::Destruct;
use crate::cmp::Ordering;
use crate::hash::{Hash, Hasher};
use crate::marker::{Destruct, StructuralPartialEq};
use crate::mem::MaybeDangling;
use crate::ops::{Deref, DerefMut, DerefPure};
use crate::ptr;

Expand Down Expand Up @@ -152,11 +155,11 @@ use crate::ptr;
/// [`MaybeUninit`]: crate::mem::MaybeUninit
#[stable(feature = "manually_drop", since = "1.20.0")]
#[lang = "manually_drop"]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Copy, Clone, Debug, Default)]
#[repr(transparent)]
#[rustc_pub_transparent]
pub struct ManuallyDrop<T: ?Sized> {
value: T,
value: MaybeDangling<T>,
}

impl<T> ManuallyDrop<T> {
Expand All @@ -179,7 +182,7 @@ impl<T> ManuallyDrop<T> {
#[rustc_const_stable(feature = "const_manually_drop", since = "1.32.0")]
#[inline(always)]
pub const fn new(value: T) -> ManuallyDrop<T> {
ManuallyDrop { value }
ManuallyDrop { value: MaybeDangling::new(value) }
}

/// Extracts the value from the `ManuallyDrop` container.
Expand All @@ -197,7 +200,7 @@ impl<T> ManuallyDrop<T> {
#[rustc_const_stable(feature = "const_manually_drop", since = "1.32.0")]
#[inline(always)]
pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
slot.value
slot.value.into_inner()
}

/// Takes the value from the `ManuallyDrop<T>` container out.
Expand All @@ -222,7 +225,7 @@ impl<T> ManuallyDrop<T> {
pub const unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
// SAFETY: we are reading from a reference, which is guaranteed
// to be valid for reads.
unsafe { ptr::read(&slot.value) }
unsafe { ptr::read(slot.value.as_ref()) }
}
}

Expand Down Expand Up @@ -259,7 +262,7 @@ impl<T: ?Sized> ManuallyDrop<T> {
// SAFETY: we are dropping the value pointed to by a mutable reference
// which is guaranteed to be valid for writes.
// It is up to the caller to make sure that `slot` isn't dropped again.
unsafe { ptr::drop_in_place(&mut slot.value) }
unsafe { ptr::drop_in_place(slot.value.as_mut()) }
}
}

Expand All @@ -269,7 +272,7 @@ impl<T: ?Sized> const Deref for ManuallyDrop<T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
&self.value
self.value.as_ref()
}
}

Expand All @@ -278,9 +281,43 @@ impl<T: ?Sized> const Deref for ManuallyDrop<T> {
impl<T: ?Sized> const DerefMut for ManuallyDrop<T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut T {
&mut self.value
self.value.as_mut()
}
}

#[unstable(feature = "deref_pure_trait", issue = "87121")]
unsafe impl<T: ?Sized> DerefPure for ManuallyDrop<T> {}

#[stable(feature = "manually_drop", since = "1.20.0")]
impl<T: ?Sized + Eq> Eq for ManuallyDrop<T> {}

#[stable(feature = "manually_drop", since = "1.20.0")]
impl<T: ?Sized + PartialEq> PartialEq for ManuallyDrop<T> {
fn eq(&self, other: &Self) -> bool {
self.value.as_ref().eq(other.value.as_ref())
}
}

#[stable(feature = "manually_drop", since = "1.20.0")]
impl<T: ?Sized> StructuralPartialEq for ManuallyDrop<T> {}

#[stable(feature = "manually_drop", since = "1.20.0")]
impl<T: ?Sized + Ord> Ord for ManuallyDrop<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.value.as_ref().cmp(other.value.as_ref())
}
}

#[stable(feature = "manually_drop", since = "1.20.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for ManuallyDrop<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.value.as_ref().partial_cmp(other.value.as_ref())
}
}

#[stable(feature = "manually_drop", since = "1.20.0")]
impl<T: ?Sized + Hash> Hash for ManuallyDrop<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.as_ref().hash(state);
}
}
110 changes: 110 additions & 0 deletions library/core/src/mem/maybe_dangling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#![unstable(feature = "maybe_dangling", issue = "118166")]

use crate::{mem, ptr};

/// Allows wrapped [references] and [boxes] to dangle.
///
/// That is, if a reference (or a `Box`) is wrapped in `MaybeDangling` (including when in a
/// (nested) field of a compound type wrapped in `MaybeDangling`), it does not have to follow
/// pointer aliasing rules or be dereferenceable.
///
/// This can be useful when the value can become dangling while the function holding it is still
/// executing (particularly in concurrent code). As a somewhat absurd example, consider this code:
///
/// ```rust,no_run
/// #![feature(box_as_ptr)]
/// # use std::alloc::{dealloc, Layout};
/// # use std::mem;
///
/// let mut boxed = Box::new(0_u32);
/// let ptr = Box::as_mut_ptr(&mut boxed);
///
/// // Safety: the pointer comes from a box and thus was allocated before; `box` is not used afterwards
/// unsafe { dealloc(ptr.cast(), Layout::new::<u32>()) };
///
/// mem::forget(boxed); // <-- this is UB!
/// ```
///
/// Even though the `Box`e's destructor is not run (and thus we don't have a double free bug), this
/// code is still UB. This is because when moving `boxed` into `forget`, its validity invariants
/// are asserted, causing UB since the `Box` is dangling. The safety comment is as such wrong, as
/// moving the `boxed` variable as part of the `forget` call *is* a use.
///
/// To fix this we could use `MaybeDangling`:
///
/// ```rust
/// #![feature(maybe_dangling, box_as_ptr)]
/// # use std::alloc::{dealloc, Layout};
/// # use std::mem::{self, MaybeDangling};
///
/// let mut boxed = MaybeDangling::new(Box::new(0_u32));
/// let ptr = Box::as_mut_ptr(boxed.as_mut());
///
/// // Safety: the pointer comes from a box and thus was allocated before; `box` is not used afterwards
/// unsafe { dealloc(ptr.cast(), Layout::new::<u32>()) };
///
/// mem::forget(boxed); // <-- this is OK!
/// ```
///
/// Note that the bit pattern must still be valid for the wrapped type. That is, [references]
/// (and [boxes]) still must be aligned and non-null.
///
/// Additionally note that safe code can still assume that the inner value in a `MaybeDangling` is
/// **not** dangling -- functions like [`as_ref`] and [`into_inner`] are safe. It is not sound to
/// return a dangling reference in a `MaybeDangling` to safe code. However, it *is* sound
/// to hold such values internally inside your code -- and there's no way to do that without
/// this type. Note that other types can use this type and thus get the same effect; in particular,
/// [`ManuallyDrop`] will use `MaybeDangling`.
///
/// Note that `MaybeDangling` doesn't prevent drops from being run, which can lead to UB if the
/// drop observes a dangling value. If you need to prevent drops from being run use [`ManuallyDrop`]
/// instead.
///
/// [references]: prim@reference
/// [boxes]: ../../std/boxed/struct.Box.html
/// [`into_inner`]: MaybeDangling::into_inner
/// [`as_ref`]: MaybeDangling::as_ref
/// [`ManuallyDrop`]: crate::mem::ManuallyDrop
#[repr(transparent)]
#[rustc_pub_transparent]
#[derive(Debug, Copy, Clone, Default)]
#[lang = "maybe_dangling"]
pub struct MaybeDangling<P: ?Sized>(P);

impl<P: ?Sized> MaybeDangling<P> {
/// Wraps a value in a `MaybeDangling`, allowing it to dangle.
pub const fn new(x: P) -> Self
where
P: Sized,
{
MaybeDangling(x)
}

/// Returns a reference to the inner value.
///
/// Note that this is UB if the inner value is currently dangling.
pub const fn as_ref(&self) -> &P {
&self.0
}

/// Returns a mutable reference to the inner value.
///
/// Note that this is UB if the inner value is currently dangling.
pub const fn as_mut(&mut self) -> &mut P {
&mut self.0
}

/// Extracts the value from the `MaybeDangling` container.
///
/// Note that this is UB if the inner value is currently dangling.
pub const fn into_inner(self) -> P
where
P: Sized,
{
// FIXME: replace this with `self.0` when const checker can figure out that `self` isn't actually dropped
// SAFETY: this is equivalent to `self.0`
let x = unsafe { ptr::read(&self.0) };
mem::forget(self);
x
}
}
Loading
Loading