[PATCH v2] rust: transmute: Add implementation for FromBytes trait

Christian dos Santos de Lima posted 1 patch 1 month, 2 weeks ago
There is a newer version of this series
rust/kernel/lib.rs       |   2 +
rust/kernel/transmute.rs | 120 ++++++++++++++++++++++++++++-----------
2 files changed, 88 insertions(+), 34 deletions(-)
[PATCH v2] rust: transmute: Add implementation for FromBytes trait
Posted by Christian dos Santos de Lima 1 month, 2 weeks ago
Add implementation and documentation for FromBytes trait.

Add new feature block in order to allow using ToBytes
and bound to from_bytes_mut function. I'm adding this feature
because is possible create a value with disallowed bit pattern
and as_byte_mut could create such value by mutating the array and
acessing the original value. So adding ToBytes this can be avoided.

Link: https://github.com/Rust-for-Linux/linux/issues/1119
Signed-off-by: Christian dos Santos de Lima <christiansantoslima21@gmail.com>
---
changes in v2:
     - Rollback the implementation for the macro in the repository and add implementation of functions in trait
---
 rust/kernel/lib.rs       |   2 +
 rust/kernel/transmute.rs | 120 ++++++++++++++++++++++++++++-----------
 2 files changed, 88 insertions(+), 34 deletions(-)

diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index dc37aef6a008..5215f5744e12 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -18,6 +18,8 @@
 #![feature(lint_reasons)]
 #![feature(new_uninit)]
 #![feature(unsize)]
+#![feature(portable_simd)]
+#![feature(trivial_bounds)]
 
 // Ensure conditional compilation based on the kernel configuration works;
 // otherwise we may silently break things like initcall handling.
diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 1c7d43771a37..bce42cc7265e 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -2,6 +2,7 @@
 
 //! Traits for transmuting types.
 
+use core::simd::ToBytes;
 /// Types for which any bit pattern is valid.
 ///
 /// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
@@ -9,15 +10,58 @@
 ///
 /// It's okay for the type to have padding, as initializing those bytes has no effect.
 ///
+/// # Example
+///
+/// This example is how to use the FromBytes trait
+/// ```
+/// // Initialize a slice of bytes
+/// let foo = &[1, 2, 3, 4];
+///
+/// //Use the function implemented by trait in integer type
+/// let result = u8::from_bytes(foo);
+///
+/// assert_eq!(*result, 0x4030201);
+/// ```
 /// # 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 {
+    ///Get an imutable slice of bytes and converts to a reference to Self
+    unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self;
+    /// Get a mutable slice of bytes and converts to a reference to Self
+    ///
+    /// # Safety
+    ///
+    ///  Bound ToBytes in order to avoid use with disallowed bit patterns
+    unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
+    where
+        Self: ToBytes;
+}
 
+//Get a reference of slice of bytes and converts into a reference of integer or a slice with a defined size
 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 {
+            unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self
+            {
+                unsafe {
+                    let slice_ptr = slice_of_bytes.as_ptr() as *const Self;
+                    &*slice_ptr
+                }
+            }
+
+            unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
+            where
+                Self: ToBytes,
+            {
+                unsafe {
+                    let slice_ptr = slice_of_bytes.as_mut_ptr() as *mut Self;
+                    &mut *slice_ptr
+                }
+
+            }
+        })*
     };
 }
 
@@ -28,44 +72,52 @@ macro_rules! impl_frombytes {
 
     // 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],
 }
 
-/// Types that can be viewed as an immutable slice of initialized bytes.
+/// Get a reference of slice of bytes and converts into a reference of an array of integers
 ///
-/// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
-/// means that it should not have any padding, as padding bytes are uninitialized. Reading
-/// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive
-/// information on the stack to userspace.
+/// Types for which any bit pattern is valid.
 ///
-/// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered
-/// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so
-/// this is a correctness requirement, but not a safety requirement.
+/// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
+/// reading arbitrary bytes into something that contains a `bool` is not okay.
 ///
-/// # Safety
+/// It's okay for the type to have padding, as initializing those bytes has no effect.
 ///
