Skip to content

Commit f15715f

Browse files
committed
lib: replace some mem::forget's with ManuallyDrop
1 parent d7aa7cf commit f15715f

File tree

17 files changed

+85
-129
lines changed

17 files changed

+85
-129
lines changed

alloc/src/rc.rs

+22-25
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ use core::intrinsics::abort;
259259
#[cfg(not(no_global_oom_handling))]
260260
use core::iter;
261261
use core::marker::{PhantomData, Unsize};
262-
use core::mem::{self, align_of_val_raw, forget, ManuallyDrop};
262+
use core::mem::{self, align_of_val_raw, ManuallyDrop};
263263
use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver};
264264
use core::panic::{RefUnwindSafe, UnwindSafe};
265265
#[cfg(not(no_global_oom_handling))]
@@ -908,19 +908,18 @@ impl<T, A: Allocator> Rc<T, A> {
908908
#[stable(feature = "rc_unique", since = "1.4.0")]
909909
pub fn try_unwrap(this: Self) -> Result<T, Self> {
910910
if Rc::strong_count(&this) == 1 {
911-
unsafe {
912-
let val = ptr::read(&*this); // copy the contained object
913-
let alloc = ptr::read(&this.alloc); // copy the allocator
914-
915-
// Indicate to Weaks that they can't be promoted by decrementing
916-
// the strong count, and then remove the implicit "strong weak"
917-
// pointer while also handling drop logic by just crafting a
918-
// fake Weak.
919-
this.inner().dec_strong();
920-
let _weak = Weak { ptr: this.ptr, alloc };
921-
forget(this);
922-
Ok(val)
923-
}
911+
let this = ManuallyDrop::new(this);
912+
913+
let val: T = unsafe { ptr::read(&**this) }; // copy the contained object
914+
let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator
915+
916+
// Indicate to Weaks that they can't be promoted by decrementing
917+
// the strong count, and then remove the implicit "strong weak"
918+
// pointer while also handling drop logic by just crafting a
919+
// fake Weak.
920+
this.inner().dec_strong();
921+
let _weak = Weak { ptr: this.ptr, alloc };
922+
Ok(val)
924923
} else {
925924
Err(this)
926925
}
@@ -1354,9 +1353,8 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {
13541353
#[stable(feature = "rc_raw", since = "1.17.0")]
13551354
#[rustc_never_returns_null_ptr]
13561355
pub fn into_raw(this: Self) -> *const T {
1357-
let ptr = Self::as_ptr(&this);
1358-
mem::forget(this);
1359-
ptr
1356+
let this = ManuallyDrop::new(this);
1357+
Self::as_ptr(&*this)
13601358
}
13611359

13621360
/// Consumes the `Rc`, returning the wrapped pointer and allocator.
@@ -2127,7 +2125,7 @@ impl<T> Rc<[T]> {
21272125
}
21282126

21292127
// All clear. Forget the guard so it doesn't free the new RcBox.
2130-
forget(guard);
2128+
mem::forget(guard);
21312129

21322130
Self::from_ptr(ptr)
21332131
}
@@ -3080,9 +3078,7 @@ impl<T: ?Sized, A: Allocator> Weak<T, A> {
30803078
#[must_use = "losing the pointer will leak memory"]
30813079
#[stable(feature = "weak_into_raw", since = "1.45.0")]
30823080
pub fn into_raw(self) -> *const T {
3083-
let result = self.as_ptr();
3084-
mem::forget(self);
3085-
result
3081+
mem::ManuallyDrop::new(self).as_ptr()
30863082
}
30873083

30883084
/// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
@@ -3762,10 +3758,11 @@ impl<T: ?Sized, A: Allocator> UniqueRcUninit<T, A> {
37623758
/// # Safety
37633759
///
37643760
/// The data must have been initialized (by writing to [`Self::data_ptr()`]).
3765-
unsafe fn into_rc(mut self) -> Rc<T, A> {
3766-
let ptr = self.ptr;
3767-
let alloc = self.alloc.take().unwrap();
3768-
mem::forget(self);
3761+
unsafe fn into_rc(self) -> Rc<T, A> {
3762+
let mut this = ManuallyDrop::new(self);
3763+
let ptr = this.ptr;
3764+
let alloc = this.alloc.take().unwrap();
3765+
37693766
// SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible
37703767
// for having initialized the data.
37713768
unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) }

alloc/src/sync.rs

+16-20
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use core::intrinsics::abort;
2020
#[cfg(not(no_global_oom_handling))]
2121
use core::iter;
2222
use core::marker::{PhantomData, Unsize};
23-
use core::mem::{self, align_of_val_raw};
23+
use core::mem::{self, align_of_val_raw, ManuallyDrop};
2424
use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, Receiver};
2525
use core::panic::{RefUnwindSafe, UnwindSafe};
2626
use core::pin::Pin;
@@ -960,16 +960,14 @@ impl<T, A: Allocator> Arc<T, A> {
960960

961961
acquire!(this.inner().strong);
962962

963-
unsafe {
964-
let elem = ptr::read(&this.ptr.as_ref().data);
965-
let alloc = ptr::read(&this.alloc); // copy the allocator
963+
let this = ManuallyDrop::new(this);
964+
let elem: T = unsafe { ptr::read(&this.ptr.as_ref().data) };
965+
let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator
966966

967-
// Make a weak pointer to clean up the implicit strong-weak reference
968-
let _weak = Weak { ptr: this.ptr, alloc };
969-
mem::forget(this);
967+
// Make a weak pointer to clean up the implicit strong-weak reference
968+
let _weak = Weak { ptr: this.ptr, alloc };
970969

971-
Ok(elem)
972-
}
970+
Ok(elem)
973971
}
974972

975973
/// Returns the inner value, if the `Arc` has exactly one strong reference.
@@ -1493,9 +1491,8 @@ impl<T: ?Sized, A: Allocator> Arc<T, A> {
14931491
#[stable(feature = "rc_raw", since = "1.17.0")]
14941492
#[rustc_never_returns_null_ptr]
14951493
pub fn into_raw(this: Self) -> *const T {
1496-
let ptr = Self::as_ptr(&this);
1497-
mem::forget(this);
1498-
ptr
1494+
let this = ManuallyDrop::new(this);
1495+
Self::as_ptr(&*this)
14991496
}
15001497

15011498
/// Consumes the `Arc`, returning the wrapped pointer and allocator.
@@ -2801,9 +2798,7 @@ impl<T: ?Sized, A: Allocator> Weak<T, A> {
28012798
#[must_use = "losing the pointer will leak memory"]
28022799
#[stable(feature = "weak_into_raw", since = "1.45.0")]
28032800
pub fn into_raw(self) -> *const T {
2804-
let result = self.as_ptr();
2805-
mem::forget(self);
2806-
result
2801+
ManuallyDrop::new(self).as_ptr()
28072802
}
28082803

28092804
/// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
@@ -3875,13 +3870,14 @@ impl<T: ?Sized, A: Allocator> UniqueArcUninit<T, A> {
38753870
/// # Safety
38763871
///
38773872
/// The data must have been initialized (by writing to [`Self::data_ptr()`]).
3878-
unsafe fn into_arc(mut self) -> Arc<T, A> {
3879-
let ptr = self.ptr;
3880-
let alloc = self.alloc.take().unwrap();
3881-
mem::forget(self);
3873+
unsafe fn into_arc(self) -> Arc<T, A> {
3874+
let mut this = ManuallyDrop::new(self);
3875+
let ptr = this.ptr.as_ptr();
3876+
let alloc = this.alloc.take().unwrap();
3877+
38823878
// SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible
38833879
// for having initialized the data.
3884-
unsafe { Arc::from_ptr_in(ptr.as_ptr(), alloc) }
3880+
unsafe { Arc::from_ptr_in(ptr, alloc) }
38853881
}
38863882
}
38873883

core/src/task/wake.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
#![stable(feature = "futures_api", since = "1.36.0")]
22

3-
use crate::mem::transmute;
4-
53
use crate::any::Any;
64
use crate::fmt;
75
use crate::marker::PhantomData;
6+
use crate::mem::{transmute, ManuallyDrop};
87
use crate::panic::AssertUnwindSafe;
98
use crate::ptr;
109

@@ -465,16 +464,14 @@ impl Waker {
465464
pub fn wake(self) {
466465
// The actual wakeup call is delegated through a virtual function call
467466
// to the implementation which is defined by the executor.
468-
let wake = self.waker.vtable.wake;
469-
let data = self.waker.data;
470467

471468
// Don't call `drop` -- the waker will be consumed by `wake`.
472-
crate::mem::forget(self);
469+
let this = ManuallyDrop::new(self);
473470

474471
// SAFETY: This is safe because `Waker::from_raw` is the only way
475472
// to initialize `wake` and `data` requiring the user to acknowledge
476473
// that the contract of `RawWaker` is upheld.
477-
unsafe { (wake)(data) };
474+
unsafe { (this.waker.vtable.wake)(this.waker.data) };
478475
}
479476

480477
/// Wake up the task associated with this `Waker` without consuming the `Waker`.
@@ -726,16 +723,14 @@ impl LocalWaker {
726723
pub fn wake(self) {
727724
// The actual wakeup call is delegated through a virtual function call
728725
// to the implementation which is defined by the executor.
729-
let wake = self.waker.vtable.wake;
730-
let data = self.waker.data;
731726

732727
// Don't call `drop` -- the waker will be consumed by `wake`.
733-
crate::mem::forget(self);
728+
let this = ManuallyDrop::new(self);
734729

735730
// SAFETY: This is safe because `Waker::from_raw` is the only way
736731
// to initialize `wake` and `data` requiring the user to acknowledge
737732
// that the contract of `RawWaker` is upheld.
738-
unsafe { (wake)(data) };
733+
unsafe { (this.waker.vtable.wake)(this.waker.data) };
739734
}
740735

741736
/// Wake up the task associated with this `LocalWaker` without consuming the `LocalWaker`.

proc_macro/src/bridge/buffer.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Buffer management for same-process client<->server communication.
22
33
use std::io::{self, Write};
4-
use std::mem;
4+
use std::mem::{self, ManuallyDrop};
55
use std::ops::{Deref, DerefMut};
66
use std::slice;
77

@@ -129,17 +129,16 @@ impl Drop for Buffer {
129129
}
130130

131131
impl From<Vec<u8>> for Buffer {
132-
fn from(mut v: Vec<u8>) -> Self {
132+
fn from(v: Vec<u8>) -> Self {
133+
let mut v = ManuallyDrop::new(v);
133134
let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity());
134-
mem::forget(v);
135135

136136
// This utility function is nested in here because it can *only*
137137
// be safely called on `Buffer`s created by *this* `proc_macro`.
138138
fn to_vec(b: Buffer) -> Vec<u8> {
139139
unsafe {
140-
let Buffer { data, len, capacity, .. } = b;
141-
mem::forget(b);
142-
Vec::from_raw_parts(data, len, capacity)
140+
let b = ManuallyDrop::new(b);
141+
Vec::from_raw_parts(b.data, b.len, b.capacity)
143142
}
144143
}
145144

proc_macro/src/bridge/client.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,7 @@ macro_rules! define_client_handles {
5151

5252
impl<S> Encode<S> for $oty {
5353
fn encode(self, w: &mut Writer, s: &mut S) {
54-
let handle = self.handle;
55-
mem::forget(self);
56-
handle.encode(w, s);
54+
mem::ManuallyDrop::new(self).handle.encode(w, s);
5755
}
5856
}
5957

std/src/os/fd/owned.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::fmt;
88
use crate::fs;
99
use crate::io;
1010
use crate::marker::PhantomData;
11-
use crate::mem::forget;
11+
use crate::mem::ManuallyDrop;
1212
#[cfg(not(any(target_arch = "wasm32", target_env = "sgx", target_os = "hermit")))]
1313
use crate::sys::cvt;
1414
use crate::sys_common::{AsInner, FromInner, IntoInner};
@@ -141,9 +141,7 @@ impl AsRawFd for OwnedFd {
141141
impl IntoRawFd for OwnedFd {
142142
#[inline]
143143
fn into_raw_fd(self) -> RawFd {
144-
let fd = self.fd;
145-
forget(self);
146-
fd
144+
ManuallyDrop::new(self).fd
147145
}
148146
}
149147

std/src/os/solid/io.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949

5050
use crate::fmt;
5151
use crate::marker::PhantomData;
52-
use crate::mem::forget;
52+
use crate::mem::ManuallyDrop;
5353
use crate::net;
5454
use crate::sys;
5555
use crate::sys_common::{self, AsInner, FromInner, IntoInner};
@@ -149,9 +149,7 @@ impl AsRawFd for OwnedFd {
149149
impl IntoRawFd for OwnedFd {
150150
#[inline]
151151
fn into_raw_fd(self) -> RawFd {
152-
let fd = self.fd;
153-
forget(self);
154-
fd
152+
ManuallyDrop::new(self).fd
155153
}
156154
}
157155

std/src/os/windows/io/handle.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::fmt;
77
use crate::fs;
88
use crate::io;
99
use crate::marker::PhantomData;
10-
use crate::mem::{forget, ManuallyDrop};
10+
use crate::mem::ManuallyDrop;
1111
use crate::ptr;
1212
use crate::sys;
1313
use crate::sys::cvt;
@@ -319,9 +319,7 @@ impl AsRawHandle for OwnedHandle {
319319
impl IntoRawHandle for OwnedHandle {
320320
#[inline]
321321
fn into_raw_handle(self) -> RawHandle {
322-
let handle = self.handle;
323-
forget(self);
324-
handle
322+
ManuallyDrop::new(self).handle
325323
}
326324
}
327325

std/src/os/windows/io/socket.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ use super::raw::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
66
use crate::fmt;
77
use crate::io;
88
use crate::marker::PhantomData;
9-
use crate::mem;
10-
use crate::mem::forget;
9+
use crate::mem::{self, ManuallyDrop};
1110
use crate::sys;
1211
#[cfg(not(target_vendor = "uwp"))]
1312
use crate::sys::cvt;
@@ -191,9 +190,7 @@ impl AsRawSocket for OwnedSocket {
191190
impl IntoRawSocket for OwnedSocket {
192191
#[inline]
193192
fn into_raw_socket(self) -> RawSocket {
194-
let socket = self.socket;
195-
forget(self);
196-
socket
193+
ManuallyDrop::new(self).socket
197194
}
198195
}
199196

std/src/sys/pal/hermit/thread.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use super::hermit_abi;
44
use crate::ffi::CStr;
55
use crate::io;
6-
use crate::mem;
6+
use crate::mem::ManuallyDrop;
77
use crate::num::NonZero;
88
use crate::ptr;
99
use crate::time::Duration;
@@ -90,9 +90,7 @@ impl Thread {
9090

9191
#[inline]
9292
pub fn into_id(self) -> Tid {
93-
let id = self.tid;
94-
mem::forget(self);
95-
id
93+
ManuallyDrop::new(self).tid
9694
}
9795
}
9896

std/src/sys/pal/sgx/abi/tls/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ impl Tls {
9595
#[allow(unused)]
9696
pub unsafe fn activate_persistent(self: Box<Self>) {
9797
// FIXME: Needs safety information. See entry.S for `set_tls_ptr` definition.
98-
unsafe { set_tls_ptr(core::ptr::addr_of!(*self) as _) };
99-
mem::forget(self);
98+
let ptr = Box::into_raw(self).cast_const().cast::<u8>();
99+
unsafe { set_tls_ptr(ptr) };
100100
}
101101

102102
unsafe fn current<'a>() -> &'a Tls {

std/src/sys/pal/sgx/abi/usercalls/alloc.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::cell::UnsafeCell;
55
use crate::cmp;
66
use crate::convert::TryInto;
77
use crate::intrinsics;
8-
use crate::mem;
8+
use crate::mem::{self, ManuallyDrop};
99
use crate::ops::{CoerceUnsized, Deref, DerefMut, Index, IndexMut};
1010
use crate::ptr::{self, NonNull};
1111
use crate::slice;
@@ -176,6 +176,7 @@ unsafe impl<T: UserSafeSized> UserSafe for [T] {
176176
/// are used solely to indicate intent: a mutable reference is for writing to
177177
/// user memory, an immutable reference for reading from user memory.
178178
#[unstable(feature = "sgx_platform", issue = "56975")]
179+
#[repr(transparent)]
179180
pub struct UserRef<T: ?Sized>(UnsafeCell<T>);
180181
/// An owned type in userspace memory. `User<T>` is equivalent to `Box<T>` in
181182
/// enclave memory. Access to the memory is only allowed by copying to avoid
@@ -266,9 +267,7 @@ where
266267
/// Converts this value into a raw pointer. The value will no longer be
267268
/// automatically freed.
268269
pub fn into_raw(self) -> *mut T {
269-
let ret = self.0;
270-
mem::forget(self);
271-
ret.as_ptr() as _
270+
ManuallyDrop::new(self).0.as_ptr() as _
272271
}
273272
}
274273

0 commit comments

Comments
 (0)