From 8b3d955f72f999ccce26aabdeb09939964d05a61 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Thu, 29 May 2025 10:10:23 +0200 Subject: rust: pin-init: improve safety documentation for `impl [Pin]Init for T` The inner SAFETY comments were missing since commit 5cfe7bef6751 ("rust: enable `clippy::undocumented_unsafe_blocks` lint"). Also rework the implementation of `__pinned_init` to better justify the SAFETY comment. Link: https://github.com/Rust-for-Linux/pin-init/pull/62/commits/df925b2e27d499b7144df7e62b01acb00d4b94b8 Reviewed-by: Boqun Feng Link: https://lore.kernel.org/all/20250529081027.297648-1-lossin@kernel.org Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index 9ab34036e6bc..d1c3ca5cfff4 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -1390,20 +1390,22 @@ where unsafe { pin_init_from_closure(init) } } -// SAFETY: Every type can be initialized by-value. +// SAFETY: the `__init` function always returns `Ok(())` and initializes every field of `slot`. unsafe impl Init for T { unsafe fn __init(self, slot: *mut T) -> Result<(), E> { - // SAFETY: TODO. + // SAFETY: `slot` is valid for writes by the safety requirements of this function. unsafe { slot.write(self) }; Ok(()) } } -// SAFETY: Every type can be initialized by-value. `__pinned_init` calls `__init`. +// SAFETY: the `__pinned_init` function always returns `Ok(())` and initializes every field of +// `slot`. Additionally, all pinning invariants of `T` are upheld. unsafe impl PinInit for T { unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { - // SAFETY: TODO. - unsafe { self.__init(slot) } + // SAFETY: `slot` is valid for writes by the safety requirements of this function. + unsafe { slot.write(self) }; + Ok(()) } } -- cgit From e832374ccadf4d1ce7bd40a85b9320bd7fbb3628 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Thu, 29 May 2025 10:10:24 +0200 Subject: rust: pin-init: change blanket impls for `[Pin]Init` and add one for `Result` Remove the error from the blanket implementations `impl Init for T` (and also for `PinInit`). Add implementations for `Result`. This allows one to easily construct (un)conditional failing initializers. It also improves the compatibility with APIs that do not use pin-init, because users can supply a `Result` to a function taking an `impl PinInit`. Suggested-by: Alice Ryhl Link: https://github.com/Rust-for-Linux/pin-init/pull/62/commits/58612514b256c6f4a4a0718be25298410e67387a [ Also fix a compile error in block. - Benno ] Reviewed-by: Boqun Feng Link: https://lore.kernel.org/all/20250529081027.297648-2-lossin@kernel.org [ Add title prefix `rust: pin-init`. - Benno ] Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index d1c3ca5cfff4..f4e034497cdd 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -1391,8 +1391,8 @@ where } // SAFETY: the `__init` function always returns `Ok(())` and initializes every field of `slot`. -unsafe impl Init for T { - unsafe fn __init(self, slot: *mut T) -> Result<(), E> { +unsafe impl Init for T { + unsafe fn __init(self, slot: *mut T) -> Result<(), Infallible> { // SAFETY: `slot` is valid for writes by the safety requirements of this function. unsafe { slot.write(self) }; Ok(()) @@ -1401,14 +1401,36 @@ unsafe impl Init for T { // SAFETY: the `__pinned_init` function always returns `Ok(())` and initializes every field of // `slot`. Additionally, all pinning invariants of `T` are upheld. -unsafe impl PinInit for T { - unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { +unsafe impl PinInit for T { + unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), Infallible> { // SAFETY: `slot` is valid for writes by the safety requirements of this function. unsafe { slot.write(self) }; Ok(()) } } +// SAFETY: when the `__init` function returns with +// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld. +// - `Err(err)`, slot was not written to. +unsafe impl Init for Result { + unsafe fn __init(self, slot: *mut T) -> Result<(), E> { + // SAFETY: `slot` is valid for writes by the safety requirements of this function. + unsafe { slot.write(self?) }; + Ok(()) + } +} + +// SAFETY: when the `__pinned_init` function returns with +// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld. +// - `Err(err)`, slot was not written to. +unsafe impl PinInit for Result { + unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { + // SAFETY: `slot` is valid for writes by the safety requirements of this function. + unsafe { slot.write(self?) }; + Ok(()) + } +} + /// Smart pointer containing uninitialized memory and that can write a value. pub trait InPlaceWrite { /// The type `Self` turns into when the contents are initialized. -- cgit From b3b4f760ccf2d08ff3db0f094c32ce70bba2eb15 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Mon, 9 Jun 2025 16:17:35 +0200 Subject: rust: pin-init: feature-gate the `stack_init_reuse` test on the `std` feature When trying to run `cargo check --all-targets --no-default-features`, an error is reported by the test, as it cannot find the `std` crate. This is to be expected, since the `--no-default-features` flag enables the `no-std` behavior of the crate. Thus exclude the test in that scenario. Link: https://github.com/Rust-for-Linux/pin-init/pull/50/commits/2813729ccacdedee9dbfcab1ed285b8721a0391b Link: https://lore.kernel.org/all/20250523125424.192843-4-lossin@kernel.org [ Changed my author email address to @kernel.org. - Benno ] Signed-off-by: Benno Lossin --- rust/pin-init/src/__internal.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/__internal.rs b/rust/pin-init/src/__internal.rs index 557b5948cddc..90f18e9a2912 100644 --- a/rust/pin-init/src/__internal.rs +++ b/rust/pin-init/src/__internal.rs @@ -188,6 +188,7 @@ impl StackInit { } #[test] +#[cfg(feature = "std")] fn stack_init_reuse() { use ::std::{borrow::ToOwned, println, string::String}; use core::pin::pin; -- cgit From 101b7cf006d4b4b98652bd15dc36e63ede8f8ad8 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Fri, 23 May 2025 16:50:57 +0200 Subject: rust: pin-init: rename `zeroed` to `init_zeroed` The name `zeroed` is a much better fit for a function that returns the type by-value. Link: https://github.com/Rust-for-Linux/pin-init/pull/56/commits/7dbe38682c9725405bab91dcabe9c4d8893d2f5e [ also rename uses in `rust/kernel/init.rs` - Benno] Link: https://lore.kernel.org/all/20250523145125.523275-2-lossin@kernel.org [ Fix wrong replacement of `mem::zeroed` in the definition of `trait Zeroable`. - Benno ] [ Also change occurrences of `zeroed` in `configfs.rs` - Benno ] Acked-by: Andreas Hindborg Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 26 +++++++++++++------------- rust/pin-init/src/macros.rs | 16 ++++++++-------- 2 files changed, 21 insertions(+), 21 deletions(-) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index f4e034497cdd..2f7ca94451e6 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -148,7 +148,7 @@ //! fn new() -> impl PinInit { //! try_pin_init!(Self { //! status <- CMutex::new(0), -//! buffer: Box::init(pin_init::zeroed())?, +//! buffer: Box::init(pin_init::init_zeroed())?, //! }? Error) //! } //! } @@ -742,7 +742,7 @@ macro_rules! stack_try_pin_init { /// - Fields that you want to initialize in-place have to use `<-` instead of `:`. /// - In front of the initializer you can write `&this in` to have access to a [`NonNull`] /// pointer named `this` inside of the initializer. -/// - Using struct update syntax one can place `..Zeroable::zeroed()` at the very end of the +/// - Using struct update syntax one can place `..Zeroable::init_zeroed()` at the very end of the /// struct, this initializes every field with 0 and then runs all initializers specified in the /// body. This can only be done if [`Zeroable`] is implemented for the struct. /// @@ -769,7 +769,7 @@ macro_rules! stack_try_pin_init { /// }); /// let init = pin_init!(Buf { /// buf: [1; 64], -/// ..Zeroable::zeroed() +/// ..Zeroable::init_zeroed() /// }); /// ``` /// @@ -805,7 +805,7 @@ macro_rules! pin_init { /// ```rust /// # #![feature(allocator_api)] /// # #[path = "../examples/error.rs"] mod error; use error::Error; -/// use pin_init::{pin_data, try_pin_init, PinInit, InPlaceInit, zeroed}; +/// use pin_init::{pin_data, try_pin_init, PinInit, InPlaceInit, init_zeroed}; /// /// #[pin_data] /// struct BigBuf { @@ -817,7 +817,7 @@ macro_rules! pin_init { /// impl BigBuf { /// fn new() -> impl PinInit { /// try_pin_init!(Self { -/// big: Box::init(zeroed())?, +/// big: Box::init(init_zeroed())?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) @@ -866,7 +866,7 @@ macro_rules! try_pin_init { /// # #[path = "../examples/error.rs"] mod error; use error::Error; /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; /// # use pin_init::InPlaceInit; -/// use pin_init::{init, Init, zeroed}; +/// use pin_init::{init, Init, init_zeroed}; /// /// struct BigBuf { /// small: [u8; 1024 * 1024], @@ -875,7 +875,7 @@ macro_rules! try_pin_init { /// impl BigBuf { /// fn new() -> impl Init { /// init!(Self { -/// small <- zeroed(), +/// small <- init_zeroed(), /// }) /// } /// } @@ -913,7 +913,7 @@ macro_rules! init { /// # #![feature(allocator_api)] /// # use core::alloc::AllocError; /// # use pin_init::InPlaceInit; -/// use pin_init::{try_init, Init, zeroed}; +/// use pin_init::{try_init, Init, init_zeroed}; /// /// struct BigBuf { /// big: Box<[u8; 1024 * 1024 * 1024]>, @@ -923,7 +923,7 @@ macro_rules! init { /// impl BigBuf { /// fn new() -> impl Init { /// try_init!(Self { -/// big: Box::init(zeroed())?, +/// big: Box::init(init_zeroed())?, /// small: [0; 1024 * 1024], /// }? AllocError) /// } @@ -1170,7 +1170,7 @@ pub unsafe trait Init: PinInit { /// /// ```rust /// # #![expect(clippy::disallowed_names)] - /// use pin_init::{init, zeroed, Init}; + /// use pin_init::{init, init_zeroed, Init}; /// /// struct Foo { /// buf: [u8; 1_000_000], @@ -1183,7 +1183,7 @@ pub unsafe trait Init: PinInit { /// } /// /// let foo = init!(Foo { - /// buf <- zeroed() + /// buf <- init_zeroed() /// }).chain(|foo| { /// foo.setup(); /// Ok(()) @@ -1508,11 +1508,11 @@ pub unsafe trait ZeroableOption {} // SAFETY: by the safety requirement of `ZeroableOption`, this is valid. unsafe impl Zeroable for Option {} -/// Create a new zeroed T. +/// Create an initializer for a zeroed `T`. /// /// The returned initializer will write `0x00` to every byte of the given `slot`. #[inline] -pub fn zeroed() -> impl Init { +pub fn init_zeroed() -> impl Init { // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T` // and because we write all zeroes, the memory is initialized. unsafe { diff --git a/rust/pin-init/src/macros.rs b/rust/pin-init/src/macros.rs index 935d77745d1d..9ced630737b8 100644 --- a/rust/pin-init/src/macros.rs +++ b/rust/pin-init/src/macros.rs @@ -1030,7 +1030,7 @@ macro_rules! __pin_data { /// /// This macro has multiple internal call configurations, these are always the very first ident: /// - nothing: this is the base case and called by the `{try_}{pin_}init!` macros. -/// - `with_update_parsed`: when the `..Zeroable::zeroed()` syntax has been handled. +/// - `with_update_parsed`: when the `..Zeroable::init_zeroed()` syntax has been handled. /// - `init_slot`: recursively creates the code that initializes all fields in `slot`. /// - `make_initializer`: recursively create the struct initializer that guarantees that every /// field has been initialized exactly once. @@ -1059,7 +1059,7 @@ macro_rules! __init_internal { @data($data, $($use_data)?), @has_data($has_data, $get_data), @construct_closure($construct_closure), - @zeroed(), // Nothing means default behavior. + @init_zeroed(), // Nothing means default behavior. ) }; ( @@ -1074,7 +1074,7 @@ macro_rules! __init_internal { @has_data($has_data:ident, $get_data:ident), // `pin_init_from_closure` or `init_from_closure`. @construct_closure($construct_closure:ident), - @munch_fields(..Zeroable::zeroed()), + @munch_fields(..Zeroable::init_zeroed()), ) => { $crate::__init_internal!(with_update_parsed: @this($($this)?), @@ -1084,7 +1084,7 @@ macro_rules! __init_internal { @data($data, $($use_data)?), @has_data($has_data, $get_data), @construct_closure($construct_closure), - @zeroed(()), // `()` means zero all fields not mentioned. + @init_zeroed(()), // `()` means zero all fields not mentioned. ) }; ( @@ -1124,7 +1124,7 @@ macro_rules! __init_internal { @has_data($has_data:ident, $get_data:ident), // `pin_init_from_closure` or `init_from_closure`. @construct_closure($construct_closure:ident), - @zeroed($($init_zeroed:expr)?), + @init_zeroed($($init_zeroed:expr)?), ) => {{ // We do not want to allow arbitrary returns, so we declare this type as the `Ok` return // type and shadow it later when we insert the arbitrary user code. That way there will be @@ -1196,7 +1196,7 @@ macro_rules! __init_internal { @data($data:ident), @slot($slot:ident), @guards($($guards:ident,)*), - @munch_fields($(..Zeroable::zeroed())? $(,)?), + @munch_fields($(..Zeroable::init_zeroed())? $(,)?), ) => { // Endpoint of munching, no fields are left. If execution reaches this point, all fields // have been initialized. Therefore we can now dismiss the guards by forgetting them. @@ -1300,11 +1300,11 @@ macro_rules! __init_internal { (make_initializer: @slot($slot:ident), @type_name($t:path), - @munch_fields(..Zeroable::zeroed() $(,)?), + @munch_fields(..Zeroable::init_zeroed() $(,)?), @acc($($acc:tt)*), ) => { // Endpoint, nothing more to munch, create the initializer. Since the users specified - // `..Zeroable::zeroed()`, the slot will already have been zeroed and all field that have + // `..Zeroable::init_zeroed()`, the slot will already have been zeroed and all field that have // not been overwritten are thus zero and initialized. We still check that all fields are // actually accessible by using the struct update syntax ourselves. // We are inside of a closure that is never executed and thus we can abuse `slot` to -- cgit From c47024ba198b01cab6bb6e3e5a69b73ed2f2aa16 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Fri, 23 May 2025 16:50:58 +0200 Subject: rust: pin-init: add `Zeroable::init_zeroed` The trait function delegates to the already existing `init_zeroed` function that returns a zeroing initializer for `Self`. The syntax `..Zeroable::init_zeroed()` is already used by the initialization macros to initialize all fields that are not mentioned in the initializer with zero. Therefore it is expected that the function also exists on the trait. Link: https://github.com/Rust-for-Linux/pin-init/pull/56/commits/a424a6c9af5a4418a8e5e986a3db26a4432e2f1a Link: https://lore.kernel.org/all/20250523145125.523275-3-lossin@kernel.org Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index 2f7ca94451e6..ef7e5a1e1c48 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -1495,7 +1495,18 @@ pub unsafe trait PinnedDrop: __internal::HasPinData { /// ```rust,ignore /// let val: Self = unsafe { core::mem::zeroed() }; /// ``` -pub unsafe trait Zeroable {} +pub unsafe trait Zeroable { + /// Create a new zeroed `Self`. + /// + /// The returned initializer will write `0x00` to every byte of the given `slot`. + #[inline] + fn init_zeroed() -> impl Init + where + Self: Sized, + { + init_zeroed() + } +} /// Marker trait for types that allow `Option` to be set to all zeroes in order to write /// `None` to that location. -- cgit From d67b37012080cf1978b5fd36f040a53f92152243 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Fri, 23 May 2025 16:50:59 +0200 Subject: rust: pin-init: add `zeroed()` & `Zeroable::zeroed()` functions `zeroed()` returns a zeroed out value of a sized type implementing `Zeroable`. The function is added as a free standing function, in addition to an associated function on `Zeroable`, because then it can be marked `const` (functions in traits can't be const at the moment). Link: https://github.com/Rust-for-Linux/pin-init/pull/56/commits/809e4ec160579c1601dce5d78b432a5b6c8e4e40 Link: https://lore.kernel.org/all/20250523145125.523275-4-lossin@kernel.org Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index ef7e5a1e1c48..a5bb3939b58b 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -1506,6 +1506,33 @@ pub unsafe trait Zeroable { { init_zeroed() } + + /// Create a `Self` consisting of all zeroes. + /// + /// Whenever a type implements [`Zeroable`], this function should be preferred over + /// [`core::mem::zeroed()`] or using `MaybeUninit::zeroed().assume_init()`. + /// + /// # Examples + /// + /// ``` + /// use pin_init::{Zeroable, zeroed}; + /// + /// #[derive(Zeroable)] + /// struct Point { + /// x: u32, + /// y: u32, + /// } + /// + /// let point: Point = zeroed(); + /// assert_eq!(point.x, 0); + /// assert_eq!(point.y, 0); + /// ``` + fn zeroed() -> Self + where + Self: Sized, + { + zeroed() + } } /// Marker trait for types that allow `Option` to be set to all zeroes in order to write @@ -1534,6 +1561,31 @@ pub fn init_zeroed() -> impl Init { } } +/// Create a `T` consisting of all zeroes. +/// +/// Whenever a type implements [`Zeroable`], this function should be preferred over +/// [`core::mem::zeroed()`] or using `MaybeUninit::zeroed().assume_init()`. +/// +/// # Examples +/// +/// ``` +/// use pin_init::{Zeroable, zeroed}; +/// +/// #[derive(Zeroable)] +/// struct Point { +/// x: u32, +/// y: u32, +/// } +/// +/// let point: Point = zeroed(); +/// assert_eq!(point.x, 0); +/// assert_eq!(point.y, 0); +/// ``` +pub const fn zeroed() -> T { + // SAFETY:By the type invariants of `Zeroable`, all zeroes is a valid bit pattern for `T`. + unsafe { core::mem::zeroed() } +} + macro_rules! impl_zeroable { ($($({$($generics:tt)*})? $t:ty, )*) => { // SAFETY: Safety comments written in the macro invocation. -- cgit From e93a238605348bc40fed77ba5582e311376d113b Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Fri, 23 May 2025 16:51:00 +0200 Subject: rust: pin-init: implement `ZeroableOption` for `&T` and `&mut T` `Option<&T>` and `Option<&mut T>` are documented [1] to have the `None` variant be all zeroes. Link: https://doc.rust-lang.org/stable/std/option/index.html#representation [1] Link: https://github.com/Rust-for-Linux/pin-init/pull/56/commits/5ef1638c79e019d3dc0c62db5905601644c2e60a Link: https://lore.kernel.org/all/20250523145125.523275-5-lossin@kernel.org Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index a5bb3939b58b..298a3e675b7f 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -1546,6 +1546,13 @@ pub unsafe trait ZeroableOption {} // SAFETY: by the safety requirement of `ZeroableOption`, this is valid. unsafe impl Zeroable for Option {} +// SAFETY: `Option<&T>` is part of the option layout optimization guarantee: +// . +unsafe impl ZeroableOption for &T {} +// SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee: +// . +unsafe impl ZeroableOption for &mut T {} + /// Create an initializer for a zeroed `T`. /// /// The returned initializer will write `0x00` to every byte of the given `slot`. -- cgit From 9f473538706b9fb5e82c9864b04089d35e4f93d5 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Fri, 23 May 2025 16:51:01 +0200 Subject: rust: pin-init: change `impl Zeroable for Option>` to `ZeroableOption for NonNull` This brings it in line with references. It too is listed in [1]. Link: https://doc.rust-lang.org/stable/std/option/index.html#representation Link: https://github.com/Rust-for-Linux/pin-init/pull/56/commits/8e52bf56ddc2190ce901d2f7c008ab8a64f653a9 Link: https://lore.kernel.org/all/20250523145125.523275-6-lossin@kernel.org Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index 298a3e675b7f..a4656e7976c7 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -1552,6 +1552,9 @@ unsafe impl ZeroableOption for &T {} // SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee: // . unsafe impl ZeroableOption for &mut T {} +// SAFETY: `Option>` is part of the option layout optimization guarantee: +// . +unsafe impl ZeroableOption for NonNull {} /// Create an initializer for a zeroed `T`. /// @@ -1630,7 +1633,6 @@ impl_zeroable! { Option, Option, Option, Option, Option, Option, Option, Option, - {} Option>, // SAFETY: `null` pointer is valid. // -- cgit From ec87ec35ca8bd61bfc1200224d332b4573b9dafa Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Fri, 23 May 2025 16:51:02 +0200 Subject: rust: pin-init: implement `ZeroableOption` for function pointers with up to 20 arguments `Option<[unsafe] [extern "abi"] fn(...args...) -> ret>` is documented [1] to also have the `None` variant equal all zeroes. Link: https://doc.rust-lang.org/stable/std/option/index.html#representation [1] Link: https://github.com/Rust-for-Linux/pin-init/pull/56/commits/b6c1ab4fb3699765f81ae512ecac5a2f032d8d51 Link: https://lore.kernel.org/all/20250523145125.523275-7-lossin@kernel.org Signed-off-by: Benno Lossin --- rust/pin-init/src/lib.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'rust/pin-init/src') diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index a4656e7976c7..3e5fe84ae547 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -1662,6 +1662,22 @@ macro_rules! impl_tuple_zeroable { impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J); +macro_rules! impl_fn_zeroable_option { + ([$($abi:literal),* $(,)?] $args:tt) => { + $(impl_fn_zeroable_option!({extern $abi} $args);)* + $(impl_fn_zeroable_option!({unsafe extern $abi} $args);)* + }; + ({$($prefix:tt)*} {$(,)?}) => {}; + ({$($prefix:tt)*} {$ret:ident, $($rest:ident),* $(,)?}) => { + // SAFETY: function pointers are part of the option layout optimization: + // . + unsafe impl<$ret, $($rest),*> ZeroableOption for $($prefix)* fn($($rest),*) -> $ret {} + impl_fn_zeroable_option!({$($prefix)*} {$($rest),*,}); + }; +} + +impl_fn_zeroable_option!(["Rust", "C"] { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U }); + /// This trait allows creating an instance of `Self` which contains exactly one /// [structurally pinned value](https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning). /// -- cgit