[PATCH 2/2] rust: uaccess: use NonEmpty in strcpy_into_buf()
From: Lorenzo Delgado
Date: Mon Oct 12 2026 - 07:57:10 EST
`strcpy_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.
Suggested-by: Gary Guo <gary@xxxxxxxxxxx>
Link: https://lore.kernel.org/rust-for-linux/DM0D9TERQAM3.2Y3HV6P68E2N8@xxxxxxxxxxx/
Link: https://github.com/Rust-for-Linux/linux/issues/1262
Signed-off-by: Lorenzo Delgado <lnsdev@xxxxxxxxx>
---
rust/kernel/uaccess.rs | 11 ++++-------
1 file changed, 4 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs
index 5f6c4d7a1a51..044c20e87ee6 100644
--- a/rust/kernel/uaccess.rs
+++ b/rust/kernel/uaccess.rs
@@ -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: &'buf mut [u8]) -> Result<&'buf CStr> {
- 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
--
2.55.0