1pub fn hashmap_random_keys() -> (u64, u64) {
2 const KEY_LEN: usize = core::mem::size_of::<u64>();
3
4 let mut v: [u8; 16] = [0u8; KEY_LEN * 2];
5 imp::fill_bytes(&mut v);
6
7 let key1: [u8; 8] = v[0..KEY_LEN].try_into().unwrap();
8 let key2: [u8; 8] = v[KEY_LEN..].try_into().unwrap();
9
10 (u64::from_ne_bytes(key1), u64::from_ne_bytes(key2))
11}
12
13#[cfg(all(
14 unix,
15 not(target_os = "macos"),
16 not(target_os = "ios"),
17 not(target_os = "tvos"),
18 not(target_os = "watchos"),
19 not(target_os = "openbsd"),
20 not(target_os = "netbsd"),
21 not(target_os = "fuchsia"),
22 not(target_os = "redox"),
23 not(target_os = "vxworks"),
24 not(target_os = "emscripten"),
25 not(target_os = "vita"),
26))]
27mod imp {
28 use crate::fs::File;
29 use crate::io::Read;
30
31 #[cfg(any(target_os = "linux", target_os = "android"))]
32 use crate::sys::weak::syscall;
33
34 #[cfg(any(target_os = "linux", target_os = "android"))]
35 fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
36 use crate::sync::atomic::{AtomicBool, Ordering};
37 use crate::sys::os::errno;
38
39 // A weak symbol allows interposition, e.g. for perf measurements that want to
40 // disable randomness for consistency. Otherwise, we'll try a raw syscall.
41 // (`getrandom` was added in glibc 2.25, musl 1.1.20, android API level 28)
42 syscall! {
43 fn getrandom(
44 buffer: *mut libc::c_void,
45 length: libc::size_t,
46 flags: libc::c_uint
47 ) -> libc::ssize_t
48 }
49
50 // This provides the best quality random numbers available at the given moment
51 // without ever blocking, and is preferable to falling back to /dev/urandom.
52 static GRND_INSECURE_AVAILABLE: AtomicBool = AtomicBool::new(true);
53 if GRND_INSECURE_AVAILABLE.load(Ordering::Relaxed) {
54 let ret = unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_INSECURE) };
55 if ret == -1 && errno() as libc::c_int == libc::EINVAL {
56 GRND_INSECURE_AVAILABLE.store(false, Ordering::Relaxed);
57 } else {
58 return ret;
59 }
60 }
61
62 unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_NONBLOCK) }
63 }
64
65 #[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "freebsd"))]
66 fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
67 unsafe { libc::getrandom(buf.as_mut_ptr().cast(), buf.len(), 0) }
68 }
69
70 #[cfg(not(any(
71 target_os = "linux",
72 target_os = "android",
73 target_os = "espidf",
74 target_os = "horizon",
75 target_os = "freebsd"
76 )))]
77 fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool {
78 false
79 }
80
81 #[cfg(any(
82 target_os = "linux",
83 target_os = "android",
84 target_os = "espidf",
85 target_os = "horizon",
86 target_os = "freebsd"
87 ))]
88 fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
89 use crate::sync::atomic::{AtomicBool, Ordering};
90 use crate::sys::os::errno;
91
92 static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
93 if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) {
94 return false;
95 }
96
97 let mut read = 0;
98 while read < v.len() {
99 let result = getrandom(&mut v[read..]);
100 if result == -1 {
101 let err = errno() as libc::c_int;
102 if err == libc::EINTR {
103 continue;
104 } else if err == libc::ENOSYS || err == libc::EPERM {
105 // Fall back to reading /dev/urandom if `getrandom` is not
106 // supported on the current kernel.
107 //
108 // Also fall back in case it is disabled by something like
109 // seccomp or inside of docker.
110 //
111 // If the `getrandom` syscall is not implemented in the current kernel version it should return an
112 // `ENOSYS` error. Docker also blocks the whole syscall inside unprivileged containers, and
113 // returns `EPERM` (instead of `ENOSYS`) when a program tries to invoke the syscall. Because of
114 // that we need to check for *both* `ENOSYS` and `EPERM`.
115 //
116 // Note that Docker's behavior is breaking other projects (notably glibc), so they're planning
117 // to update their filtering to return `ENOSYS` in a future release:
118 //
119 // https://github.com/moby/moby/issues/42680
120 //
121 GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
122 return false;
123 } else if err == libc::EAGAIN {
124 return false;
125 } else {
126 panic!("unexpected getrandom error: {err}");
127 }
128 } else {
129 read += result as usize;
130 }
131 }
132 true
133 }
134
135 pub fn fill_bytes(v: &mut [u8]) {
136 // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
137 // meaning it would have blocked because the non-blocking pool (urandom)
138 // has not initialized in the kernel yet due to a lack of entropy. The
139 // fallback we do here is to avoid blocking applications which could
140 // depend on this call without ever knowing they do and don't have a
141 // work around. The PRNG of /dev/urandom will still be used but over a
142 // possibly predictable entropy pool.
143 if getrandom_fill_bytes(v) {
144 return;
145 }
146
147 // getrandom failed because it is permanently or temporarily (because
148 // of missing entropy) unavailable. Open /dev/urandom, read from it,
149 // and close it again.
150 let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
151 file.read_exact(v).expect("failed to read /dev/urandom")
152 }
153}
154
155#[cfg(target_vendor = "apple")]
156mod imp {
157 use crate::io;
158 use libc::{c_int, c_void, size_t};
159
160 #[inline(always)]
161 fn random_failure() -> ! {
162 panic!("unexpected random generation error: {}", io::Error::last_os_error());
163 }
164
165 #[cfg(target_os = "macos")]
166 fn getentropy_fill_bytes(v: &mut [u8]) {
167 extern "C" {
168 fn getentropy(bytes: *mut c_void, count: size_t) -> c_int;
169 }
170
171 // getentropy(2) permits a maximum buffer size of 256 bytes
172 for s in v.chunks_mut(256) {
173 let ret = unsafe { getentropy(s.as_mut_ptr().cast(), s.len()) };
174 if ret == -1 {
175 random_failure()
176 }
177 }
178 }
179
180 #[cfg(not(target_os = "macos"))]
181 fn ccrandom_fill_bytes(v: &mut [u8]) {
182 extern "C" {
183 fn CCRandomGenerateBytes(bytes: *mut c_void, count: size_t) -> c_int;
184 }
185
186 let ret = unsafe { CCRandomGenerateBytes(v.as_mut_ptr().cast(), v.len()) };
187 if ret == -1 {
188 random_failure()
189 }
190 }
191
192 pub fn fill_bytes(v: &mut [u8]) {
193 // All supported versions of macOS (10.12+) support getentropy.
194 //
195 // `getentropy` is measurably faster (via Divan) then the other alternatives so its preferred
196 // when usable.
197 #[cfg(target_os = "macos")]
198 getentropy_fill_bytes(v);
199
200 // On Apple platforms, `CCRandomGenerateBytes` and `SecRandomCopyBytes` simply
201 // call into `CCRandomCopyBytes` with `kCCRandomDefault`. `CCRandomCopyBytes`
202 // manages a CSPRNG which is seeded from the kernel's CSPRNG and which runs on
203 // its own thread accessed via GCD. This seems needlessly heavyweight for our purposes
204 // so we only use it on non-Mac OSes where the better entrypoints are blocked.
205 //
206 // `CCRandomGenerateBytes` is used instead of `SecRandomCopyBytes` because the former is accessible
207 // via `libSystem` (libc) while the other needs to link to `Security.framework`.
208 //
209 // Note that while `getentropy` has a available attribute in the macOS headers, the lack
210 // of a header in the iOS (and others) SDK means that its can cause app store rejections.
211 // Just use `CCRandomGenerateBytes` instead.
212 #[cfg(not(target_os = "macos"))]
213 ccrandom_fill_bytes(v);
214 }
215}
216
217#[cfg(any(target_os = "openbsd", target_os = "emscripten", target_os = "vita"))]
218mod imp {
219 use crate::sys::os::errno;
220
221 pub fn fill_bytes(v: &mut [u8]) {
222 // getentropy(2) permits a maximum buffer size of 256 bytes
223 for s in v.chunks_mut(256) {
224 let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
225 if ret == -1 {
226 panic!("unexpected getentropy error: {}", errno());
227 }
228 }
229 }
230}
231
232// FIXME: once the 10.x release becomes the minimum, this can be dropped for simplification.
233#[cfg(target_os = "netbsd")]
234mod imp {
235 use crate::ptr;
236
237 pub fn fill_bytes(v: &mut [u8]) {
238 let mib = [libc::CTL_KERN, libc::KERN_ARND];
239 // kern.arandom permits a maximum buffer size of 256 bytes
240 for s in v.chunks_mut(256) {
241 let mut s_len = s.len();
242 let ret = unsafe {
243 libc::sysctl(
244 mib.as_ptr(),
245 mib.len() as libc::c_uint,
246 s.as_mut_ptr() as *mut _,
247 &mut s_len,
248 ptr::null(),
249 0,
250 )
251 };
252 if ret == -1 || s_len != s.len() {
253 panic!(
254 "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
255 ret,
256 s.len(),
257 s_len
258 );
259 }
260 }
261 }
262}
263
264#[cfg(target_os = "fuchsia")]
265mod imp {
266 #[link(name = "zircon")]
267 extern "C" {
268 fn zx_cprng_draw(buffer: *mut u8, len: usize);
269 }
270
271 pub fn fill_bytes(v: &mut [u8]) {
272 unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
273 }
274}
275
276#[cfg(target_os = "redox")]
277mod imp {
278 use crate::fs::File;
279 use crate::io::Read;
280
281 pub fn fill_bytes(v: &mut [u8]) {
282 // Open rand:, read from it, and close it again.
283 let mut file = File::open("rand:").expect("failed to open rand:");
284 file.read_exact(v).expect("failed to read rand:")
285 }
286}
287
288#[cfg(target_os = "vxworks")]
289mod imp {
290 use crate::io;
291 use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
292
293 pub fn fill_bytes(v: &mut [u8]) {
294 static RNG_INIT: AtomicBool = AtomicBool::new(false);
295 while !RNG_INIT.load(Relaxed) {
296 let ret = unsafe { libc::randSecure() };
297 if ret < 0 {
298 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
299 } else if ret > 0 {
300 RNG_INIT.store(true, Relaxed);
301 break;
302 }
303 unsafe { libc::usleep(10) };
304 }
305 let ret = unsafe {
306 libc::randABytes(v.as_mut_ptr() as *mut libc::c_uchar, v.len() as libc::c_int)
307 };
308 if ret < 0 {
309 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
310 }
311 }
312}
313