Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor Cleanups for 0.2 #136

Merged
merged 5 commits into from
Apr 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ env:

jobs:
include:
- name: "Linux, 1.32.0"
rust: 1.32.0
- name: "Linux, 1.33.0"
rust: 1.33.0

- name: "OSX, 1.32.0"
rust: 1.32.0
- name: "OSX, 1.33.0"
rust: 1.33.0
os: osx

- name: "Linux, stable"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ to switch to a custom implementation with a support of your target.

## Minimum Supported Rust Version

This crate requires Rust 1.32.0 or later.
This crate requires Rust 1.33.0 or later.

# License

Expand Down
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ environment:

matrix:
- TARGET: x86_64-pc-windows-msvc
CHANNEL: 1.32.0
CHANNEL: 1.33.0
- TARGET: x86_64-pc-windows-msvc
CHANNEL: stable
- TARGET: x86_64-pc-windows-msvc
Expand Down
2 changes: 0 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ fn main() {
if target.contains("-uwp-windows-") {
// for BCryptGenRandom
println!("cargo:rustc-link-lib=bcrypt");
// to work around unavailability of `target_vendor` on Rust 1.33
println!("cargo:rustc-cfg=getrandom_uwp");
} else if target.contains("windows") {
// for RtlGenRandom (aka SystemFunction036)
println!("cargo:rustc-link-lib=advapi32");
Expand Down
2 changes: 0 additions & 2 deletions custom/stdweb/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
compile_error!("This crate is only for the `wasm32-unknown-unknown` target");

use core::mem;
use std::sync::Once;

use stdweb::js;
Expand All @@ -26,7 +25,6 @@ enum RngSource {
register_custom_getrandom!(getrandom_inner);

fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
assert_eq!(mem::size_of::<usize>(), 4);
static ONCE: Once = Once::new();
static mut RNG_SOURCE: Result<RngSource, Error> = Ok(RngSource::Node);

Expand Down
3 changes: 0 additions & 3 deletions custom/wasm-bindgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
compile_error!("This crate is only for the `wasm32-unknown-unknown` target");

use core::cell::RefCell;
use core::mem;
use std::thread_local;

use wasm_bindgen::prelude::*;
Expand All @@ -32,8 +31,6 @@ thread_local!(
register_custom_getrandom!(getrandom_inner);

fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
assert_eq!(mem::size_of::<usize>(), 4);

RNG_SOURCE.with(|f| {
let mut source = f.borrow_mut();
if source.is_none() {
Expand Down
3 changes: 1 addition & 2 deletions src/bsd_arandom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
// except according to those terms.

//! Implementation for FreeBSD and NetBSD
use crate::util_libc::sys_fill_exact;
use crate::Error;
use crate::{util_libc::sys_fill_exact, Error};
use core::ptr;

fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
Expand Down
36 changes: 17 additions & 19 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::fmt;
use core::num::NonZeroU32;
use core::{fmt, num::NonZeroU32};

/// A small and `no_std` compatible error type.
///
Expand All @@ -19,36 +18,35 @@ use core::num::NonZeroU32;
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Error(NonZeroU32);

// TODO: Convert to a function when min_version >= 1.33
macro_rules! internal_error {
($n:expr) => {
Error(unsafe { NonZeroU32::new_unchecked(Error::INTERNAL_START + $n as u16 as u32) })
};
const fn internal_error(n: u16) -> Error {
// SAFETY: code > 0 as INTERNAL_START > 0 and adding n won't overflow a u32.
let code = Error::INTERNAL_START + (n as u32);
Error(unsafe { NonZeroU32::new_unchecked(code) })
}

impl Error {
/// This target/platform is not supported by `getrandom`.
pub const UNSUPPORTED: Error = internal_error!(0);
pub const UNSUPPORTED: Error = internal_error(0);
/// The platform-specific `errno` returned a non-positive value.
pub const ERRNO_NOT_POSITIVE: Error = internal_error!(1);
pub const ERRNO_NOT_POSITIVE: Error = internal_error(1);
/// Call to iOS [`SecRandomCopyBytes`](https://developer.apple.com/documentation/security/1399291-secrandomcopybytes) failed.
pub const IOS_SEC_RANDOM: Error = internal_error!(3);
pub const IOS_SEC_RANDOM: Error = internal_error(3);
/// Call to Windows [`RtlGenRandom`](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom) failed.
pub const WINDOWS_RTL_GEN_RANDOM: Error = internal_error!(4);
pub const WINDOWS_RTL_GEN_RANDOM: Error = internal_error(4);
/// RDRAND instruction failed due to a hardware issue.
pub const FAILED_RDRAND: Error = internal_error!(5);
pub const FAILED_RDRAND: Error = internal_error(5);
/// RDRAND instruction unsupported on this target.
pub const NO_RDRAND: Error = internal_error!(6);
pub const NO_RDRAND: Error = internal_error(6);
/// Using `wasm-bindgen`, browser does not support `self.crypto`.
pub const BINDGEN_CRYPTO_UNDEF: Error = internal_error!(7);
pub const BINDGEN_CRYPTO_UNDEF: Error = internal_error(7);
/// Using `wasm-bindgen`, browser does not support `crypto.getRandomValues`.
pub const BINDGEN_GRV_UNDEF: Error = internal_error!(8);
pub const BINDGEN_GRV_UNDEF: Error = internal_error(8);
/// Using `stdweb`, no cryptographic RNG is available.
pub const STDWEB_NO_RNG: Error = internal_error!(9);
pub const STDWEB_NO_RNG: Error = internal_error(9);
/// Using `stdweb`, invoking a cryptographic RNG failed.
pub const STDWEB_RNG_FAILED: Error = internal_error!(10);
pub const STDWEB_RNG_FAILED: Error = internal_error(10);
/// On VxWorks, call to `randSecure` failed (random number generator is not yet initialized).
pub const VXWORKS_RAND_SECURE: Error = internal_error!(11);
pub const VXWORKS_RAND_SECURE: Error = internal_error(11);

/// Codes below this point represent OS Errors (i.e. positive i32 values).
/// Codes at or above this point, but below [`Error::CUSTOM_START`] are
Expand Down Expand Up @@ -80,7 +78,7 @@ impl Error {
/// This code can either come from the underlying OS, or be a custom error.
/// Use [`Error::raw_os_error()`] to disambiguate.
#[inline]
pub fn code(self) -> NonZeroU32 {
pub const fn code(self) -> NonZeroU32 {
self.0
}
}
Expand Down
13 changes: 4 additions & 9 deletions src/ios.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,16 @@

//! Implementation for iOS
use crate::Error;

// TODO: Make extern once extern_types feature is stabilized. See:
// https://github.com/rust-lang/rust/issues/43467
#[repr(C)]
struct SecRandom([u8; 0]);
use core::{ffi::c_void, ptr::null};

#[link(name = "Security", kind = "framework")]
extern "C" {
static kSecRandomDefault: *const SecRandom;

fn SecRandomCopyBytes(rnd: *const SecRandom, count: usize, bytes: *mut u8) -> i32;
fn SecRandomCopyBytes(rnd: *const c_void, count: usize, bytes: *mut u8) -> i32;
}

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, dest.len(), dest.as_mut_ptr()) };
// Apple's documentation guarantees kSecRandomDefault is a synonym for NULL.
let ret = unsafe { SecRandomCopyBytes(null(), dest.len(), dest.as_mut_ptr()) };
if ret == -1 {
Err(Error::IOS_SEC_RANDOM)
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ cfg_if! {
} else if #[cfg(target_os = "vxworks")] {
mod util_libc;
#[path = "vxworks.rs"] mod imp;
} else if #[cfg(all(windows, getrandom_uwp))] {
} else if #[cfg(all(windows, target_vendor = "uwp"))] {
#[path = "windows_uwp.rs"] mod imp;
} else if #[cfg(windows)] {
#[path = "windows.rs"] mod imp;
Expand Down
8 changes: 5 additions & 3 deletions src/linux_android.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
// except according to those terms.

//! Implementation for Linux / Android
use crate::util::LazyBool;
use crate::util_libc::{last_os_error, sys_fill_exact};
use crate::{use_file, Error};
use crate::{
util::LazyBool,
util_libc::{last_os_error, sys_fill_exact},
{use_file, Error},
};

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
static HAS_GETRANDOM: LazyBool = LazyBool::new();
Expand Down
7 changes: 5 additions & 2 deletions src/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
// except according to those terms.

//! Implementation for macOS
use crate::util_libc::{last_os_error, Weak};
use crate::{use_file, Error};
use crate::{
use_file,
util_libc::{last_os_error, Weak},
Error,
};
use core::mem;

type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int;
Expand Down
3 changes: 1 addition & 2 deletions src/openbsd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
// except according to those terms.

//! Implementation for OpenBSD
use crate::util_libc::last_os_error;
use crate::Error;
use crate::{util_libc::last_os_error, Error};

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
for chunk in dest.chunks_mut(256) {
Expand Down
7 changes: 5 additions & 2 deletions src/solaris_illumos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
//! To make sure we can compile on both Solaris and its derivatives, as well as
//! function, we check for the existence of getrandom(2) in libc by calling
//! libc::dlsym.
use crate::util_libc::{sys_fill_exact, Weak};
use crate::{use_file, Error};
use crate::{
use_file,
util_libc::{sys_fill_exact, Weak},
Error,
};
use core::mem;

#[cfg(target_os = "illumos")]
Expand Down
16 changes: 10 additions & 6 deletions src/use_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@
// except according to those terms.

//! Implementations that just need to read from a file
use crate::util::LazyUsize;
use crate::util_libc::{open_readonly, sys_fill_exact};
use crate::Error;
use core::cell::UnsafeCell;
use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use crate::{
util::LazyUsize,
util_libc::{open_readonly, sys_fill_exact},
Error,
};
use core::{
cell::UnsafeCell,
sync::atomic::{AtomicUsize, Ordering::Relaxed},
};

#[cfg(target_os = "redox")]
const FILE_PATH: &str = "rand:\0";
Expand Down Expand Up @@ -99,7 +103,7 @@ fn wait_until_rng_ready() -> Result<(), Error> {
// A negative timeout means an infinite timeout.
let res = unsafe { libc::poll(&mut pfd, 1, -1) };
if res >= 0 {
assert_eq!(res, 1); // We only used one fd, and cannot timeout.
debug_assert_eq!(res, 1); // We only used one fd, and cannot timeout.
return Ok(());
}
let err = crate::util_libc::last_os_error();
Expand Down
8 changes: 3 additions & 5 deletions src/util_libc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
use crate::util::LazyUsize;
use crate::Error;
use core::num::NonZeroU32;
use core::ptr::NonNull;
use crate::{util::LazyUsize, Error};
use core::{num::NonZeroU32, ptr::NonNull};

cfg_if! {
if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] {
Expand Down Expand Up @@ -108,7 +106,7 @@ cfg_if! {

// SAFETY: path must be null terminated, FD must be manually closed.
pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> {
debug_assert!(path.as_bytes().last() == Some(&0));
debug_assert_eq!(path.as_bytes().last(), Some(&0));
let fd = open(path.as_ptr() as *const _, libc::O_RDONLY | libc::O_CLOEXEC);
if fd < 0 {
return Err(last_os_error());
Expand Down
3 changes: 1 addition & 2 deletions src/vxworks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
// except according to those terms.

//! Implementation for VxWorks
use crate::util_libc::last_os_error;
use crate::Error;
use crate::{util_libc::last_os_error, Error};
use core::sync::atomic::{AtomicBool, Ordering::Relaxed};

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
Expand Down