1 //! Implementation for Linux / Android with `/dev/urandom` fallback
2 use crate::{
3     lazy::LazyBool,
4     util_libc::{getrandom_syscall, last_os_error, sys_fill_exact},
5     {use_file, Error},
6 };
7 use core::mem::MaybeUninit;
8 
getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>9 pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
10     // getrandom(2) was introduced in Linux 3.17
11     static HAS_GETRANDOM: LazyBool = LazyBool::new();
12     if HAS_GETRANDOM.unsync_init(is_getrandom_available) {
13         sys_fill_exact(dest, getrandom_syscall)
14     } else {
15         use_file::getrandom_inner(dest)
16     }
17 }
18 
is_getrandom_available() -> bool19 fn is_getrandom_available() -> bool {
20     if getrandom_syscall(&mut []) < 0 {
21         match last_os_error().raw_os_error() {
22             Some(libc::ENOSYS) => false, // No kernel support
23             // The fallback on EPERM is intentionally not done on Android since this workaround
24             // seems to be needed only for specific Linux-based products that aren't based
25             // on Android. See https://github.com/rust-random/getrandom/issues/229.
26             #[cfg(target_os = "linux")]
27             Some(libc::EPERM) => false, // Blocked by seccomp
28             _ => true,
29         }
30     } else {
31         true
32     }
33 }
34