4 pub fn hashmap_random_keys() -> (u64, u64) {
7 let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v));
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(target_os = "macos")]
144 use crate::sys::os::errno;
145 use crate::sys::weak::weak;
146 use libc::{c_int, c_void, size_t};
148 fn getentropy_fill_bytes(v: &mut [u8]) -> bool {
149 weak!(fn getentropy(*mut c_void, size_t) -> c_int);
154 // getentropy(2) permits a maximum buffer size of 256 bytes
155 for s in v.chunks_mut(256) {
156 let ret = unsafe { f(s.as_mut_ptr() as *mut c_void, s.len()) };
158 panic!("unexpected getentropy error: {}", errno());
166 pub fn fill_bytes(v: &mut [u8]) {
167 if getentropy_fill_bytes(v) {
171 // for older macos which doesn't support getentropy
172 let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
173 file.read_exact(v).expect("failed to read /dev/urandom")
177 #[cfg(target_os = "openbsd")]
179 use crate::sys::os::errno;
181 pub fn fill_bytes(v: &mut [u8]) {
182 // getentropy(2) permits a maximum buffer size of 256 bytes
183 for s in v.chunks_mut(256) {
184 let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
186 panic!("unexpected getentropy error: {}", errno());
192 // On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
193 // `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
194 // from `/dev/random` and which runs on its own thread accessed via GCD.
195 // This seems needlessly heavyweight for the purposes of generating two u64s
196 // once per thread in `hashmap_random_keys`. Therefore `SecRandomCopyBytes` is
197 // only used on iOS where direct access to `/dev/urandom` is blocked by the
199 #[cfg(any(target_os = "ios", target_os = "watchos"))]
203 use libc::{c_int, size_t};
207 #[allow(non_upper_case_globals)]
208 const kSecRandomDefault: *const SecRandom = ptr::null();
211 fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
214 pub fn fill_bytes(v: &mut [u8]) {
215 let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
217 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
222 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
226 pub fn fill_bytes(v: &mut [u8]) {
227 let mib = [libc::CTL_KERN, libc::KERN_ARND];
228 // kern.arandom permits a maximum buffer size of 256 bytes
229 for s in v.chunks_mut(256) {
230 let mut s_len = s.len();
234 mib.len() as libc::c_uint,
235 s.as_mut_ptr() as *mut _,
241 if ret == -1 || s_len != s.len() {
243 "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
253 #[cfg(target_os = "fuchsia")]
255 #[link(name = "zircon")]
257 fn zx_cprng_draw(buffer: *mut u8, len: usize);
260 pub fn fill_bytes(v: &mut [u8]) {
261 unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
265 #[cfg(target_os = "redox")]
270 pub fn fill_bytes(v: &mut [u8]) {
271 // Open rand:, read from it, and close it again.
272 let mut file = File::open("rand:").expect("failed to open rand:");
273 file.read_exact(v).expect("failed to read rand:")
277 #[cfg(target_os = "vxworks")]
280 use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
282 pub fn fill_bytes(v: &mut [u8]) {
283 static RNG_INIT: AtomicBool = AtomicBool::new(false);
284 while !RNG_INIT.load(Relaxed) {
285 let ret = unsafe { libc::randSecure() };
287 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
289 RNG_INIT.store(true, Relaxed);
292 unsafe { libc::usleep(10) };
295 libc::randABytes(v.as_mut_ptr() as *mut libc::c_uchar, v.len() as libc::c_int)
298 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());