Skip to content

Commit 813b117

Browse files
committed
freebsd: Try getrandom() first
1 parent 32b221f commit 813b117

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,10 +7,12 @@
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;
1212
use core::num::NonZeroU32;
13-
use core::ptr;
13+
use core::{mem, ptr};
14+
15+
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
1416

1517
fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
1618
static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
@@ -34,7 +36,13 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
3436
}
3537

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

4048
#[inline(always)]

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]
@@ -118,6 +118,7 @@
118118
//! [18]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
119119
//! [19]: https://www.unix.com/man-page/mojave/2/getentropy/
120120
//! [20]: https://www.unix.com/man-page/mojave/4/random/
121+
//! [21]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
121122
122123
#![doc(
123124
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",

0 commit comments

Comments
 (0)