[PATCH v6 06/18] rust: str: add `bytes_to_bool` helper function

Andreas Hindborg posted 18 patches 1 month, 1 week ago
There is a newer version of this series
[PATCH v6 06/18] rust: str: add `bytes_to_bool` helper function
Posted by Andreas Hindborg 1 month, 1 week ago
Add a convenience function to convert byte slices to boolean values by
wrapping them in a null-terminated C string and delegating to the
existing `kstrtobool` function. Only considers the first two bytes of
the input slice, following the kernel's boolean parsing semantics.

Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
 rust/kernel/str.rs | 35 +++++++++++++++++++++++++++++------
 1 file changed, 29 insertions(+), 6 deletions(-)

diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index d070c0bd86c3..b185262b4851 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -921,6 +921,20 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
     }
 }
 
+/// # Safety
+///
+/// - `string` must point to a null terminated string that is valid for read.
+unsafe fn kstrtobool_raw(string: *const u8) -> Result<bool> {
+    let mut result: bool = false;
+
+    // SAFETY:
+    // - By function safety requirement, `string` is a valid null-terminated string.
+    // - `result` is a valid `bool` that we own.
+    let ret = unsafe { bindings::kstrtobool(string, &mut result) };
+
+    kernel::error::to_result(ret).map(|()| result)
+}
+
 /// Convert common user inputs into boolean values using the kernel's `kstrtobool` function.
 ///
 /// This routine returns `Ok(bool)` if the first character is one of 'YyTt1NnFf0', or
@@ -968,13 +982,22 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
 /// assert_eq!(kstrtobool(c_str!("2")), Err(EINVAL));
 /// ```
 pub fn kstrtobool(string: &CStr) -> Result<bool> {
-    let mut result: bool = false;
-
-    // SAFETY: `string` is a valid null-terminated C string, and `result` is a valid
-    // pointer to a bool that we own.
-    let ret = unsafe { bindings::kstrtobool(string.as_char_ptr(), &mut result) };
+    // SAFETY:
+    // - The pointer returned by `CStr::as_char_ptr` is guaranteed to be
+    //   null terminated.
+    // - `string` is live and thus the string is valid for read.
+    unsafe { kstrtobool_raw(string.as_char_ptr()) }
+}
 
-    kernel::error::to_result(ret).map(|()| result)
+/// Convert `&[u8]` to `bool` by deferring to [`kernel::str::kstrtobool`].
+///
+/// Only considers at most the first two bytes of `bytes`.
+pub fn kstrtobool_bytes(bytes: &[u8]) -> Result<bool> {
+    // `ktostrbool` only considers the first two bytes of the input.
+    let stack_string = [*bytes.first().unwrap_or(&0), *bytes.get(1).unwrap_or(&0), 0];
+    // SAFETY: `stack_string` is null terminated and it is live on the stack so
+    // it is valid for read.
+    unsafe { kstrtobool_raw(stack_string.as_ptr()) }
 }
 
 /// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.

-- 
2.47.2
Re: [PATCH v6 06/18] rust: str: add `bytes_to_bool` helper function
Posted by Daniel Almeida 1 month ago

