Skip to content

Commit

Permalink
rust: error: Add Error::from_errno{_unchecked}()
Browse files Browse the repository at this point in the history
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 <[email protected]>
Signed-off-by: Fox Chen <[email protected]>
Co-developed-by: Wedson Almeida Filho <[email protected]>
Signed-off-by: Wedson Almeida Filho <[email protected]>
Signed-off-by: Miguel Ojeda <[email protected]>
Reviewed-by: Andreas Hindborg <[email protected]>
Reviewed-by: Gary Guo <[email protected]>
Reviewed-by: Martin Rodriguez Reboredo <[email protected]>
Signed-off-by: Asahi Lina <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
[ Mark the new associated functions as `#[allow(dead_code)]`. ]
Signed-off-by: Miguel Ojeda <[email protected]>
  • Loading branch information
ojeda committed Apr 10, 2023
1 parent 609a73b commit 5a172a0
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,38 @@ 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.
#[allow(dead_code)]
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)
}

/// Creates an [`Error`] from a kernel error code.
///
/// # Safety
///
/// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
#[allow(dead_code)]
unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
// INVARIANT: The contract ensures the type invariant
// will hold.
Error(errno)
}

/// Returns the kernel error code.
pub fn to_errno(self) -> core::ffi::c_int {
self.0
Expand Down

0 comments on commit 5a172a0

Please sign in to comment.