]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/weak.rs
Rollup merge of #92366 - jhpratt:derive-default-enum, r=Mark-Simulacrum
[rust.git] / library / std / src / sys / unix / weak.rs
1 //! Support for "weak linkage" to symbols on Unix
2 //!
3 //! Some I/O operations we do in libstd require newer versions of OSes but we
4 //! need to maintain binary compatibility with older releases for now. In order
5 //! to use the new functionality when available we use this module for
6 //! detection.
7 //!
8 //! One option to use here is weak linkage, but that is unfortunately only
9 //! really workable with ELF. Otherwise, use dlsym to get the symbol value at
10 //! runtime. This is also done for compatibility with older versions of glibc,
11 //! and to avoid creating dependencies on GLIBC_PRIVATE symbols. It assumes that
12 //! we've been dynamically linked to the library the symbol comes from, but that
13 //! is currently always the case for things like libpthread/libc.
14 //!
15 //! A long time ago this used weak linkage for the __pthread_get_minstack
16 //! symbol, but that caused Debian to detect an unnecessarily strict versioned
17 //! dependency on libc6 (#23628) because it is GLIBC_PRIVATE. We now use `dlsym`
18 //! for a runtime lookup of that symbol to avoid the ELF versioned dependency.
19
20 // There are a variety of `#[cfg]`s controlling which targets are involved in
21 // each instance of `weak!` and `syscall!`. Rather than trying to unify all of
22 // that, we'll just allow that some unix targets don't use this module at all.
23 #![allow(dead_code, unused_macros)]
24
25 use crate::ffi::CStr;
26 use crate::marker::PhantomData;
27 use crate::mem;
28 use crate::sync::atomic::{self, AtomicUsize, Ordering};
29
30 // We can use true weak linkage on ELF targets.
31 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
32 pub(crate) macro weak {
33     (fn $name:ident($($t:ty),*) -> $ret:ty) => (
34         let ref $name: ExternWeak<unsafe extern "C" fn($($t),*) -> $ret> = {
35             extern "C" {
36                 #[linkage = "extern_weak"]
37                 static $name: *const libc::c_void;
38             }
39             #[allow(unused_unsafe)]
40             ExternWeak::new(unsafe { $name })
41         };
42     )
43 }
44
45 // On non-ELF targets, use the dlsym approximation of weak linkage.
46 #[cfg(any(target_os = "macos", target_os = "ios"))]
47 pub(crate) use self::dlsym as weak;
48
49 pub(crate) struct ExternWeak<F> {
50     weak_ptr: *const libc::c_void,
51     _marker: PhantomData<F>,
52 }
53
54 impl<F> ExternWeak<F> {
55     #[inline]
56     pub(crate) fn new(weak_ptr: *const libc::c_void) -> Self {
57         ExternWeak { weak_ptr, _marker: PhantomData }
58     }
59 }
60
61 impl<F> ExternWeak<F> {
62     #[inline]
63     pub(crate) fn get(&self) -> Option<F> {
64         unsafe {
65             if self.weak_ptr.is_null() {
66                 None
67             } else {
68                 Some(mem::transmute_copy::<*const libc::c_void, F>(&self.weak_ptr))
69             }
70         }
71     }
72 }
73
74 pub(crate) macro dlsym {
75     (fn $name:ident($($t:ty),*) -> $ret:ty) => (
76          dlsym!(fn $name($($t),*) -> $ret, stringify!($name));
77     ),
78     (fn $name:ident($($t:ty),*) -> $ret:ty, $sym:expr) => (
79         static DLSYM: DlsymWeak<unsafe extern "C" fn($($t),*) -> $ret> =
80             DlsymWeak::new(concat!($sym, '\0'));
81         let $name = &DLSYM;
82     )
83 }
84 pub(crate) struct DlsymWeak<F> {
85     name: &'static str,
86     addr: AtomicUsize,
87     _marker: PhantomData<F>,
88 }
89
90 impl<F> DlsymWeak<F> {
91     pub(crate) const fn new(name: &'static str) -> Self {
92         DlsymWeak { name, addr: AtomicUsize::new(1), _marker: PhantomData }
93     }
94
95     #[inline]
96     pub(crate) fn get(&self) -> Option<F> {
97         unsafe {
98             // Relaxed is fine here because we fence before reading through the
99             // pointer (see the comment below).
100             match self.addr.load(Ordering::Relaxed) {
101                 1 => self.initialize(),
102                 0 => None,
103                 addr => {
104                     let func = mem::transmute_copy::<usize, F>(&addr);
105                     // The caller is presumably going to read through this value
106                     // (by calling the function we've dlsymed). This means we'd
107                     // need to have loaded it with at least C11's consume
108                     // ordering in order to be guaranteed that the data we read
109                     // from the pointer isn't from before the pointer was
110                     // stored. Rust has no equivalent to memory_order_consume,
111                     // so we use an acquire fence (sorry, ARM).
112                     //
113                     // Now, in practice this likely isn't needed even on CPUs
114                     // where relaxed and consume mean different things. The
115                     // symbols we're loading are probably present (or not) at
116                     // init, and even if they aren't the runtime dynamic loader
117                     // is extremely likely have sufficient barriers internally
118                     // (possibly implicitly, for example the ones provided by
119                     // invoking `mprotect`).
120                     //
121                     // That said, none of that's *guaranteed*, and so we fence.
122                     atomic::fence(Ordering::Acquire);
123                     Some(func)
124                 }
125             }
126         }
127     }
128
129     // Cold because it should only happen during first-time initialization.
130     #[cold]
131     unsafe fn initialize(&self) -> Option<F> {
132         assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
133
134         let val = fetch(self.name);
135         // This synchronizes with the acquire fence in `get`.
136         self.addr.store(val, Ordering::Release);
137
138         match val {
139             0 => None,
140             addr => Some(mem::transmute_copy::<usize, F>(&addr)),
141         }
142     }
143 }
144
145 unsafe fn fetch(name: &str) -> usize {
146     let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
147         Ok(cstr) => cstr,
148         Err(..) => return 0,
149     };
150     libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize
151 }
152
153 #[cfg(not(any(target_os = "linux", target_os = "android")))]
154 pub(crate) macro syscall {
155     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
156         unsafe fn $name($($arg_name: $t),*) -> $ret {
157             weak! { fn $name($($t),*) -> $ret }
158
159             if let Some(fun) = $name.get() {
160                 fun($($arg_name),*)
161             } else {
162                 super::os::set_errno(libc::ENOSYS);
163                 -1
164             }
165         }
166     )
167 }
168
169 #[cfg(any(target_os = "linux", target_os = "android"))]
170 pub(crate) macro syscall {
171     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
172         unsafe fn $name($($arg_name:$t),*) -> $ret {
173             weak! { fn $name($($t),*) -> $ret }
174
175             // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
176             // interposition, but if it's not found just use a raw syscall.
177             if let Some(fun) = $name.get() {
178                 fun($($arg_name),*)
179             } else {
180                 // This looks like a hack, but concat_idents only accepts idents
181                 // (not paths).
182                 use libc::*;
183
184                 syscall(
185                     concat_idents!(SYS_, $name),
186                     $($arg_name),*
187                 ) as $ret
188             }
189         }
190     )
191 }
192
193 #[cfg(any(target_os = "linux", target_os = "android"))]
194 pub(crate) macro raw_syscall {
195     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
196         unsafe fn $name($($arg_name:$t),*) -> $ret {
197             // This looks like a hack, but concat_idents only accepts idents
198             // (not paths).
199             use libc::*;
200
201             syscall(
202                 concat_idents!(SYS_, $name),
203                 $($arg_name),*
204             ) as $ret
205         }
206     )
207 }