|
1 | | -// Copyright 2018 Developers of the Rand project. |
| 1 | +// Copyright 2019 Developers of the Rand project. |
2 | 2 | // |
3 | 3 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
4 | 4 | // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
5 | 5 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
6 | 6 | // option. This file may not be copied, modified, or distributed |
7 | 7 | // except according to those terms. |
8 | 8 |
|
9 | | -//! Implementation for MacOS / iOS |
| 9 | +//! Implementation for macOS |
10 | 10 | extern crate std; |
11 | 11 |
|
12 | | -use crate::Error; |
| 12 | +use crate::{use_file, Error}; |
| 13 | +use core::mem; |
13 | 14 | use core::num::NonZeroU32; |
| 15 | +use lazy_static::lazy_static; |
14 | 16 | use std::io; |
15 | 17 |
|
16 | | -// TODO: Make extern once extern_types feature is stabilized. See: |
17 | | -// https://github.com/rust-lang/rust/issues/43467 |
18 | | -#[repr(C)] |
19 | | -struct SecRandom([u8; 0]); |
| 18 | +type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int; |
20 | 19 |
|
21 | | -#[link(name = "Security", kind = "framework")] |
22 | | -extern "C" { |
23 | | - static kSecRandomDefault: *const SecRandom; |
24 | | - |
25 | | - fn SecRandomCopyBytes(rnd: *const SecRandom, count: usize, bytes: *mut u8) -> i32; |
| 20 | +fn fetch_getentropy() -> Option<GetEntropyFn> { |
| 21 | + let name = "getentropy\0"; |
| 22 | + let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) }; |
| 23 | + unsafe { mem::transmute(addr) } |
26 | 24 | } |
27 | 25 |
|
28 | 26 | pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { |
29 | | - let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, dest.len(), dest.as_mut_ptr()) }; |
30 | | - if ret == -1 { |
31 | | - error!("SecRandomCopyBytes call failed"); |
32 | | - Err(io::Error::last_os_error().into()) |
33 | | - } else { |
| 27 | + lazy_static! { |
| 28 | + static ref GETENTROPY_FUNC: Option<GetEntropyFn> = fetch_getentropy(); |
| 29 | + } |
| 30 | + if let Some(fptr) = *GETENTROPY_FUNC { |
| 31 | + for chunk in dest.chunks_mut(256) { |
| 32 | + let ret = unsafe { fptr(chunk.as_mut_ptr(), chunk.len()) }; |
| 33 | + if ret != 0 { |
| 34 | + error!("getentropy syscall failed with ret={}", ret); |
| 35 | + return Err(io::Error::last_os_error().into()); |
| 36 | + } |
| 37 | + } |
34 | 38 | Ok(()) |
| 39 | + } else { |
| 40 | + // We fallback to reading from /dev/random instead of SecRandomCopyBytes |
| 41 | + // to avoid high startup costs and linking the Security framework. |
| 42 | + use_file::getrandom_inner(dest) |
35 | 43 | } |
36 | 44 | } |
37 | 45 |
|
|
0 commit comments