Debian Codegraph @

debian/rust-vendor/getrandom/src/backends/netbsd.rs

raw
1 //! Implementation for NetBSD
2 //!
3 //! `getrandom(2)` was introduced in NetBSD 10. To support older versions we
4 //! implement our own weak linkage to it, and provide a fallback based on the
5 //! KERN_ARND sysctl.
6 use crate::Error;
7 use core::{
8 cmp,
9 ffi::c_void,
10 mem::{self, MaybeUninit},
11 ptr::{self, NonNull},
12 };
13
14 pub use crate::util::{inner_u32, inner_u64};
15
16 #[path = "../utils/sys_fill_exact.rs"]
17 mod utils;
18
19 unsafe extern "C" fn polyfill_using_kern_arand(
20 buf: *mut c_void,
21 buflen: libc::size_t,
22 flags: libc::c_uint,
23 ) -> libc::ssize_t {
24 debug_assert_eq!(flags, 0);
25
26 const MIB_LEN: libc::c_uint = 2;
27 static MIB: [libc::c_int; MIB_LEN as usize] = [libc::CTL_KERN, libc::KERN_ARND];
28
29 // NetBSD will only return up to 256 bytes at a time, and
30 // older NetBSD kernels will fail on longer buffers.
31 let mut len = cmp::min(buflen, 256);
32 let ret = unsafe { libc::sysctl(MIB.as_ptr(), MIB_LEN, buf, &mut len, ptr::null(), 0) };
33
34 match ret {
35 0 if len <= 256 => libc::ssize_t::try_from(len).expect("len is in the range of 0..=256"),
36 -1 => -1,
37 // Zero return result will be converted into `Error::UNEXPECTED` by `sys_fill_exact`
38 _ => 0,
39 }
40 }
41
42 type GetRandomFn = unsafe extern "C" fn(*mut c_void, libc::size_t, libc::c_uint) -> libc::ssize_t;
43
44 #[cold]
45 #[inline(never)]
46 fn init() -> NonNull<c_void> {
47 let ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"getrandom".as_ptr()) };
48 if !cfg!(getrandom_test_netbsd_fallback) {
49 if let Some(ptr) = NonNull::new(ptr) {
50 return ptr;
51 }
52 }
53 // Verify `polyfill_using_kern_arand` has the right signature.
54 const POLYFILL: GetRandomFn = polyfill_using_kern_arand;
55 unsafe { NonNull::new_unchecked(POLYFILL as *mut c_void) }
56 }
57
58 #[inline]
59 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
60 #[path = "../utils/lazy_ptr.rs"]
61 mod lazy;
62
63 static GETRANDOM_FN: lazy::LazyPtr<c_void> = lazy::LazyPtr::new();
64
65 let fptr = GETRANDOM_FN.unsync_init(init);
66 let fptr = unsafe { mem::transmute::<*mut c_void, GetRandomFn>(fptr.as_ptr()) };
67 utils::sys_fill_exact(dest, |buf| unsafe {
68 fptr(buf.as_mut_ptr().cast::<c_void>(), buf.len(), 0)
69 })
70 }