Skip to content
Open
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
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);
}
}
100 changes: 100 additions & 0 deletions library/core/src/mem/maybe_dangling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#![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.
///
/// 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.
///
/// [references]: prim@reference
/// [boxes]: ../../std/boxed/struct.Box.html
/// [`into_inner`]: MaybeDangling::into_inner
/// [`as_ref`]: MaybeDangling::as_ref
#[repr(transparent)]
#[rustc_pub_transparent]
#[derive(Debug, Copy, Clone, Default)]
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
}
}
4 changes: 4 additions & 0 deletions library/core/src/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ mod maybe_uninit;
#[stable(feature = "maybe_uninit", since = "1.36.0")]
pub use maybe_uninit::MaybeUninit;

mod maybe_dangling;
#[unstable(feature = "maybe_dangling", issue = "118166")]
pub use maybe_dangling::MaybeDangling;

mod transmutability;
#[unstable(feature = "transmutability", issue = "99571")]
pub use transmutability::{Assume, TransmuteFrom};
Expand Down
6 changes: 3 additions & 3 deletions src/etc/gdb_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,20 +298,20 @@ def cast_to_internal(node):

for i in xrange(0, length + 1):
if height > 0:
child_ptr = edges[i]["value"]["value"]
child_ptr = edges[i]["value"]["value"][ZERO_FIELD]
for child in children_of_node(child_ptr, height - 1):
yield child
if i < length:
# Avoid "Cannot perform pointer math on incomplete type" on zero-sized arrays.
key_type_size = keys.type.sizeof
val_type_size = vals.type.sizeof
key = (
keys[i]["value"]["value"]
keys[i]["value"]["value"][ZERO_FIELD]
if key_type_size > 0
else gdb.parse_and_eval("()")
)
val = (
vals[i]["value"]["value"]
vals[i]["value"]["value"][ZERO_FIELD]
if val_type_size > 0
else gdb.parse_and_eval("()")
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
0..1: [ SharedReadWrite<TAG> ]
0..1: [ SharedReadWrite<TAG> ]
0..1: [ SharedReadWrite<TAG> ]
0..1: [ SharedReadWrite<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> ]
0..1: [ SharedReadWrite<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> SharedReadOnly<TAG> ]
0..1: [ SharedReadWrite<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> Unique<TAG> ]
0..1: [ SharedReadWrite<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> Disabled<TAG> SharedReadOnly<TAG> ]
0..1: [ unknown-bottom(..<TAG>) ]
Loading
Loading