* [PATCH v4] Add methods for FromBytes trait.
@ 2025-03-14 3:49 christian
2025-03-14 10:45 ` Benno Lossin
0 siblings, 1 reply; 4+ messages in thread
From: christian @ 2025-03-14 3:49 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 the invalid case return the EINVAL error.
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 <christiansantoslima21@gmail.com>
---
rust/kernel/transmute.rs | 67 ++++++++++++++++++++++++++++++++++++++--
1 file changed, 64 insertions(+), 3 deletions(-)
diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 1c7d43771a37..5924c0daccfc 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -2,6 +2,8 @@
//! Traits for transmuting types.
+use crate::prelude::{Error, EINVAL};
+
/// 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
@@ -12,26 +14,85 @@
/// # Safety
///
/// All bit-patterns must be valid for this type. This type must not have interior mutability.
-pub unsafe trait FromBytes {}
+///
+/// # Example
+///
+/// ```
+/// let foo = &[1, 2, 3, 4];
+///
+/// let result = u8::from_bytes(foo);
+///
+/// assert_eq!(*result, 0x40300201);
+/// ```
+pub trait FromBytes {
+ /// Receives a slice of bytes and converts to a valid reference of Self when it's possible.
+ fn from_bytes(slice_of_bytes: &[u8]) -> Result<&Self, Error>;
+
+ /// Receives a mutable slice of bytes and converts to a valid reference of Self when it's possible.
+ fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut Self, Error>;
+}
macro_rules! impl_frombytes {
($($({$($generics:tt)*})? $t:ty, )*) => {
// SAFETY: Safety comments written in the macro invocation.
- $(unsafe impl$($($generics)*)? FromBytes for $t {})*
+ $(impl$($($generics)*)? FromBytes for $t {
+ fn from_bytes(slice_of_bytes: &[u8]) -> Result<&$t, Error> {
+ if slice_of_bytes.len() == core::mem::size_of::<$t>() {
+ let slice_ptr = slice_of_bytes.as_ptr() as *const $t;
+ unsafe { Ok(&*slice_ptr) }
+ } else {
+ Err(EINVAL)
+ }
+ }
+
+ fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut $t, Error> {
+ if mut_slice_of_bytes.len() == core::mem::size_of::<$t>() {
+ let slice_ptr = mut_slice_of_bytes.as_mut_ptr() as *mut $t;
+ unsafe { Ok(&mut *slice_ptr) }
+ } else {
+ Err(EINVAL)
+ }
+ }
+ })*
};
}
impl_frombytes! {
// SAFETY: All bit patterns are acceptable values of the types below.
+ // SAFETY: Dereferencing the pointer is safe because slice has the same size of Self.
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],
+ // SAFETY: Dereferencing the pointer is safe because slice has the same size of Self.
{<T: FromBytes, const N: usize>} [T; N],
}
+impl<T: FromBytes> FromBytes for [T] {
+ fn from_bytes(slice_of_bytes: &[u8]) -> Result<&Self, Error> {
+ let slice_ptr = slice_of_bytes.as_ptr() as *const T;
+ if slice_of_bytes.len() % core::mem::size_of::<T>() == 0 {
+ let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
+ // SAFETY: Creating a slice is safe because the slice can be divided into T sized blocks.
+ unsafe { Ok(core::slice::from_raw_parts(slice_ptr, slice_len)) }
+ } else {
+ Err(EINVAL)
+ }
+ }
+
+ fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut Self, Error> {
+ let slice_ptr = mut_slice_of_bytes.as_mut_ptr() as *mut T;
+ if mut_slice_of_bytes.len() % core::mem::size_of::<T>() == 0 {
+ let slice_len = mut_slice_of_bytes.len() / core::mem::size_of::<T>();
+ // SAFETY: Creating a slice is safe because the slice can be divided into T sized blocks.
+ unsafe { Ok(core::slice::from_raw_parts_mut(slice_ptr, slice_len)) }
+ } else {
+ Err(EINVAL)
+ }
+ }
+}
+
/// 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.48.1
^ permalink raw reply related [flat|nested] 4+ messages in thread
* Re: [PATCH v4] Add methods for FromBytes trait.
2025-03-14 3:49 [PATCH v4] Add methods for FromBytes trait christian
@ 2025-03-14 10:45 ` Benno Lossin
2025-03-17 23:14 ` Christian
0 siblings, 1 reply; 4+ messages in thread
From: Benno Lossin @ 2025-03-14 10:45 UTC (permalink / raw)
To: christian, 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 Fri Mar 14, 2025 at 4:49 AM CET, christian wrote:
> Methods receive a slice and perform size check to add
> a valid way to make conversion safe.
> In the invalid case return the EINVAL error.
>
> 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 <christiansantoslima21@gmail.com>
> ---
It usually is a good idea to include a changelog and a link to any prior
versions after this `---`. It won't be included in the final commit
message, but help reviewers and others keep track of this series.
> rust/kernel/transmute.rs | 67 ++++++++++++++++++++++++++++++++++++++--
> 1 file changed, 64 insertions(+), 3 deletions(-)
>
> diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
> index 1c7d43771a37..5924c0daccfc 100644
> --- a/rust/kernel/transmute.rs
> +++ b/rust/kernel/transmute.rs
> @@ -2,6 +2,8 @@
>
> //! Traits for transmuting types.
>
> +use crate::prelude::{Error, EINVAL};
> +
> /// 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
> @@ -12,26 +14,85 @@
> /// # Safety
> ///
> /// All bit-patterns must be valid for this type. This type must not have interior mutability.
> -pub unsafe trait FromBytes {}
> +///
> +/// # Example
I think this section should go before the `Safety` section.
> +///
> +/// ```
> +/// let foo = &[1, 2, 3, 4];
> +///
> +/// let result = u8::from_bytes(foo);
> +///
> +/// assert_eq!(*result, 0x40300201);
> +/// ```
> +pub trait FromBytes {
Why is this trait becoming safe?
> + /// Receives a slice of bytes and converts to a valid reference of Self when it's possible.
> + fn from_bytes(slice_of_bytes: &[u8]) -> Result<&Self, Error>;
IMO it makes more sense for the return type to be `Option<&Self>`.
> +
> + /// Receives a mutable slice of bytes and converts to a valid reference of Self when it's possible.
> + fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut Self, Error>;
This must also require that `Self: AsBytes`, since otherwise the user
could write padding bytes into the original slice.
Also the parameter name `mut_slice_of_bytes` is a bit long, how about
`bytes`?
> +}
>
> macro_rules! impl_frombytes {
> ($($({$($generics:tt)*})? $t:ty, )*) => {
> // SAFETY: Safety comments written in the macro invocation.
> - $(unsafe impl$($($generics)*)? FromBytes for $t {})*
> + $(impl$($($generics)*)? FromBytes for $t {
> + fn from_bytes(slice_of_bytes: &[u8]) -> Result<&$t, Error> {
> + if slice_of_bytes.len() == core::mem::size_of::<$t>() {
> + let slice_ptr = slice_of_bytes.as_ptr() as *const $t;
> + unsafe { Ok(&*slice_ptr) }
> + } else {
> + Err(EINVAL)
> + }
> + }
> +
> + fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut $t, Error> {
> + if mut_slice_of_bytes.len() == core::mem::size_of::<$t>() {
> + let slice_ptr = mut_slice_of_bytes.as_mut_ptr() as *mut $t;
> + unsafe { Ok(&mut *slice_ptr) }
> + } else {
> + Err(EINVAL)
> + }
> + }
> + })*
> };
> }
>
> impl_frombytes! {
> // SAFETY: All bit patterns are acceptable values of the types below.
> + // SAFETY: Dereferencing the pointer is safe because slice has the same size of Self.
What is this safety comment for?
> 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],
If you're removing this line, you should also remove its safety comment
above. But since the trait should be `unsafe`, you should move it down
to the impl below.
> + // SAFETY: Dereferencing the pointer is safe because slice has the same size of Self.
> {<T: FromBytes, const N: usize>} [T; N],
> }
>
> +impl<T: FromBytes> FromBytes for [T] {
> + fn from_bytes(slice_of_bytes: &[u8]) -> Result<&Self, Error> {
> + let slice_ptr = slice_of_bytes.as_ptr() as *const T;
> + if slice_of_bytes.len() % core::mem::size_of::<T>() == 0 {
> + let slice_len = slice_of_bytes.len() / core::mem::size_of::<T>();
> + // SAFETY: Creating a slice is safe because the slice can be divided into T sized blocks.
You're not justifying why the pointer is valid. Also please avoid
repeating the obvious "Creating a slice is safe".
---
Cheers,
Benno
> + unsafe { Ok(core::slice::from_raw_parts(slice_ptr, slice_len)) }
> + } else {
> + Err(EINVAL)
> + }
> + }
> +
> + fn from_bytes_mut(mut_slice_of_bytes: &mut [u8]) -> Result<&mut Self, Error> {
> + let slice_ptr = mut_slice_of_bytes.as_mut_ptr() as *mut T;
> + if mut_slice_of_bytes.len() % core::mem::size_of::<T>() == 0 {
> + let slice_len = mut_slice_of_bytes.len() / core::mem::size_of::<T>();
> + // SAFETY: Creating a slice is safe because the slice can be divided into T sized blocks.
> + unsafe { Ok(core::slice::from_raw_parts_mut(slice_ptr, slice_len)) }
> + } else {
> + Err(EINVAL)
> + }
> + }
> +}
> +
> /// 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 v4] Add methods for FromBytes trait.
2025-03-14 10:45 ` Benno Lossin
@ 2025-03-17 23:14 ` Christian
2025-03-18 9:05 ` Benno Lossin
0 siblings, 1 reply; 4+ messages in thread
From: Christian @ 2025-03-17 23:14 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.
> It usually is a good idea to include a changelog and a link to any prior
> versions after this `---`. It won't be included in the final commit
> message, but help reviewers and others keep track of this series.
Yeah, my bad. I forgot.
> I think this section should go before the `Safety` section.
I followed this section:
https://docs.kernel.org/rust/coding-guidelines.html#code-documentation,
but no problem, I'll change.
> Why is this trait becoming safe?
I thought that if we change to a Result and get the Err case, it's not
a problem to be safe.
> IMO it makes more sense for the return type to be `Option<&Self>`.
I agree. I'll change.
> This must also require that `Self: AsBytes`, since otherwise the user
> could write padding bytes into the original slice.
Did you mean `ToBytes`? Should I create another patch with an empty trait, e.g
```
unsafe trait ToBytes {}
```
or create the trait and its methods?
> Also the parameter name `mut_slice_of_bytes` is a bit long, how about
> `bytes`?
I liked it, I'll change to `bytes` and `bytes_mut`
> What is this safety comment for?
Idk if I should create another safety comment or just continue. In
this case, I choose the first and submit the patch. So how should I
proceed?
Thanks,
Christian
^ permalink raw reply [flat|nested] 4+ messages in thread
* Re: [PATCH v4] Add methods for FromBytes trait.
2025-03-17 23:14 ` Christian
@ 2025-03-18 9:05 ` Benno Lossin
0 siblings, 0 replies; 4+ messages in thread
From: Benno Lossin @ 2025-03-18 9:05 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 Tue Mar 18, 2025 at 12:14 AM CET, Christian wrote:
> Hi, Benno.
>
>> It usually is a good idea to include a changelog and a link to any prior
>> versions after this `---`. It won't be included in the final commit
>> message, but help reviewers and others keep track of this series.
>
> Yeah, my bad. I forgot.
>
>> I think this section should go before the `Safety` section.
>
> I followed this section:
> https://docs.kernel.org/rust/coding-guidelines.html#code-documentation,
> but no problem, I'll change.
Ah I see, I'll change that then.
>> Why is this trait becoming safe?
>
> I thought that if we change to a Result and get the Err case, it's not
> a problem to be safe.
A trait being `unsafe` means that the implementer needs to justify why
their implementation is correct. The fact that you change the return
type to `Result` doesn't change that the type must be transmutable from
sufficiently many bytes.
>> IMO it makes more sense for the return type to be `Option<&Self>`.
>
> I agree. I'll change.
>
>> This must also require that `Self: AsBytes`, since otherwise the user
>> could write padding bytes into the original slice.
>
> Did you mean `ToBytes`? Should I create another patch with an empty trait, e.g
> ```
> unsafe trait ToBytes {}
> ```
> or create the trait and its methods?
Nope, I mean `AsBytes`, it already exists in `rust/kernel/transmute.rs`.
>> Also the parameter name `mut_slice_of_bytes` is a bit long, how about
>> `bytes`?
>
> I liked it, I'll change to `bytes` and `bytes_mut`
I wouldn't put `_mut` in the parameter name, just name both of them
`bytes`.
>> What is this safety comment for?
>
> Idk if I should create another safety comment or just continue. In
> this case, I choose the first and submit the patch. So how should I
> proceed?
I don't understand, the safety comment that you added there doesn't make
any sense to me. I wouldn't have added it.
---
Cheers,
Benno
^ permalink raw reply [flat|nested] 4+ messages in thread
end of thread, other threads:[~2025-03-18 9:05 UTC | newest]
Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-03-14 3:49 [PATCH v4] Add methods for FromBytes trait christian
2025-03-14 10:45 ` Benno Lossin
2025-03-17 23:14 ` Christian
2025-03-18 9:05 ` 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).