Skip to content

Commit

Permalink
Enforce OS errors are in the allowed range (rust-random#441)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
briansmith authored Jun 4, 2024
1 parent 8933c05 commit 05cdf6f
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 21 deletions.
17 changes: 17 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,23 @@ impl Error {
/// custom errors.
pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30);

/// Creates a new instance of an `Error` from a particular OS error code.
///
/// This method is analogous to [`std::io::Error::from_raw_os_error()`][1],
/// except that it works in `no_std` contexts and `code` will be
/// replaced with `Error::UNEXPECTED` if it isn't in the range
/// `1..Error::INTERNAL_START`. Thus, for the result `r`,
/// `r == Self::UNEXPECTED || r.raw_os_error().unsigned_abs() == code`.
///
/// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.from_raw_os_error
#[allow(dead_code)]
pub(super) fn from_os_error(code: u32) -> Self {
match NonZeroU32::new(code) {
Some(code) if code.get() < Self::INTERNAL_START => Self(code),
_ => Self::UNEXPECTED,
}
}

/// Extract the raw OS error code (if this error came from the OS)
///
/// This method is identical to [`std::io::Error::raw_os_error()`][1], except
Expand Down
5 changes: 2 additions & 3 deletions src/hermit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Implementation for Hermit
use crate::Error;
use core::{mem::MaybeUninit, num::NonZeroU32};
use core::mem::MaybeUninit;

extern "C" {
fn sys_read_entropy(buffer: *mut u8, length: usize, flags: u32) -> isize;
Expand All @@ -16,8 +16,7 @@ pub fn getrandom_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
let err = if res < 0 {
u32::try_from(res.unsigned_abs())
.ok()
.and_then(NonZeroU32::new)
.map_or(Error::UNEXPECTED, Error::from)
.map_or(Error::UNEXPECTED, Error::from_os_error)
} else {
Error::UNEXPECTED
};
Expand Down
4 changes: 2 additions & 2 deletions src/solid.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Implementation for SOLID
use crate::Error;
use core::{mem::MaybeUninit, num::NonZeroU32};
use core::mem::MaybeUninit;

extern "C" {
pub fn SOLID_RNG_SampleRandomBytes(buffer: *mut u8, length: usize) -> i32;
Expand All @@ -13,6 +13,6 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
} else {
// ITRON error numbers are always negative, so we negate it so that it
// falls in the dedicated OS error range (1..INTERNAL_START).
Err(NonZeroU32::new(ret.unsigned_abs()).map_or(Error::UNEXPECTED, Error::from))
Err(Error::from_os_error(ret.unsigned_abs()))
}
}
10 changes: 5 additions & 5 deletions src/util_libc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(dead_code)]
use crate::Error;
use core::{mem::MaybeUninit, num::NonZeroU32};
use core::mem::MaybeUninit;

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

u32::try_from(errno)
.ok()
.and_then(NonZeroU32::new)
.map_or(Error::ERRNO_NOT_POSITIVE, Error::from)
match u32::try_from(errno) {
Ok(code) if code != 0 => Error::from_os_error(code),
_ => Error::ERRNO_NOT_POSITIVE,
}
}

// Fill a buffer by repeatedly invoking a system call. The `sys_fill` function:
Expand Down
14 changes: 3 additions & 11 deletions src/wasi.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
//! Implementation for WASI
use crate::Error;
use core::{
mem::MaybeUninit,
num::{NonZeroU16, NonZeroU32},
};
use core::mem::MaybeUninit;
use wasi::random_get;

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

0 comments on commit 05cdf6f

Please sign in to comment.