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 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.
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).
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)]
27 use crate::sync::atomic::{AtomicUsize, Ordering};
30 (fn $name:ident($($t:ty),*) -> $ret:ty) => (
31 static $name: crate::sys::weak::Weak<unsafe extern fn($($t),*) -> $ret> =
32 crate::sys::weak::Weak::new(concat!(stringify!($name), '\0'));
39 _marker: marker::PhantomData<F>,
43 pub const fn new(name: &'static str) -> Weak<F> {
44 Weak { name, addr: AtomicUsize::new(1), _marker: marker::PhantomData }
47 pub fn get(&self) -> Option<F> {
48 assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
50 if self.addr.load(Ordering::SeqCst) == 1 {
51 self.addr.store(fetch(self.name), Ordering::SeqCst);
53 match self.addr.load(Ordering::SeqCst) {
55 addr => Some(mem::transmute_copy::<usize, F>(&addr)),
61 unsafe fn fetch(name: &str) -> usize {
62 let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
66 libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize
69 #[cfg(not(target_os = "linux"))]
70 macro_rules! syscall {
71 (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
72 unsafe fn $name($($arg_name: $t),*) -> $ret {
75 weak! { fn $name($($t),*) -> $ret }
77 if let Some(fun) = $name.get() {
80 os::set_errno(libc::ENOSYS);
87 #[cfg(target_os = "linux")]
88 macro_rules! syscall {
89 (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
90 unsafe fn $name($($arg_name:$t),*) -> $ret {
91 // This looks like a hack, but concat_idents only accepts idents
96 concat_idents!(SYS_, $name),
97 $($arg_name as c_long),*