]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/weak.rs
explain mem::forget(env_lock) in fork/exec
[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::ptr;
29 use crate::sync::atomic::{self, AtomicPtr, Ordering};
30
31 // We can use true weak linkage on ELF targets.
32 #[cfg(all(not(any(target_os = "macos", target_os = "ios")), not(bootstrap)))]
33 pub(crate) macro weak {
34     (fn $name:ident($($t:ty),*) -> $ret:ty) => (
35         let ref $name: ExternWeak<unsafe extern "C" fn($($t),*) -> $ret> = {
36             extern "C" {
37                 #[linkage = "extern_weak"]
38                 static $name: Option<unsafe extern "C" fn($($t),*) -> $ret>;
39             }
40             #[allow(unused_unsafe)]
41             ExternWeak::new(unsafe { $name })
42         };
43     )
44 }
45
46 #[cfg(all(not(any(target_os = "macos", target_os = "ios")), bootstrap))]
47 pub(crate) macro weak {
48     (fn $name:ident($($t:ty),*) -> $ret:ty) => (
49         let ref $name: ExternWeak<unsafe extern "C" fn($($t),*) -> $ret> = {
50             extern "C" {
51                 #[linkage = "extern_weak"]
52                 static $name: *const libc::c_void;
53             }
54             #[allow(unused_unsafe)]
55             ExternWeak::new(unsafe { $name })
56         };
57     )
58 }
59
60 // On non-ELF targets, use the dlsym approximation of weak linkage.
61 #[cfg(any(target_os = "macos", target_os = "ios"))]
62 pub(crate) use self::dlsym as weak;
63
64 #[cfg(not(bootstrap))]
65 pub(crate) struct ExternWeak<F: Copy> {
66     weak_ptr: Option<F>,
67 }
68
69 #[cfg(not(bootstrap))]
70 impl<F: Copy> ExternWeak<F> {
71     #[inline]
72     pub(crate) fn new(weak_ptr: Option<F>) -> Self {
73         ExternWeak { weak_ptr }
74     }
75
76     #[inline]
77     pub(crate) fn get(&self) -> Option<F> {
78         self.weak_ptr
79     }
80 }
81
82 #[cfg(bootstrap)]
83 pub(crate) struct ExternWeak<F> {
84     weak_ptr: *const libc::c_void,
85     _marker: PhantomData<F>,
86 }
87
88 #[cfg(bootstrap)]
89 impl<F> ExternWeak<F> {
90     #[inline]
91     pub(crate) fn new(weak_ptr: *const libc::c_void) -> Self {
92         ExternWeak { weak_ptr, _marker: PhantomData }
93     }
94 }
95
96 #[cfg(bootstrap)]
97 impl<F> ExternWeak<F> {
98     #[inline]
99     pub(crate) fn get(&self) -> Option<F> {
100         unsafe {
101             if self.weak_ptr.is_null() {
102                 None
103             } else {
104                 Some(mem::transmute_copy::<*const libc::c_void, F>(&self.weak_ptr))
105             }
106         }
107     }
108 }
109
110 pub(crate) macro dlsym {
111     (fn $name:ident($($t:ty),*) -> $ret:ty) => (
112          dlsym!(fn $name($($t),*) -> $ret, stringify!($name));
113     ),
114     (fn $name:ident($($t:ty),*) -> $ret:ty, $sym:expr) => (
115         static DLSYM: DlsymWeak<unsafe extern "C" fn($($t),*) -> $ret> =
116             DlsymWeak::new(concat!($sym, '\0'));
117         let $name = &DLSYM;
118     )
119 }
120 pub(crate) struct DlsymWeak<F> {
121     name: &'static str,
122     func: AtomicPtr<libc::c_void>,
123     _marker: PhantomData<F>,
124 }
125
126 impl<F> DlsymWeak<F> {
127     pub(crate) const fn new(name: &'static str) -> Self {
128         DlsymWeak { name, func: AtomicPtr::new(ptr::invalid_mut(1)), _marker: PhantomData }
129     }
130
131     #[inline]
132     pub(crate) fn get(&self) -> Option<F> {
133         unsafe {
134             // Relaxed is fine here because we fence before reading through the
135             // pointer (see the comment below).
136             match self.func.load(Ordering::Relaxed) {
137                 func if func.addr() == 1 => self.initialize(),
138                 func if func.is_null() => None,
139                 func => {
140                     let func = mem::transmute_copy::<*mut libc::c_void, F>(&func);
141                     // The caller is presumably going to read through this value
142                     // (by calling the function we've dlsymed). This means we'd
143                     // need to have loaded it with at least C11's consume
144                     // ordering in order to be guaranteed that the data we read
145                     // from the pointer isn't from before the pointer was
146                     // stored. Rust has no equivalent to memory_order_consume,
147                     // so we use an acquire fence (sorry, ARM).
148                     //
149                     // Now, in practice this likely isn't needed even on CPUs
150                     // where relaxed and consume mean different things. The
151                     // symbols we're loading are probably present (or not) at
152                     // init, and even if they aren't the runtime dynamic loader
153                     // is extremely likely have sufficient barriers internally
154                     // (possibly implicitly, for example the ones provided by
155                     // invoking `mprotect`).
156                     //
157                     // That said, none of that's *guaranteed*, and so we fence.
158                     atomic::fence(Ordering::Acquire);
159                     Some(func)
160                 }
161             }
162         }
163     }
164
165     // Cold because it should only happen during first-time initialization.
166     #[cold]
167     unsafe fn initialize(&self) -> Option<F> {
168         assert_eq!(mem::size_of::<F>(), mem::size_of::<*mut libc::c_void>());
169
170         let val = fetch(self.name);
171         // This synchronizes with the acquire fence in `get`.
172         self.func.store(val, Ordering::Release);
173
174         if val.is_null() { None } else { Some(mem::transmute_copy::<*mut libc::c_void, F>(&val)) }
175     }
176 }
177
178 unsafe fn fetch(name: &str) -> *mut libc::c_void {
179     let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
180         Ok(cstr) => cstr,
181         Err(..) => return ptr::null_mut(),
182     };
183     libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr())
184 }
185
186 #[cfg(not(any(target_os = "linux", target_os = "android")))]
187 pub(crate) macro syscall {
188     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
189         unsafe fn $name($($arg_name: $t),*) -> $ret {
190             weak! { fn $name($($t),*) -> $ret }
191
192             if let Some(fun) = $name.get() {
193                 fun($($arg_name),*)
194             } else {
195                 super::os::set_errno(libc::ENOSYS);
196                 -1
197             }
198         }
199     )
200 }
201
202 #[cfg(any(target_os = "linux", target_os = "android"))]
203 pub(crate) macro syscall {
204     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
205         unsafe fn $name($($arg_name:$t),*) -> $ret {
206             weak! { fn $name($($t),*) -> $ret }
207
208             // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
209             // interposition, but if it's not found just use a raw syscall.
210             if let Some(fun) = $name.get() {
211                 fun($($arg_name),*)
212             } else {
213                 // This looks like a hack, but concat_idents only accepts idents
214                 // (not paths).
215                 use libc::*;
216
217                 syscall(
218                     concat_idents!(SYS_, $name),
219                     $($arg_name),*
220                 ) as $ret
221             }
222         }
223     )
224 }
225
226 #[cfg(any(target_os = "linux", target_os = "android"))]
227 pub(crate) macro raw_syscall {
228     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
229         unsafe fn $name($($arg_name:$t),*) -> $ret {
230             // This looks like a hack, but concat_idents only accepts idents
231             // (not paths).
232             use libc::*;
233
234             syscall(
235                 concat_idents!(SYS_, $name),
236                 $($arg_name),*
237             ) as $ret
238         }
239     )
240 }