[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <20241109055442.85190-1-christiansantoslima21@gmail.com>
Date: Sat, 9 Nov 2024 02:54:42 -0300
From: Christian dos Santos de Lima <christiansantoslima21@...il.com>
To: rust-for-linux@...r.kernel.org,
linux-kernel@...r.kernel.org,
Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>,
Boqun Feng <boqun.feng@...il.com>,
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>,
~lkcamp/patches@...ts.sr.ht
Subject: [PATCH v3] rust: transmute: Add implementation for FromBytes trait
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
accessing 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@...il.com>
---
Changes in v2:
- Rollback the implementation for the macro in the repository and add implementation of functions in trait
Changes in v3:
- Fix grammar errors
- Remove repeated tests
- Fix alignment errors errors
- Fix tests not building
- Link to v2: https://lore.kernel.org/rust-for-linux/20241012193657.290cc79c@eugeo/T/#t
---
rust/kernel/lib.rs | 2 +
rust/kernel/transmute.rs | 87 +++++++++++++++++++++++++++++++++++++---
2 files changed, 84 insertions(+), 5 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..a4b462e07639 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,60 @@
///
/// 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
+/// ```
+/// use kernel::transmute::FromBytes;
+/// // Initialize a slice of bytes
+/// let foo = &[1, 2, 3, 4];
+///
+/// //Use the function implemented by trait in integer type
+/// unsafe {
+/// let result = u32::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,10 +74,43 @@ 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],
}
+/// Get a reference of slice of bytes and converts into a reference of an array of integers
+///
+/// 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
+/// reading arbitrary bytes into something that contains a `bool` is not okay.
+///
+/// It's okay for the type to have padding, as initializing those bytes has no effect.
+///
+// 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 initialized
+ 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)
+ }
+ }
+
+ unsafe fn from_bytes_mut(slice_of_bytes: &mut [u8]) -> &mut Self
+ where
+ Self: ToBytes,
+ {
+ // Safety: Guarantee that all values are initialized
+ 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)
+ }
+ }
+}
+
/// 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
@@ -48,7 +127,6 @@ macro_rules! impl_frombytes {
/// 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.
@@ -63,7 +141,6 @@ macro_rules! impl_asbytes {
bool,
char,
str,
-
// 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],
--
2.47.0
Powered by blists - more mailing lists