Skip to content

Commit

Permalink
Don't block in getrandom() detection (#26)
Browse files Browse the repository at this point in the history
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.
josephlr authored and newpavlov committed Jun 10, 2019
1 parent 0a18857 commit db27e97
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/linux_android.rs
Original file line number Diff line number Diff line change
@@ -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),
};

0 comments on commit db27e97

Please sign in to comment.