Don't block in getrandom() detection (#26)

On Linux, we detect if `getrandom` is present by calling getrandom with
an empty buffer and seeing if `ENOSYS` is returned. However, even with
an empty buffer, this call will block unless we explicitly pass a flag.

This can be seen in the source for `getrandom`:
  https://elixir.bootlin.com/linux/v5.1.8/source/drivers/char/random.c#L2043

This change adds a boolean parameter to `syscall_getrandom` to control
the blocking behavior. We now don't block in initialization, but do
block when actually reading random data.
This commit is contained in:
Joseph Richey 2019-06-10 12:34:43 -04:00 committed by Artyom Pavlov
parent 0a18857988
commit db27e97d94

View File

@ -16,6 +16,8 @@ use core::cell::RefCell;
use core::num::NonZeroU32;
use core::sync::atomic::{AtomicBool, Ordering};
// This flag tells getrandom() to return EAGAIN instead of blocking.
const GRND_NONBLOCK: libc::c_uint = 0x0001;
static RNG_INIT: AtomicBool = AtomicBool::new(false);
enum RngSource {
@ -27,9 +29,10 @@ thread_local!(
static RNG_SOURCE: RefCell<Option<RngSource>> = RefCell::new(None);
);
fn syscall_getrandom(dest: &mut [u8]) -> Result<(), io::Error> {
fn syscall_getrandom(dest: &mut [u8], block: bool) -> Result<(), io::Error> {
let flags = if block { 0 } else { GRND_NONBLOCK };
let ret = unsafe {
libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), 0)
libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), flags)
};
if ret < 0 || (ret as usize) != dest.len() {
error!("Linux getrandom syscall failed with return value {}", ret);
@ -56,7 +59,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
Ok(s)
}, |f| {
match f {
RngSource::GetRandom => syscall_getrandom(dest),
RngSource::GetRandom => syscall_getrandom(dest, true),
RngSource::Device(f) => f.read_exact(dest),
}.map_err(From::from)
})
@ -71,7 +74,7 @@ fn is_getrandom_available() -> bool {
CHECKER.call_once(|| {
let mut buf: [u8; 0] = [];
let available = match syscall_getrandom(&mut buf) {
let available = match syscall_getrandom(&mut buf, false) {
Ok(()) => true,
Err(err) => err.raw_os_error() != Some(libc::ENOSYS),
};