> On 22 Aug 2025, at 09:14, Andreas Hindborg <a.hindborg@kernel.org> wrote:
> 
> Add a convenience function to convert byte slices to boolean values by
> wrapping them in a null-terminated C string and delegating to the
> existing `kstrtobool` function. Only considers the first two bytes of
> the input slice, following the kernel's boolean parsing semantics.
> 
> Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
> ---
> rust/kernel/str.rs | 35 +++++++++++++++++++++++++++++------
> 1 file changed, 29 insertions(+), 6 deletions(-)
> 
> diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
> index d070c0bd86c3..b185262b4851 100644
> --- a/rust/kernel/str.rs
> +++ b/rust/kernel/str.rs
> @@ -921,6 +921,20 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
>     }
> }
> 
> +/// # Safety
> +///
> +/// - `string` must point to a null terminated string that is valid for read.
> +unsafe fn kstrtobool_raw(string: *const u8) -> Result<bool> {
> +    let mut result: bool = false;
> +
> +    // SAFETY:
> +    // - By function safety requirement, `string` is a valid null-terminated string.
> +    // - `result` is a valid `bool` that we own.
> +    let ret = unsafe { bindings::kstrtobool(string, &mut result) };
> +
> +    kernel::error::to_result(ret).map(|()| result)
> +}
> +
> /// Convert common user inputs into boolean values using the kernel's `kstrtobool` function.
> ///
> /// This routine returns `Ok(bool)` if the first character is one of 'YyTt1NnFf0', or
> @@ -968,13 +982,22 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
> /// assert_eq!(kstrtobool(c_str!("2")), Err(EINVAL));
> /// ```
> pub fn kstrtobool(string: &CStr) -> Result<bool> {
> -    let mut result: bool = false;
> -
> -    // SAFETY: `string` is a valid null-terminated C string, and `result` is a valid
> -    // pointer to a bool that we own.
> -    let ret = unsafe { bindings::kstrtobool(string.as_char_ptr(), &mut result) };
> +    // SAFETY:
> +    // - The pointer returned by `CStr::as_char_ptr` is guaranteed to be
> +    //   null terminated.
> +    // - `string` is live and thus the string is valid for read.
> +    unsafe { kstrtobool_raw(string.as_char_ptr()) }
> +}
> 
> -    kernel::error::to_result(ret).map(|()| result)
> +/// Convert `&[u8]` to `bool` by deferring to [`kernel::str::kstrtobool`].
> +///
> +/// Only considers at most the first two bytes of `bytes`.
> +pub fn kstrtobool_bytes(bytes: &[u8]) -> Result<bool> {
> +    // `ktostrbool` only considers the first two bytes of the input.
> +    let stack_string = [*bytes.first().unwrap_or(&0), *bytes.get(1).unwrap_or(&0), 0];
> +    // SAFETY: `stack_string` is null terminated and it is live on the stack so
> +    // it is valid for read.
> +    unsafe { kstrtobool_raw(stack_string.as_ptr()) }
> }
> 
> /// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.
> 
> -- 
> 2.47.2
> 
> 
> 

Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com>
Re: [PATCH v6 06/18] rust: str: add `bytes_to_bool` helper function
Posted by Alice Ryhl 1 month ago
On Fri, Aug 22, 2025 at 2:15 PM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>
> Add a convenience function to convert byte slices to boolean values by
> wrapping them in a null-terminated C string and delegating to the
> existing `kstrtobool` function. Only considers the first two bytes of
> the input slice, following the kernel's boolean parsing semantics.
>
> Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>

One nit below, but generally looks good.
Reviewed-by: Alice Ryhl <aliceryhl@google.com>

