1use crate::{
3 util_libc::{open_readonly, sys_fill_exact},
4 Error,
5};
6use core::{
7 cell::UnsafeCell,
8 mem::MaybeUninit,
9 sync::atomic::{AtomicUsize, Ordering::Relaxed},
10};
11
12const FILE_PATH: &str = "/dev/urandom\0";
19const FD_UNINIT: usize = usize::max_value();
20
21pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
22 let fd = get_rng_fd()?;
23 sys_fill_exact(dest, |buf| unsafe {
24 libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len())
25 })
26}
27
28fn get_rng_fd() -> Result<libc::c_int, Error> {
32 static FD: AtomicUsize = AtomicUsize::new(FD_UNINIT);
33 fn get_fd() -> Option<libc::c_int> {
34 match FD.load(Relaxed) {
35 FD_UNINIT => None,
36 val => Some(val as libc::c_int),
37 }
38 }
39
40 if let Some(fd) = get_fd() {
42 return Ok(fd);
43 }
44
45 static MUTEX: Mutex = Mutex::new();
48 unsafe { MUTEX.lock() };
49 let _guard = DropGuard(|| unsafe { MUTEX.unlock() });
50
51 if let Some(fd) = get_fd() {
52 return Ok(fd);
53 }
54
55 #[cfg(any(target_os = "android", target_os = "linux"))]
57 wait_until_rng_ready()?;
58
59 let fd = unsafe { open_readonly(FILE_PATH)? };
60 debug_assert!(fd >= 0 && (fd as usize) < FD_UNINIT);
62 FD.store(fd as usize, Relaxed);
63
64 Ok(fd)
65}
66
67#[cfg(any(target_os = "android", target_os = "linux"))]
69fn wait_until_rng_ready() -> Result<(), Error> {
70 let fd = unsafe { open_readonly("/dev/random\0")? };
72 let mut pfd = libc::pollfd {
73 fd,
74 events: libc::POLLIN,
75 revents: 0,
76 };
77 let _guard = DropGuard(|| unsafe {
78 libc::close(fd);
79 });
80
81 loop {
82 let res = unsafe { libc::poll(&mut pfd, 1, -1) };
84 if res >= 0 {
85 debug_assert_eq!(res, 1); return Ok(());
87 }
88 let err = crate::util_libc::last_os_error();
89 match err.raw_os_error() {
90 Some(libc::EINTR) | Some(libc::EAGAIN) => continue,
91 _ => return Err(err),
92 }
93 }
94}
95
96struct Mutex(UnsafeCell<libc::pthread_mutex_t>);
97
98impl Mutex {
99 const fn new() -> Self {
100 Self(UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER))
101 }
102 unsafe fn lock(&self) {
103 let r = libc::pthread_mutex_lock(self.0.get());
104 debug_assert_eq!(r, 0);
105 }
106 unsafe fn unlock(&self) {
107 let r = libc::pthread_mutex_unlock(self.0.get());
108 debug_assert_eq!(r, 0);
109 }
110}
111
112unsafe impl Sync for Mutex {}
113
114struct DropGuard<F: FnMut()>(F);
115
116impl<F: FnMut()> Drop for DropGuard<F> {
117 fn drop(&mut self) {
118 self.0()
119 }
120}