Skip to content
Snippets Groups Projects
Commit 26949bac authored by Wedson Almeida Filho's avatar Wedson Almeida Filho Committed by Miguel Ojeda
Browse files

rust: types: implement `ForeignOwnable` for `Box<T>`


This allows us to hand ownership of Rust dynamically allocated
objects to the C side of the kernel.

Signed-off-by: default avatarWedson Almeida Filho <wedsonaf@gmail.com>
Reviewed-by: default avatarGary Guo <gary@garyguo.net>
Reviewed-by: default avatarVincenzo Palazzo <vincenzopalazzodev@gmail.com>
Reviewed-by: default avatarAlice Ferrazzi <alice.ferrazzi@miraclelinux.com>
Reviewed-by: default avatarAndreas Hindborg <a.hindborg@samsung.com>
Signed-off-by: default avatarMiguel Ojeda <ojeda@kernel.org>
parent 0fc4424d
No related branches found
No related tags found
No related merge requests found
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
//! Kernel types. //! Kernel types.
use alloc::boxed::Box;
use core::{ use core::{
cell::UnsafeCell, cell::UnsafeCell,
mem::MaybeUninit, mem::MaybeUninit,
...@@ -62,6 +63,28 @@ pub trait ForeignOwnable: Sized { ...@@ -62,6 +63,28 @@ pub trait ForeignOwnable: Sized {
unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self; unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self;
} }
impl<T: 'static> ForeignOwnable for Box<T> {
type Borrowed<'a> = &'a T;
fn into_foreign(self) -> *const core::ffi::c_void {
Box::into_raw(self) as _
}
unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T {
// SAFETY: The safety requirements for this function ensure that the object is still alive,
// so it is safe to dereference the raw pointer.
// The safety requirements of `from_foreign` also ensure that the object remains alive for
// the lifetime of the returned value.
unsafe { &*ptr.cast() }
}
unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
// call to `Self::into_foreign`.
unsafe { Box::from_raw(ptr as _) }
}
}
/// Runs a cleanup function/closure when dropped. /// Runs a cleanup function/closure when dropped.
/// ///
/// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running. /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment