Skip to content

Commit 05cdf6f

Browse files
authored
Enforce OS errors are in the allowed range (#441)
Avoid the `From<NonZeroU32>` implementation in favor of a constructor that centralizes all the range checking in one place. Besides being more consistent in the range checking, this also reduces the boilerplate in callers, which makes it easier to maintain the ports to less-common operating systems.
1 parent 8933c05 commit 05cdf6f

File tree

5 files changed

+29
-21
lines changed

5 files changed

+29
-21
lines changed

src/error.rs

+17
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,23 @@ impl Error {
6868
/// custom errors.
6969
pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30);
7070

71+
/// Creates a new instance of an `Error` from a particular OS error code.
72+
///
73+
/// This method is analogous to [`std::io::Error::from_raw_os_error()`][1],
74+
/// except that it works in `no_std` contexts and `code` will be
75+
/// replaced with `Error::UNEXPECTED` if it isn't in the range
76+
/// `1..Error::INTERNAL_START`. Thus, for the result `r`,
77+
/// `r == Self::UNEXPECTED || r.raw_os_error().unsigned_abs() == code`.
78+
///
79+
/// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.from_raw_os_error
80+
#[allow(dead_code)]
81+
pub(super) fn from_os_error(code: u32) -> Self {
82+
match NonZeroU32::new(code) {
83+
Some(code) if code.get() < Self::INTERNAL_START => Self(code),
84+
_ => Self::UNEXPECTED,
85+
}
86+
}
87+
7188
/// Extract the raw OS error code (if this error came from the OS)
7289
///
7390
/// This method is identical to [`std::io::Error::raw_os_error()`][1], except

src/hermit.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Implementation for Hermit
22
use crate::Error;
3-
use core::{mem::MaybeUninit, num::NonZeroU32};
3+
use core::mem::MaybeUninit;
44

55
extern "C" {
66
fn sys_read_entropy(buffer: *mut u8, length: usize, flags: u32) -> isize;
@@ -16,8 +16,7 @@ pub fn getrandom_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
1616
let err = if res < 0 {
1717
u32::try_from(res.unsigned_abs())
1818
.ok()
19-
.and_then(NonZeroU32::new)
20-
.map_or(Error::UNEXPECTED, Error::from)
19+
.map_or(Error::UNEXPECTED, Error::from_os_error)
2120
} else {
2221
Error::UNEXPECTED
2322
};

src/solid.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Implementation for SOLID
22
use crate::Error;
3-
use core::{mem::MaybeUninit, num::NonZeroU32};
3+
use core::mem::MaybeUninit;
44

55
extern "C" {
66
pub fn SOLID_RNG_SampleRandomBytes(buffer: *mut u8, length: usize) -> i32;
@@ -13,6 +13,6 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
1313
} else {
1414
// ITRON error numbers are always negative, so we negate it so that it
1515
// falls in the dedicated OS error range (1..INTERNAL_START).
16-
Err(NonZeroU32::new(ret.unsigned_abs()).map_or(Error::UNEXPECTED, Error::from))
16+
Err(Error::from_os_error(ret.unsigned_abs()))
1717
}
1818
}

src/util_libc.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#![allow(dead_code)]
22
use crate::Error;
3-
use core::{mem::MaybeUninit, num::NonZeroU32};
3+
use core::mem::MaybeUninit;
44

55
cfg_if! {
66
if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] {
@@ -40,10 +40,10 @@ pub fn last_os_error() -> Error {
4040
// c_int-to-u32 conversion is lossless for nonnegative values if they are the same size.
4141
const _: () = assert!(core::mem::size_of::<libc::c_int>() == core::mem::size_of::<u32>());
4242

43-
u32::try_from(errno)
44-
.ok()
45-
.and_then(NonZeroU32::new)
46-
.map_or(Error::ERRNO_NOT_POSITIVE, Error::from)
43+
match u32::try_from(errno) {
44+
Ok(code) if code != 0 => Error::from_os_error(code),
45+
_ => Error::ERRNO_NOT_POSITIVE,
46+
}
4747
}
4848

4949
// Fill a buffer by repeatedly invoking a system call. The `sys_fill` function:

src/wasi.rs

+3-11
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,9 @@
11
//! Implementation for WASI
22
use crate::Error;
3-
use core::{
4-
mem::MaybeUninit,
5-
num::{NonZeroU16, NonZeroU32},
6-
};
3+
use core::mem::MaybeUninit;
74
use wasi::random_get;
85

96
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
10-
unsafe { random_get(dest.as_mut_ptr().cast::<u8>(), dest.len()) }.map_err(|e| {
11-
// The WASI errno will always be non-zero, but we check just in case.
12-
match NonZeroU16::new(e.raw()) {
13-
Some(r) => Error::from(NonZeroU32::from(r)),
14-
None => Error::ERRNO_NOT_POSITIVE,
15-
}
16-
})
7+
unsafe { random_get(dest.as_mut_ptr().cast::<u8>(), dest.len()) }
8+
.map_err(|e| Error::from_os_error(e.raw().into()))
179
}

0 commit comments

Comments
 (0)