std/sys/pal/unix/
weak.rs

1//! Support for "weak linkage" to symbols on Unix
2//!
3//! Some I/O operations we do in std require newer versions of OSes but we need
4//! to maintain binary compatibility with older releases for now. In order to
5//! use the new functionality when available we use this module for detection.
6//!
7//! One option to use here is weak linkage, but that is unfortunately only
8//! really workable with ELF. Otherwise, use dlsym to get the symbol value at
9//! runtime. This is also done for compatibility with older versions of glibc,
10//! and to avoid creating dependencies on GLIBC_PRIVATE symbols. It assumes that
11//! we've been dynamically linked to the library the symbol comes from, but that
12//! is currently always the case for things like libpthread/libc.
13//!
14//! A long time ago this used weak linkage for the __pthread_get_minstack
15//! symbol, but that caused Debian to detect an unnecessarily strict versioned
16//! dependency on libc6 (#23628) because it is GLIBC_PRIVATE. We now use `dlsym`
17//! for a runtime lookup of that symbol to avoid the ELF versioned dependency.
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
24use crate::ffi::CStr;
25use crate::marker::PhantomData;
26use crate::sync::atomic::{self, AtomicPtr, Ordering};
27use crate::{mem, ptr};
28
29// We can use true weak linkage on ELF targets.
30#[cfg(all(unix, not(target_vendor = "apple")))]
31pub(crate) macro weak {
32    (fn $name:ident($($param:ident : $t:ty),* $(,)?) -> $ret:ty;) => (
33        let ref $name: ExternWeak<unsafe extern "C" fn($($t),*) -> $ret> = {
34            unsafe extern "C" {
35                #[linkage = "extern_weak"]
36                static $name: Option<unsafe extern "C" fn($($t),*) -> $ret>;
37            }
38            #[allow(unused_unsafe)]
39            ExternWeak::new(unsafe { $name })
40        };
41    )
42}
43
44// On non-ELF targets, use the dlsym approximation of weak linkage.
45#[cfg(target_vendor = "apple")]
46pub(crate) use self::dlsym as weak;
47
48pub(crate) struct ExternWeak<F: Copy> {
49    weak_ptr: Option<F>,
50}
51
52impl<F: Copy> ExternWeak<F> {
53    #[inline]
54    pub(crate) fn new(weak_ptr: Option<F>) -> Self {
55        ExternWeak { weak_ptr }
56    }
57
58    #[inline]
59    pub(crate) fn get(&self) -> Option<F> {
60        self.weak_ptr
61    }
62}
63
64pub(crate) macro dlsym {
65    (fn $name:ident($($param:ident : $t:ty),* $(,)?) -> $ret:ty;) => (
66         dlsym!(
67            #[link_name = stringify!($name)]
68            fn $name($($param : $t),*) -> $ret;
69        );
70    ),
71    (
72        #[link_name = $sym:expr]
73        fn $name:ident($($param:ident : $t:ty),* $(,)?) -> $ret:ty;
74    ) => (
75        static DLSYM: DlsymWeak<unsafe extern "C" fn($($t),*) -> $ret> =
76            DlsymWeak::new(concat!($sym, '\0'));
77        let $name = &DLSYM;
78    )
79}
80pub(crate) struct DlsymWeak<F> {
81    name: &'static str,
82    func: AtomicPtr<libc::c_void>,
83    _marker: PhantomData<F>,
84}
85
86impl<F> DlsymWeak<F> {
87    pub(crate) const fn new(name: &'static str) -> Self {
88        DlsymWeak {
89            name,
90            func: AtomicPtr::new(ptr::without_provenance_mut(1)),
91            _marker: PhantomData,
92        }
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.func.load(Ordering::Relaxed) {
101                func if func.addr() == 1 => self.initialize(),
102                func if func.is_null() => None,
103                func => {
104                    let func = mem::transmute_copy::<*mut libc::c_void, F>(&func);
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!(size_of::<F>(), size_of::<*mut libc::c_void>());
133
134        let val = fetch(self.name);
135        // This synchronizes with the acquire fence in `get`.
136        self.func.store(val, Ordering::Release);
137
138        if val.is_null() { None } else { Some(mem::transmute_copy::<*mut libc::c_void, F>(&val)) }
139    }
140}
141
142unsafe fn fetch(name: &str) -> *mut libc::c_void {
143    let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
144        Ok(cstr) => cstr,
145        Err(..) => return ptr::null_mut(),
146    };
147    libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr())
148}
149
150#[cfg(not(any(target_os = "linux", target_os = "android")))]
151pub(crate) macro syscall {
152    (fn $name:ident($($param:ident : $t:ty),* $(,)?) -> $ret:ty;) => (
153        // FIXME(#115199): Rust currently omits weak function definitions
154        // and its metadata from LLVM IR.
155        #[no_sanitize(cfi)]
156        unsafe fn $name($($param: $t),*) -> $ret {
157            weak!(fn $name($($param: $t),*) -> $ret;);
158
159            if let Some(fun) = $name.get() {
160                fun($($param),*)
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"))]
170pub(crate) macro syscall {
171    (
172        fn $name:ident($($param:ident : $t:ty),* $(,)?) -> $ret:ty;
173    ) => (
174        unsafe fn $name($($param: $t),*) -> $ret {
175            weak!(fn $name($($param: $t),*) -> $ret;);
176
177            // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
178            // interposition, but if it's not found just use a raw syscall.
179            if let Some(fun) = $name.get() {
180                fun($($param),*)
181            } else {
182                libc::syscall(libc::${concat(SYS_, $name)}, $($param),*) as $ret
183            }
184        }
185    )
186}
187
188#[cfg(any(target_os = "linux", target_os = "android"))]
189pub(crate) macro raw_syscall {
190    (fn $name:ident($($param:ident : $t:ty),* $(,)?) -> $ret:ty;) => (
191        unsafe fn $name($($param: $t),*) -> $ret {
192            libc::syscall(libc::${concat(SYS_, $name)}, $($param),*) as $ret
193        }
194    )
195}