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 = match CStr::from_bytes_with_nul(name.as_bytes()) {
140 Ok(c_str) => c_str,
141 Err(..) => return null_mut(),
142 };
143 libc::dlsym(libc::RTLD_DEFAULT, 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 trait AsSyscallArg {
171 type SyscallArgType;
172 fn into_syscall_arg(self) -> Self::SyscallArgType;
173 }
174
175 // Pass pointer types as pointers, to preserve provenance.
176 impl<T> AsSyscallArg for *mut T {
177 type SyscallArgType = *mut T;
178 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
179 }
180 impl<T> AsSyscallArg for *const T {
181 type SyscallArgType = *const T;
182 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
183 }
184
185 // Pass `BorrowedFd` values as the integer value.
186 impl AsSyscallArg for $crate::fd::BorrowedFd<'_> {
187 type SyscallArgType = ::libc::c_int;
188 fn into_syscall_arg(self) -> Self::SyscallArgType {
189 $crate::fd::AsRawFd::as_raw_fd(&self) as _
190 }
191 }
192
193 // Coerce integer values into `c_long`.
194 impl AsSyscallArg for i8 {
195 type SyscallArgType = ::libc::c_int;
196 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
197 }
198 impl AsSyscallArg for u8 {
199 type SyscallArgType = ::libc::c_int;
200 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
201 }
202 impl AsSyscallArg for i16 {
203 type SyscallArgType = ::libc::c_int;
204 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
205 }
206 impl AsSyscallArg for u16 {
207 type SyscallArgType = ::libc::c_int;
208 fn into_syscall_arg(self) -> Self::SyscallArgType { self.into() }
209 }
210 impl AsSyscallArg for i32 {
211 type SyscallArgType = ::libc::c_int;
212 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
213 }
214 impl AsSyscallArg for u32 {
215 type SyscallArgType = ::libc::c_uint;
216 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
217 }
218 impl AsSyscallArg for usize {
219 type SyscallArgType = ::libc::c_ulong;
220 fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ }
221 }
222
223 // On 64-bit platforms, also coerce `i64` and `u64` since `c_long`
224 // is 64-bit and can hold those values.
225 #[cfg(target_pointer_width = "64")]
226 impl AsSyscallArg for i64 {
227 type SyscallArgType = ::libc::c_long;
228 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
229 }
230 #[cfg(target_pointer_width = "64")]
231 impl AsSyscallArg for u64 {
232 type SyscallArgType = ::libc::c_ulong;
233 fn into_syscall_arg(self) -> Self::SyscallArgType { self }
234 }
235
236 // `concat_idents` is [unstable], so we take an extra `sys_name`
237 // parameter and have our users do the concat for us for now.
238 //
239 // [unstable]: https://github.com/rust-lang/rust/issues/29599
240 /*
241 syscall(
242 concat_idents!(SYS_, $name),
243 $($arg_name.into_syscall_arg()),*
244 ) as $ret
245 */
246
247 syscall($sys_name, $($arg_name.into_syscall_arg()),*) as $ret
248 }
249 )
250}
251
252macro_rules! weakcall {
253 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
254 $vis unsafe fn $name($($arg_name: $t),*) -> $ret {
255 weak! { fn $name($($t),*) -> $ret }
256
257 // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
258 // interposition, but if it's not found just fail.
259 if let Some(fun) = $name.get() {
260 fun($($arg_name),*)
261 } else {
262 libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
263 -1
264 }
265 }
266 )
267}
268
269/// A combination of `weakcall` and `syscall`. Use the libc function if it's
270/// available, and fall back to `libc::syscall` otherwise.
271macro_rules! weak_or_syscall {
272 ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
273 $vis unsafe fn $name($($arg_name: $t),*) -> $ret {
274 weak! { fn $name($($t),*) -> $ret }
275
276 // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
277 // interposition, but if it's not found just fail.
278 if let Some(fun) = $name.get() {
279 fun($($arg_name),*)
280 } else {
281 syscall! { fn $name($($arg_name: $t),*) via $sys_name -> $ret }
282 $name($($arg_name),*)
283 }
284 }
285 )
286}
287