]>
Commit | Line | Data |
---|---|---|
f20569fa XL |
1 | // Copyright 2019 Developers of the Rand project. |
2 | // | |
3 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
4 | // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
5 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your | |
6 | // option. This file may not be copied, modified, or distributed | |
7 | // except according to those terms. | |
8 | ||
9 | //! Implementation for macOS | |
10 | use crate::{ | |
11 | use_file, | |
12 | util_libc::{last_os_error, Weak}, | |
13 | Error, | |
14 | }; | |
15 | use core::mem; | |
16 | ||
17 | type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int; | |
18 | ||
19 | pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { | |
20 | static GETENTROPY: Weak = unsafe { Weak::new("getentropy\0") }; | |
21 | if let Some(fptr) = GETENTROPY.ptr() { | |
22 | let func: GetEntropyFn = unsafe { mem::transmute(fptr) }; | |
23 | for chunk in dest.chunks_mut(256) { | |
24 | let ret = unsafe { func(chunk.as_mut_ptr(), chunk.len()) }; | |
25 | if ret != 0 { | |
26 | return Err(last_os_error()); | |
27 | } | |
28 | } | |
29 | Ok(()) | |
30 | } else { | |
31 | // We fallback to reading from /dev/random instead of SecRandomCopyBytes | |
32 | // to avoid high startup costs and linking the Security framework. | |
33 | use_file::getrandom_inner(dest) | |
34 | } | |
35 | } |