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 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 value
78 // (by calling the function we've dlsymed). This means we'd
79 // need to have loaded it with at least C11's consume
80 // ordering in order to be guaranteed that the data we read
81 // from the pointer isn't from before the pointer was
82 // stored. Rust has no equivalent to memory_order_consume,
83 // so we use an acquire fence (sorry, ARM).
84 //
85 // Now, in practice this likely isn't needed even on CPUs
86 // where relaxed and consume mean different things. The
87 // symbols we're loading are probably present (or not) at
88 // init, and even if they aren't the runtime dynamic loader
89 // is extremely likely have sufficient barriers internally
90 // (possibly implicitly, for example the ones provided by
91 // invoking `mprotect`).
92 //
93 // That said, none of that's *guaranteed*, and so we fence.
94 atomic::fence(Ordering::Acquire);
95 Some(func)
96 }
97 }
98 }
99 }
100
101 // Cold because it should only happen during first-time initialization.
102 #[cold]
103 unsafe fn initialize(&self) -> Option<F> {
104 let val = fetch(self.name);
105 // This synchronizes with the acquire fence in `get`.
106 self.addr.store(val, Ordering::Release);
107
108 match val {
109 NULL => None,
110 addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)),
111 }
112 }
113}
114
115// To avoid having the `linux_raw` backend depend on the libc crate, just
116// declare the few things we need in a module called `libc` so that `fetch`
117// uses it.
118#[cfg(linux_raw)]
119mod libc {
120 use core::ptr;
121 use linux_raw_sys::ctypes::{c_char, c_void};
122
123 #[cfg(all(target_os = "android", target_pointer_width = "32"))]
124 pub(super) const RTLD_DEFAULT: *mut c_void = -1isize as *mut c_void;
125 #[cfg(not(all(target_os = "android", target_pointer_width = "32")))]
126 pub(super) const RTLD_DEFAULT: *mut c_void = ptr::null_mut();
127
128 extern "C" {
129 pub(super) fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
130 }
131
132 #[test]
133 fn test_abi() {
134 assert_eq!(self::RTLD_DEFAULT, ::libc::RTLD_DEFAULT);
135 }
136}
137
138unsafe fn fetch(name: &str) -> *mut c_void {
139 let name: &CStr = match CStr::from_bytes_with_nul(name.as_bytes()) {
140 Ok(c_str: &CStr) => c_str,
141 Err(..) => return null_mut(),
142 };
143 libc::dlsym(handle:libc::RTLD_DEFAULT, symbol:name.as_ptr().cast())
144}
145
146#[cfg(not(linux_kernel))]
147macro_rules! syscall {
148 (fn $name:ident($($arg_name:ident: $t:ty),*) via $_sys_name:ident -> $ret:ty) => (
149 unsafe fn $name($($arg_name: $t),*) -> $ret {
150 weak! { fn $name($($t),*) -> $ret }
151
152 if let Some(fun) = $name.get() {
153 fun($($arg_name),*)
154 } else {
155 libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
156 -1
157 }
158 }
159 )
160}
161
162#[cfg(linux_kernel)]
163macro_rules! syscall {
164 (fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
165 unsafe fn $name($($arg_name:$t),*) -> $ret {
166 // This looks like a hack, but `concat_idents` only accepts idents
167 // (not paths).
168 use libc::*;
169
170 #[allow(dead_code)]
171 trait AsSyscallArg {
172 type SyscallArgType;
173 fn into_syscall_arg(self) -> Self::SyscallArgType;
174 }
175
176 // Pass pointer types as pointers, to preserve provenance.
177 impl<T> AsSyscallArg for *mut T {
178 type SyscallArgType = *mut T;
179 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
180 }
181 impl<T> AsSyscallArg for *const T {
182 type SyscallArgType = *const T;
183 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
184 }
185
186 // Pass `BorrowedFd` values as the integer value.
187 impl AsSyscallArg for $crate::fd::BorrowedFd<'_> {
188 type SyscallArgType = ::libc::c_int;
189 fn into_syscall_arg(self) -> Self::SyscallArgType {
190 $crate::fd::AsRawFd::as_raw_fd(&self) as _
191 }
192 }
193
194 // Coerce integer values into `c_long`.
195 impl AsSyscallArg for i8 {
196 type SyscallArgType = ::libc::c_int;
197 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
198 }
199 impl AsSyscallArg for u8 {
200 type SyscallArgType = ::libc::c_int;
201 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
202 }
203 impl AsSyscallArg for i16 {
204 type SyscallArgType = ::libc::c_int;
205 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
206 }
207 impl AsSyscallArg for u16 {
208 type SyscallArgType = ::libc::c_int;
209 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
210 }
211 impl AsSyscallArg for i32 {
212 type SyscallArgType = ::libc::c_int;
213 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
214 }
215 impl AsSyscallArg for u32 {
216 type SyscallArgType = ::libc::c_uint;
217 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
218 }
219 impl AsSyscallArg for usize {
220 type SyscallArgType = ::libc::c_ulong;
221 fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ }
222 }
223
224 // On 64-bit platforms, also coerce `i64` and `u64` since `c_long`
225 // is 64-bit and can hold those values.
226 #[cfg(target_pointer_width = "64")]
227 impl AsSyscallArg for i64 {
228 type SyscallArgType = ::libc::c_long;
229 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
230 }
231 #[cfg(target_pointer_width = "64")]
232 impl AsSyscallArg for u64 {
233 type SyscallArgType = ::libc::c_ulong;
234 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
235 }
236
237 // `concat_idents` is [unstable], so we take an extra `sys_name`
238 // parameter and have our users do the concat for us for now.
239 //
240 // [unstable]: https://github.com/rust-lang/rust/issues/29599
241 /*
242 syscall(
243 concat_idents!(SYS_, $name),
244 $($arg_name.into_syscall_arg()),*
245 ) as $ret
246 */
247
248 syscall($sys_name, $($arg_name.into_syscall_arg()),*) as $ret
249 }
250 )
251}
252
253macro_rules! weakcall {
254 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
255 $vis unsafe fn $name($($arg_name: $t),*) -> $ret {
256 weak! { fn $name($($t),*) -> $ret }
257
258 // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
259 // interposition, but if it's not found just fail.
260 if let Some(fun) = $name.get() {
261 fun($($arg_name),*)
262 } else {
263 libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
264 -1
265 }
266 }
267 )
268}
269
270/// A combination of `weakcall` and `syscall`. Use the libc function if it's
271/// available, and fall back to `libc::syscall` otherwise.
272macro_rules! weak_or_syscall {
273 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
274 $vis unsafe fn $name($($arg_name: $t),*) -> $ret {
275 weak! { fn $name($($t),*) -> $ret }
276
277 // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
278 // interposition, but if it's not found just fail.
279 if let Some(fun) = $name.get() {
280 fun($($arg_name),*)
281 } else {
282 syscall! { fn $name($($arg_name: $t),*) via $sys_name -> $ret }
283 $name($($arg_name),*)
284 }
285 }
286 )
287}
288