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 = "openbsd"),
18 not(target_os = "freebsd"),
19 not(target_os = "netbsd"),
20 not(target_os = "fuchsia"),
21 not(target_os = "redox"),
22 not(target_os = "vxworks")
28 #[cfg(any(target_os = "linux", target_os = "android"))]
29 use crate::sys::weak::syscall;
31 #[cfg(any(target_os = "linux", target_os = "android"))]
32 fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
33 // A weak symbol allows interposition, e.g. for perf measurements that want to
34 // disable randomness for consistency. Otherwise, we'll try a raw syscall.
35 // (`getrandom` was added in glibc 2.25, musl 1.1.20, android API level 28)
38 buffer: *mut libc::c_void,
44 unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_NONBLOCK) }
47 #[cfg(target_os = "espidf")]
48 fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
49 unsafe { libc::getrandom(buf.as_mut_ptr().cast(), buf.len(), 0) }
52 #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "espidf")))]
53 fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool {
57 #[cfg(any(target_os = "linux", target_os = "android", target_os = "espidf"))]
58 fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
59 use crate::sync::atomic::{AtomicBool, Ordering};
60 use crate::sys::os::errno;
62 static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
63 if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) {
68 while read < v.len() {
69 let result = getrandom(&mut v[read..]);
71 let err = errno() as libc::c_int;
72 if err == libc::EINTR {
74 } else if err == libc::ENOSYS || err == libc::EPERM {
75 // Fall back to reading /dev/urandom if `getrandom` is not
76 // supported on the current kernel.
78 // Also fall back in case it is disabled by something like
79 // seccomp or inside of virtual machines.
80 GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
82 } else if err == libc::EAGAIN {
85 panic!("unexpected getrandom error: {}", err);
88 read += result as usize;
94 pub fn fill_bytes(v: &mut [u8]) {
95 // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
96 // meaning it would have blocked because the non-blocking pool (urandom)
97 // has not initialized in the kernel yet due to a lack of entropy. The
98 // fallback we do here is to avoid blocking applications which could
99 // depend on this call without ever knowing they do and don't have a
100 // work around. The PRNG of /dev/urandom will still be used but over a
101 // possibly predictable entropy pool.
102 if getrandom_fill_bytes(v) {
106 // getrandom failed because it is permanently or temporarily (because
107 // of missing entropy) unavailable. Open /dev/urandom, read from it,
108 // and close it again.
109 let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
110 file.read_exact(v).expect("failed to read /dev/urandom")
114 #[cfg(target_os = "macos")]
118 use crate::sys::os::errno;
119 use crate::sys::weak::weak;
120 use libc::{c_int, c_void, size_t};
122 fn getentropy_fill_bytes(v: &mut [u8]) -> bool {
123 weak!(fn getentropy(*mut c_void, size_t) -> c_int);
128 // getentropy(2) permits a maximum buffer size of 256 bytes
129 for s in v.chunks_mut(256) {
130 let ret = unsafe { f(s.as_mut_ptr() as *mut c_void, s.len()) };
132 panic!("unexpected getentropy error: {}", errno());
140 pub fn fill_bytes(v: &mut [u8]) {
141 if getentropy_fill_bytes(v) {
145 // for older macos which doesn't support getentropy
146 let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
147 file.read_exact(v).expect("failed to read /dev/urandom")
151 #[cfg(target_os = "openbsd")]
153 use crate::sys::os::errno;
155 pub fn fill_bytes(v: &mut [u8]) {
156 // getentropy(2) permits a maximum buffer size of 256 bytes
157 for s in v.chunks_mut(256) {
158 let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
160 panic!("unexpected getentropy error: {}", errno());
166 // On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
167 // `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
168 // from `/dev/random` and which runs on its own thread accessed via GCD.
169 // This seems needlessly heavyweight for the purposes of generating two u64s
170 // once per thread in `hashmap_random_keys`. Therefore `SecRandomCopyBytes` is
171 // only used on iOS where direct access to `/dev/urandom` is blocked by the
173 #[cfg(target_os = "ios")]
177 use libc::{c_int, size_t};
181 #[allow(non_upper_case_globals)]
182 const kSecRandomDefault: *const SecRandom = ptr::null();
185 fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
188 pub fn fill_bytes(v: &mut [u8]) {
189 let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
191 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
196 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
200 pub fn fill_bytes(v: &mut [u8]) {
201 let mib = [libc::CTL_KERN, libc::KERN_ARND];
202 // kern.arandom permits a maximum buffer size of 256 bytes
203 for s in v.chunks_mut(256) {
204 let mut s_len = s.len();
208 mib.len() as libc::c_uint,
209 s.as_mut_ptr() as *mut _,
215 if ret == -1 || s_len != s.len() {
217 "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
227 #[cfg(target_os = "fuchsia")]
229 #[link(name = "zircon")]
231 fn zx_cprng_draw(buffer: *mut u8, len: usize);
234 pub fn fill_bytes(v: &mut [u8]) {
235 unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
239 #[cfg(target_os = "redox")]
244 pub fn fill_bytes(v: &mut [u8]) {
245 // Open rand:, read from it, and close it again.
246 let mut file = File::open("rand:").expect("failed to open rand:");
247 file.read_exact(v).expect("failed to read rand:")
251 #[cfg(target_os = "vxworks")]
254 use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
256 pub fn fill_bytes(v: &mut [u8]) {
257 static RNG_INIT: AtomicBool = AtomicBool::new(false);
258 while !RNG_INIT.load(Relaxed) {
259 let ret = unsafe { libc::randSecure() };
261 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
263 RNG_INIT.store(true, Relaxed);
266 unsafe { libc::usleep(10) };
269 libc::randABytes(v.as_mut_ptr() as *mut libc::c_uchar, v.len() as libc::c_int)
272 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());