rustix/weak.rs
1// Implementation derived from `weak` in Rust's
2// library/std/src/sys/unix/weak.rs at revision
3// fd0cb0cdc21dd9c06025277d772108f8d42cb25f.
4//
5// Ideally we should update to a newer version which doesn't need `dlsym`,
6// however that depends on the `extern_weak` feature which is currently
7// unstable.
8
9#![cfg_attr(linux_raw, allow(unsafe_code))]
10
11//! Support for "weak linkage" to symbols on Unix
12//!
13//! Some I/O operations we do in libstd require newer versions of OSes but we
14//! need to maintain binary compatibility with older releases for now. In order
15//! to use the new functionality when available we use this module for
16//! detection.
17//!
18//! One option to use here is weak linkage, but that is unfortunately only
19//! really workable on Linux. Hence, use dlsym to get the symbol value at
20//! runtime. This is also done for compatibility with older versions of glibc,
21//! and to avoid creating dependencies on `GLIBC_PRIVATE` symbols. It assumes
22//! that we've been dynamically linked to the library the symbol comes from,
23//! but that is currently always the case for things like libpthread/libc.
24//!
25//! A long time ago this used weak linkage for the `__pthread_get_minstack`
26//! symbol, but that caused Debian to detect an unnecessarily strict versioned
27//! dependency on libc6 (#23628).
28
29// There are a variety of `#[cfg]`s controlling which targets are involved in
30// each instance of `weak!` and `syscall!`. Rather than trying to unify all of
31// that, we'll just allow that some unix targets don't use this module at all.
32#![allow(dead_code, unused_macros)]
33#![allow(clippy::doc_markdown)]
34
35use crate::ffi::CStr;
36use core::ffi::c_void;
37use core::ptr::null_mut;
38use core::sync::atomic::{self, AtomicPtr, Ordering};
39use core::{marker, mem};
40
41const NULL: *mut c_void = null_mut();
42const INVALID: *mut c_void = 1 as *mut c_void;
43
44macro_rules! weak {
45 ($vis:vis fn $name:ident($($t:ty),*) -> $ret:ty) => (
46 #[allow(non_upper_case_globals)]
47 $vis static $name: $crate::weak::Weak<unsafe extern "C" fn($($t),*) -> $ret> =
48 $crate::weak::Weak::new(concat!(stringify!($name), '\0'));
49 )
50}
51
52pub(crate) struct Weak<F> {
53 name: &'static str,
54 addr: AtomicPtr<c_void>,
55 _marker: marker::PhantomData<F>,
56}
57
58impl<F> Weak<F> {
59 pub(crate) const fn new(name: &'static str) -> Self {
60 Self {
61 name,
62 addr: AtomicPtr::new(INVALID),
63 _marker: marker::PhantomData,
64 }
65 }
66
67 pub(crate) fn get(&self) -> Option<F> {
68 assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
69 unsafe {
70 // Relaxed is fine here because we fence before reading through the
71 // pointer (see the comment below).
72 match self.addr.load(Ordering::Relaxed) {
73 INVALID => self.initialize(),
74 NULL => None,
75 addr => {
76 let func = mem::transmute_copy::<*mut c_void, F>(&addr);
77 // The caller is presumably going to read through this
78 // value (by calling the function we've dlsymed). This
79 // means we'd need to have loaded it with at least C11's
80 // consume ordering in order to be guaranteed that the data
81 // we read from the pointer isn't from before the pointer
82 // was stored. Rust has no equivalent to
83 // memory_order_consume, so we use an acquire fence (sorry,
84 // ARM).
85 //
86 // Now, in practice this likely isn't needed even on CPUs
87 // where relaxed and consume mean different things. The
88 // symbols we're loading are probably present (or not) at
89 // init, and even if they aren't the runtime dynamic loader
90 // is extremely likely have sufficient barriers internally
91 // (possibly implicitly, for example the ones provided by
92 // invoking `mprotect`).
93 //
94 // That said, none of that's *guaranteed*, and so we fence.
95 atomic::fence(Ordering::Acquire);
96 Some(func)
97 }
98 }
99 }
100 }
101
102 // Cold because it should only happen during first-time initialization.
103 #[cold]
104 unsafe fn initialize(&self) -> Option<F> {
105 let val = fetch(self.name);
106 // This synchronizes with the acquire fence in `get`.
107 self.addr.store(val, Ordering::Release);
108
109 match val {
110 NULL => None,
111 addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)),
112 }
113 }
114}
115
116// To avoid having the `linux_raw` backend depend on the libc crate, just
117// declare the few things we need in a module called `libc` so that `fetch`
118// uses it.
119#[cfg(linux_raw)]
120mod libc {
121 use core::ptr;
122 use linux_raw_sys::ctypes::{c_char, c_void};
123
124 #[cfg(all(target_os = "android", target_pointer_width = "32"))]
125 pub(super) const RTLD_DEFAULT: *mut c_void = -1isize as *mut c_void;
126 #[cfg(not(all(target_os = "android", target_pointer_width = "32")))]
127 pub(super) const RTLD_DEFAULT: *mut c_void = ptr::null_mut();
128
129 extern "C" {
130 pub(super) fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
131 }
132
133 #[test]
134 fn test_abi() {
135 assert_eq!(self::RTLD_DEFAULT, ::libc::RTLD_DEFAULT);
136 }
137}
138
139unsafe fn fetch(name: &str) -> *mut c_void {
140 let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
141 Ok(c_str) => c_str,
142 Err(..) => return null_mut(),
143 };
144 libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast())
145}
146
147#[cfg(not(linux_kernel))]
148macro_rules! syscall {
149 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $_sys_name:ident -> $ret:ty) => (
150 $vis unsafe fn $name($($arg_name: $t),*) -> $ret {
151 weak! { fn $name($($t),*) -> $ret }
152
153 if let Some(fun) = $name.get() {
154 fun($($arg_name),*)
155 } else {
156 libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
157 -1
158 }
159 }
160 )
161}
162
163#[cfg(linux_kernel)]
164macro_rules! syscall {
165 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
166 $vis unsafe fn $name($($arg_name:$t),*) -> $ret {
167 // This looks like a hack, but `concat_idents` only accepts idents
168 // (not paths).
169 use libc::*;
170
171 #[allow(dead_code)]
172 trait AsSyscallArg {
173 type SyscallArgType;
174 fn into_syscall_arg(self) -> Self::SyscallArgType;
175 }
176
177 // Pass pointer types as pointers, to preserve provenance.
178 impl<T> AsSyscallArg for *mut T {
179 type SyscallArgType = *mut T;
180 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
181 }
182 impl<T> AsSyscallArg for *const T {
183 type SyscallArgType = *const T;
184 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
185 }
186
187 // Pass `BorrowedFd` values as the integer value.
188 impl AsSyscallArg for $crate::fd::BorrowedFd<'_> {
189 type SyscallArgType = ::libc::c_int;
190 fn into_syscall_arg(self) -> Self::SyscallArgType {
191 $crate::fd::AsRawFd::as_raw_fd(&self) as _
192 }
193 }
194
195 // Coerce integer values into `c_long`.
196 impl AsSyscallArg for i8 {
197 type SyscallArgType = ::libc::c_int;
198 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
199 }
200 impl AsSyscallArg for u8 {
201 type SyscallArgType = ::libc::c_int;
202 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
203 }
204 impl AsSyscallArg for i16 {
205 type SyscallArgType = ::libc::c_int;
206 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
207 }
208 impl AsSyscallArg for u16 {
209 type SyscallArgType = ::libc::c_int;
210 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
211 }
212 impl AsSyscallArg for i32 {
213 type SyscallArgType = ::libc::c_int;
214 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
215 }
216 impl AsSyscallArg for u32 {
217 type SyscallArgType = ::libc::c_uint;
218 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
219 }
220 impl AsSyscallArg for usize {
221 type SyscallArgType = ::libc::c_ulong;
222 fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ }
223 }
224
225 // On 64-bit platforms, also coerce `i64` and `u64` since `c_long`
226 // is 64-bit and can hold those values.
227 #[cfg(target_pointer_width = "64")]
228 impl AsSyscallArg for i64 {
229 type SyscallArgType = ::libc::c_long;
230 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
231 }
232 #[cfg(target_pointer_width = "64")]
233 impl AsSyscallArg for u64 {
234 type SyscallArgType = ::libc::c_ulong;
235 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
236 }
237
238 // `concat_idents` is [unstable], so we take an extra `sys_name`
239 // parameter and have our users do the concat for us for now.
240 //
241 // [unstable]: https://github.com/rust-lang/rust/issues/29599
242 /*
243 syscall(
244 concat_idents!(SYS_, $name),
245 $($arg_name.into_syscall_arg()),*
246 ) as $ret
247 */
248
249 syscall($sys_name, $($arg_name.into_syscall_arg()),*) as $ret
250 }
251 )
252}
253
254macro_rules! weakcall {
255 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
256 $vis unsafe fn $name($($arg_name: $t),*) -> $ret {
257 weak! { fn $name($($t),*) -> $ret }
258
259 // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
260 // interposition, but if it's not found just fail.
261 if let Some(fun) = $name.get() {
262 fun($($arg_name),*)
263 } else {
264 libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
265 -1
266 }
267 }
268 )
269}
270
271/// A combination of `weakcall` and `syscall`. Use the libc function if it's
272/// available, and fall back to `libc::syscall` otherwise.
273macro_rules! weak_or_syscall {
274 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
275 $vis unsafe fn $name($($arg_name: $t),*) -> $ret {
276 weak! { fn $name($($t),*) -> $ret }
277
278 // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
279 // interposition, but if it's not found just fail.
280 if let Some(fun) = $name.get() {
281 fun($($arg_name),*)
282 } else {
283 syscall! { fn $name($($arg_name: $t),*) via $sys_name -> $ret }
284 $name($($arg_name),*)
285 }
286 }
287 )
288}