Skip to content
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
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ matrix:
install:
- rustup component add rustfmt
script:
- cargo fmt --all -- src/*.rs --check
- cargo fmt --all -- */*.rs --check

- rust: nightly
os: linux
Expand Down
7 changes: 3 additions & 4 deletions benches/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#![feature(test)]
extern crate test;
extern crate getrandom;
extern crate test;

#[bench]
fn bench_64(b: &mut test::Bencher) {
let mut buf = [0u8; 64];
b.iter(|| {
getrandom::getrandom(&mut buf[..]).unwrap();
test::black_box(&buf);
test::black_box(&buf);
});
b.bytes = buf.len() as u64;
}
Expand All @@ -17,8 +17,7 @@ fn bench_65536(b: &mut test::Bencher) {
let mut buf = [0u8; 65536];
b.iter(|| {
getrandom::getrandom(&mut buf[..]).unwrap();
test::black_box(&buf);
test::black_box(&buf);
});
b.bytes = buf.len() as u64;
}

6 changes: 4 additions & 2 deletions src/cloudabi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
// except according to those terms.

//! Implementation for CloudABI
use core::num::NonZeroU32;
use crate::Error;
use core::num::NonZeroU32;

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
let errno = unsafe { cloudabi::random_get(dest) };
Expand All @@ -22,4 +22,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
6 changes: 4 additions & 2 deletions src/dummy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@

//! A dummy implementation for unsupported targets which always returns
//! `Err(Error::UNAVAILABLE)`
use core::num::NonZeroU32;
use crate::Error;
use core::num::NonZeroU32;

pub fn getrandom_inner(_: &mut [u8]) -> Result<(), Error> {
error!("no support for this platform");
Err(Error::UNAVAILABLE)
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
14 changes: 5 additions & 9 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
// <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::num::NonZeroU32;
use core::convert::From;
use core::fmt;
use core::num::NonZeroU32;

// A randomly-chosen 24-bit prefix for our codes
pub(crate) const CODE_PREFIX: u32 = 0x57f4c500;
Expand All @@ -22,14 +22,10 @@ pub struct Error(pub(crate) NonZeroU32);

impl Error {
/// An unknown error.
pub const UNKNOWN: Error = Error(unsafe {
NonZeroU32::new_unchecked(CODE_UNKNOWN)
});
pub const UNKNOWN: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNKNOWN) });

/// No generator is available.
pub const UNAVAILABLE: Error = Error(unsafe {
NonZeroU32::new_unchecked(CODE_UNAVAILABLE)
});
pub const UNAVAILABLE: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNAVAILABLE) });

/// Extract the error code.
///
Expand All @@ -48,7 +44,7 @@ impl Error {
match *self {
Error::UNKNOWN => Some("getrandom: unknown error"),
Error::UNAVAILABLE => Some("getrandom: unavailable"),
_ => None
_ => None,
}
}
}
Expand Down Expand Up @@ -80,8 +76,8 @@ impl From<NonZeroU32> for Error {

#[cfg(test)]
mod tests {
use core::mem::size_of;
use super::Error;
use core::mem::size_of;

#[test]
fn test_size() {
Expand Down
6 changes: 3 additions & 3 deletions src/error_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
// except according to those terms.
extern crate std;

use std::{io, error};
use crate::error::Error;
use core::convert::From;
use core::num::NonZeroU32;
use crate::error::Error;
use std::{error, io};

impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Expand All @@ -31,4 +31,4 @@ impl From<Error> for io::Error {
}
}

impl error::Error for Error { }
impl error::Error for Error {}
8 changes: 5 additions & 3 deletions src/freebsd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
extern crate std;

use crate::Error;
use std::io;
use core::ptr;
use core::num::NonZeroU32;
use core::ptr;
use std::io;

fn kern_arnd(buf: &mut [u8]) -> Result<usize, Error> {
static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
Expand Down Expand Up @@ -43,4 +43,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
6 changes: 4 additions & 2 deletions src/fuchsia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
// except according to those terms.

//! Implementation for Fuchsia Zircon
use core::num::NonZeroU32;
use crate::Error;
use core::num::NonZeroU32;

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
fuchsia_cprng::cprng_draw(dest);
Ok(())
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
26 changes: 15 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@
//! features are activated for this crate. Note that if both features are
//! enabled `wasm-bindgen` will be used. If neither feature is enabled,
//! `getrandom` will always fail.
//!
//!
//! The WASI target `wasm32-wasi` uses the `__wasi_random_get` function defined
//! by the WASI standard.
//!
//!
//!
//! ## Early boot
//!
Expand Down Expand Up @@ -115,18 +115,22 @@
//! [16]: #support-for-webassembly-and-amsjs
//! [17]: https://github.com/CraneStation/wasmtime/blob/master/docs/WASI-api.md#__wasi_random_get

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://rust-random.github.io/rand/")]
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://rust-random.github.io/rand/"
)]
#![no_std]
#![cfg_attr(feature = "stdweb", recursion_limit="128")]
#![cfg_attr(feature = "stdweb", recursion_limit = "128")]

#[cfg(feature = "log")]
#[macro_use]
extern crate log;
#[cfg(not(feature = "log"))]
#[allow(unused)]
macro_rules! error { ($($x:tt)*) => () }
macro_rules! error {
($($x:tt)*) => {};
}

// temp fix for stdweb
#[cfg(target_arch = "wasm32")]
Expand All @@ -144,13 +148,14 @@ macro_rules! mod_use {
#[$cond]
mod $module;
#[$cond]
use crate::$module::{getrandom_inner, error_msg_inner};
}
use crate::$module::{error_msg_inner, getrandom_inner};
};
}

