blob: d44121254111720efef1c891aa330d02ac0f1a8a [file] [log] [blame]
Joel Galenson4be0c6d2020-07-07 13:20:14 -07001// Copyright 2018 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 FreeBSD and NetBSD
ThiƩbaud Weksteen9791b302021-03-03 16:30:20 +010010use crate::{util_libc::sys_fill_exact, Error};
Joel Galenson4be0c6d2020-07-07 13:20:14 -070011use core::ptr;
12
13fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
14 static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
15 let mut len = buf.len();
16 let ret = unsafe {
17 libc::sysctl(
18 MIB.as_ptr(),
19 MIB.len() as libc::c_uint,
20 buf.as_mut_ptr() as *mut _,
21 &mut len,
22 ptr::null(),
23 0,
24 )
25 };
26 if ret == -1 {
Joel Galenson4be0c6d2020-07-07 13:20:14 -070027 -1
28 } else {
29 len as libc::ssize_t
30 }
31}
32
33pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
Jeff Vander Stoep4d7867d2022-12-12 11:02:41 +010034 // getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0
Joel Galenson4be0c6d2020-07-07 13:20:14 -070035 #[cfg(target_os = "freebsd")]
36 {
37 use crate::util_libc::Weak;
38 static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
39 type GetRandomFn =
40 unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
41
42 if let Some(fptr) = GETRANDOM.ptr() {
43 let func: GetRandomFn = unsafe { core::mem::transmute(fptr) };
44 return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) });
45 }
46 }
ThiƩbaud Weksteen9791b302021-03-03 16:30:20 +010047 // Both FreeBSD and NetBSD will only return up to 256 bytes at a time, and
48 // older NetBSD kernels will fail on longer buffers.
49 for chunk in dest.chunks_mut(256) {
50 sys_fill_exact(chunk, kern_arnd)?
51 }
52 Ok(())
Joel Galenson4be0c6d2020-07-07 13:20:14 -070053}