Skip to content

Commit 4d11c3f

Browse files
authored
Rollup merge of rust-lang#71107 - vorner:weak-into-raw-dangling, r=Amanieu
Address concerns of weak-into-raw This should address the standing concerns in rust-lang#60728 (comment). I've still left the ability to create a new dangling pointer from `null`, as I feel like this is the natural behaviour to expect, but I'm fine removing that too. I've modified the documentation to allow the `as_ptr` or `into_ptr` to return whatever garbage in case of a dangling pointer. I've also removed the guarantee to be able to do `from_raw(as_ptr)` from the documentation (but it would still work right now). I've renamed the method and added implementations for `Rc`/`Arc`. I've also tried if I can just „enable“ unsized types. I believe the current interface is compatible with them. But the inner implementation will be a bit challenging ‒ I can't use the `data_offset` as is used by `Rc` or `Arc` because it AFAIK „touches“ (creates a reference to) the live value of `T` ‒ and in case of `Weak`, it might be completely bogus or already dead ‒ so that would be UB. `./x.py test tidy` is completely mad on my own system all over the code base :-(. I'll just hope it goes through CI, or will fix as necessary. Is it OK if I ask @Amanieu for review, as the concerns are from you? ~r @Amanieu
2 parents 36b1a92 + f4ded11 commit 4d11c3f

File tree

2 files changed

+80
-54
lines changed

2 files changed

+80
-54
lines changed

src/liballoc/rc.rs

