Skip to content

Commit

Permalink
rust: check range and add type invariant to Error
Browse files Browse the repository at this point in the history
We will need to make sure that no Error with out of
range error code can be constructed.

This commit
1. Adds a constructor method "new()" to Error with errno check
2. Uses the "new()" method to create Error in from_kernel_errno()
3. Provides a unchecked version from_kernel_errno_unchecked()

And when an invalid errno is found, it will
1) Print a  warning.
2) Convert it to EINVAL.

Signed-off-by: Fox Chen <[email protected]>
  • Loading branch information
foxhlchen committed May 31, 2021
1 parent 7884043 commit 0bc70a3
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,34 @@ impl Error {
pub const EBADF: Self = Error(-(bindings::EBADF as i32));

/// Creates an [`Error`] from a kernel error code.
/// when errno given is invalid,
/// it will print a warning message and convert it to EINVAL
pub fn from_kernel_errno(errno: c_types::c_int) -> Error {
Error::new(errno)
}

/// Creates an [`Error`] from a kernel error code without a sanity check
pub fn from_kernel_errno_unchecked(errno: c_types::c_int) -> Error {
Error(errno)
}

/// Returns the kernel error code.
pub fn to_kernel_errno(self) -> c_types::c_int {
self.0
}

/// INVARIANT: make sure Error is initialized with a sane value
/// When an invalid errno is found, it will
/// 1) print a warning message
/// 2) convert it to EINVAL
pub fn new(errno: c_types::c_int) -> Error {
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
crate::pr_warn!("Creating Error with an invalid errno {}, convert it to EINVAL", errno);
Error::EINVAL
} else {
Error(errno)
}
}
}

impl fmt::Debug for Error {
Expand Down

0 comments on commit 0bc70a3

Please sign in to comment.