#[cfg(any(
feature = "std",
windows, unix,
windows,
unix,
target_os = "cloudabi",
target_os = "redox",
target_arch = "wasm32",
Expand Down Expand Up @@ -238,7 +243,6 @@ mod_use!(
dummy
);


/// Fill `dest` with random bytes from the system's preferred random number
/// source.
///
Expand Down
18 changes: 10 additions & 8 deletions src/linux_android.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ use std::io;

fn syscall_getrandom(dest: &mut [u8], block: bool) -> Result<usize, io::Error> {
let flags = if block { 0 } else { libc::GRND_NONBLOCK };
let ret = unsafe {
libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), flags)
};
let ret = unsafe { libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), flags) };
if ret < 0 {
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EINTR) {
Expand All @@ -31,15 +29,17 @@ fn syscall_getrandom(dest: &mut [u8], block: bool) -> Result<usize, io::Error> {
}

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
lazy_static! { static ref HAS_GETRANDOM: bool = is_getrandom_available(); }
lazy_static! {
static ref HAS_GETRANDOM: bool = is_getrandom_available();
}
match *HAS_GETRANDOM {
true => {
let mut start = 0;
while start < dest.len() {
start += syscall_getrandom(&mut dest[start..], true)?;
}
Ok(())
},
}
false => use_file::getrandom_inner(dest),
}
}
Expand All @@ -48,12 +48,14 @@ fn is_getrandom_available() -> bool {
match syscall_getrandom(&mut [], false) {
Err(err) => match err.raw_os_error() {
Some(libc::ENOSYS) => false, // No kernel support
Some(libc::EPERM) => false, // Blocked by seccomp
Some(libc::EPERM) => false, // Blocked by seccomp
_ => true,
}
},
Ok(_) => true,
}
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
8 changes: 5 additions & 3 deletions src/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@
extern crate std;

use crate::Error;
use std::io;
use core::num::NonZeroU32;
use std::io;

// TODO: Make extern once extern_types feature is stabilized. See:
// https://github.com/rust-lang/rust/issues/43467
#[repr(C)]
struct SecRandom([u8; 0]);

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

fn SecRandomCopyBytes(rnd: *const SecRandom, count: usize, bytes: *mut u8) -> libc::c_int;
Expand All @@ -36,4 +36,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
11 changes: 4 additions & 7 deletions src/openbsd_bitrig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,7 @@ use std::num::NonZeroU32;

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
for chunk in dest.chunks_mut(256) {
let ret = unsafe {
libc::getentropy(
chunk.as_mut_ptr() as *mut libc::c_void,
chunk.len()
)
};
let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) };
if ret == -1 {
error!("libc::getentropy call failed");
return Err(io::Error::last_os_error().into());
Expand All @@ -30,4 +25,6 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
6 changes: 4 additions & 2 deletions src/rdrand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

//! Implementation for SGX using RDRAND instruction
use crate::Error;
use core::mem;
use core::arch::x86_64::{__cpuid, _rdrand64_step};
use core::mem;
use core::num::NonZeroU32;
use lazy_static::lazy_static;

Expand Down Expand Up @@ -80,4 +80,6 @@ unsafe fn rdrand_exact(dest: &mut [u8]) -> Result<(), Error> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
8 changes: 6 additions & 2 deletions src/solaris_illumos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ fn libc_getrandom(rand: GetRandomFn, dest: &mut [u8]) -> Result<(), Error> {
}

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
lazy_static! { static ref GETRANDOM_FUNC: Option<GetRandomFn> = fetch_getrandom(); }
lazy_static! {
static ref GETRANDOM_FUNC: Option<GetRandomFn> = fetch_getrandom();
}

// 256 bytes is the lowest common denominator across all the Solaris
// derived platforms for atomically obtaining random data.
Expand All @@ -62,4 +64,6 @@ fn fetch_getrandom() -> Option<GetRandomFn> {
}

#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
8 changes: 6 additions & 2 deletions src/use_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ const FILE_PATH: &str = "/dev/urandom";
const FILE_PATH: &str = "/dev/random";

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
lazy_static! { static ref RNG_FD: Result<RawFd, Error> = init_file(); }
lazy_static! {
static ref RNG_FD: Result<RawFd, Error> = init_file();
}
let mut f = unsafe { File::from_raw_fd((*RNG_FD)?) };

if cfg!(target_os = "emscripten") {
Expand All @@ -56,4 +58,6 @@ fn init_file() -> Result<RawFd, Error> {

#[inline(always)]
#[allow(dead_code)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> {
None
}
Loading