rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v5] rust: transmute: Add methods for FromBytes trait
@ 2025-03-20  1:40 Christian S. Lima
  2025-03-20 13:09 ` Benno Lossin
  0 siblings, 1 reply; 4+ messages in thread
From: Christian S. Lima @ 2025-03-20  1:40 UTC (permalink / raw)
  To: rust-for-linux, linux-kernel, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
	~lkcamp/patches, richard120310

Methods receive a slice and perform size check to add
a valid way to make conversion safe.
In this patch, I use an Option, in error case just
return `None` instead of an Error and
removed some commentaries.

The conversion between slices `[T]`
is separated from others, because I couldn't implement it
in the same way as the other conversions.

Link: https://github.com/Rust-for-Linux/linux/issues/1119
Signed-off-by: Christian S. Lima <christiansantoslima21@gmail.com>
---
Changes in v2:
- Rollback the implementation for the macro in the repository
and implement methods in trai
- Link to v2: https://lore.kernel.org/rust-for-linux/20241012193657.290cc79c@eugeo/T/#t

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/

- Link to v1: https://lore.kernel.org/rust-for-linux/20241009014810.23279-1-christiansantoslima21@gmail.com/
---
 rust/kernel/transmute.rs | 74 +++++++++++++++++++++++++++++++++++++---
 1 file changed, 69 insertions(+), 5 deletions(-)

diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 1c7d43771a37..5f2cf66187ad 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -9,15 +9,53 @@
 ///
 /// It's okay for the type to have padding, as initializing those bytes has no effect.
 ///
+/// # Example
+/// ```
+/// let foo = &[1, 2, 3, 4];
+///
+/// let result = u8::from_bytes(foo);
+///
+/// assert_eq!(*result, 0x40300201);
+/// ```
+///
 /// # 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 {
+    /// Receives a slice of bytes and converts to a valid reference of Self when it's possible.
+    fn from_bytes(bytes: &[u8]) -> Option<&Self>;
+
+    /// Receives a mutable slice of bytes and converts to a valid reference of Self when it's possible.
+    fn from_bytes_mut(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>() {
+                    let slice_ptr = bytes.as_ptr() as *const $t;
+                    unsafe { Some(&*slice_ptr) }
+                } else {
+                    None
+                }
+            }
+
+            fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut $t>
+            where
+                Self: AsBytes,
+            {
+                if bytes.len() == core::mem::size_of::<$t>() {
+                    let slice_ptr = bytes.as_mut_ptr() as *mut $t;
+                    unsafe { Some(&mut *slice_ptr) }
+                } else {
+                    None
+                }
+            }
+        })*
     };
 }
 
@@ -26,12 +64,38 @@ macro_rules! impl_frombytes {
     u8, u16, u32, u64, usize,
     i8, i16, i32, i64, isize,
 
-    // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
-    // patterns are also acceptable for arrays of that type.
-    {<T: FromBytes>} [T],
     {<T: FromBytes, const N: usize>} [T; N],
 }
 
+unsafe impl<T: FromBytes> FromBytes for [T] {
+    fn from_bytes(bytes: &[u8]) -> Option<&Self> {
+        let slice_ptr = bytes.as_ptr() as *const T;
+        if bytes.len() % core::mem::size_of::<T>() == 0 {
+            let slice_len = bytes.len() / core::mem::size_of::<T>();
+            // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
+            // patterns are also acceptable for arrays of that type.
+            unsafe { Some(core::slice::from_raw_parts(slice_ptr, slice_len)) }
+        } else {
+            None
+        }
+    }
+
+    fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self>
+    where
+        Self: AsBytes,
+    {
+        let slice_ptr = bytes.as_mut_ptr() as *mut T;
+        if bytes.len() % core::mem::size_of::<T>() == 0 {
+            let slice_len = bytes.len() / core::mem::size_of::<T>();
+            // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
+            // patterns are also acceptable for arrays of that type.
+            unsafe { Some(core::slice::from_raw_parts_mut(slice_ptr, slice_len)) }
+        } else {
+            None
+        }
+    }
+}
+
 /// Types that can be viewed as an immutable slice of initialized bytes.
 ///
 /// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