+40-27
Original file line numberDiff line numberDiff line change
@@ -569,9 +569,33 @@ impl<T: ?Sized> Rc<T> {
569569
/// ```
570570
#[stable(feature = "rc_raw", since = "1.17.0")]
571571
pub fn into_raw(this: Self) -> *const T {
572+
let ptr = Self::as_ptr(&this);
573+
mem::forget(this);
574+
ptr
575+
}
576+
577+
/// Provides a raw pointer to the data.
578+
///
579+
/// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
580+
/// for as long there are strong counts in the `Rc`.
581+
///
582+
/// # Examples
583+
///
584+
/// ```
585+
/// #![feature(weak_into_raw)]
586+
///
587+
/// use std::rc::Rc;
588+
///
589+
/// let x = Rc::new("hello".to_owned());
590+
/// let y = Rc::clone(&x);
591+
/// let x_ptr = Rc::as_ptr(&x);
592+
/// assert_eq!(x_ptr, Rc::as_ptr(&y));
593+
/// assert_eq!(unsafe { &*x_ptr }, "hello");
594+
/// ```
595+
#[unstable(feature = "weak_into_raw", issue = "60728")]
596+
pub fn as_ptr(this: &Self) -> *const T {
572597
let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr);
573598
let fake_ptr = ptr as *mut T;
574-
mem::forget(this);
575599

576600
// SAFETY: This cannot go through Deref::deref.
577601
// Instead, we manually offset the pointer rather than manifesting a reference.
@@ -1644,8 +1668,8 @@ impl<T> Weak<T> {
16441668

16451669
/// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
16461670
///
1647-
/// The pointer is valid only if there are some strong references. The pointer may be dangling
1648-
/// or even [`null`] otherwise.
1671+
/// The pointer is valid only if there are some strong references. The pointer may be dangling,
1672+
/// unaligned or even [`null`] otherwise.
16491673
///
16501674
/// # Examples
16511675
///
@@ -1658,31 +1682,22 @@ impl<T> Weak<T> {
16581682
/// let strong = Rc::new("hello".to_owned());
16591683
/// let weak = Rc::downgrade(&strong);
16601684
/// // Both point to the same object
1661-
/// assert!(ptr::eq(&*strong, weak.as_raw()));
1685+
/// assert!(ptr::eq(&*strong, weak.as_ptr()));
16621686
/// // The strong here keeps it alive, so we can still access the object.
1663-
/// assert_eq!("hello", unsafe { &*weak.as_raw() });
1687+
/// assert_eq!("hello", unsafe { &*weak.as_ptr() });
16641688
///
16651689
/// drop(strong);
1666-
/// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1690+
/// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
16671691
/// // undefined behaviour.
1668-
/// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1692+
/// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
16691693
/// ```
16701694
///
16711695
/// [`null`]: ../../std/ptr/fn.null.html
16721696
#[unstable(feature = "weak_into_raw", issue = "60728")]
1673-
pub fn as_raw(&self) -> *const T {
1674-
match self.inner() {
1675-
None => ptr::null(),
1676-
Some(inner) => {
1677-
let offset = data_offset_sized::<T>();
1678-
let ptr = inner as *const RcBox<T>;
1679-
// Note: while the pointer we create may already point to dropped value, the
1680-
// allocation still lives (it must hold the weak point as long as we are alive).
1681-
// Therefore, the offset is OK to do, it won't get out of the allocation.
1682-
let ptr = unsafe { (ptr as *const u8).offset(offset) };
1683-
ptr as *const T
1684-
}
1685-
}
1697+
pub fn as_ptr(&self) -> *const T {
1698+
let offset = data_offset_sized::<T>();
1699+
let ptr = self.ptr.cast::<u8>().as_ptr().wrapping_offset(offset);
1700+
ptr as *const T
16861701
}
16871702

16881703
/// Consumes the `Weak<T>` and turns it into a raw pointer.
@@ -1691,7 +1706,7 @@ impl<T> Weak<T> {
16911706
/// can be turned back into the `Weak<T>` with [`from_raw`].
16921707
///
16931708
/// The same restrictions of accessing the target of the pointer as with
1694-
/// [`as_raw`] apply.
1709+
/// [`as_ptr`] apply.
16951710
///
16961711
/// # Examples
16971712
///
@@ -1712,10 +1727,10 @@ impl<T> Weak<T> {
17121727
/// ```
17131728
///
17141729
/// [`from_raw`]: struct.Weak.html#method.from_raw
1715-
/// [`as_raw`]: struct.Weak.html#method.as_raw
1730+
/// [`as_ptr`]: struct.Weak.html#method.as_ptr
17161731
#[unstable(feature = "weak_into_raw", issue = "60728")]
17171732
pub fn into_raw(self) -> *const T {
1718-
let result = self.as_raw();
1733+
let result = self.as_ptr();
17191734
mem::forget(self);
17201735
result
17211736
}
@@ -1730,9 +1745,8 @@ impl<T> Weak<T> {
17301745
///
17311746
/// # Safety
17321747
///
1733-
/// The pointer must have originated from the [`into_raw`] (or [`as_raw`], provided there was
1734-
/// a corresponding [`forget`] on the `Weak<T>`) and must still own its potential weak reference
1735-
/// count.
1748+
/// The pointer must have originated from the [`into_raw`] and must still own its potential
1749+
/// weak reference count.
17361750
///
17371751
/// It is allowed for the strong count to be 0 at the time of calling this, but the weak count
17381752
/// must be non-zero or the pointer must have originated from a dangling `Weak<T>` (one created
@@ -1765,7 +1779,6 @@ impl<T> Weak<T> {
17651779
/// [`upgrade`]: struct.Weak.html#method.upgrade
17661780
/// [`Rc`]: struct.Rc.html
17671781
/// [`Weak`]: struct.Weak.html
1768-
/// [`as_raw`]: struct.Weak.html#method.as_raw
17691782
/// [`new`]: struct.Weak.html#method.new
17701783
/// [`forget`]: ../../std/mem/fn.forget.html
17711784
#[unstable(feature = "weak_into_raw", issue = "60728")]

src/liballoc/sync.rs

+40-27
Original file line numberDiff line numberDiff line change
@@ -566,9 +566,33 @@ impl<T: ?Sized> Arc<T> {
566566
/// ```
567567
#[stable(feature = "rc_raw", since = "1.17.0")]
568568
pub fn into_raw(this: Self) -> *const T {
569+
let ptr = Self::as_ptr(&this);
570+
mem::forget(this);
571+
ptr
572+
}
573+
574+
/// Provides a raw pointer to the data.
575+
///
576+
/// The counts are not affected in way and the `Arc` is not consumed. The pointer is valid for
577+
/// as long as there are strong counts in the `Arc`.
578+
///
579+
/// # Examples
580+
///
581+
/// ```
582+
/// #![feature(weak_into_raw)]
583+
///
584+
/// use std::sync::Arc;
585+
///
586+
/// let x = Arc::new("hello".to_owned());
587+
/// let y = Arc::clone(&x);
588+
/// let x_ptr = Arc::as_ptr(&x);
589+
/// assert_eq!(x_ptr, Arc::as_ptr(&y));
590+
/// assert_eq!(unsafe { &*x_ptr }, "hello");
591+
/// ```
592+
#[unstable(feature = "weak_into_raw", issue = "60728")]
593+
pub fn as_ptr(this: &Self) -> *const T {
569594
let ptr: *mut ArcInner<T> = NonNull::as_ptr(this.ptr);
570595
let fake_ptr = ptr as *mut T;
571-
mem::forget(this);
572596

573597
// SAFETY: This cannot go through Deref::deref.
574598
// Instead, we manually offset the pointer rather than manifesting a reference.
@@ -1340,8 +1364,8 @@ impl<T> Weak<T> {
13401364

13411365
/// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
13421366
///
1343-
/// The pointer is valid only if there are some strong references. The pointer may be dangling
1344-
/// or even [`null`] otherwise.
1367+
/// The pointer is valid only if there are some strong references. The pointer may be dangling,
1368+
/// unaligned or even [`null`] otherwise.
13451369
///
13461370
/// # Examples
13471371
///
@@ -1354,31 +1378,22 @@ impl<T> Weak<T> {
13541378
/// let strong = Arc::new("hello".to_owned());
13551379
/// let weak = Arc::downgrade(&strong);
13561380
/// // Both point to the same object
1357-
/// assert!(ptr::eq(&*strong, weak.as_raw()));
1381+
/// assert!(ptr::eq(&*strong, weak.as_ptr()));
13581382
/// // The strong here keeps it alive, so we can still access the object.
1359-
/// assert_eq!("hello", unsafe { &*weak.as_raw() });
1383+
/// assert_eq!("hello", unsafe { &*weak.as_ptr() });
13601384
///
13611385
/// drop(strong);
1362-
/// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1386+
/// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
13631387
/// // undefined behaviour.
1364-
/// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1388+
/// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
13651389
/// ```
13661390
///
13671391
/// [`null`]: ../../std/ptr/fn.null.html
13681392
#[unstable(feature = "weak_into_raw", issue = "60728")]
1369-
pub fn as_raw(&self) -> *const T {
1370-
match self.inner() {
1371-
None => ptr::null(),
1372-
Some(inner) => {
1373-
let offset = data_offset_sized::<T>();
1374-
let ptr = inner as *const ArcInner<T>;
1375-
// Note: while the pointer we create may already point to dropped value, the
1376-
// allocation still lives (it must hold the weak point as long as we are alive).
1377-
// Therefore, the offset is OK to do, it won't get out of the allocation.
1378-
let ptr = unsafe { (ptr as *const u8).offset(offset) };
1379-
ptr as *const T
1380-
}
1381-
}
1393+
pub fn as_ptr(&self) -> *const T {
1394+
let offset = data_offset_sized::<T>();
1395+
let ptr = self.ptr.cast::<u8>().as_ptr().wrapping_offset(offset);
1396+
ptr as *const T
13821397
}
13831398

13841399
/// Consumes the `Weak<T>` and turns it into a raw pointer.
@@ -1387,7 +1402,7 @@ impl<T> Weak<T> {
13871402
/// can be turned back into the `Weak<T>` with [`from_raw`].
13881403
///
13891404
/// The same restrictions of accessing the target of the pointer as with
1390-
/// [`as_raw`] apply.
1405+
/// [`as_ptr`] apply.
13911406
///
13921407
/// # Examples
13931408
///
@@ -1408,10 +1423,10 @@ impl<T> Weak<T> {
14081423
/// ```
14091424
///
14101425
/// [`from_raw`]: struct.Weak.html#method.from_raw
1411-
/// [`as_raw`]: struct.Weak.html#method.as_raw
1426+
/// [`as_ptr`]: struct.Weak.html#method.as_ptr
14121427
#[unstable(feature = "weak_into_raw", issue = "60728")]
14131428
pub fn into_raw(self) -> *const T {
1414-
let result = self.as_raw();
1429+
let result = self.as_ptr();
14151430
mem::forget(self);
14161431
result
14171432
}
@@ -1427,9 +1442,8 @@ impl<T> Weak<T> {
14271442
///
14281443
/// # Safety
14291444
///
1430-
/// The pointer must have originated from the [`into_raw`] (or [`as_raw'], provided there was
1431-
/// a corresponding [`forget`] on the `Weak<T>`) and must still own its potential weak reference
1432-
/// count.
1445+
/// The pointer must have originated from the [`into_raw`] and must still own its potential
1446+
/// weak reference count.
14331447
///
14341448
/// It is allowed for the strong count to be 0 at the time of calling this, but the weak count
14351449
/// must be non-zero or the pointer must have originated from a dangling `Weak<T>` (one created
@@ -1458,7 +1472,6 @@ impl<T> Weak<T> {
14581472
/// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
14591473
/// ```
14601474
///
1461-
/// [`as_raw`]: struct.Weak.html#method.as_raw
14621475
/// [`new`]: struct.Weak.html#method.new
14631476
/// [`into_raw`]: struct.Weak.html#method.into_raw
14641477
/// [`upgrade`]: struct.Weak.html#method.upgrade

0 commit comments

Comments
 (0)