1 pub fn hashmap_random_keys() -> (u64, u64) {
2 const KEY_LEN: usize = core::mem::size_of::<u64>();
4 let mut v = [0u8; KEY_LEN * 2];
5 imp::fill_bytes(&mut v);
7 let key1 = v[0..KEY_LEN].try_into().unwrap();
8 let key2 = v[KEY_LEN..].try_into().unwrap();
10 (u64::from_ne_bytes(key1), u64::from_ne_bytes(key2))
15 not(target_os = "macos"),
16 not(target_os = "ios"),
17 not(target_os = "watchos"),
18 not(target_os = "openbsd"),
19 not(target_os = "freebsd"),
20 not(target_os = "netbsd"),
21 not(target_os = "fuchsia"),
22 not(target_os = "redox"),
23 not(target_os = "vxworks")
29 #[cfg(any(target_os = "linux", target_os = "android"))]
30 use crate::sys::weak::syscall;
32 #[cfg(any(target_os = "linux", target_os = "android"))]
33 fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
34 use crate::sync::atomic::{AtomicBool, Ordering};
35 use crate::sys::os::errno;
37 // A weak symbol allows interposition, e.g. for perf measurements that want to
38 // disable randomness for consistency. Otherwise, we'll try a raw syscall.
39 // (`getrandom` was added in glibc 2.25, musl 1.1.20, android API level 28)
42 buffer: *mut libc::c_void,
48 // This provides the best quality random numbers available at the given moment
49 // without ever blocking, and is preferable to falling back to /dev/urandom.
50 static GRND_INSECURE_AVAILABLE: AtomicBool = AtomicBool::new(true);
51 if GRND_INSECURE_AVAILABLE.load(Ordering::Relaxed) {
52 let ret = unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_INSECURE) };
53 if ret == -1 && errno() as libc::c_int == libc::EINVAL {
54 GRND_INSECURE_AVAILABLE.store(false, Ordering::Relaxed);
60 unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_NONBLOCK) }
63 #[cfg(any(target_os = "espidf", target_os = "horizon"))]
64 fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
65 unsafe { libc::getrandom(buf.as_mut_ptr().cast(), buf.len(), 0) }
70 target_os = "android",
74 fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool {
80 target_os = "android",
84 fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
85 use crate::sync::atomic::{AtomicBool, Ordering};
86 use crate::sys::os::errno;
88 static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
89 if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) {
94 while read < v.len() {
95 let result = getrandom(&mut v[read..]);
97 let err = errno() as libc::c_int;
98 if err == libc::EINTR {
100 } else if err == libc::ENOSYS || err == libc::EPERM {
101 // Fall back to reading /dev/urandom if `getrandom` is not
102 // supported on the current kernel.
104 // Also fall back in case it is disabled by something like
105 // seccomp or inside of virtual machines.
106 GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
108 } else if err == libc::EAGAIN {
111 panic!("unexpected getrandom error: {err}");
114 read += result as usize;
120 pub fn fill_bytes(v: &mut [u8]) {
121 // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
122 // meaning it would have blocked because the non-blocking pool (urandom)
123 // has not initialized in the kernel yet due to a lack of entropy. The
124 // fallback we do here is to avoid blocking applications which could
125 // depend on this call without ever knowing they do and don't have a
126 // work around. The PRNG of /dev/urandom will still be used but over a
127 // possibly predictable entropy pool.
128 if getrandom_fill_bytes(v) {
132 // getrandom failed because it is permanently or temporarily (because
133 // of missing entropy) unavailable. Open /dev/urandom, read from it,
134 // and close it again.
135 let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
136 file.read_exact(v).expect("failed to read /dev/urandom")
140 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
143 use crate::sys::weak::weak;
144 use libc::{c_int, c_void, size_t};
146 fn getentropy_fill_bytes(v: &mut [u8]) -> bool {
147 weak!(fn getentropy(*mut c_void, size_t) -> c_int);
152 // getentropy(2) permits a maximum buffer size of 256 bytes
153 for s in v.chunks_mut(256) {
154 let ret = unsafe { f(s.as_mut_ptr() as *mut c_void, s.len()) };
156 panic!("unexpected getentropy error: {}", io::Error::last_os_error());
164 #[cfg(target_os = "macos")]
165 fn fallback_fill_bytes(v: &mut [u8]) {
169 let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
170 file.read_exact(v).expect("failed to read /dev/urandom")
173 // On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
174 // `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
175 // from `/dev/random` and which runs on its own thread accessed via GCD.
177 // This is very heavyweight compared to the alternatives, but they may not be usable:
178 // - `getentropy` was added in iOS 10, but we support a minimum of iOS 7
179 // - `/dev/urandom` is not accessible inside the iOS app sandbox.
181 // Therefore `SecRandomCopyBytes` is only used on older iOS versions where no
182 // better options are present.
183 #[cfg(target_os = "ios")]
184 fn fallback_fill_bytes(v: &mut [u8]) {
189 #[allow(non_upper_case_globals)]
190 const kSecRandomDefault: *const SecRandom = ptr::null();
193 fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
196 let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
198 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
202 // All supported versions of watchOS (>= 5) have support for `getentropy`.
203 #[cfg(target_os = "watchos")]
205 fn fallback_fill_bytes(_: &mut [u8]) {
209 pub fn fill_bytes(v: &mut [u8]) {
210 if getentropy_fill_bytes(v) {
214 // Older macOS versions (< 10.12) don't support `getentropy`. Fallback to
215 // reading from `/dev/urandom` on these systems.
217 // Older iOS versions (< 10) don't support it either. Fallback to
218 // `SecRandomCopyBytes` on these systems. On watchOS, this is unreachable
219 // because the minimum supported version is 5 while `getentropy` became accessible
221 fallback_fill_bytes(v)
225 #[cfg(target_os = "openbsd")]
227 use crate::sys::os::errno;
229 pub fn fill_bytes(v: &mut [u8]) {
230 // getentropy(2) permits a maximum buffer size of 256 bytes
231 for s in v.chunks_mut(256) {
232 let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
234 panic!("unexpected getentropy error: {}", errno());
240 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
244 pub fn fill_bytes(v: &mut [u8]) {
245 let mib = [libc::CTL_KERN, libc::KERN_ARND];
246 // kern.arandom permits a maximum buffer size of 256 bytes
247 for s in v.chunks_mut(256) {
248 let mut s_len = s.len();
252 mib.len() as libc::c_uint,
253 s.as_mut_ptr() as *mut _,
259 if ret == -1 || s_len != s.len() {
261 "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
271 #[cfg(target_os = "fuchsia")]
273 #[link(name = "zircon")]
275 fn zx_cprng_draw(buffer: *mut u8, len: usize);
278 pub fn fill_bytes(v: &mut [u8]) {
279 unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
283 #[cfg(target_os = "redox")]
288 pub fn fill_bytes(v: &mut [u8]) {
289 // Open rand:, read from it, and close it again.
290 let mut file = File::open("rand:").expect("failed to open rand:");
291 file.read_exact(v).expect("failed to read rand:")
295 #[cfg(target_os = "vxworks")]
298 use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
300 pub fn fill_bytes(v: &mut [u8]) {
301 static RNG_INIT: AtomicBool = AtomicBool::new(false);
302 while !RNG_INIT.load(Relaxed) {
303 let ret = unsafe { libc::randSecure() };
305 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
307 RNG_INIT.store(true, Relaxed);
310 unsafe { libc::usleep(10) };
313 libc::randABytes(v.as_mut_ptr() as *mut libc::c_uchar, v.len() as libc::c_int)
316 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());