Re: [PATCH v3 2/2] rust: uaccess: use NonEmpty in strcpy_into_buf()
From: Alexandre Courbot
Date: Thu Oct 15 2026 - 22:41:24 EST
On Thu Oct 15, 2026 at 11:04 PM JST, Gary Guo wrote:
> On Thu Oct 15, 2026 at 2:06 PM BST, Alexandre Courbot wrote:
>> On Wed Oct 14, 2026 at 5:30 PM JST, Lorenzo Delgado wrote:
>> <...>
>>> diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs
>>> index 5f6c4d7a1a51..1cc5c7580d3a 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},
>>> @@ -383,20 +384,16 @@ pub fn read_all<A: Allocator>(mut self, buf: &mut Vec<u8, A>, flags: Flags) -> R
>>> /// Read a NUL-terminated string from userspace and return it.
>>> ///
>>> /// The string is read into `buf` and a NUL-terminator is added if the end of `buf` is reached.
>>> - /// Since there must be space to add a NUL-terminator, the buffer must not be empty. The
>>> + /// Since there must be space to add a NUL-terminator, `buf` is a [`NonEmpty`] slice. The
>>> /// returned `&CStr` points into `buf`.
>>> ///
>>> /// Fails with [`EFAULT`] if the read happens on a bad address (some data may have been
>>> /// 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);
>>> - }
>>> -
>>> + pub fn strcpy_into_buf<'buf>(self, buf: &'buf mut NonEmpty<[u8]>) -> Result<&'buf CStr> {
>>
>> I understand this was done per the v1 feedback, but won't it make it
>> more tedious for users to call this method? (hard to tell as there are
>> no users at the moment :))
>>
>> We could still benefit from `NonEmpty` if we replace the `buf.is_empty`
>> by an attempt to build it and return `EINVAL` if that fails (what v1 did
>> basically) and calling `last_mut` on it to remove the
>> `unwrap_unchecked`.
>>
>> Of course if callers are expected to already work with a `NonEmpty` then
>> that's fine, but otherwise my concern is that every one of them would
>> have to manually build one to perform a check that this method can
>> easily do.
>
> I think it might also be reasonable to invoke errorenous behaviour here, by do a
> `WARN` and just return c""?
That would make the doccomment saying that "The returned `&CStr` points
into `buf`" incorrect though.
If callers are expected to mostly pass slices into fixed-size arrays,
`NonEmpty::from_mut()` makes building one trivial (and we could even
envision a `From` conversion to makes it implicit), so I don't feel
strongly about it as long as we can confirm that this is how this method
will be used.