use atomic bool to check RNG initialization
This commit is contained in:
@@ -5,8 +5,6 @@
|
||||
// <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.
|
||||
|
||||
|
||||
#![no_std]
|
||||
|
||||
#[cfg(any(
|
||||
|
||||
@@ -15,6 +15,9 @@ use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
|
||||
|
||||
static RNG_INIT: AtomicBool = ATOMIC_BOOL_INIT;
|
||||
|
||||
enum RngSource {
|
||||
GetRandom,
|
||||
@@ -44,7 +47,10 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
|
||||
} else {
|
||||
// read one byte from "/dev/random" to ensure that
|
||||
// OS RNG has initialized
|
||||
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
|
||||
if !RNG_INIT.load(Ordering::Relaxed) {
|
||||
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
|
||||
RNG_INIT.store(true, Ordering::Relaxed)
|
||||
}
|
||||
RngSource::Device(File::open("/dev/urandom")?)
|
||||
};
|
||||
Ok(s)
|
||||
@@ -58,7 +64,6 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
|
||||
}
|
||||
|
||||
fn is_getrandom_available() -> bool {
|
||||
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
|
||||
use std::sync::{Once, ONCE_INIT};
|
||||
|
||||
static CHECKER: Once = ONCE_INIT;
|
||||
|
||||
+7
-1
@@ -13,6 +13,9 @@ use super::utils::use_init;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
|
||||
|
||||
static RNG_INIT: AtomicBool = ATOMIC_BOOL_INIT;
|
||||
|
||||
thread_local!(static RNG_FILE: RefCell<Option<File>> = RefCell::new(None));
|
||||
|
||||
@@ -21,7 +24,10 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
|
||||
use_init(f, || {
|
||||
// read one byte from "/dev/random" to ensure that
|
||||
// OS RNG has initialized
|
||||
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
|
||||
if !RNG_INIT.load(Ordering::Relaxed) {
|
||||
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
|
||||
RNG_INIT.store(true, Ordering::Relaxed)
|
||||
}
|
||||
File::open("/dev/urandom")
|
||||
}, |f| f.read_exact(dest))
|
||||
}).map_err(|_| Error::Unknown)
|
||||
|
||||
Reference in New Issue
Block a user