Skip to content

Commit 89cf0c7

Browse files
committed
rust: check range and add type invariant to Error
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]>
1 parent 7884043 commit 89cf0c7

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

rust/kernel/error.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,34 @@ impl Error {
5757
pub const EBADF: Self = Error(-(bindings::EBADF as i32));
5858

5959
/// Creates an [`Error`] from a kernel error code.
60+
/// when errno given is invalid,
61+
/// it will convert it to EINVAL, and print a warning message.
6062
pub fn from_kernel_errno(errno: c_types::c_int) -> Error {
63+
Error::new(errno)
64+
}
65+
66+
/// Creates an [`Error`] from a kernel error code without a sanity check
67+
pub fn from_kernel_errno_unchecked(errno: c_types::c_int) -> Error {
6168
Error(errno)
6269
}
6370

6471
/// Returns the kernel error code.
6572
pub fn to_kernel_errno(self) -> c_types::c_int {
6673
self.0
6774
}
75+
76+
/// INVARIANT: make sure Error is initialized with a sane value
77+
/// When an invalid errno is found, it will
78+
/// 1) convert it to EINVAL
79+
/// 2) print a warning message
80+
pub fn new(errno: c_types::c_int) -> Error {
81+
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
82+
crate::pr_warn!("Creating Error with an invalid errno {}, convert it to EINVAL", errno);
83+
Error::EINVAL
84+
} else {
85+
Error(errno)
86+
}
87+
}
6888
}
6989

7090
impl fmt::Debug for Error {

0 commit comments

Comments
 (0)