Debian Codegraph @

.cargo/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,
12 sync::atomic::{AtomicPtr, Ordering},
13 };
14
15 pub use crate::util::{inner_u32, inner_u64};
16
17 #[path = "../util_libc.rs"]
18 mod util_libc;
19
20 unsafe extern "C" fn polyfill_using_kern_arand(
21 buf: *mut c_void,
22 buflen: libc::size_t,
23 flags: libc::c_uint,
24 ) -> libc::ssize_t {
25 debug_assert_eq!(flags, 0);
26
27 const MIB_LEN: libc::c_uint = 2;
28 static MIB: [libc::c_int; MIB_LEN as usize] = [libc::CTL_KERN, libc::KERN_ARND];
29
30 // NetBSD will only return up to 256 bytes at a time, and
31 // older NetBSD kernels will fail on longer buffers.
32 let mut len = cmp::min(buflen, 256);
33 let ret = unsafe { libc::sysctl(MIB.as_ptr(), MIB_LEN, buf, &mut len, ptr::null(), 0) };
34
35 match ret {
36 0 if len <= 256 => libc::ssize_t::try_from(len).expect("len is in the range of 0..=256"),
37 -1 => -1,
38 // Zero return result will be converted into `Error::UNEXPECTED` by `sys_fill_exact`
39 _ => 0,
40 }
41 }
42
43 type GetRandomFn = unsafe extern "C" fn(*mut c_void, libc::size_t, libc::c_uint) -> libc::ssize_t;
44
45 static GETRANDOM: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
46
47 #[cold]
48 #[inline(never)]
49 fn init() -> *mut c_void {
50 static NAME: &[u8] = b"getrandom\0";
51 let name_ptr = NAME.as_ptr().cast::<libc::c_char>();
52 let mut ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name_ptr) };
53 if ptr.is_null() || cfg!(getrandom_test_netbsd_fallback) {
54 // Verify `polyfill_using_kern_arand` has the right signature.
55 const POLYFILL: GetRandomFn = polyfill_using_kern_arand;
56 ptr = POLYFILL as *mut c_void;
57 }
58 GETRANDOM.store(ptr, Ordering::Release);
59 ptr
60 }
61
62 #[inline]
63 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
64 // Despite being only a single atomic variable, we still cannot always use
65 // Ordering::Relaxed, as we need to make sure a successful call to `init`
66 // is "ordered before" any data read through the returned pointer (which
67 // occurs when the function is called). Our implementation mirrors that of
68 // the one in libstd, meaning that the use of non-Relaxed operations is
69 // probably unnecessary.
70 let mut fptr = GETRANDOM.load(Ordering::Acquire);
71 if fptr.is_null() {
72 fptr = init();
73 }
74 let fptr = unsafe { mem::transmute::<*mut c_void, GetRandomFn>(fptr) };
75 util_libc::sys_fill_exact(dest, |buf| unsafe {
76 fptr(buf.as_mut_ptr().cast::<c_void>(), buf.len(), 0)
77 })
78 }