Skip to content

Commit bcbadc1

Browse files
authored
Rename Weak to LazyPtr and move it to lazy.rs (#427)
Currently the `Weak` type is used only by the NetBSD backend, but in future it may be used by other backends. To simplify code a bit and prepare for potential use on Windows, `Weak` now accepts a "pointer initialization function" instead of a function name, i.e. it now works similarly to `LazyUsize` and `LazyBool`.
1 parent cf65e83 commit bcbadc1

File tree

4 files changed

+75
-77
lines changed

4 files changed

+75
-77
lines changed

src/lazy.rs

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};
1+
#![allow(dead_code)]
2+
use core::{
3+
ffi::c_void,
4+
sync::atomic::{AtomicPtr, AtomicUsize, Ordering},
5+
};
26

37
// This structure represents a lazily initialized static usize value. Useful
48
// when it is preferable to just rerun initialization instead of locking.
@@ -21,22 +25,22 @@ use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};
2125
pub(crate) struct LazyUsize(AtomicUsize);
2226

2327
impl LazyUsize {
28+
// The initialization is not completed.
29+
const UNINIT: usize = usize::max_value();
30+
2431
pub const fn new() -> Self {
2532
Self(AtomicUsize::new(Self::UNINIT))
2633
}
2734

28-
// The initialization is not completed.
29-
pub const UNINIT: usize = usize::max_value();
30-
3135
// Runs the init() function at most once, returning the value of some run of
3236
// init(). Multiple callers can run their init() functions in parallel.
3337
// init() should always return the same value, if it succeeds.
3438
pub fn unsync_init(&self, init: impl FnOnce() -> usize) -> usize {
3539
// Relaxed ordering is fine, as we only have a single atomic variable.
36-
let mut val = self.0.load(Relaxed);
40+
let mut val = self.0.load(Ordering::Relaxed);
3741
if val == Self::UNINIT {
3842
val = init();
39-
self.0.store(val, Relaxed);
43+
self.0.store(val, Ordering::Relaxed);
4044
}
4145
val
4246
}
@@ -54,3 +58,53 @@ impl LazyBool {
5458
self.0.unsync_init(|| init() as usize) != 0
5559
}
5660
}
61+
62+
// This structure represents a lazily initialized static pointer value.
63+
///
64+
/// It's intended to be used for weak linking of a C function that may
65+
/// or may not be present at runtime.
66+
///
67+
/// Based off of the DlsymWeak struct in libstd:
68+
/// https://github.com/rust-lang/rust/blob/1.61.0/library/std/src/sys/unix/weak.rs#L84
69+
/// except that the caller must manually cast self.ptr() to a function pointer.
70+
pub struct LazyPtr {
71+
addr: AtomicPtr<c_void>,
72+
}
73+
74+
impl LazyPtr {
75+
/// A non-null pointer value which indicates we are uninitialized.
76+
///
77+
/// This constant should ideally not be a valid pointer. However,
78+
/// if by chance initialization function passed to the `unsync_init`
79+
/// method does return UNINIT, there will not be undefined behavior.
80+
/// The initialization function will just be called each time `get()`
81+
/// is called. This would be inefficient, but correct.
82+
const UNINIT: *mut c_void = !0usize as *mut c_void;
83+
84+
/// Construct new `LazyPtr` in uninitialized state.
85+
pub const fn new() -> Self {
86+
Self {
87+
addr: AtomicPtr::new(Self::UNINIT),
88+
}
89+
}
90+
91+
// Runs the init() function at most once, returning the value of some run of
92+
// init(). Multiple callers can run their init() functions in parallel.
93+
// init() should always return the same value, if it succeeds.
94+
pub fn unsync_init(&self, init: impl Fn() -> *mut c_void) -> *mut c_void {
95+
// Despite having only a single atomic variable (self.addr), we still
96+
// cannot always use Ordering::Relaxed, as we need to make sure a
97+
// successful call to `init` is "ordered before" any data read through
98+
// the returned pointer (which occurs when the function is called).
99+
// Our implementation mirrors that of the one in libstd, meaning that
100+
// the use of non-Relaxed operations is probably unnecessary.
101+
match self.addr.load(Ordering::Acquire) {
102+
Self::UNINIT => {
103+
let addr = init();
104+
self.addr.store(addr, Ordering::Release);
105+
addr
106+
}
107+
addr => addr,
108+
}
109+
}
110+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,7 @@ cfg_if! {
306306
#[path = "solaris.rs"] mod imp;
307307
} else if #[cfg(target_os = "netbsd")] {
308308
mod util_libc;
309+
mod lazy;
309310
#[path = "netbsd.rs"] mod imp;
310311
} else if #[cfg(target_os = "fuchsia")] {
311312
#[path = "fuchsia.rs"] mod imp;

