Re: [PATCH v3 07/13] rust: init: add `PinnedDrop` trait and macros

From: Gary Guo
Date: Thu Mar 30 2023 - 07:01:20 EST


On Wed, 29 Mar 2023 22:33:24 +0000
y86-dev@xxxxxxxxxxxxxx wrote:

> From: Benno Lossin <y86-dev@xxxxxxxxxxxxxx>
>
> The `PinnedDrop` trait that facilitates destruction of pinned types.
> It has to be implemented via the `#[pinned_drop]` macro, since the
> `drop` function should not be called by normal code, only by other
> destructors. It also only works on structs that are annotated with
> `#[pin_data(PinnedDrop)]`.
>
> Co-developed-by: Gary Guo <gary@xxxxxxxxxxx>
> Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
> Signed-off-by: Benno Lossin <y86-dev@xxxxxxxxxxxxxx>
> ---
> rust/kernel/init.rs | 111 ++++++++++++++
> rust/kernel/init/__internal.rs | 15 ++
> rust/kernel/init/macros.rs | 263 +++++++++++++++++++++++++++++++++
> rust/macros/lib.rs | 49 ++++++
> rust/macros/pinned_drop.rs | 49 ++++++
> 5 files changed, 487 insertions(+)
> create mode 100644 rust/macros/pinned_drop.rs
>
> diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.rs
> index 692942a008b3..4a3c7bf27a06 100644
> --- a/rust/kernel/init/__internal.rs
> +++ b/rust/kernel/init/__internal.rs
> @@ -132,3 +132,18 @@ impl<T: ?Sized> Drop for DropGuard<T> {
> }
> }
> }
> +
> +/// Token used by `PinnedDrop` to prevent calling the function without creating this unsafely
> +/// created struct. This is needed, because the `drop` function is safe, but should not be called
> +/// manually.
> +pub struct OnlyCallFromDrop(());
> +
> +impl OnlyCallFromDrop {
> + /// # Safety
> + ///
> + /// This function should only be called from the [`Drop::drop`] function and only be used to
> + /// delegate the destruction to the pinned destructor [`PinnedDrop::drop`] of the same type.
> + pub unsafe fn create() -> Self {

Although this is impl detail and the name doesn't really matter, but I
am wondering why this is called `create` instead of just `new`.

> + Self(())
> + }
> +}