Skip to content

Commit 6c2d0ad

Browse files
Darksonnojeda
authored andcommitted
rust: implement ForeignOwnable for Pin<Box<T>>
We already implement ForeignOwnable for Box<T>, but it may be useful to store pinned data in a ForeignOwnable container. This patch makes that possible. This will be used together with upcoming miscdev abstractions, which Binder will use when binderfs is disabled. Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20240730-foreign-ownable-pin-box-v1-1-b1d70cdae541@google.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 08f983a commit 6c2d0ad

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

rust/kernel/types.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use core::{
99
marker::{PhantomData, PhantomPinned},
1010
mem::MaybeUninit,
1111
ops::{Deref, DerefMut},
12+
pin::Pin,
1213
ptr::NonNull,
1314
};
1415

@@ -89,6 +90,32 @@ impl<T: 'static> ForeignOwnable for Box<T> {
8990
}
9091
}
9192

93+
impl<T: 'static> ForeignOwnable for Pin<Box<T>> {
94+
type Borrowed<'a> = Pin<&'a T>;
95+
96+
fn into_foreign(self) -> *const core::ffi::c_void {
97+
// SAFETY: We are still treating the box as pinned.
98+
Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _
99+
}
100+
101+
unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> {
102+
// SAFETY: The safety requirements for this function ensure that the object is still alive,
103+
// so it is safe to dereference the raw pointer.
104+
// The safety requirements of `from_foreign` also ensure that the object remains alive for
105+
// the lifetime of the returned value.
106+
let r = unsafe { &*ptr.cast() };
107+
108+
// SAFETY: This pointer originates from a `Pin<Box<T>>`.
109+
unsafe { Pin::new_unchecked(r) }
110+
}
111+
112+
unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
113+
// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
114+
// call to `Self::into_foreign`.
115+
unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) }
116+
}
117+
}
118+
92119
impl ForeignOwnable for () {
93120
type Borrowed<'a> = ();
94121

0 commit comments

Comments
 (0)