]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/weak.rs
Rollup merge of #90704 - ijackson:exitstatus-comments, r=joshtriplett
[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 on Linux. Hence, 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).
18
19 // There are a variety of `#[cfg]`s controlling which targets are involved in
20 // each instance of `weak!` and `syscall!`. Rather than trying to unify all of
21 // that, we'll just allow that some unix targets don't use this module at all.
22 #![allow(dead_code, unused_macros)]
23
24 use crate::ffi::CStr;
25 use crate::marker;
26 use crate::mem;
27 use crate::sync::atomic::{self, AtomicUsize, Ordering};
28
29 pub(crate) macro weak {
30     (fn $name:ident($($t:ty),*) -> $ret:ty) => (
31         #[allow(non_upper_case_globals)]
32         static $name: crate::sys::weak::Weak<unsafe extern "C" fn($($t),*) -> $ret> =
33             crate::sys::weak::Weak::new(concat!(stringify!($name), '\0'));
34     )
35 }
36
37 pub struct Weak<F> {
38     name: &'static str,
39     addr: AtomicUsize,
40     _marker: marker::PhantomData<F>,
41 }
42
43 impl<F> Weak<F> {
44     pub const fn new(name: &'static str) -> Weak<F> {
45         Weak { name, addr: AtomicUsize::new(1), _marker: marker::PhantomData }
46     }
47
48     pub fn get(&self) -> Option<F> {
49         assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
50         unsafe {
51             // Relaxed is fine here because we fence before reading through the
52             // pointer (see the comment below).
53             match self.addr.load(Ordering::Relaxed) {
54                 1 => self.initialize(),
55                 0 => None,
56                 addr => {
57                     let func = mem::transmute_copy::<usize, F>(&addr);
58                     // The caller is presumably going to read through this value
59                     // (by calling the function we've dlsymed). This means we'd
60                     // need to have loaded it with at least C11's consume
61                     // ordering in order to be guaranteed that the data we read
62                     // from the pointer isn't from before the pointer was
63                     // stored. Rust has no equivalent to memory_order_consume,
64                     // so we use an acquire fence (sorry, ARM).
65                     //
66                     // Now, in practice this likely isn't needed even on CPUs
67                     // where relaxed and consume mean different things. The
68                     // symbols we're loading are probably present (or not) at
69                     // init, and even if they aren't the runtime dynamic loader
70                     // is extremely likely have sufficient barriers internally
71                     // (possibly implicitly, for example the ones provided by
72                     // invoking `mprotect`).
73                     //
74                     // That said, none of that's *guaranteed*, and so we fence.
75                     atomic::fence(Ordering::Acquire);
76                     Some(func)
77                 }
78             }
79         }
80     }
81
82     // Cold because it should only happen during first-time initalization.
83     #[cold]
84     unsafe fn initialize(&self) -> Option<F> {
85         let val = fetch(self.name);
86         // This synchronizes with the acquire fence in `get`.
87         self.addr.store(val, Ordering::Release);
88
89         match val {
90             0 => None,
91             addr => Some(mem::transmute_copy::<usize, F>(&addr)),
92         }
93     }
94 }
95
96 unsafe fn fetch(name: &str) -> usize {
97     let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
98         Ok(cstr) => cstr,
99         Err(..) => return 0,
100     };
101     libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize
102 }
103
104 #[cfg(not(any(target_os = "linux", target_os = "android")))]
105 pub(crate) macro syscall {
106     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
107         unsafe fn $name($($arg_name: $t),*) -> $ret {
108             use super::os;
109
110             weak! { fn $name($($t),*) -> $ret }
111
112             if let Some(fun) = $name.get() {
113                 fun($($arg_name),*)
114             } else {
115                 os::set_errno(libc::ENOSYS);
116                 -1
117             }
118         }
119     )
120 }
121
122 #[cfg(any(target_os = "linux", target_os = "android"))]
123 pub(crate) macro syscall {
124     (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
125         unsafe fn $name($($arg_name:$t),*) -> $ret {
126             use weak;
127             // This looks like a hack, but concat_idents only accepts idents
128             // (not paths).
129             use libc::*;
130
131             weak! { fn $name($($t),*) -> $ret }
132
133             // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
134             // interposition, but if it's not found just use a raw syscall.
135             if let Some(fun) = $name.get() {
136                 fun($($arg_name),*)
137             } else {
138                 syscall(
139                     concat_idents!(SYS_, $name),
140                     $($arg_name),*
141                 ) as $ret
142             }
143         }
144     )
145 }