Skip to content

Commit 51f6af8

Browse files
Darksonnojeda
authored andcommitted
rust: sync: add ArcBorrow::from_raw
Allows access to a value in an `Arc` that is currently held as a raw pointer due to use of `Arc::into_raw`, without destroying or otherwise consuming that raw pointer. This is a dependency of the linked list that Rust Binder uses. The linked list uses this method when iterating over the linked list [1]. Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Boqun Feng <boqun.feng@gmail.com> Link: https://lore.kernel.org/r/20240402-linked-list-v1-6-b1c59ba7ae3b@google.com [1] Signed-off-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20240402-arc-for-list-v4-1-54db6440a9a9@google.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent be2ca1e commit 51f6af8

File tree

1 file changed

+58
-18
lines changed

1 file changed

+58
-18
lines changed

rust/kernel/sync/arc.rs

Lines changed: 58 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,39 @@ struct ArcInner<T: ?Sized> {
138138
data: T,
139139
}
140140

141+
impl<T: ?Sized> ArcInner<T> {
142+
/// Converts a pointer to the contents of an [`Arc`] into a pointer to the [`ArcInner`].
143+
///
144+
/// # Safety
145+
///
146+
/// `ptr` must have been returned by a previous call to [`Arc::into_raw`], and the `Arc` must
147+
/// not yet have been destroyed.
148+
unsafe fn container_of(ptr: *const T) -> NonNull<ArcInner<T>> {
149+
let refcount_layout = Layout::new::<bindings::refcount_t>();
150+
// SAFETY: The caller guarantees that the pointer is valid.
151+
let val_layout = Layout::for_value(unsafe { &*ptr });
152+
// SAFETY: We're computing the layout of a real struct that existed when compiling this
153+
// binary, so its layout is not so large that it can trigger arithmetic overflow.
154+
let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
155+
156+
// Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and
157+
// `ArcInner<T>` is the same since `ArcInner` is a struct with `T` as its last field.
158+
//
159+
// This is documented at:
160+
// <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
161+
let ptr = ptr as *const ArcInner<T>;
162+
163+
// SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the
164+
// pointer, since it originates from a previous call to `Arc::into_raw` on an `Arc` that is
165+
// still valid.
166+
let ptr = unsafe { ptr.byte_sub(val_offset) };
167+
168+
// SAFETY: The pointer can't be null since you can't have an `ArcInner<T>` value at the null
169+
// address.
170+
unsafe { NonNull::new_unchecked(ptr.cast_mut()) }
171+
}
172+
}
173+
141174
// This is to allow [`Arc`] (and variants) to be used as the type of `self`.
142175
impl<T: ?Sized> core::ops::Receiver for Arc<T> {}
143176

@@ -233,27 +266,13 @@ impl<T: ?Sized> Arc<T> {
233266
/// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it
234267
/// must not be called more than once for each previous call to [`Arc::into_raw`].
235268
pub unsafe fn from_raw(ptr: *const T) -> Self {
236-
let refcount_layout = Layout::new::<bindings::refcount_t>();
237-
// SAFETY: The caller guarantees that the pointer is valid.
238-
let val_layout = Layout::for_value(unsafe { &*ptr });
239-
// SAFETY: We're computing the layout of a real struct that existed when compiling this
240-
// binary, so its layout is not so large that it can trigger arithmetic overflow.
241-
let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
242-
243-
// Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and
244-
// `ArcInner<T>` is the same since `ArcInner` is a struct with `T` as its last field.
245-
//
246-
// This is documented at:
247-
// <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
248-
let ptr = ptr as *const ArcInner<T>;
249-
250-
// SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the
251-
// pointer, since it originates from a previous call to `Arc::into_raw` and is still valid.
252-
let ptr = unsafe { ptr.byte_sub(val_offset) };
269+
// SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
270+
// `Arc` that is still valid.
271+
let ptr = unsafe { ArcInner::container_of(ptr) };
253272

254273
// SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the
255274
// reference count held then will be owned by the new `Arc` object.
256-
unsafe { Self::from_inner(NonNull::new_unchecked(ptr.cast_mut())) }
275+
unsafe { Self::from_inner(ptr) }
257276
}
258277

259278
/// Returns an [`ArcBorrow`] from the given [`Arc`].
@@ -454,6 +473,27 @@ impl<T: ?Sized> ArcBorrow<'_, T> {
454473
_p: PhantomData,
455474
}
456475
}
476+
477+
/// Creates an [`ArcBorrow`] to an [`Arc`] that has previously been deconstructed with
478+
/// [`Arc::into_raw`].
479+
///
480+
/// # Safety
481+
///
482+
/// * The provided pointer must originate from a call to [`Arc::into_raw`].
483+
/// * For the duration of the lifetime annotated on this `ArcBorrow`, the reference count must
484+
/// not hit zero.
485+
/// * For the duration of the lifetime annotated on this `ArcBorrow`, there must not be a
486+
/// [`UniqueArc`] reference to this value.
487+
pub unsafe fn from_raw(ptr: *const T) -> Self {
488+
// SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
489+
// `Arc` that is still valid.
490+
let ptr = unsafe { ArcInner::container_of(ptr) };
491+
492+
// SAFETY: The caller promises that the value remains valid since the reference count must
493+
// not hit zero, and no mutable reference will be created since that would involve a
494+
// `UniqueArc`.
495+
unsafe { Self::new(ptr) }
496+
}
457497
}
458498

459499
impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {

0 commit comments

Comments
 (0)