Skip to content

Commit f860bde

Browse files
committed
use atomic bool to check RNG initialization
1 parent 5ebbaf7 commit f860bde

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

src/lib.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
66
// option. This file may not be copied, modified, or distributed
77
// except according to those terms.
8-
9-
108
#![no_std]
119

1210
#[cfg(any(

src/linux_android.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ use std::fs::File;
1515
use std::io;
1616
use std::io::Read;
1717
use std::cell::RefCell;
18+
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
19+
20+
static RNG_INIT: AtomicBool = ATOMIC_BOOL_INIT;
1821

1922
enum RngSource {
2023
GetRandom,
@@ -44,7 +47,10 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
4447
} else {
4548
// read one byte from "/dev/random" to ensure that
4649
// OS RNG has initialized
47-
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
50+
if !RNG_INIT.load(Ordering::Relaxed) {
51+
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
52+
RNG_INIT.store(true, Ordering::Relaxed)
53+
}
4854
RngSource::Device(File::open("/dev/urandom")?)
4955
};
5056
Ok(s)
@@ -58,7 +64,6 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
5864
}
5965

6066
fn is_getrandom_available() -> bool {
61-
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
6267
use std::sync::{Once, ONCE_INIT};
6368

6469
static CHECKER: Once = ONCE_INIT;

src/netbsd.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ use super::utils::use_init;
1313
use std::fs::File;
1414
use std::io::Read;
1515
use std::cell::RefCell;
16+
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
17+
18+
static RNG_INIT: AtomicBool = ATOMIC_BOOL_INIT;
1619

1720
thread_local!(static RNG_FILE: RefCell<Option<File>> = RefCell::new(None));
1821

@@ -21,7 +24,10 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
2124
use_init(f, || {
2225
// read one byte from "/dev/random" to ensure that
2326
// OS RNG has initialized
24-
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
27+
if !RNG_INIT.load(Ordering::Relaxed) {
28+
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
29+
RNG_INIT.store(true, Ordering::Relaxed)
30+
}
2531
File::open("/dev/urandom")
2632
}, |f| f.read_exact(dest))
2733
}).map_err(|_| Error::Unknown)

0 commit comments

Comments
 (0)