src/netbsd.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
//! Implementation for NetBSD
2-
use crate::{
3-
util_libc::{sys_fill_exact, Weak},
4-
Error,
5-
};
6-
use core::{mem::MaybeUninit, ptr};
2+
use crate::{lazy::LazyPtr, util_libc::sys_fill_exact, Error};
3+
use core::{ffi::c_void, mem::MaybeUninit, ptr};
74

85
fn kern_arnd(buf: &mut [MaybeUninit<u8>]) -> libc::ssize_t {
96
static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
@@ -27,10 +24,18 @@ fn kern_arnd(buf: &mut [MaybeUninit<u8>]) -> libc::ssize_t {
2724

2825
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
2926

27+
// getrandom(2) was introduced in NetBSD 10.0
28+
static GETRANDOM: LazyPtr = LazyPtr::new();
29+
30+
fn dlsym_getrandom() -> *mut c_void {
31+
static NAME: &[u8] = b"getrandom\0";
32+
let name_ptr = NAME.as_ptr() as *const libc::c_char;
33+
unsafe { libc::dlsym(libc::RTLD_DEFAULT, name_ptr) }
34+
}
35+
3036
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
31-
// getrandom(2) was introduced in NetBSD 10.0
32-
static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
33-
if let Some(fptr) = GETRANDOM.ptr() {
37+
let fptr = GETRANDOM.unsync_init(dlsym_getrandom);
38+
if !fptr.is_null() {
3439
let func: GetRandomFn = unsafe { core::mem::transmute(fptr) };
3540
return sys_fill_exact(dest, |buf| unsafe {
3641
func(buf.as_mut_ptr() as *mut u8, buf.len(), 0)

src/util_libc.rs

Lines changed: 1 addition & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
11
#![allow(dead_code)]
22
use crate::Error;
3-
use core::{
4-
mem::MaybeUninit,
5-
num::NonZeroU32,
6-
ptr::NonNull,
7-
sync::atomic::{fence, AtomicPtr, Ordering},
8-
};
9-
use libc::c_void;
3+
use core::{mem::MaybeUninit, num::NonZeroU32};
104

115
cfg_if! {
126
if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] {
@@ -76,62 +70,6 @@ pub fn sys_fill_exact(
7670
Ok(())
7771
}
7872

79-
// A "weak" binding to a C function that may or may not be present at runtime.
80-
// Used for supporting newer OS features while still building on older systems.
81-
// Based off of the DlsymWeak struct in libstd:
82-
// https://github.com/rust-lang/rust/blob/1.61.0/library/std/src/sys/unix/weak.rs#L84
83-
// except that the caller must manually cast self.ptr() to a function pointer.
84-
pub struct Weak {
85-
name: &'static str,
86-
addr: AtomicPtr<c_void>,
87-
}
88-
89-
impl Weak {
90-
// A non-null pointer value which indicates we are uninitialized. This
91-
// constant should ideally not be a valid address of a function pointer.
92-
// However, if by chance libc::dlsym does return UNINIT, there will not
93-
// be undefined behavior. libc::dlsym will just be called each time ptr()
94-
// is called. This would be inefficient, but correct.
95-
// TODO: Replace with core::ptr::invalid_mut(1) when that is stable.
96-
const UNINIT: *mut c_void = 1 as *mut c_void;
97-
98-
// Construct a binding to a C function with a given name. This function is
99-
// unsafe because `name` _must_ be null terminated.
100-
pub const unsafe fn new(name: &'static str) -> Self {
101-
Self {
102-
name,
103-
addr: AtomicPtr::new(Self::UNINIT),
104-
}
105-
}
106-
107-
// Return the address of a function if present at runtime. Otherwise,
108-
// return None. Multiple callers can call ptr() concurrently. It will
109-
// always return _some_ value returned by libc::dlsym. However, the
110-
// dlsym function may be called multiple times.
111-
pub fn ptr(&self) -> Option<NonNull<c_void>> {
112-
// Despite having only a single atomic variable (self.addr), we still
113-
// cannot always use Ordering::Relaxed, as we need to make sure a
114-
// successful call to dlsym() is "ordered before" any data read through
115-
// the returned pointer (which occurs when the function is called).
116-
// Our implementation mirrors that of the one in libstd, meaning that
117-
// the use of non-Relaxed operations is probably unnecessary.
118-
match self.addr.load(Ordering::Relaxed) {
119-
Self::UNINIT => {
120-
let symbol = self.name.as_ptr() as *const _;
121-
let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) };
122-
// Synchronizes with the Acquire fence below
123-
self.addr.store(addr, Ordering::Release);
124-
NonNull::new(addr)
125-
}
126-
addr => {
127-
let func = NonNull::new(addr)?;
128-
fence(Ordering::Acquire);
129-
Some(func)
130-
}
131-
}
132-
}
133-
}
134-
13573
// SAFETY: path must be null terminated, FD must be manually closed.
13674
pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> {
13775
debug_assert_eq!(path.as_bytes().last(), Some(&0));

0 commit comments

Comments
 (0)