Auto merge of #116319 - BlackHoleFox:apple-rand-take-2, r=thomcc

Remove Apple RNG fallbacks and simplify implementation

Now that we have [higher Apple platform requirements](https://github.com/rust-lang/rust/pull/104385), the RNG code can be simplified a lot. Since `getentropy` still doesn't look to be usable outside macOS this implementation:
- Removes any macOS fallback paths and unconditionally links to `getentropy`
- Minimizes the implementation for everything else (iOS, watchOS, etc).

`CCRandomGenerateBytes` was added in iOS 8 which means that we can use it now. It and `SecRandomCopyBytes` have the exact same functionality, but the former has a simpler API and no longer requires libstd to link to `Security.framework` for one function. Its also available in all the other target's SDKs.

Why care about `getentropy` then though on macOS? Well, its still much more performant. Benchmarking shows it runs at ~2x the speed of `CCRandomGenerateBytes`, which makes sense since it directly pulls from the kernel vs going through its own generator etc.

Semi-related to a previous, but reverted, attempt at improving this logic in https://github.com/rust-lang/rust/pull/101011
This commit is contained in:
bors 2023-10-24 06:11:51 +00:00
commit 6eb3e97d55
2 changed files with 51 additions and 57 deletions

View File

@ -415,7 +415,6 @@ pub fn abort_internal() -> ! {
} else if #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "watchos"))] { } else if #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "watchos"))] {
#[link(name = "System")] #[link(name = "System")]
#[link(name = "objc")] #[link(name = "objc")]
#[link(name = "Security", kind = "framework")]
#[link(name = "Foundation", kind = "framework")] #[link(name = "Foundation", kind = "framework")]
extern "C" {} extern "C" {}
} else if #[cfg(target_os = "fuchsia")] { } else if #[cfg(target_os = "fuchsia")] {

View File

@ -151,40 +151,65 @@ pub fn fill_bytes(v: &mut [u8]) {
} }
} }
#[cfg(target_os = "macos")] #[cfg(target_vendor = "apple")]
mod imp { mod imp {
use crate::fs::File; use crate::io;
use crate::io::Read;
use crate::sys::os::errno;
use crate::sys::weak::weak;
use libc::{c_int, c_void, size_t}; use libc::{c_int, c_void, size_t};
fn getentropy_fill_bytes(v: &mut [u8]) -> bool { #[inline(always)]
weak!(fn getentropy(*mut c_void, size_t) -> c_int); fn random_failure() -> ! {
panic!("unexpected random generation error: {}", io::Error::last_os_error());
}
getentropy #[cfg(target_os = "macos")]
.get() fn getentropy_fill_bytes(v: &mut [u8]) {
.map(|f| { extern "C" {
// getentropy(2) permits a maximum buffer size of 256 bytes fn getentropy(bytes: *mut c_void, count: size_t) -> c_int;
for s in v.chunks_mut(256) { }
let ret = unsafe { f(s.as_mut_ptr() as *mut c_void, s.len()) };
if ret == -1 { // getentropy(2) permits a maximum buffer size of 256 bytes
panic!("unexpected getentropy error: {}", errno()); for s in v.chunks_mut(256) {
} let ret = unsafe { getentropy(s.as_mut_ptr().cast(), s.len()) };
} if ret == -1 {
true random_failure()
}) }
.unwrap_or(false) }
}
#[cfg(not(target_os = "macos"))]
fn ccrandom_fill_bytes(v: &mut [u8]) {
extern "C" {
fn CCRandomGenerateBytes(bytes: *mut c_void, count: size_t) -> c_int;
}
let ret = unsafe { CCRandomGenerateBytes(v.as_mut_ptr().cast(), v.len()) };
if ret == -1 {
random_failure()
}
} }
pub fn fill_bytes(v: &mut [u8]) { pub fn fill_bytes(v: &mut [u8]) {
if getentropy_fill_bytes(v) { // All supported versions of macOS (10.12+) support getentropy.
return; //
} // `getentropy` is measurably faster (via Divan) then the other alternatives so its preferred
// when usable.
#[cfg(target_os = "macos")]
getentropy_fill_bytes(v);
// for older macos which doesn't support getentropy // On Apple platforms, `CCRandomGenerateBytes` and `SecRandomCopyBytes` simply
let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom"); // call into `CCRandomCopyBytes` with `kCCRandomDefault`. `CCRandomCopyBytes`
file.read_exact(v).expect("failed to read /dev/urandom") // manages a CSPRNG which is seeded from the kernel's CSPRNG and which runs on
// its own thread accessed via GCD. This seems needlessly heavyweight for our purposes
// so we only use it on non-Mac OSes where the better entrypoints are blocked.
//
// `CCRandomGenerateBytes` is used instead of `SecRandomCopyBytes` because the former is accessible
// via `libSystem` (libc) while the other needs to link to `Security.framework`.
//
// Note that while `getentropy` has a available attribute in the macOS headers, the lack
// of a header in the iOS (and others) SDK means that its can cause app store rejections.
// Just use `CCRandomGenerateBytes` instead.
#[cfg(not(target_os = "macos"))]
ccrandom_fill_bytes(v);
} }
} }
@ -203,36 +228,6 @@ pub fn fill_bytes(v: &mut [u8]) {
} }
} }
// On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
// `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
// from `/dev/random` and which runs on its own thread accessed via GCD.
// This seems needlessly heavyweight for the purposes of generating two u64s
// once per thread in `hashmap_random_keys`. Therefore `SecRandomCopyBytes` is
// only used on iOS where direct access to `/dev/urandom` is blocked by the
// sandbox.
#[cfg(any(target_os = "ios", target_os = "tvos", target_os = "watchos"))]
mod imp {
use crate::io;
use crate::ptr;
use libc::{c_int, size_t};
enum SecRandom {}
#[allow(non_upper_case_globals)]
const kSecRandomDefault: *const SecRandom = ptr::null();
extern "C" {
fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
}
pub fn fill_bytes(v: &mut [u8]) {
let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
if ret == -1 {
panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
}
}
}
// FIXME: once the 10.x release becomes the minimum, this can be dropped for simplification. // FIXME: once the 10.x release becomes the minimum, this can be dropped for simplification.
#[cfg(target_os = "netbsd")] #[cfg(target_os = "netbsd")]
mod imp { mod imp {