Skip to content

Commit 1e74809

Browse files
wedsonafDarksonn
authored andcommitted
rust: sync: add Arc::{from_raw, into_raw}
These methods can be used to turn an `Arc` into a raw pointer and back, in a way that preserves the metadata for fat pointers. This is done using the unstable ptr_metadata feature [1]. However, it could also be done using the unstable pointer_byte_offsets feature [2], which is likely to have a shorter path to stabilization than ptr_metadata. Link: rust-lang/rust#81513 [1] Link: rust-lang/rust#96283 [2] Signed-off-by: Wedson Almeida Filho <[email protected]> Co-developed-by: Alice Ryhl <[email protected]> Signed-off-by: Alice Ryhl <[email protected]> Reviewed-by: Martin Rodriguez Reboredo <[email protected]>
1 parent 6b47f6a commit 1e74809

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

rust/kernel/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#![feature(generic_associated_types)]
2323
#![feature(new_uninit)]
2424
#![feature(pin_macro)]
25+
#![feature(ptr_metadata)]
2526
#![feature(receiver_trait)]
2627
#![feature(unsize)]
2728

rust/kernel/sync/arc.rs

+41-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use crate::{
2424
};
2525
use alloc::boxed::Box;
2626
use core::{
27-
alloc::AllocError,
27+
alloc::{AllocError, Layout},
2828
fmt,
2929
marker::{PhantomData, Unsize},
3030
mem::{ManuallyDrop, MaybeUninit},
@@ -210,6 +210,46 @@ impl<T: ?Sized> Arc<T> {
210210
}
211211
}
212212

213+
/// Convert the [`Arc`] into a raw pointer.
214+
///
215+
/// The raw pointer has ownership of the refcount that this Arc object owned.
216+
pub fn into_raw(self) -> *const T {
217+
let ptr = self.ptr.as_ptr();
218+
core::mem::forget(self);
219+
// SAFETY: The pointer is valid.
220+
unsafe { core::ptr::addr_of!((*ptr).data) }
221+
}
222+
223+
/// Recreates an [`Arc`] instance previously deconstructed via [`Arc::into_raw`].
224+
///
225+
/// This code relies on the `repr(C)` layout of structs as described in
226+
/// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
227+
///
228+
/// # Safety
229+
///
230+
/// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it
231+
/// can only be called once for each previous call to [`Arc::into_raw`].
232+
pub unsafe fn from_raw(ptr: *const T) -> Self {
233+
let refcount_layout = Layout::new::<bindings::refcount_t>();
234+
// SAFETY: The caller guarantees that the pointer is valid.
235+
let val_layout = unsafe { Layout::for_value(&*ptr) };
236+
// SAFETY: We're computing the layout of a real struct that existed when compiling this
237+
// binary, so its layout is not so large that it can trigger arithmetic overflow.
238+
let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
239+
240+
// This preserves the metadata in the pointer, if any.
241+
//
242+
// Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
243+
// <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
244+
let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);
245+
let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
246+
let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
247+
248+
// SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the
249+
// reference count held then will be owned by the new `Arc` object.
250+
unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
251+
}
252+
213253
/// Returns an [`ArcBorrow`] from the given [`Arc`].
214254
///
215255
/// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method

0 commit comments

Comments
 (0)