> +/// # Safety
> +///
> +/// - `string` must point to a null terminated string that is valid for read.
> +unsafe fn kstrtobool_raw(string: *const u8) -> Result<bool> {
> +    let mut result: bool = false;
> +
> +    // SAFETY:
> +    // - By function safety requirement, `string` is a valid null-terminated string.
> +    // - `result` is a valid `bool` that we own.
> +    let ret = unsafe { bindings::kstrtobool(string, &mut result) };
> +
> +    kernel::error::to_result(ret).map(|()| result)

I think this is easier to read as:

to_result(unsafe { bindings::kstrtobool(string, &mut result) })?;
Ok(result)

Alice
Re: [PATCH v6 06/18] rust: str: add `bytes_to_bool` helper function
Posted by Daniel Almeida 1 month, 1 week ago

> On 22 Aug 2025, at 09:14, Andreas Hindborg <a.hindborg@kernel.org> wrote:
> 
> Add a convenience function to convert byte slices to boolean values by
> wrapping them in a null-terminated C string and delegating to the
> existing `kstrtobool` function. Only considers the first two bytes of
> the input slice, following the kernel's boolean parsing semantics.
> 
> Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
> ---
> rust/kernel/str.rs | 35 +++++++++++++++++++++++++++++------
> 1 file changed, 29 insertions(+), 6 deletions(-)
> 
> diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
> index d070c0bd86c3..b185262b4851 100644
> --- a/rust/kernel/str.rs
> +++ b/rust/kernel/str.rs
> @@ -921,6 +921,20 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
>     }
> }
> 
> +/// # Safety
> +///
> +/// - `string` must point to a null terminated string that is valid for read.
> +unsafe fn kstrtobool_raw(string: *const u8) -> Result<bool> {
> +    let mut result: bool = false;
> +
> +    // SAFETY:
> +    // - By function safety requirement, `string` is a valid null-terminated string.
> +    // - `result` is a valid `bool` that we own.
> +    let ret = unsafe { bindings::kstrtobool(string, &mut result) };
> +
> +    kernel::error::to_result(ret).map(|()| result)
> +}
> +
> /// Convert common user inputs into boolean values using the kernel's `kstrtobool` function.
> ///
> /// This routine returns `Ok(bool)` if the first character is one of 'YyTt1NnFf0', or
> @@ -968,13 +982,22 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
> /// assert_eq!(kstrtobool(c_str!("2")), Err(EINVAL));
> /// ```
> pub fn kstrtobool(string: &CStr) -> Result<bool> {
> -    let mut result: bool = false;
> -
> -    // SAFETY: `string` is a valid null-terminated C string, and `result` is a valid
> -    // pointer to a bool that we own.
> -    let ret = unsafe { bindings::kstrtobool(string.as_char_ptr(), &mut result) };
> +    // SAFETY:
> +    // - The pointer returned by `CStr::as_char_ptr` is guaranteed to be
> +    //   null terminated.
> +    // - `string` is live and thus the string is valid for read.
> +    unsafe { kstrtobool_raw(string.as_char_ptr()) }
> +}
> 
> -    kernel::error::to_result(ret).map(|()| result)
> +/// Convert `&[u8]` to `bool` by deferring to [`kernel::str::kstrtobool`].
> +///
> +/// Only considers at most the first two bytes of `bytes`.
> +pub fn kstrtobool_bytes(bytes: &[u8]) -> Result<bool> {
> +    // `ktostrbool` only considers the first two bytes of the input.
> +    let stack_string = [*bytes.first().unwrap_or(&0), *bytes.get(1).unwrap_or(&0), 0];

Can’t this be CStr::from_bytes_with_nul() ?

This means that kstrtobool_raw could take a &CStr directly and thus not be unsafe IIUC?

> +    // SAFETY: `stack_string` is null terminated and it is live on the stack so
> +    // it is valid for read.
> +    unsafe { kstrtobool_raw(stack_string.as_ptr()) }
> }
> 
> /// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.
> 
> -- 
> 2.47.2
> 
> 
> 
Re: [PATCH v6 06/18] rust: str: add `bytes_to_bool` helper function
Posted by Alice Ryhl 1 month ago
On Wed, Aug 27, 2025 at 3:46 PM Daniel Almeida
<daniel.almeida@collabora.com> wrote:
>
>
>
> > On 22 Aug 2025, at 09:14, Andreas Hindborg <a.hindborg@kernel.org> wrote:
> >
> > Add a convenience function to convert byte slices to boolean values by
> > wrapping them in a null-terminated C string and delegating to the
> > existing `kstrtobool` function. Only considers the first two bytes of
> > the input slice, following the kernel's boolean parsing semantics.
> >
> > Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
> > ---
> > rust/kernel/str.rs | 35 +++++++++++++++++++++++++++++------
> > 1 file changed, 29 insertions(+), 6 deletions(-)
> >
> > diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
> > index d070c0bd86c3..b185262b4851 100644
> > --- a/rust/kernel/str.rs
> > +++ b/rust/kernel/str.rs
> > @@ -921,6 +921,20 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
> >     }
> > }
> >
> > +/// # Safety
> > +///
> > +/// - `string` must point to a null terminated string that is valid for read.
> > +unsafe fn kstrtobool_raw(string: *const u8) -> Result<bool> {
> > +    let mut result: bool = false;
> > +
> > +    // SAFETY:
> > +    // - By function safety requirement, `string` is a valid null-terminated string.
> > +    // - `result` is a valid `bool` that we own.
> > +    let ret = unsafe { bindings::kstrtobool(string, &mut result) };
> > +
> > +    kernel::error::to_result(ret).map(|()| result)
> > +}
> > +
> > /// Convert common user inputs into boolean values using the kernel's `kstrtobool` function.
> > ///
> > /// This routine returns `Ok(bool)` if the first character is one of 'YyTt1NnFf0', or
> > @@ -968,13 +982,22 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
> > /// assert_eq!(kstrtobool(c_str!("2")), Err(EINVAL));
> > /// ```
> > pub fn kstrtobool(string: &CStr) -> Result<bool> {
> > -    let mut result: bool = false;
> > -
> > -    // SAFETY: `string` is a valid null-terminated C string, and `result` is a valid
> > -    // pointer to a bool that we own.
> > -    let ret = unsafe { bindings::kstrtobool(string.as_char_ptr(), &mut result) };
> > +    // SAFETY:
> > +    // - The pointer returned by `CStr::as_char_ptr` is guaranteed to be
> > +    //   null terminated.
> > +    // - `string` is live and thus the string is valid for read.
> > +    unsafe { kstrtobool_raw(string.as_char_ptr()) }
> > +}
> >
> > -    kernel::error::to_result(ret).map(|()| result)
> > +/// Convert `&[u8]` to `bool` by deferring to [`kernel::str::kstrtobool`].
> > +///
> > +/// Only considers at most the first two bytes of `bytes`.
> > +pub fn kstrtobool_bytes(bytes: &[u8]) -> Result<bool> {
> > +    // `ktostrbool` only considers the first two bytes of the input.
> > +    let stack_string = [*bytes.first().unwrap_or(&0), *bytes.get(1).unwrap_or(&0), 0];
>
> Can’t this be CStr::from_bytes_with_nul() ?
>
> This means that kstrtobool_raw could take a &CStr directly and thus not be unsafe IIUC?

That's what Andreas did in the previous version. It ended up being
pretty complex because CStr::from_bytes_with_nul() requires that we
compute the length of `stack_string`, which isn't really needed here.
I recommended having a _raw method like this to avoid that complexity.
I don't think this is meaningfully more unsafe the way it is in this
patch.

Alice
Re: [PATCH v6 06/18] rust: str: add `bytes_to_bool` helper function
Posted by Andreas Hindborg 1 month ago
"Daniel Almeida" <daniel.almeida@collabora.com> writes:

>> On 22 Aug 2025, at 09:14, Andreas Hindborg <a.hindborg@kernel.org> wrote:

<cut>

>> -    kernel::error::to_result(ret).map(|()| result)
>> +/// Convert `&[u8]` to `bool` by deferring to [`kernel::str::kstrtobool`].
>> +///
>> +/// Only considers at most the first two bytes of `bytes`.
>> +pub fn kstrtobool_bytes(bytes: &[u8]) -> Result<bool> {
>> +    // `ktostrbool` only considers the first two bytes of the input.
>> +    let stack_string = [*bytes.first().unwrap_or(&0), *bytes.get(1).unwrap_or(&0), 0];
>
> Can’t this be CStr::from_bytes_with_nul() ?
>
> This means that kstrtobool_raw could take a &CStr directly and thus not be unsafe IIUC?

By design, the input to this function need not be null terminated. My
use case is parsing the contents of a configfs file, and I would not
want to change the contents of the file, or allocate to create a null
terminated string, before calling this method.

We could add another function `kstrtobool_cstr` to do what you are
asking, but I think that could be a separate patch.


Best regards,
Andreas Hindborg