Re: [PATCH v2 3/6] rust: error: Add Error::from_errno()

From: Gary Guo
Date: Wed Mar 29 2023 - 16:36:27 EST


On Wed, 29 Mar 2023 21:04:35 +0900
Asahi Lina <lina@xxxxxxxxxxxxx> wrote:

> From: Miguel Ojeda <ojeda@xxxxxxxxxx>
>
> Add a function to create `Error` values out of a kernel error return,
> which safely upholds the invariant that the error code is well-formed
> (negative and greater than -MAX_ERRNO). If a malformed code is passed
> in, it will be converted to EINVAL.
>
> Lina: Imported from rust-for-linux/rust as authored by Miguel and Fox
> with refactoring from Wedson, renamed from_kernel_errno() to
> from_errno().
>
> Co-developed-by: Fox Chen <foxhlchen@xxxxxxxxx>
> Signed-off-by: Fox Chen <foxhlchen@xxxxxxxxx>
> Co-developed-by: Wedson Almeida Filho <wedsonaf@xxxxxxxxx>
> Signed-off-by: Wedson Almeida Filho <wedsonaf@xxxxxxxxx>
> Signed-off-by: Miguel Ojeda <ojeda@xxxxxxxxxx>
> Reviewed-by: Andreas Hindborg <a.hindborg@xxxxxxxxxxx>
> Signed-off-by: Asahi Lina <lina@xxxxxxxxxxxxx>
> ---
> rust/kernel/error.rs | 19 +++++++++++++++++++
> 1 file changed, 19 insertions(+)
>
> diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs
> index e97e652a1aec..659468bd1735 100644
> --- a/rust/kernel/error.rs
> +++ b/rust/kernel/error.rs
> @@ -72,6 +72,25 @@ pub mod code {
> pub struct Error(core::ffi::c_int);
>
> impl Error {
> + /// Creates an [`Error`] from a kernel error code.
> + ///
> + /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
> + /// be returned in such a case.
> + pub(crate) fn from_errno(errno: core::ffi::c_int) -> Error {
> + if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
> + // TODO: Make it a `WARN_ONCE` once available.
> + crate::pr_warn!(
> + "attempted to create `Error` with out of range `errno`: {}",
> + errno
> + );
> + return code::EINVAL;
> + }
> +
> + // INVARIANT: The check above ensures the type invariant
> + // will hold.
> + Error(errno)
> + }
> +
> /// Returns the kernel error code.
> pub fn to_errno(self) -> core::ffi::c_int {
> self.0
>

Reviewed-by: Gary Guo <gary@xxxxxxxxxxx>