[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <DANSZ6Q476EC.3GY00K717QVUL@nvidia.com>
Date: Mon, 16 Jun 2025 17:09:21 +0900
From: "Alexandre Courbot" <acourbot@...dia.com>
To: "Every2" <christiansantoslima21@...il.com>, "Miguel Ojeda"
<ojeda@...nel.org>, "Alex Gaynor" <alex.gaynor@...il.com>, "Boqun Feng"
<boqun.feng@...il.com>, "Gary Guo" <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>, "Benno Lossin"
<benno.lossin@...ton.me>, "Andreas Hindborg" <a.hindborg@...nel.org>,
"Alice Ryhl" <aliceryhl@...gle.com>, "Trevor Gross" <tmgross@...ch.edu>,
"Danilo Krummrich" <dakr@...nel.org>, <rust-for-linux@...r.kernel.org>,
<linux-kernel@...r.kernel.org>, <~lkcamp/patches@...ts.sr.ht>,
<richard120310@...il.com>
Subject: Re: [PATCH v7] rust: transmute: Add methods for FromBytes trait
On Sun Jun 15, 2025 at 4:20 PM JST, Every2 wrote:
> Methods receive a slice and perform size check to add a valid way to make
> conversion safe. An Option is used, in error case just return `None`.
>
> Link: https://github.com/Rust-for-Linux/linux/issues/1119
> Signed-off-by: Every2 <christiansantoslima21@...il.com>
> ---
> Changes in v2:
> - Rollback the implementation for the macro in the repository and implement
> methods in trait
> - Link to v2: https://lore.kernel.org/rust-for-linux/20241012070121.110481-1-christiansantoslima21@gmail.com/
>
> Changes in v3:
> - Fix grammar errors
> - Remove repeated tests
> - Fix alignment errors
> - Fix tests not building
> - Link to v3: https://lore.kernel.org/rust-for-linux/20241109055442.85190-1-christiansantoslima21@gmail.com/
>
> Changes in v4:
> - Removed core::simd::ToBytes
> - Changed trait and methods to safe Add
> - Result<&Self, Error> in order to make safe methods
> - Link to v4: https://lore.kernel.org/rust-for-linux/20250314034910.134463-1-christiansantoslima21@gmail.com/
>
> Changes in v5:
> - Changed from Result to Option
> - Removed commentaries
> - Returned trait impl to unsafe
> - Link to v5: https://lore.kernel.org/rust-for-linux/20250320014041.101470-1-christiansantoslima21@gmail.com/
>
> Changes in v6:
> - Add endianess check to doc test and use match to check
> success case
> - Reformulated safety comments
> - Link to v6: https://lore.kernel.org/rust-for-linux/20250330234039.29814-1-christiansantoslima21@gmail.com/
>
> Changes in v7:
> - Add alignment check
> ---
> rust/kernel/transmute.rs | 95 +++++++++++++++++++++++++++++++++++++---
> 1 file changed, 89 insertions(+), 6 deletions(-)
>
> diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
> index 1c7d43771a37..5443355de17d 100644
> --- a/rust/kernel/transmute.rs
> +++ b/rust/kernel/transmute.rs
> @@ -9,29 +9,112 @@
> ///
> /// It's okay for the type to have padding, as initializing those bytes has no effect.
> ///
> +/// # Example
> +/// ```
This test won't build unless you add a
/// use kernel::transmute::FromBytes;
here.
Also, two other tests in `rust/kernel/dma.rs` break as a resulf of the new
methods added to `FromBytes`.
> +/// let arr = [1, 2, 3, 4];
> +///
> +/// let result = u32::from_bytes(&arr);
> +///
> +/// #[cfg(target_endian = "little")]
> +/// match result {
> +/// Some(x) => assert_eq!(*x, 0x4030201),
> +/// None => unreachable!()
> +/// }
> +///
> +/// #[cfg(target_endian = "big")]
> +/// match result {
> +/// Some(x) => assert_eq!(*x, 0x1020304),
> +/// None => unreachable!()
> +/// }
> +/// ```
> +///
> /// # Safety
> ///
> /// All bit-patterns must be valid for this type. This type must not have interior mutability.
> -pub unsafe trait FromBytes {}
> +pub unsafe trait FromBytes {
> + /// Converts a slice of bytes to a reference to `Self` when possible.
> + fn from_bytes(bytes: &[u8]) -> Option<&Self>;
> +
> + /// Converts a mutable slice of bytes to a reference to `Self` when possible.
> + fn from_mut_bytes(bytes: &mut [u8]) -> Option<&mut Self>
> + where
> + Self: AsBytes;
> +}
>
> macro_rules! impl_frombytes {
> ($($({$($generics:tt)*})? $t:ty, )*) => {
> // SAFETY: Safety comments written in the macro invocation.
> - $(unsafe impl$($($generics)*)? FromBytes for $t {})*
> + $(unsafe impl$($($generics)*)? FromBytes for $t {
> + fn from_bytes(bytes: &[u8]) -> Option<&$t> {
> + if bytes.len() == core::mem::size_of::<$t>()
> + && (bytes.as_ptr() as usize) % core::mem::align_of::<$t>() == 0
> + {
> + let slice_ptr = bytes.as_ptr().cast::<$t>();
> + unsafe { Some(&*slice_ptr) }
> + } else {
> + None
> + }
> + }
> +
> + fn from_mut_bytes(bytes: &mut [u8]) -> Option<&mut $t>
> + where
> + Self: AsBytes,
> + {
> + if bytes.len() == core::mem::size_of::<$t>()
> + && (bytes.as_mut_ptr() as usize) % core::mem::align_of::<$t>() == 0
> + {
> + let slice_ptr = bytes.as_mut_ptr().cast::<$t>();
> + unsafe { Some(&mut *slice_ptr) }
> + } else {
> + None
> + }
> + }
> + })*
I asked this in the previous revision [1] but didn't get a reply: why aren't we
defining this as the default implementations for `FromBytes`, since must users
will want to do exactly this anyway? I tried to do it and it failed because it
only works if `Self` is `Sized`, and we cannot conditionally implement a
default method of a trait.
We can, however, use a proxy trait that provides an implementation of
`FromBytes` for any type that is `Sized`:
pub unsafe trait FromBytesSized: Sized {}
unsafe impl<T> FromBytes for T
where
T: FromBytesSized,
{
fn from_bytes(bytes: &[u8]) -> Option<&Self> {
if bytes.len() == core::mem::size_of::<Self>()
&& (bytes.as_ptr() as usize) % core::mem::align_of::<Self>() == 0
{
let slice_ptr = bytes.as_ptr().cast::<Self>();
unsafe { Some(&*slice_ptr) }
} else {
None
}
}
fn from_mut_bytes(bytes: &mut [u8]) -> Option<&mut Self>
where
Self: AsBytes,
{
if bytes.len() == core::mem::size_of::<Self>()
&& (bytes.as_mut_ptr() as usize) % core::mem::align_of::<Self>() == 0
{
let slice_ptr = bytes.as_mut_ptr().cast::<Self>();
unsafe { Some(&mut *slice_ptr) }
} else {
None
}
}
}
You can then implement `FromBytesSized` for all the types given to
`impl_frombytes!`.
The main benefit over the `impl_frombytes!` macro is that `FromBytesSized` is
public, and external users can just implement it on their types without having
to provide implementations for `from_bytes` and `from_mut_bytes` which would in
all likelihood be identical to the ones of `impl_frombytes!` anyway. And if
they need something different, they can always implement `FromBytes` directly.
For instance, the failing tests in `dma.rs` that I mentioned above can be fixed
by making them implement `FromBytesSized` instead of `FromBytes`.
[1] https://lore.kernel.org/rust-for-linux/D9D876NZCA5O.KFO526Q4HEED@nvidia.com/
Powered by blists - more mailing lists