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. Add errno check in from_kernel_errno()
2. 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 e021924
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,28 @@ impl Error {
pub const EBADF: Self = Error(-(bindings::EBADF as i32));

/// Creates an [`Error`] from a kernel error code.
/// When errno given is invalid, a warning will be printed
/// and the errno will be converted to EINVAL.
pub fn from_kernel_errno(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);
return Error::EINVAL;
}

Error(errno)
}

/// Creates an [`Error`] from a kernel error code without a sanity check
/// # Safety: errno must be within error code range (i.e. >= -MAX_ERRNO && < 0)
pub unsafe 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 {
// INVARIANT: the safety contract and check ensure the type invariant
// will hold.
self.0
}
}
Expand Down

0 comments on commit e021924

Please sign in to comment.