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).
22 use crate::sync::atomic::{AtomicUsize, Ordering};
25 (fn $name:ident($($t:ty),*) -> $ret:ty) => (
26 static $name: crate::sys::weak::Weak<unsafe extern fn($($t),*) -> $ret> =
27 crate::sys::weak::Weak::new(concat!(stringify!($name), '\0'));
34 _marker: marker::PhantomData<F>,
38 pub const fn new(name: &'static str) -> Weak<F> {
41 addr: AtomicUsize::new(1),
42 _marker: marker::PhantomData,
46 pub fn get(&self) -> Option<F> {
47 assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
49 if self.addr.load(Ordering::SeqCst) == 1 {
50 self.addr.store(fetch(self.name), Ordering::SeqCst);
52 match self.addr.load(Ordering::SeqCst) {
54 addr => Some(mem::transmute_copy::<usize, F>(&addr)),
60 unsafe fn fetch(name: &str) -> usize {
61 let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
65 libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize
68 #[cfg(not(target_os = "linux"))]
69 macro_rules! syscall {
70 (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
71 unsafe fn $name($($arg_name: $t),*) -> $ret {
74 weak! { fn $name($($t),*) -> $ret }
76 if let Some(fun) = $name.get() {
79 os::set_errno(libc::ENOSYS);
86 #[cfg(target_os = "linux")]
87 macro_rules! syscall {
88 (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
89 unsafe fn $name($($arg_name:$t),*) -> $ret {
90 // This looks like a hack, but concat_idents only accepts idents
95 concat_idents!(SYS_, $name),
96 $($arg_name as c_long),*