-- 
2.49.0


^ permalink raw reply related	[flat|nested] 4+ messages in thread

* Re: [PATCH v5] rust: transmute: Add methods for FromBytes trait
  2025-03-20  1:40 [PATCH v5] rust: transmute: Add methods for FromBytes trait Christian S. Lima
@ 2025-03-20 13:09 ` Benno Lossin
  2025-03-24  2:41   ` Christian
  0 siblings, 1 reply; 4+ messages in thread
From: Benno Lossin @ 2025-03-20 13:09 UTC (permalink / raw)
  To: Christian S. Lima, rust-for-linux, linux-kernel, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
	~lkcamp/patches, richard120310

On Thu Mar 20, 2025 at 2:40 AM CET, Christian S. Lima wrote:
> Methods receive a slice and perform size check to add
> a valid way to make conversion safe.
> In this patch, I use an Option, in error case just
> return `None` instead of an Error and
> removed some commentaries.
>
> The conversion between slices `[T]`
> is separated from others, because I couldn't implement it
> in the same way as the other conversions.

Why is this commit message wrapped like this?

>
> Link: https://github.com/Rust-for-Linux/linux/issues/1119
> Signed-off-by: Christian S. Lima <christiansantoslima21@gmail.com>
> ---
> Changes in v2:
> - Rollback the implementation for the macro in the repository
> and implement methods in trai
> - Link to v2: https://lore.kernel.org/rust-for-linux/20241012193657.290cc79c@eugeo/T/#t
>
> 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/
>
> - Link to v1: https://lore.kernel.org/rust-for-linux/20241009014810.23279-1-christiansantoslima21@gmail.com/

What changed in version 5? Or does "Changes in v4" mean "Changes done to
v4"?

> ---
>  rust/kernel/transmute.rs | 74 +++++++++++++++++++++++++++++++++++++---
>  1 file changed, 69 insertions(+), 5 deletions(-)
>
> diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
> index 1c7d43771a37..5f2cf66187ad 100644
> --- a/rust/kernel/transmute.rs
> +++ b/rust/kernel/transmute.rs
> @@ -9,15 +9,53 @@
>  ///
>  /// It's okay for the type to have padding, as initializing those bytes has no effect.
>  ///
> +/// # Example
> +/// ```
> +/// let foo = &[1, 2, 3, 4];
> +///
> +/// let result = u8::from_bytes(foo);
> +///
> +/// assert_eq!(*result, 0x40300201);

AFAIU this relies on the endianess of the architecture, I would check
the endianess in the test and then change the assertion based on that.

> +/// ```
> +///
>  /// # 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 {
> +    /// Receives a slice of bytes and converts to a valid reference of Self when it's possible.

/// Converts a slice of bytes to a reference to `Self` when possible.

> +    fn from_bytes(bytes: &[u8]) -> Option<&Self>;
> +
> +    /// Receives a mutable slice of bytes and converts to a valid reference of Self when it's possible.

Similarly here.

