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