-/// Values of this type may not contain any uninitialized bytes. This type must not have interior
-/// mutability.
-pub unsafe trait AsBytes {}
-
-macro_rules! impl_asbytes {
-    ($($({$($generics:tt)*})? $t:ty, )*) => {
-        // SAFETY: Safety comments written in the macro invocation.
-        $(unsafe impl$($($generics)*)? AsBytes for $t {})*
-    };
-}
-
-impl_asbytes! {
-    // SAFETY: Instances of the following types have no uninitialized portions.
-    u8, u16, u32, u64, usize,
-    i8, i16, i32, i64, isize,
-    bool,
-    char,
-    str,
+/// # Example
+///
+/// This example is how to use the FromBytes trait
+/// ```
+/// // Initialize a slice of bytes
+/// let foo = &[1, 2, 3, 4];
+///
+/// //Use the function implemented by trait in integer type
+/// let result = <[u32]>::from_bytes(slice_of_bytes);
+///
+/// assert_eq!(*result, 0x4030201);
+/// ```
+// 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 impl<T: FromBytes> FromBytes for [T] {
+    unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self {
+        //Safety: Guarantee that all values are initiliazed
+        unsafe {
+            let slice_ptr = slice_of_bytes.as_ptr() as *const T;
+            let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
+            core::slice::from_raw_parts(slice_ptr, slice_len)
+        }
+    }
 
-    // SAFETY: If individual values in an array have no uninitialized portions, then the array
-    // itself does not have any uninitialized portions either.
-    {<T: AsBytes>} [T],
-    {<T: AsBytes, const N: usize>} [T; N],
+    //Safety: Guarantee that all values are initiliazed
+    unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
+    where
+        Self: ToBytes,
+    {
+        //Safety: Guarantee that all values are initiliazed
+        unsafe {
+            let slice_ptr = slice_of_bytes.as_mut_ptr() as *mut T;
+            let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
+            core::slice::from_raw_parts_mut(slice_ptr, slice_len)
+        }
+    }
 }
-- 
2.47.0
Re: [PATCH v2] rust: transmute: Add implementation for FromBytes trait
Posted by kernel test robot 1 month, 1 week ago
Hi Christian,

kernel test robot noticed the following build errors:

