1 //! Support for "weak linkage" to symbols on Unix
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
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.
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.
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)]
26 use crate::marker::PhantomData;
29 use crate::sync::atomic::{self, AtomicPtr, Ordering};
31 // We can use true weak linkage on ELF targets.
32 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
33 pub(crate) macro weak {
34 (fn $name:ident($($t:ty),*) -> $ret:ty) => (
35 let ref $name: ExternWeak<unsafe extern "C" fn($($t),*) -> $ret> = {
37 #[linkage = "extern_weak"]
38 static $name: Option<unsafe extern "C" fn($($t),*) -> $ret>;
40 #[allow(unused_unsafe)]
41 ExternWeak::new(unsafe { $name })
46 // On non-ELF targets, use the dlsym approximation of weak linkage.
47 #[cfg(any(target_os = "macos", target_os = "ios"))]
48 pub(crate) use self::dlsym as weak;
50 pub(crate) struct ExternWeak<F: Copy> {
54 impl<F: Copy> ExternWeak<F> {
56 pub(crate) fn new(weak_ptr: Option<F>) -> Self {
57 ExternWeak { weak_ptr }
61 pub(crate) fn get(&self) -> Option<F> {
66 pub(crate) macro dlsym {
67 (fn $name:ident($($t:ty),*) -> $ret:ty) => (
68 dlsym!(fn $name($($t),*) -> $ret, stringify!($name));
70 (fn $name:ident($($t:ty),*) -> $ret:ty, $sym:expr) => (
71 static DLSYM: DlsymWeak<unsafe extern "C" fn($($t),*) -> $ret> =
72 DlsymWeak::new(concat!($sym, '\0'));
76 pub(crate) struct DlsymWeak<F> {
78 func: AtomicPtr<libc::c_void>,
79 _marker: PhantomData<F>,
82 impl<F> DlsymWeak<F> {
83 pub(crate) const fn new(name: &'static str) -> Self {
84 DlsymWeak { name, func: AtomicPtr::new(ptr::invalid_mut(1)), _marker: PhantomData }
88 pub(crate) fn get(&self) -> Option<F> {
90 // Relaxed is fine here because we fence before reading through the
91 // pointer (see the comment below).
92 match self.func.load(Ordering::Relaxed) {
93 func if func.addr() == 1 => self.initialize(),
94 func if func.is_null() => None,
96 let func = mem::transmute_copy::<*mut libc::c_void, F>(&func);
97 // The caller is presumably going to read through this value
98 // (by calling the function we've dlsymed). This means we'd
99 // need to have loaded it with at least C11's consume
100 // ordering in order to be guaranteed that the data we read
101 // from the pointer isn't from before the pointer was
102 // stored. Rust has no equivalent to memory_order_consume,
103 // so we use an acquire fence (sorry, ARM).
105 // Now, in practice this likely isn't needed even on CPUs
106 // where relaxed and consume mean different things. The
107 // symbols we're loading are probably present (or not) at
108 // init, and even if they aren't the runtime dynamic loader
109 // is extremely likely have sufficient barriers internally
110 // (possibly implicitly, for example the ones provided by
111 // invoking `mprotect`).
113 // That said, none of that's *guaranteed*, and so we fence.
114 atomic::fence(Ordering::Acquire);
121 // Cold because it should only happen during first-time initialization.
123 unsafe fn initialize(&self) -> Option<F> {
124 assert_eq!(mem::size_of::<F>(), mem::size_of::<*mut libc::c_void>());
126 let val = fetch(self.name);
127 // This synchronizes with the acquire fence in `get`.
128 self.func.store(val, Ordering::Release);
130 if val.is_null() { None } else { Some(mem::transmute_copy::<*mut libc::c_void, F>(&val)) }
134 unsafe fn fetch(name: &str) -> *mut libc::c_void {
135 let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
137 Err(..) => return ptr::null_mut(),
139 libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr())
142 #[cfg(not(any(target_os = "linux", target_os = "android")))]
143 pub(crate) macro syscall {
144 (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
145 unsafe fn $name($($arg_name: $t),*) -> $ret {
146 weak! { fn $name($($t),*) -> $ret }
148 if let Some(fun) = $name.get() {
151 super::os::set_errno(libc::ENOSYS);
158 #[cfg(any(target_os = "linux", target_os = "android"))]
159 pub(crate) macro syscall {
160 (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
161 unsafe fn $name($($arg_name:$t),*) -> $ret {
162 weak! { fn $name($($t),*) -> $ret }
164 // Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
165 // interposition, but if it's not found just use a raw syscall.
166 if let Some(fun) = $name.get() {
169 // This looks like a hack, but concat_idents only accepts idents
174 concat_idents!(SYS_, $name),
182 #[cfg(any(target_os = "linux", target_os = "android"))]
183 pub(crate) macro raw_syscall {
184 (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
185 unsafe fn $name($($arg_name:$t),*) -> $ret {
186 // This looks like a hack, but concat_idents only accepts idents
191 concat_idents!(SYS_, $name),