Skip to content

Commit db27e97

Browse files
josephlrnewpavlov
authored andcommitted
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.
1 parent 0a18857 commit db27e97

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/linux_android.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ use core::cell::RefCell;
1616
use core::num::NonZeroU32;
1717
use core::sync::atomic::{AtomicBool, Ordering};
1818

19+
// This flag tells getrandom() to return EAGAIN instead of blocking.
20+
const GRND_NONBLOCK: libc::c_uint = 0x0001;
1921
static RNG_INIT: AtomicBool = AtomicBool::new(false);
2022

2123
enum RngSource {
@@ -27,9 +29,10 @@ thread_local!(
2729
static RNG_SOURCE: RefCell<Option<RngSource>> = RefCell::new(None);
2830
);
2931

30-
fn syscall_getrandom(dest: &mut [u8]) -> Result<(), io::Error> {
32+
fn syscall_getrandom(dest: &mut [u8], block: bool) -> Result<(), io::Error> {
33+
let flags = if block { 0 } else { GRND_NONBLOCK };
3134
let ret = unsafe {
32-
libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), 0)
35+
libc::syscall(libc::SYS_getrandom, dest.as_mut_ptr(), dest.len(), flags)
3336
};
3437
if ret < 0 || (ret as usize) != dest.len() {
3538
error!("Linux getrandom syscall failed with return value {}", ret);
@@ -56,7 +59,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
5659
Ok(s)
5760
}, |f| {
5861
match f {
59-
RngSource::GetRandom => syscall_getrandom(dest),
62+
RngSource::GetRandom => syscall_getrandom(dest, true),
6063
RngSource::Device(f) => f.read_exact(dest),
6164
}.map_err(From::from)
6265
})
@@ -71,7 +74,7 @@ fn is_getrandom_available() -> bool {
7174

7275
CHECKER.call_once(|| {
7376
let mut buf: [u8; 0] = [];
74-
let available = match syscall_getrandom(&mut buf) {
77+
let available = match syscall_getrandom(&mut buf, false) {
7578
Ok(()) => true,
7679
Err(err) => err.raw_os_error() != Some(libc::ENOSYS),
7780
};

0 commit comments

Comments
 (0)