[auto build test ERROR on rust/rust-next]
[also build test ERROR on next-20241015]
[cannot apply to linus/master v6.12-rc3]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Christian-dos-Santos-de-Lima/rust-transmute-Add-implementation-for-FromBytes-trait/20241012-150333
base:   https://github.com/Rust-for-Linux/linux rust-next
patch link:    https://lore.kernel.org/r/20241012070121.110481-1-christiansantoslima21%40gmail.com
patch subject: [PATCH v2] rust: transmute: Add implementation for FromBytes trait
config: um-randconfig-002-20241015 (https://download.01.org/0day-ci/archive/20241016/202410160946.XR7mVFjR-lkp@intel.com/config)
compiler: clang version 20.0.0git (https://github.com/llvm/llvm-project bfe84f7085d82d06d61c632a7bad1e692fd159e4)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20241016/202410160946.XR7mVFjR-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202410160946.XR7mVFjR-lkp@intel.com/

All errors (new ones prefixed by >>):

   |                                                   ^
   In file included from rust/helpers/helpers.c:10:
   In file included from rust/helpers/blk.c:3:
   In file included from include/linux/blk-mq.h:5:
   In file included from include/linux/blkdev.h:9:
   In file included from include/linux/blk_types.h:10:
   In file included from include/linux/bvec.h:10:
   In file included from include/linux/highmem.h:12:
   In file included from include/linux/hardirq.h:11:
   In file included from arch/um/include/asm/hardirq.h:5:
   In file included from include/asm-generic/hardirq.h:17:
   In file included from include/linux/irq.h:20:
   In file included from include/linux/io.h:14:
   In file included from arch/um/include/asm/io.h:24:
   include/asm-generic/io.h:574:61: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   574 |         val = __le32_to_cpu((__le32 __force)__raw_readl(PCI_IOBASE + addr));
   |                                                         ~~~~~~~~~~ ^
   include/uapi/linux/byteorder/little_endian.h:35:51: note: expanded from macro '__le32_to_cpu'
   35 | #define __le32_to_cpu(x) ((__force __u32)(__le32)(x))
   |                                                   ^
   In file included from rust/helpers/helpers.c:10:
   In file included from rust/helpers/blk.c:3:
   In file included from include/linux/blk-mq.h:5:
   In file included from include/linux/blkdev.h:9:
   In file included from include/linux/blk_types.h:10:
   In file included from include/linux/bvec.h:10:
   In file included from include/linux/highmem.h:12:
   In file included from include/linux/hardirq.h:11:
   In file included from arch/um/include/asm/hardirq.h:5:
   In file included from include/asm-generic/hardirq.h:17:
   In file included from include/linux/irq.h:20:
   In file included from include/linux/io.h:14:
   In file included from arch/um/include/asm/io.h:24:
   include/asm-generic/io.h:585:33: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   585 |         __raw_writeb(value, PCI_IOBASE + addr);
   |                             ~~~~~~~~~~ ^
   include/asm-generic/io.h:595:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   595 |         __raw_writew((u16 __force)cpu_to_le16(value), PCI_IOBASE + addr);
   |                                                       ~~~~~~~~~~ ^
   include/asm-generic/io.h:605:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   605 |         __raw_writel((u32 __force)cpu_to_le32(value), PCI_IOBASE + addr);
   |                                                       ~~~~~~~~~~ ^
   include/asm-generic/io.h:693:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   693 |         readsb(PCI_IOBASE + addr, buffer, count);
   |                ~~~~~~~~~~ ^
   include/asm-generic/io.h:701:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   701 |         readsw(PCI_IOBASE + addr, buffer, count);
   |                ~~~~~~~~~~ ^
   include/asm-generic/io.h:709:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   709 |         readsl(PCI_IOBASE + addr, buffer, count);
   |                ~~~~~~~~~~ ^
   include/asm-generic/io.h:718:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   718 |         writesb(PCI_IOBASE + addr, buffer, count);
   |                 ~~~~~~~~~~ ^
   include/asm-generic/io.h:727:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   727 |         writesw(PCI_IOBASE + addr, buffer, count);
   |                 ~~~~~~~~~~ ^
   include/asm-generic/io.h:736:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   736 |         writesl(PCI_IOBASE + addr, buffer, count);
   |                 ~~~~~~~~~~ ^
   13 warnings generated.
   clang diag: include/linux/vmstat.h:518:36: warning: arithmetic between different enumeration types ('enum node_stat_item' and 'enum lru_list') [-Wenum-enum-conversion]
   clang diag: include/asm-generic/io.h:548:31: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:561:61: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:574:61: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:585:33: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:595:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:605:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:693:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:701:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:709:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:718:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:727:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:736:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/linux/vmstat.h:518:36: warning: arithmetic between different enumeration types ('enum node_stat_item' and 'enum lru_list') [-Wenum-enum-conversion]
   clang diag: include/asm-generic/io.h:548:31: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:561:61: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:574:61: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:585:33: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:595:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:605:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:693:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:701:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:709:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:718:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:727:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:736:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/linux/vmstat.h:518:36: warning: arithmetic between different enumeration types ('enum node_stat_item' and 'enum lru_list') [-Wenum-enum-conversion]
   clang diag: include/asm-generic/io.h:548:31: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:561:61: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:574:61: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:585:33: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:595:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:605:59: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:693:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:701:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:709:20: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:718:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:727:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
   clang diag: include/asm-generic/io.h:736:21: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
>> error[E0432]: unresolved import `crate::transmute::AsBytes`
   --> rust/kernel/uaccess.rs:12:17
   |
   12 |     transmute::{AsBytes, FromBytes},
   |                 ^^^^^^^
   |                 |
   |                 no `AsBytes` in `transmute`
   |                 help: a similar name exists in the module: `ToBytes`

-- 
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
Re: [PATCH v2] rust: transmute: Add implementation for FromBytes trait
Posted by Gary Guo 1 month, 2 weeks ago
On Sat, 12 Oct 2024 04:01:21 -0300
Christian dos Santos de Lima <christiansantoslima21@gmail.com> wrote:

> Add implementation and documentation for FromBytes trait.
> 
> Add new feature block in order to allow using ToBytes
> and bound to from_bytes_mut function. I'm adding this feature
> because is possible create a value with disallowed bit pattern
> and as_byte_mut could create such value by mutating the array and
> acessing the original value. So adding ToBytes this can be avoided.
> 
> Link: https://github.com/Rust-for-Linux/linux/issues/1119
> Signed-off-by: Christian dos Santos de Lima <christiansantoslima21@gmail.com>
> ---
> changes in v2:
>      - Rollback the implementation for the macro in the repository and add implementation of functions in trait
> ---
>  rust/kernel/lib.rs       |   2 +
>  rust/kernel/transmute.rs | 120 ++++++++++++++++++++++++++++-----------
>  2 files changed, 88 insertions(+), 34 deletions(-)
> 
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index dc37aef6a008..5215f5744e12 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -18,6 +18,8 @@
>  #![feature(lint_reasons)]
>  #![feature(new_uninit)]
>  #![feature(unsize)]
> +#![feature(portable_simd)]
> +#![feature(trivial_bounds)]
>  
>  // Ensure conditional compilation based on the kernel configuration works;
>  // otherwise we may silently break things like initcall handling.
> diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
> index 1c7d43771a37..bce42cc7265e 100644
> --- a/rust/kernel/transmute.rs
> +++ b/rust/kernel/transmute.rs
> @@ -2,6 +2,7 @@
>  
>  //! Traits for transmuting types.
>  
> +use core::simd::ToBytes;
>  /// Types for which any bit pattern is valid.
>  ///
>  /// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
> @@ -9,15 +10,58 @@
>  ///
>  /// It's okay for the type to have padding, as initializing those bytes has no effect.
>  ///
> +/// # Example
> +///
> +/// This example is how to use the FromBytes trait
> +/// ```
> +/// // Initialize a slice of bytes
> +/// let foo = &[1, 2, 3, 4];
> +///
> +/// //Use the function implemented by trait in integer type
> +/// let result = u8::from_bytes(foo);
> +///
> +/// assert_eq!(*result, 0x4030201);
> +/// ```
>  /// # 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 {
> +    ///Get an imutable slice of bytes and converts to a reference to Self

missing space after `///`.

> +    unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self;

There's no safety section. The only reason for this being unsafe is
length mismatch? I would rather have the impl perform length check and
return an Result type. If there's a case where length is known, people
can use `unwrap_unchecked` instead.

> +    /// Get a mutable slice of bytes and converts to a reference to Self
> +    ///
> +    /// # Safety
> +    ///
> +    ///  Bound ToBytes in order to avoid use with disallowed bit patterns
> +    unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
> +    where
> +        Self: ToBytes;
> +}
>  
> +//Get a reference of slice of bytes and converts into a reference of integer or a slice with a defined size
>  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 {
> +            unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self
> +            {
> +                unsafe {
> +                    let slice_ptr = slice_of_bytes.as_ptr() as *const Self;
> +                    &*slice_ptr

I don't think we want a manual implementation like this for each type
(even if it's abstracted behind macros). I'd suggestion take
inspiration from zerocopy's KnownLayout type:
https://docs.rs/zerocopy/latest/zerocopy/trait.KnownLayout.html

Best,
Gary

> +                }
> +            }
> +
> +            unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
> +            where
> +                Self: ToBytes,
> +            {
> +                unsafe {
> +                    let slice_ptr = slice_of_bytes.as_mut_ptr() as *mut Self;
> +                    &mut *slice_ptr
> +                }
> +
> +            }
> +        })*
>      };
>  }
>  
> @@ -28,44 +72,52 @@ macro_rules! impl_frombytes {
>  
>      // 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],
>  }
>  
> -/// Types that can be viewed as an immutable slice of initialized bytes.
> +/// Get a reference of slice of bytes and converts into a reference of an array of integers
>  ///
> -/// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
> -/// means that it should not have any padding, as padding bytes are uninitialized. Reading
> -/// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive
> -/// information on the stack to userspace.
> +/// Types for which any bit pattern is valid.
>  ///
> -/// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered
> -/// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so
> -/// this is a correctness requirement, but not a safety requirement.
> +/// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
> +/// reading arbitrary bytes into something that contains a `bool` is not okay.
>  ///
> -/// # Safety
> +/// It's okay for the type to have padding, as initializing those bytes has no effect.
>  ///
> -/// Values of this type may not contain any uninitialized bytes. This type must not have interior
> -/// mutability.
> -pub unsafe trait AsBytes {}
> -
> -macro_rules! impl_asbytes {
> -    ($($({$($generics:tt)*})? $t:ty, )*) => {
> -        // SAFETY: Safety comments written in the macro invocation.
> -        $(unsafe impl$($($generics)*)? AsBytes for $t {})*
> -    };
> -}
> -
> -impl_asbytes! {
> -    // SAFETY: Instances of the following types have no uninitialized portions.
> -    u8, u16, u32, u64, usize,
> -    i8, i16, i32, i64, isize,
> -    bool,
> -    char,
> -    str,
> +/// # Example
> +///
> +/// This example is how to use the FromBytes trait
> +/// ```
> +/// // Initialize a slice of bytes
> +/// let foo = &[1, 2, 3, 4];
> +///
> +/// //Use the function implemented by trait in integer type
> +/// let result = <[u32]>::from_bytes(slice_of_bytes);
> +///
> +/// assert_eq!(*result, 0x4030201);
> +/// ```
> +// 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 impl<T: FromBytes> FromBytes for [T] {
> +    unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self {
> +        //Safety: Guarantee that all values are initiliazed
> +        unsafe {
> +            let slice_ptr = slice_of_bytes.as_ptr() as *const T;
> +            let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
> +            core::slice::from_raw_parts(slice_ptr, slice_len)
> +        }
> +    }
>  
> -    // SAFETY: If individual values in an array have no uninitialized portions, then the array
> -    // itself does not have any uninitialized portions either.
> -    {<T: AsBytes>} [T],
> -    {<T: AsBytes, const N: usize>} [T; N],
> +    //Safety: Guarantee that all values are initiliazed
> +    unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
> +    where
> +        Self: ToBytes,
> +    {
> +        //Safety: Guarantee that all values are initiliazed
> +        unsafe {
> +            let slice_ptr = slice_of_bytes.as_mut_ptr() as *mut T;
> +            let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
> +            core::slice::from_raw_parts_mut(slice_ptr, slice_len)
> +        }
> +    }
>  }
Re: [PATCH v2] rust: transmute: Add implementation for FromBytes trait
Posted by Dirk Behme 1 month, 2 weeks ago
On 12.10.24 09:01, Christian dos Santos de Lima wrote:
> Add implementation and documentation for FromBytes trait.
> 
> Add new feature block in order to allow using ToBytes
> and bound to from_bytes_mut function. I'm adding this feature
> because is possible create a value with disallowed bit pattern
> and as_byte_mut could create such value by mutating the array and
> acessing the original value. So adding ToBytes this can be avoided.
> 
> Link: https://github.com/Rust-for-Linux/linux/issues/1119
> Signed-off-by: Christian dos Santos de Lima <christiansantoslima21@gmail.com>


