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
35 use crate::ffi::CStr;
36 use core::ffi::c_void;
37 use core::ptr::null_mut;
38 use core::sync::atomic::{self, AtomicPtr, Ordering};
39 use core::{marker, mem};
40
41 use errno as libc_errno;
42
43 const NULL: *mut c_void = null_mut();
44 const INVALID: *mut c_void = 1 as *mut c_void;
45
46 macro_rules! weak {
47 ($vis:vis fn $name:ident($($t:ty),*) -> $ret:ty) => (
48 #[allow(non_upper_case_globals)]
49 $vis static $name: $crate::weak::Weak<unsafe extern fn($($t),*) -> $ret> =
50 $crate::weak::Weak::new(concat!(stringify!($name), '\0'));
51 )
52 }
53
54 pub(crate) struct Weak<F> {
55 name: &'static str,
56 addr: AtomicPtr<c_void>,
57 _marker: marker::PhantomData<F>,
58 }
59
60 impl<F> Weak<F> {
new(name: &'static str) -> Self61 pub(crate) const fn new(name: &'static str) -> Self {
62 Self {
63 name,
64 addr: AtomicPtr::new(INVALID),
65 _marker: marker::PhantomData,
66 }
67 }
68
get(&self) -> Option<F>69 pub(crate) fn get(&self) -> Option<F> {
70 assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
71 unsafe {
72 // Relaxed is fine here because we fence before reading through the
73 // pointer (see the comment below).
74 match self.addr.load(Ordering::Relaxed) {
75 INVALID => self.initialize(),
76 NULL => None,
77 addr => {
78 let func = mem::transmute_copy::<*mut c_void, F>(&addr);
79 // The caller is presumably going to read through this value
80 // (by calling the function we've dlsymed). This means we'd
81 // need to have loaded it with at least C11's consume
82 // ordering in order to be guaranteed that the data we read
83 // from the pointer isn't from before the pointer was
84 // stored. Rust has no equivalent to memory_order_consume,
85 // so we use an acquire fence (sorry, ARM).
86 //
87 // Now, in practice this likely isn't needed even on CPUs
88 // where relaxed and consume mean different things. The
89 // symbols we're loading are probably present (or not) at
90 // init, and even if they aren't the runtime dynamic loader
91 // is extremely likely have sufficient barriers internally
92 // (possibly implicitly, for example the ones provided by
93 // invoking `mprotect`).
94 //
95 // That said, none of that's *guaranteed*, and so we fence.
96 atomic::fence(Ordering::Acquire);
97 Some(func)
98 }
99 }
100 }
101 }
102
103 // Cold because it should only happen during first-time initialization.
104 #[cold]
initialize(&self) -> Option<F>105 unsafe fn initialize(&self) -> Option<F> {
106 let val = fetch(self.name);
107 // This synchronizes with the acquire fence in `get`.
108 self.addr.store(val, Ordering::Release);
109
110 match val {
111 NULL => None,
112 addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)),
113 }
114 }
115 }
116
117 // To avoid having the `linux_raw` backend depend on the libc crate, just
118 // declare the few things we need in a module called `libc` so that `fetch`
119 // uses it.
120 #[cfg(linux_raw)]
121 mod libc {
122 use core::ptr;
123 use linux_raw_sys::ctypes::{c_char, c_void};
124
125 #[cfg(all(target_os = "android", target_pointer_width = "32"))]
126 pub(super) const RTLD_DEFAULT: *mut c_void = -1isize as *mut c_void;
127 #[cfg(not(all(target_os = "android", target_pointer_width = "32")))]
128 pub(super) const RTLD_DEFAULT: *mut c_void = ptr::null_mut();
129
130 extern "C" {
dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void131 pub(super) fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
132 }
133
134 #[test]
test_abi()135 fn test_abi() {
136 assert_eq!(self::RTLD_DEFAULT, ::libc::RTLD_DEFAULT);
137 }
138 }
139
fetch(name: &str) -> *mut c_void140 unsafe fn fetch(name: &str) -> *mut c_void {
141 let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
142 Ok(c_str) => c_str,
143 Err(..) => return null_mut(),
144 };
145 libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast())
146 }
147
148 #[cfg(not(linux_kernel))]
149 macro_rules! syscall {
150 (fn $name:ident($($arg_name:ident: $t:ty),*) via $_sys_name:ident -> $ret:ty) => (
151 unsafe fn $name($($arg_name: $t),*) -> $ret {
152 weak! { fn $name($($t),*) -> $ret }
153
154 if let Some(fun) = $name.get() {
155 fun($($arg_name),*)
156 } else {
157 libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
158 -1
159 }
160 }
161 )
162 }
163
164 #[cfg(linux_kernel)]
165 macro_rules! syscall {
166 (fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
167 unsafe fn $name($($arg_name:$t),*) -> $ret {
168 // This looks like a hack, but `concat_idents` only accepts idents
169 // (not paths).
170 use libc::*;
171
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
254 macro_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.
273 macro_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 }
289