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