> +    fn from_bytes_mut(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>() {
> +                    let slice_ptr = bytes.as_ptr() as *const $t;

Please use `.cast::<$t>()` instead of `as`.

> +                    unsafe { Some(&*slice_ptr) }

Missing safety comment.

> +                } else {
> +                    None
> +                }
> +            }
> +
> +            fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut $t>
> +            where
> +                Self: AsBytes,
> +            {
> +                if bytes.len() == core::mem::size_of::<$t>() {
> +                    let slice_ptr = bytes.as_mut_ptr() as *mut $t;

Please use `cast`.

> +                    unsafe { Some(&mut *slice_ptr) }

Missing safety comment.

> +                } else {
> +                    None
> +                }
> +            }
> +        })*
>      };
>  }
>  
> @@ -26,12 +64,38 @@ macro_rules! impl_frombytes {
>      u8, u16, u32, u64, usize,
>      i8, i16, i32, i64, isize,
>  
> -    // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
> -    // patterns are also acceptable for arrays of that type.
> -    {<T: FromBytes>} [T],
>      {<T: FromBytes, const N: usize>} [T; N],

Missing SAFETY comment (the one that you remove above should still be
there).

>  }
>  
> +unsafe impl<T: FromBytes> FromBytes for [T] {

Missing SAFETY comment, you should copy the one from above.

> +    fn from_bytes(bytes: &[u8]) -> Option<&Self> {
> +        let slice_ptr = bytes.as_ptr() as *const T;
> +        if bytes.len() % core::mem::size_of::<T>() == 0 {
> +            let slice_len = bytes.len() / core::mem::size_of::<T>();
> +            // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
> +            // patterns are also acceptable for arrays of that type.

This safety comment doesn't match the called function below.

> +            unsafe { Some(core::slice::from_raw_parts(slice_ptr, slice_len)) }
> +        } else {
> +            None
> +        }
> +    }
> +
> +    fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self>
> +    where
> +        Self: AsBytes,
> +    {
> +        let slice_ptr = bytes.as_mut_ptr() as *mut T;
> +        if bytes.len() % core::mem::size_of::<T>() == 0 {
> +            let slice_len = bytes.len() / core::mem::size_of::<T>();
> +            // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
> +            // patterns are also acceptable for arrays of that type.

Ditto.

---
Cheers,
Benno

> +            unsafe { Some(core::slice::from_raw_parts_mut(slice_ptr, slice_len)) }
> +        } else {
> +            None
> +        }
> +    }
> +}
> +
>  /// Types that can be viewed as an immutable slice of initialized bytes.
>  ///
>  /// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This



^ permalink raw reply	[flat|nested] 4+ messages in thread

* Re: [PATCH v5] rust: transmute: Add methods for FromBytes trait
  2025-03-20 13:09 ` Benno Lossin
@ 2025-03-24  2:41   ` Christian
  2025-03-24 12:31     ` Benno Lossin
  0 siblings, 1 reply; 4+ messages in thread
From: Christian @ 2025-03-24  2:41 UTC (permalink / raw)
  To: Benno Lossin
  Cc: rust-for-linux, linux-kernel, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, ~lkcamp/patches,
	richard120310

Hi, Benno.

> Why is this commit message wrapped like this?

Probably my text editor.

> What changed in version 5? Or does "Changes in v4" mean "Changes done to
> v4"?

Changes done to v4. I misinterpreted it? If that's the case, I'll
change in the next patch.

> AFAIU this relies on the endianess of the architecture, I would check
> the endianess in the test and then change the assertion based on that.

I see, good catch!

Thanks,
Christian

^ permalink raw reply	[flat|nested] 4+ messages in thread

* Re: [PATCH v5] rust: transmute: Add methods for FromBytes trait
  2025-03-24  2:41   ` Christian
@ 2025-03-24 12:31     ` Benno Lossin
  0 siblings, 0 replies; 4+ messages in thread
From: Benno Lossin @ 2025-03-24 12:31 UTC (permalink / raw)
  To: Christian
  Cc: rust-for-linux, linux-kernel, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, ~lkcamp/patches,
	richard120310

On Mon Mar 24, 2025 at 3:41 AM CET, Christian wrote:
>> What changed in version 5? Or does "Changes in v4" mean "Changes done to
>> v4"?
>
> Changes done to v4. I misinterpreted it? If that's the case, I'll
> change in the next patch.

I was just confused by the labeling, I've normally seen headings like
"What changed in v5" as opposed to "What changed from v4".

---
Cheers,
Benno


^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2025-03-24 12:31 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-03-20  1:40 [PATCH v5] rust: transmute: Add methods for FromBytes trait Christian S. Lima
2025-03-20 13:09 ` Benno Lossin
2025-03-24  2:41   ` Christian
2025-03-24 12:31     ` Benno Lossin

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).