Skip to content

Commit

Permalink
rust: types: implement ForeignOwnable for Box<T>
Browse files Browse the repository at this point in the history
This allows us to hand ownership of Rust dynamically allocated
objects to the C side of the kernel.

Signed-off-by: Wedson Almeida Filho <[email protected]>
Reviewed-by: Gary Guo <[email protected]>
Reviewed-by: Vincenzo Palazzo <[email protected]>
Reviewed-by: Alice Ferrazzi <[email protected]>
Reviewed-by: Andreas Hindborg <[email protected]>
Signed-off-by: Miguel Ojeda <[email protected]>
  • Loading branch information
wedsonaf authored and ojeda committed Feb 1, 2023
1 parent 0fc4424 commit 26949ba
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions rust/kernel/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

//! Kernel types.

use alloc::boxed::Box;
use core::{
cell::UnsafeCell,
mem::MaybeUninit,
Expand Down Expand Up @@ -62,6 +63,28 @@ pub trait ForeignOwnable: Sized {
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.
///
/// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.
Expand Down

0 comments on commit 26949ba

Please sign in to comment.