#![cfg_attr(not(feature = "std"), no_std)]
extern crate rand_core;
#[cfg(feature = "std")]
extern crate core;
pub mod changelog;
use rand_core::{RngCore, CryptoRng, Error, ErrorKind};
const RETRY_LIMIT: u8 = 127;
#[cold]
#[inline(never)]
pub(crate) fn busy_loop_fail() -> ! {
panic!("hardware generator failure");
}
#[derive(Clone, Copy)]
pub struct RdRand(());
#[derive(Clone, Copy)]
pub struct RdSeed(());
impl CryptoRng for RdRand {}
impl CryptoRng for RdSeed {}
mod arch {
#[cfg(target_arch = "x86_64")]
pub use core::arch::x86_64::*;
#[cfg(target_arch = "x86")]
pub use core::arch::x86::*;
#[cfg(target_arch = "x86")]
pub(crate) unsafe fn _rdrand64_step(dest: &mut u64) -> i32 {
let mut ret1: u32 = 0;
let mut ret2: u32 = 0;
if _rdrand32_step(&mut ret1) != 0 && _rdrand32_step(&mut ret2) != 0 {
*dest = (ret1 as u64) << 32 | (ret2 as u64);
1
} else {
0
}
}
#[cfg(target_arch = "x86")]
pub(crate) unsafe fn _rdseed64_step(dest: &mut u64) -> i32 {
let mut ret1: u32 = 0;
let mut ret2: u32 = 0;
if _rdseed32_step(&mut ret1) != 0 && _rdseed32_step(&mut ret2) != 0 {
*dest = (ret1 as u64) << 32 | (ret2 as u64);
1
} else {
0
}
}
}
#[cfg(not(feature = "std"))]
macro_rules! is_x86_feature_detected {
("rdrand") => {{
if cfg!(target_feature="rdrand") {
true
} else if cfg!(target_env = "sgx") {
false
} else {
const FLAG : u32 = 1 << 30;
unsafe { arch::__cpuid(1).ecx & FLAG == FLAG }
}
}};
("rdseed") => {{
if cfg!(target_feature = "rdseed") {
true
} else if cfg!(target_env = "sgx") {
false
} else {
const FLAG : u32 = 1 << 18;
unsafe { arch::__cpuid(7).ebx & FLAG == FLAG }
}
}};
}
macro_rules! loop_rand {
($el: ty, $step: path) => { {
let mut idx = 0;
loop {
let mut el: $el = 0;
if $step(&mut el) != 0 {
break Some(el);
} else if idx == RETRY_LIMIT {
break None;
}
idx += 1;
}
} }
}
macro_rules! impl_rand {
($gen:ident, $feat:tt, $step16: path, $step32:path, $step64:path,
maxstep = $maxstep:path, maxty = $maxty: ty) => {
impl $gen {
pub fn new() -> Result<Self, Error> {
if is_x86_feature_detected!($feat) {
Ok($gen(()))
} else {
Err(Error::new(rand_core::ErrorKind::Unavailable,
"the instruction is not supported"))
}
}
#[inline(always)]
pub fn try_next_u16(&self) -> Option<u16> {
#[target_feature(enable = $feat)]
unsafe fn imp()
-> Option<u16> {
loop_rand!(u16, $step16)
}
unsafe { imp() }
}
#[inline(always)]
pub fn try_next_u32(&self) -> Option<u32> {
#[target_feature(enable = $feat)]
unsafe fn imp()
-> Option<u32> {
loop_rand!(u32, $step32)
}
unsafe { imp() }
}
#[inline(always)]
pub fn try_next_u64(&self) -> Option<u64> {
#[target_feature(enable = $feat)]
unsafe fn imp()
-> Option<u64> {
loop_rand!(u64, $step64)
}
unsafe { imp() }
}
}
impl RngCore for $gen {
#[inline(always)]
fn next_u32(&mut self) -> u32 {
if let Some(result) = self.try_next_u32() {
result
} else {
busy_loop_fail()
}
}
#[inline(always)]
fn next_u64(&mut self) -> u64 {
if let Some(result) = self.try_next_u64() {
result
} else {
busy_loop_fail()
}
}
#[inline(always)]
fn fill_bytes(&mut self, dest: &mut [u8]) {
if let Err(_) = self.try_fill_bytes(dest) {
busy_loop_fail()
}
}
#[inline(always)]
fn try_fill_bytes(&mut self, dest: &mut [u8])
-> Result<(), Error> {
#[target_feature(enable = $feat)]
unsafe fn imp(dest: &mut [u8])
-> Result<(), Error>
{
fn slow_fill_bytes<'a>(mut left: &'a mut [u8], mut right: &'a mut [u8])
-> Result<(), Error>
{
const LEN: usize = core::mem::size_of::<$maxty>();
let mut word = [0; LEN];
let mut valid_range = LEN..;
while !left.is_empty() {
if valid_range.start >= LEN {
unsafe {
if let Some(w) = loop_rand!($maxty, $maxstep) {
word = core::mem::transmute(w); valid_range = 0..;
} else {
return Err(Error::new(ErrorKind::Unexpected,
"hardware generator failure"));
}
}
}
let len = left.len().min(core::mem::size_of::<$maxty>() - valid_range.start);
let (copy_dest, dest_leftover) = { left }.split_at_mut(len);
copy_dest.copy_from_slice(&word[valid_range.start..][..len]);
valid_range.start += len;
left = dest_leftover;
if left.is_empty() {
::core::mem::swap(&mut left, &mut right);
}
}
Ok(())
}
let destlen = dest.len();
if destlen > ::core::mem::size_of::<$maxty>() {
let (left, mid, right) = dest.align_to_mut();
for el in mid {
if let Some(val) = loop_rand!($maxty, $maxstep) {
*el = val;
} else {
return Err(Error::new(ErrorKind::Unexpected,
"hardware generator failure"));
}
}
slow_fill_bytes(left, right)
} else {
slow_fill_bytes(dest, &mut [])
}
}
unsafe { imp(dest) }
}
}
}
}
#[cfg(target_arch = "x86_64")]
impl_rand!(RdRand, "rdrand",
arch::_rdrand16_step, arch::_rdrand32_step, arch::_rdrand64_step,
maxstep = arch::_rdrand64_step, maxty = u64);
#[cfg(target_arch = "x86_64")]
impl_rand!(RdSeed, "rdseed",
arch::_rdseed16_step, arch::_rdseed32_step, arch::_rdseed64_step,
maxstep = arch::_rdseed64_step, maxty = u64);
#[cfg(target_arch = "x86")]
impl_rand!(RdRand, "rdrand",
arch::_rdrand16_step, arch::_rdrand32_step, arch::_rdrand64_step,
maxstep = arch::_rdrand32_step, maxty = u32);
#[cfg(target_arch = "x86")]
impl_rand!(RdSeed, "rdseed",
arch::_rdseed16_step, arch::_rdseed32_step, arch::_rdseed64_step,
maxstep = arch::_rdseed32_step, maxty = u32);
#[test]
fn rdrand_works() {
let _ = RdRand::new().map(|mut r| {
r.next_u32();
r.next_u64();
});
}
#[test]
fn fill_fills_all_bytes() {
let _ = RdRand::new().map(|mut r| {
let mut peach;
let mut banana;
let mut start = 0;
let mut end = 128;
'outer: while start < end {
banana = [0; 128];
for _ in 0..512 {
peach = [0; 128];
r.fill_bytes(&mut peach[start..end]);
for (b, p) in banana.iter_mut().zip(peach.iter()) {
*b = *b | *p;
}
if (&banana[start..end]).iter().all(|x| *x != 0) {
assert!(banana[..start].iter().all(|x| *x == 0), "all other values must be 0");
assert!(banana[end..].iter().all(|x| *x == 0), "all other values must be 0");
if start < 17 {
start += 1;
} else {
end -= 3;
}
continue 'outer;
}
}
panic!("wow, we broke it? {} {} {:?}", start, end, &banana[..])
}
});
}
#[test]
fn rdseed_works() {
let _ = RdSeed::new().map(|mut r| {
r.next_u32();
r.next_u64();
});
}