Skip to content

Commit 61eaf8f

Browse files
committed
freebsd: Try getrandom() first
1 parent f3f947b commit 61eaf8f

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/freebsd.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77
// except according to those terms.
88

99
//! Implementation for FreeBSD
10-
use crate::util_libc::fill_exact;
10+
use crate::util_libc::{fill_exact, Weak};
1111
use crate::Error;
12-
use core::ptr;
12+
use core::{mem, ptr};
13+
14+
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
1315

1416
fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
1517
static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
@@ -33,5 +35,11 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
3335
}
3436

3537
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
36-
fill_exact(dest, kern_arnd)
38+
static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
39+
if let Some(fptr) = GETRANDOM.ptr() {
40+
let func: GetRandomFn = unsafe { mem::transmute(fptr) };
41+
fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) })
42+
} else {
43+
fill_exact(dest, kern_arnd)
44+
}
3745
}

src/lib.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
//! | Windows | [`RtlGenRandom`][3]
1717
//! | macOS | [`getentropy()`][19] if available, otherise [`/dev/random`][20] (identical to `/dev/urandom`)
1818
//! | iOS | [`SecRandomCopyBytes`][4]
19-
//! | FreeBSD | [`kern.arandom`][5]
19+
//! | FreeBSD | [`getrandom()`][21] if available, otherise [`kern.arandom`][5]
2020
//! | OpenBSD | [`getentropy`][6]
2121
//! | NetBSD | [`/dev/urandom`][7] after reading from `/dev/random` once
2222
//! | Dragonfly BSD | [`/dev/random`][8]
@@ -101,6 +101,7 @@
101101
//! [18]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
102102
//! [19]: https://www.unix.com/man-page/mojave/2/getentropy/
103103
//! [20]: https://www.unix.com/man-page/mojave/4/random/
104+
//! [21]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
104105
105106
#![doc(
106107
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",

0 commit comments

Comments
 (0)