1 // 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
10 use crate::util_libc::sys_fill_exact;
11 use crate::Error;
12 use core::ptr;
13 
kern_arnd(buf: &mut [u8]) -> libc::ssize_t14 fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
15     static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
16     let mut len = buf.len();
17     let ret = unsafe {
18         libc::sysctl(
19             MIB.as_ptr(),
20             MIB.len() as libc::c_uint,
21             buf.as_mut_ptr() as *mut _,
22             &mut len,
23             ptr::null(),
24             0,
25         )
26     };
27     if ret == -1 {
28         error!("sysctl kern.arandom: syscall failed");
29         -1
30     } else {
31         len as libc::ssize_t
32     }
33 }
34 
getrandom_inner(dest: &mut [u8]) -> Result<(), Error>35 pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
36     #[cfg(target_os = "freebsd")]
37     {
38         use crate::util_libc::Weak;
39         static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
40         type GetRandomFn =
41             unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
42 
43         if let Some(fptr) = GETRANDOM.ptr() {
44             let func: GetRandomFn = unsafe { core::mem::transmute(fptr) };
45             return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) });
46         }
47     }
48     sys_fill_exact(dest, kern_arnd)
49 }
50