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