Applying this on top of rust-next which has

https://github.com/Rust-for-Linux/linux/commit/ce1c54fdff7c4556b08f5b875a331d8952e8b6b7

I'm getting

error[E0405]: cannot find trait `AsBytes` in this scope
    --> rust/kernel/uaccess.rs:360:21
     |
360 |     pub fn write<T: AsBytes>(&mut self, value: &T) -> Result {
     |                     ^^^^^^^ not found in this scope

error: aborting due to 1 previous error

Additionally, could you review the two examples? They don't build. And 
they look identical? Is this intended?

And at several places there seem to miss a space after //.

./scripts/checkpatch.pl --codespell reports

WARNING: 'acessing' may be misspelled - perhaps 'accessing'?
#12:
acessing the original value. So adding ToBytes this can be avoided.
^^^^^^^^

WARNING: 'initiliazed' may be misspelled - perhaps 'initialized'?
#167: FILE: rust/kernel/transmute.rs:103:
+        //Safety: Guarantee that all values are initiliazed
                                                  ^^^^^^^^^^^

WARNING: 'initiliazed' may be misspelled - perhaps 'initialized'?
#179: FILE: rust/kernel/transmute.rs:111:
+    //Safety: Guarantee that all values are initiliazed
                                              ^^^^^^^^^^^

WARNING: 'initiliazed' may be misspelled - perhaps 'initialized'?
#184: FILE: rust/kernel/transmute.rs:116:
+        //Safety: Guarantee that all values are initiliazed
                                                  ^^^^^^^^^^^

Best regards

Dirk

> ---
> changes in v2:
>       - Rollback the implementation for the macro in the repository and add implementation of functions in trait
> ---
>   rust/kernel/lib.rs       |   2 +
>   rust/kernel/transmute.rs | 120 ++++++++++++++++++++++++++++-----------
>   2 files changed, 88 insertions(+), 34 deletions(-)
> 
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index dc37aef6a008..5215f5744e12 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -18,6 +18,8 @@
>   #![feature(lint_reasons)]
>   #![feature(new_uninit)]
>   #![feature(unsize)]
> +#![feature(portable_simd)]
> +#![feature(trivial_bounds)]
>   
>   // Ensure conditional compilation based on the kernel configuration works;
>   // otherwise we may silently break things like initcall handling.
> diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
> index 1c7d43771a37..bce42cc7265e 100644
> --- a/rust/kernel/transmute.rs
> +++ b/rust/kernel/transmute.rs
> @@ -2,6 +2,7 @@
>   
>   //! Traits for transmuting types.
>   
> +use core::simd::ToBytes;
>   /// Types for which any bit pattern is valid.
>   ///
>   /// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
> @@ -9,15 +10,58 @@
>   ///
>   /// It's okay for the type to have padding, as initializing those bytes has no effect.
>   ///
> +/// # Example
> +///
> +/// This example is how to use the FromBytes trait
> +/// ```
> +/// // Initialize a slice of bytes
> +/// let foo = &[1, 2, 3, 4];
> +///
> +/// //Use the function implemented by trait in integer type
> +/// let result = u8::from_bytes(foo);
> +///
> +/// assert_eq!(*result, 0x4030201);
> +/// ```
>   /// # 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 {
> +    ///Get an imutable slice of bytes and converts to a reference to Self
> +    unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self;
> +    /// Get a mutable slice of bytes and converts to a reference to Self
> +    ///
> +    /// # Safety
> +    ///
> +    ///  Bound ToBytes in order to avoid use with disallowed bit patterns
> +    unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
> +    where
> +        Self: ToBytes;
> +}
>   
> +//Get a reference of slice of bytes and converts into a reference of integer or a slice with a defined size
>   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 {
> +            unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self
> +            {
> +                unsafe {
> +                    let slice_ptr = slice_of_bytes.as_ptr() as *const Self;
> +                    &*slice_ptr
> +                }
> +            }
> +
> +            unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
> +            where
> +                Self: ToBytes,
> +            {
> +                unsafe {
> +                    let slice_ptr = slice_of_bytes.as_mut_ptr() as *mut Self;
> +                    &mut *slice_ptr
> +                }
> +
> +            }
> +        })*
>       };
>   }
>   
> @@ -28,44 +72,52 @@ macro_rules! impl_frombytes {
>   
>       // 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],
>   }
>   
> -/// Types that can be viewed as an immutable slice of initialized bytes.
> +/// Get a reference of slice of bytes and converts into a reference of an array of integers
>   ///
> -/// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
> -/// means that it should not have any padding, as padding bytes are uninitialized. Reading
> -/// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive
> -/// information on the stack to userspace.
> +/// Types for which any bit pattern is valid.
>   ///
> -/// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered
> -/// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so
> -/// this is a correctness requirement, but not a safety requirement.
> +/// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
> +/// reading arbitrary bytes into something that contains a `bool` is not okay.
>   ///
> -/// # Safety
> +/// It's okay for the type to have padding, as initializing those bytes has no effect.
>   ///
> -/// Values of this type may not contain any uninitialized bytes. This type must not have interior
> -/// mutability.
> -pub unsafe trait AsBytes {}
> -
> -macro_rules! impl_asbytes {
> -    ($($({$($generics:tt)*})? $t:ty, )*) => {
> -        // SAFETY: Safety comments written in the macro invocation.
> -        $(unsafe impl$($($generics)*)? AsBytes for $t {})*
> -    };
> -}
> -
> -impl_asbytes! {
> -    // SAFETY: Instances of the following types have no uninitialized portions.
> -    u8, u16, u32, u64, usize,
> -    i8, i16, i32, i64, isize,
> -    bool,
> -    char,
> -    str,
> +/// # Example
> +///
> +/// This example is how to use the FromBytes trait
> +/// ```
> +/// // Initialize a slice of bytes
> +/// let foo = &[1, 2, 3, 4];
> +///
> +/// //Use the function implemented by trait in integer type
> +/// let result = <[u32]>::from_bytes(slice_of_bytes);
> +///
> +/// assert_eq!(*result, 0x4030201);
> +/// ```
> +// 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 impl<T: FromBytes> FromBytes for [T] {
> +    unsafe fn from_bytes(slice_of_bytes: &[u8]) -> &Self {
> +        //Safety: Guarantee that all values are initiliazed
> +        unsafe {
> +            let slice_ptr = slice_of_bytes.as_ptr() as *const T;
> +            let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
> +            core::slice::from_raw_parts(slice_ptr, slice_len)
> +        }
> +    }
>   
> -    // SAFETY: If individual values in an array have no uninitialized portions, then the array
> -    // itself does not have any uninitialized portions either.
> -    {<T: AsBytes>} [T],
> -    {<T: AsBytes, const N: usize>} [T; N],
> +    //Safety: Guarantee that all values are initiliazed
> +    unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
> +    where
> +        Self: ToBytes,
> +    {
> +        //Safety: Guarantee that all values are initiliazed
> +        unsafe {
> +            let slice_ptr = slice_of_bytes.as_mut_ptr() as *mut T;
> +            let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
> +            core::slice::from_raw_parts_mut(slice_ptr, slice_len)
> +        }
> +    }
>   }