rust: add NonEmpty
cover rust: add NonEmpty
Some functions check that a container is not empty and later rely on it through unwrap_unchecked(), unwrap() or an error path that can't be taken. Gary suggested a non-empty type for this while reviewing Thorsten Blum's uaccess patch [1], and Miguel filed it as #1262 [2].
Patch 1 adds NonEmpty<C> in kernel::non_empty, with only what the first user needs: slices, try_from_mut() and last_mut(). Patch 2 uses it in strcpy_into_buf(), which drops an unsafe block.
Some notes:
- IsEmpty is a safe trait. Unsafe code only relies on the implementations in kernel::non_empty, and the docs require the result not to change while the container is only reachable through a shared reference. If a generic accessor ever needs to rely on it, it can become an unsafe trait then.
- Since APIs aren't added without users, other accessors (first(), try_from_ref(), ...) and containers are left for later. I plan to send follow-ups for net/phy.rs and scatterlist.rs, which both reject an empty slice and then rely on it.
- I put it in its own kernel::non_empty module. Would a broader home like kernel::collections be better?
Francis Laniel posted a slice-only RFC [3]. Following Gary's suggestion on the issue, this version is generic over the container.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] https://github.com/Rust-for-Linux/linux/issues/1262
[3] https://lore.kernel.org/rust-for-linux/[email protected]/
---
Lorenzo Delgado (2):
rust: non_empty: add NonEmpty
rust: uaccess: use NonEmpty in strcpy_into_buf()
rust/kernel/lib.rs | 1 + rust/kernel/non_empty.rs | 100 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 11 ++---- 3 files changed, 105 insertions(+), 7 deletions(-)
---
base-commit: 2dee3d3adcadcc57d62ba6608cd02f50b0c10264
change-id: 20261011-nonempty-slice-022084ba9a5a
Best regards,
Signature · 1 line
Lorenzo Delgado <[email protected]>
PATCH 1/2 rust: non_empty: add NonEmpty
Some functions reject an empty container up front and later rely on it having at least one element. The type system does not see that check, so the later access ends up as an unwrap_unchecked() with a SAFETY comment pointing back at it, or as an unwrap() or an error path that can never be taken. strcpy_into_buf() in uaccess is one such case.
Add NonEmpty<C>, a transparent wrapper that can only be created from a container its IsEmpty implementation reports as non-empty. It dereferences to the container, and a method whose Option only exists for the empty case can be shadowed by a version that returns the value directly.
DerefMut is implemented per container, only where a mutable reference cannot change the length. For a growable container it would let clear() break the invariant.
For now only slices are supported, with the one constructor and accessor that the uaccess conversion needs. Other containers and accessors can follow with their users.
--- rust/kernel/lib.rs | 1 + rust/kernel/non_empty.rs | 100 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -105,6 +105,7 @@pub mod module_param;#[cfg( CONFIG_NET )] pub mod net; +pub mod non_empty;pub mod num;pub mod of;#[cfg( CONFIG_PM_OPP )]
rust/kernel/non_empty.rs new file +100 -0
100 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 2/2 rust: uaccess: use NonEmpty in strcpy_into_buf()
In reply to Lorenzo Delgadostrcpy_into_buf() returns EINVAL for an empty buffer and later writes the NUL terminator through last_mut().unwrap_unchecked(), relying on that earlier check.
Turn the buffer into a NonEmpty<[u8]> at the start instead. The emptiness check and its EINVAL stay the same, but last_mut() now returns the element directly, so the unsafe block goes away.
The MaybeUninit cast still starts from [u8], so its SAFETY comment does not depend on the layout of the wrapper.
--- rust/kernel/uaccess.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-)
rust/kernel/uaccess.rs +4 -7
@@ -11,6 +11,7 @@ error::Result, ffi::{c_char, c_void}, fs::file, + non_empty::NonEmpty, prelude::*, ptr::KnownSize, transmute::{AsBytes, FromBytes},
@@ -390,13 +391,11 @@ pub fn read_all<A: Allocator>(mut self, buf: &mut Vec<u8, A>, flags: Flags) -> R/// copied). #[doc(alias = "strncpy_from_user" )] pub fn strcpy_into_buf <'buf>(self, buf: &'bufmut [u8 ]) ->Result <&'bufCStr > { -if buf.is_empty () { -return Err (EINVAL ); - } +let buf =NonEmpty ::try_from_mut (buf).ok_or (EINVAL )?;// SAFETY: The types are compatible and `strncpy_from_user` doesn't write uninitialized // bytes to `buf`. -let mut dst =unsafe { &mut *(core::ptr::from_mut (buf)as *mut [MaybeUninit <u8 >]) }; +let mut dst =unsafe { &mut *(core::ptr::from_mut ::<[u8 ]>(buf)as *mut [MaybeUninit <u8 >]) };// We never read more than `self.length` bytes. if dst.len () > self.length {
@@ -422,9 +421,7 @@ pub fn strcpy_into_buf<'buf>(self, buf: &'buf mut [u8]) -> Result<&'buf CStr> {// This means that we filled the buffer exactly. In this case, we add a NUL-terminator // and return it. Unlike the `len < dst.len()` branch, don't modify `len` because it // already represents the length including the NUL-terminator. -// -// SAFETY: Due to the check at the beginning, the buffer is not empty. -unsafe { *buf.last_mut ().unwrap_unchecked () =0 }; + *buf.last_mut () =0 ; }// This method consumes `self`, so it can only be called once, thus we do not need to
Signature · 1 line
2.55.0
Re: [PATCH 2/2] rust: uaccess: use NonEmpty in strcpy_into_buf()
Quoted 2 lines · Lorenzo Delgado
Turn the buffer into a
NonEmpty<[u8]>at the start instead. The
Hmm... I thought the idea was to request a NonEmpty in the signature.
Is it not possible for some reason?
Cheers,
Miguel
Re: [PATCH 2/2] rust: uaccess: use NonEmpty in strcpy_into_buf()
Quoted 4 lines · Miguel Ojeda
Hmm... I thought the idea was to request a
NonEmptyin the signature.Is it not possible for some reason?
It's possible. I kept the signature as is to limit the change to the inside of the function, but you're right: the point of the newtype is to put the requirement in the signature. In v2 it will take &mut NonEmpty<[u8]> and the EINVAL case goes away.
Since callers will usually pass a fixed-size array, v2 also adds a constructor from &mut [T; N] that checks N > 0 at compile time, so they don't need a runtime check either.
Thanks,
Lorenzo