[PATCH 1/2] rust: Zeroable: allow struct update syntax outside init macros

Paolo Bonzini posted 2 patches 1 year, 2 months ago
[PATCH 1/2] rust: Zeroable: allow struct update syntax outside init macros
Posted by Paolo Bonzini 1 year, 2 months ago
The Zeroable trait is a marker trait, even though the various init macros
use a "fake" struct update syntax.  Sometimes, such a struct update
syntax can be useful even outside the init macros.  Add an associated
const that returns an all-zero instance of a Zeroable type.

The exact syntax used by the init macros cannot be reproduced without
forgoing the ability to use Zeroable::ZERO in const context.  However,
it might not be a good idea to add a fn zeroed() inside the
Zeroable trait, to avoid confusion with the init::zeroed() function
and because Zeroable::ZERO is unrelated to the Init and PinInit
traits.  In other words, let's treat this difference as a
feature rather than a bug.

The definition of the ZERO constant requires adding a Sized boundary, but
this is not a problem either because neither slices nor trait objects
are zeroable.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
---
 rust/kernel/init.rs | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletion(-)

diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs
index a17ac8762d8f..a00e7ff6a513 100644
--- a/rust/kernel/init.rs
+++ b/rust/kernel/init.rs
@@ -1392,7 +1392,12 @@ pub unsafe trait PinnedDrop: __internal::HasPinData {
 /// ```rust,ignore
 /// let val: Self = unsafe { core::mem::zeroed() };
 /// ```
-pub unsafe trait Zeroable {}
+pub unsafe trait Zeroable: Sized {
+    /// Return a value of Self whose memory representation consists of all zeroes.
+    // SAFETY: the Zeroable trait itself is unsafe, and declaring it (whether
+    // manually or via derivation) implies that this is not undefined behavior.
+    const ZERO: Self = unsafe { core::mem::zeroed() };
+}
 
 /// Create a new zeroed T.
 ///
@@ -1444,7 +1444,7 @@ macro_rules! impl_zeroable {
     {<T>} Opaque<T>,
 
     // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`.
-    {<T: ?Sized + Zeroable>} UnsafeCell<T>,
+    {<T: Zeroable>} UnsafeCell<T>,
 
     // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee).
     Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>,
-- 
2.47.0
Re: [PATCH 1/2] rust: Zeroable: allow struct update syntax outside init macros
Posted by Alice Ryhl 1 year, 2 months ago
On Thu, Nov 28, 2024 at 3:13 PM Paolo Bonzini <pbonzini@redhat.com> wrote:
>
> The Zeroable trait is a marker trait, even though the various init macros
> use a "fake" struct update syntax.  Sometimes, such a struct update
> syntax can be useful even outside the init macros.  Add an associated
> const that returns an all-zero instance of a Zeroable type.
>
> The exact syntax used by the init macros cannot be reproduced without
> forgoing the ability to use Zeroable::ZERO in const context.  However,
> it might not be a good idea to add a fn zeroed() inside the
> Zeroable trait, to avoid confusion with the init::zeroed() function
> and because Zeroable::ZERO is unrelated to the Init and PinInit
> traits.  In other words, let's treat this difference as a
> feature rather than a bug.
>
> The definition of the ZERO constant requires adding a Sized boundary, but
> this is not a problem either because neither slices nor trait objects
> are zeroable.
>
> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>

Slices are zeroable. I know they don't implement the trait, but they
could implement it, and this could be used to implement e.g.:

pub fn write_zero<T: Zeroed + ?Sized>(value: &mut T) {
    memset(0, ...);
}

Alice
Re: [PATCH 1/2] rust: Zeroable: allow struct update syntax outside init macros
Posted by Paolo Bonzini 1 year, 2 months ago
On 11/28/24 15:40, Alice Ryhl wrote:
>> The definition of the ZERO constant requires adding a Sized boundary, but
>> this is not a problem either because neither slices nor trait objects
>> are zeroable.
>>
>> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
> 
> Slices are zeroable. I know they don't implement the trait,

Right, I should have used the uppercase "Zeroable" for clarity.

> but they could implement it, and this could be used to implement e.g.:
> 
> pub fn write_zero<T: Zeroed + ?Sized>(value: &mut T) {
>      memset(0, ...);
> }

Yeah, that would be I think

     pub fn write_zero<T: Zeroable + ?Sized>(value: &mut T) {
         unsafe {
            ptr::write_bytes((value as *mut T).cast::<u8>(), 0,
                             std::mem::size_of_val(value))
         }
     }

?  And it works for both sized values and slices.  If Zeroable is 
limited to sized types, I guess you could still do:

     pub fn write_zero_slice<T: Zeroable>(value: &mut [T]) {
         ptr::write_bytes(value.as_mut_ptr(), 0, value.len())
     }

So the question is whether the ZERO constant is worthwhile enough, to 
justify the limitation of the Sized bound (e.g. having separate 
write_zero and write_zero_slice in the future).

Thanks,

Paolo
Re: [PATCH 1/2] rust: Zeroable: allow struct update syntax outside init macros
Posted by Alice Ryhl 1 year, 2 months ago
On Thu, Nov 28, 2024 at 5:43 PM Paolo Bonzini <pbonzini@redhat.com> wrote:
>
> On 11/28/24 15:40, Alice Ryhl wrote:
> >> The definition of the ZERO constant requires adding a Sized boundary, but
> >> this is not a problem either because neither slices nor trait objects
> >> are zeroable.
> >>
> >> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
> >
> > Slices are zeroable. I know they don't implement the trait,
>
> Right, I should have used the uppercase "Zeroable" for clarity.
>
> > but they could implement it, and this could be used to implement e.g.:
> >
> > pub fn write_zero<T: Zeroed + ?Sized>(value: &mut T) {
> >      memset(0, ...);
> > }
>
> Yeah, that would be I think
>
>      pub fn write_zero<T: Zeroable + ?Sized>(value: &mut T) {
>          unsafe {
>             ptr::write_bytes((value as *mut T).cast::<u8>(), 0,
>                              std::mem::size_of_val(value))
>          }
>      }
>
> ?  And it works for both sized values and slices.  If Zeroable is
> limited to sized types, I guess you could still do:
>
>      pub fn write_zero_slice<T: Zeroable>(value: &mut [T]) {
>          ptr::write_bytes(value.as_mut_ptr(), 0, value.len())
>      }
>
> So the question is whether the ZERO constant is worthwhile enough, to
> justify the limitation of the Sized bound (e.g. having separate
> write_zero and write_zero_slice in the future).

Why not both?

If you change the constant to a const fn, then you don't have to rule
out either use-case.

Alice