1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 pub fn hashmap_random_keys() -> (u64, u64) {
17 let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8,
18 mem::size_of_val(&v));
19 imp::fill_bytes(view);
25 not(target_os = "ios"),
26 not(target_os = "openbsd"),
27 not(target_os = "freebsd"),
28 not(target_os = "fuchsia")))]
33 use sync::atomic::{AtomicBool, AtomicI32, Ordering};
36 static GETRANDOM_URANDOM_FD: AtomicI32 = AtomicI32::new(-1);
37 #[cfg(any(target_os = "linux", target_os = "android"))]
38 static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
40 #[cfg(any(target_os = "linux", target_os = "android"))]
41 fn is_getrandom_permanently_unavailable() -> bool {
42 GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed)
45 #[cfg(not(any(target_os = "linux", target_os = "android")))]
46 fn is_getrandom_permanently_unavailable() -> bool {
50 #[cfg(any(target_os = "linux", target_os = "android"))]
51 fn getrandom(buf: &mut [u8]) -> libc::c_long {
53 libc::syscall(libc::SYS_getrandom, buf.as_mut_ptr(), buf.len(), libc::GRND_NONBLOCK)
57 #[cfg(not(any(target_os = "linux", target_os = "android")))]
58 fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool { false }
60 #[cfg(any(target_os = "linux", target_os = "android"))]
61 fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
62 if is_getrandom_permanently_unavailable() {
67 while read < v.len() {
68 let result = getrandom(&mut v[read..]);
70 let err = errno() as libc::c_int;
71 if err == libc::EINTR {
73 } else if err == libc::ENOSYS {
74 GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
75 } else if err == libc::EAGAIN {
78 panic!("unexpected getrandom error: {}", err);
81 read += result as usize;
87 pub fn fill_bytes(v: &mut [u8]) {
88 // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
89 // meaning it would have blocked because the non-blocking pool (urandom)
90 // has not initialized in the kernel yet due to a lack of entropy. The
91 // fallback we do here is to avoid blocking applications which could
92 // depend on this call without ever knowing they do and don't have a
93 // work around. The PRNG of /dev/urandom will still be used but over a
94 // possibly predictable entropy pool.
95 if getrandom_fill_bytes(v) {
99 // getrandom failed for some reason. If the getrandom call is
100 // permanently unavailable (OS without getrandom, or OS version without
101 // getrandom), we'll keep around the fd for /dev/urandom for future
102 // requests, to avoid re-opening the file on every call.
104 // Otherwise, open /dev/urandom, read from it, and close it again.
105 use super::super::ext::io::{FromRawFd, IntoRawFd};
106 let mut fd = GETRANDOM_URANDOM_FD.load(Ordering::Relaxed);
107 let mut close_fd = false;
109 if !is_getrandom_permanently_unavailable() {
112 let file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
113 fd = file.into_raw_fd();
114 // If some other thread also opened /dev/urandom and set the global
115 // fd already, we close our fd at the end of the function.
116 if !close_fd && GETRANDOM_URANDOM_FD.compare_and_swap(-1, fd, Ordering::Relaxed) != -1 {
120 let mut file = unsafe { File::from_raw_fd(fd) };
121 let res = file.read_exact(v);
123 let _ = file.into_raw_fd();
125 res.expect("failed to read /dev/urandom");
129 #[cfg(target_os = "openbsd")]
134 pub fn fill_bytes(v: &mut [u8]) {
135 // getentropy(2) permits a maximum buffer size of 256 bytes
136 for s in v.chunks_mut(256) {
138 libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
141 panic!("unexpected getentropy error: {}", errno());
147 #[cfg(target_os = "ios")]
150 use libc::{c_int, size_t};
155 #[allow(non_upper_case_globals)]
156 const kSecRandomDefault: *const SecRandom = ptr::null();
159 fn SecRandomCopyBytes(rnd: *const SecRandom,
161 bytes: *mut u8) -> c_int;
164 pub fn fill_bytes(v: &mut [u8]) {
166 SecRandomCopyBytes(kSecRandomDefault,
171 panic!("couldn't generate random bytes: {}",
172 io::Error::last_os_error());
177 #[cfg(target_os = "freebsd")]
182 pub fn fill_bytes(v: &mut [u8]) {
183 let mib = [libc::CTL_KERN, libc::KERN_ARND];
184 // kern.arandom permits a maximum buffer size of 256 bytes
185 for s in v.chunks_mut(256) {
186 let mut s_len = s.len();
188 libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
189 s.as_mut_ptr() as *mut _, &mut s_len,
192 if ret == -1 || s_len != s.len() {
193 panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
194 ret, s.len(), s_len);
200 #[cfg(target_os = "fuchsia")]
202 #[link(name = "zircon")]
204 fn zx_cprng_draw(buffer: *mut u8, len: usize);
207 pub fn fill_bytes(v: &mut [u8]) {
208 unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }