Skip to content

Commit 5ce8496

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. 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]>
1 parent 7884043 commit 5ce8496

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,12 +57,32 @@ impl Error {
5757
pub const EBADF: Self = Error(-(bindings::EBADF as i32));
5858

5959
/// Creates an [`Error`] from a kernel error code.
60+
///
61+
/// When errno given is invalid, a warning will be printed
62+
/// and the errno will be converted to EINVAL.
6063
pub fn from_kernel_errno(errno: c_types::c_int) -> Error {
64+
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
65+
crate::pr_warn!("Creating Error with an invalid errno {}, convert \
66+
it to EINVAL", errno);
67+
return Error::EINVAL;
68+
}
69+
70+
Error(errno)
71+
}
72+
73+
/// Creates an [`Error`] from a kernel error code without a sanity check
74+
///
75+
/// # Safety
76+
///
77+
/// errno must be within error code range (i.e. >= -MAX_ERRNO && < 0).
78+
pub unsafe fn from_kernel_errno_unchecked(errno: c_types::c_int) -> Error {
6179
Error(errno)
6280
}
6381

6482
/// Returns the kernel error code.
6583
pub fn to_kernel_errno(self) -> c_types::c_int {
84+
// INVARIANT: the safety contract and check ensure the type invariant
85+
// will hold.
6686
self.0
6787
}
6888
}

0 commit comments

Comments
 (0)