Skip to content

Commit ec4b957

Browse files
authored
Fix use-libc-auxv to use a weak dependency on getauxval. (#535)
* Fix `use-libc-auxv` to use a weak dependency on `getauxval`. glibc <= 2.15 lacks `getauxval`, so avoid a strong dependency on it in the `use-libc-auxv` implementation.
1 parent 56bb421 commit ec4b957

File tree

3 files changed

+256
-14
lines changed

3 files changed

+256
-14
lines changed

src/backend/linux_raw/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
//! such as which pointers are array slices, out parameters, or in-out
1515
//! parameters, which integers are owned or borrowed file descriptors, etc.
1616
17+
// Weak symbols used by the use-libc-auxv feature for glibc 2.15 support.
18+
#[cfg(feature = "use-libc-auxv")]
19+
#[macro_use]
20+
mod weak;
21+
1722
#[macro_use]
1823
mod arch;
1924
mod conv;

src/backend/linux_raw/param/libc_auxv.rs

+23-14
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
//! This uses raw pointers to locate and read the kernel-provided auxv array.
66
#![allow(unsafe_code)]
77

8-
#[cfg(any(feature = "param", feature = "runtime"))]
9-
use super::super::c;
108
use super::super::elf::*;
119
#[cfg(feature = "param")]
1210
use crate::ffi::CStr;
1311
#[cfg(feature = "runtime")]
1412
use core::slice;
1513

14+
// `getauxval` wasn't supported in glibc until 2.16.
15+
weak!(fn getauxval(libc::c_ulong) -> *mut libc::c_void);
16+
1617
#[cfg(feature = "param")]
1718
#[inline]
1819
pub(crate) fn page_size() -> usize {
@@ -22,35 +23,39 @@ pub(crate) fn page_size() -> usize {
2223
#[cfg(feature = "param")]
2324
#[inline]
2425
pub(crate) fn clock_ticks_per_second() -> u64 {
25-
unsafe { libc::getauxval(libc::AT_CLKTCK) as u64 }
26+
unsafe { libc::sysconf(libc::_SC_CLK_TCK) as u64 }
2627
}
2728

2829
#[cfg(feature = "param")]
2930
#[inline]
3031
pub(crate) fn linux_hwcap() -> (usize, usize) {
31-
unsafe {
32-
(
33-
libc::getauxval(libc::AT_HWCAP) as usize,
34-
libc::getauxval(libc::AT_HWCAP2) as usize,
35-
)
32+
if let Some(libc_getauxval) = getauxval.get() {
33+
unsafe {
34+
let hwcap = libc_getauxval(libc::AT_HWCAP) as usize;
35+
let hwcap2 = libc_getauxval(libc::AT_HWCAP2) as usize;
36+
(hwcap, hwcap2)
37+
}
38+
} else {
39+
(0, 0)
3640
}
3741
}
3842

3943
#[cfg(feature = "param")]
4044
#[inline]
4145
pub(crate) fn linux_execfn() -> &'static CStr {
42-
unsafe {
43-
let execfn = libc::getauxval(libc::AT_EXECFN) as *const c::c_char;
44-
CStr::from_ptr(execfn.cast())
46+
if let Some(libc_getauxval) = getauxval.get() {
47+
unsafe { CStr::from_ptr(libc_getauxval(libc::AT_EXECFN).cast()) }
48+
} else {
49+
cstr!("")
4550
}
4651
}
4752

4853
#[cfg(feature = "runtime")]
4954
#[inline]
50-
pub(crate) fn exe_phdrs() -> (*const c::c_void, usize) {
55+
pub(crate) fn exe_phdrs() -> (*const libc::c_void, usize) {
5156
unsafe {
5257
(
53-
libc::getauxval(libc::AT_PHDR) as *const c::c_void,
58+
libc::getauxval(libc::AT_PHDR) as *const libc::c_void,
5459
libc::getauxval(libc::AT_PHNUM) as usize,
5560
)
5661
}
@@ -70,5 +75,9 @@ pub(in super::super) fn exe_phdrs_slice() -> &'static [Elf_Phdr] {
7075
/// so if we don't see it, this function returns a null pointer.
7176
#[inline]
7277
pub(in super::super) fn sysinfo_ehdr() -> *const Elf_Ehdr {
73-
unsafe { libc::getauxval(linux_raw_sys::general::AT_SYSINFO_EHDR.into()) as *const Elf_Ehdr }
78+
if let Some(libc_getauxval) = getauxval.get() {
79+
unsafe { libc_getauxval(linux_raw_sys::general::AT_SYSINFO_EHDR.into()) as *const Elf_Ehdr }
80+
} else {
81+
core::ptr::null()
82+
}
7483
}

src/backend/linux_raw/weak.rs

+228
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
// Implementation derived from `weak` in Rust's
2+
// library/std/src/sys/unix/weak.rs at revision
3+
// fd0cb0cdc21dd9c06025277d772108f8d42cb25f.
4+
5+
#![allow(unsafe_code)]
6+
7+
//! Support for "weak linkage" to symbols on Unix
8+
//!
9+
//! Some I/O operations we do in libstd require newer versions of OSes but we
10+
//! need to maintain binary compatibility with older releases for now. In order
11+
//! to use the new functionality when available we use this module for
12+
//! detection.
13+
//!
14+
//! One option to use here is weak linkage, but that is unfortunately only
15+
//! really workable on Linux. Hence, use dlsym to get the symbol value at
16+
//! runtime. This is also done for compatibility with older versions of glibc,
17+
//! and to avoid creating dependencies on `GLIBC_PRIVATE` symbols. It assumes
18+
//! that we've been dynamically linked to the library the symbol comes from,
19+
//! but that is currently always the case for things like libpthread/libc.
20+
//!
21+
//! A long time ago this used weak linkage for the `__pthread_get_minstack`
22+
//! symbol, but that caused Debian to detect an unnecessarily strict versioned
23+
//! dependency on libc6 (#23628).
24+
25+
// There are a variety of `#[cfg]`s controlling which targets are involved in
26+
// each instance of `weak!` and `syscall!`. Rather than trying to unify all of
27+
// that, we'll just allow that some unix targets don't use this module at all.
28+
#![allow(dead_code, unused_macros)]
29+
#![allow(clippy::doc_markdown)]
30+
31+
use crate::ffi::CStr;
32+
use core::ffi::c_void;
33+
use core::ptr::null_mut;
34+
use core::sync::atomic::{self, AtomicPtr, Ordering};
35+
use core::{marker, mem};
36+
37+
const NULL: *mut c_void = null_mut();
38+
const INVALID: *mut c_void = 1 as *mut c_void;
39+
40+
macro_rules! weak {
41+
($vis:vis fn $name:ident($($t:ty),*) -> $ret:ty) => (
42+
#[allow(non_upper_case_globals)]
43+
$vis static $name: $crate::backend::weak::Weak<unsafe extern fn($($t),*) -> $ret> =
44+
$crate::backend::weak::Weak::new(concat!(stringify!($name), '\0'));
45+
)
46+
}
47+
48+
pub(crate) struct Weak<F> {
49+
name: &'static str,
50+
addr: AtomicPtr<c_void>,
51+
_marker: marker::PhantomData<F>,
52+
}
53+
54+
impl<F> Weak<F> {
55+
pub(crate) const fn new(name: &'static str) -> Self {
56+
Self {
57+
name,
58+
addr: AtomicPtr::new(INVALID),
59+
_marker: marker::PhantomData,
60+
}
61+
}
62+
63+
pub(crate) fn get(&self) -> Option<F> {
64+
assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
65+
unsafe {
66+
// Relaxed is fine here because we fence before reading through the
67+
// pointer (see the comment below).
68+
match self.addr.load(Ordering::Relaxed) {
69+
INVALID => self.initialize(),
70+
NULL => None,
71+
addr => {
72+
let func = mem::transmute_copy::<*mut c_void, F>(&addr);
73+
// The caller is presumably going to read through this value
74+
// (by calling the function we've dlsymed). This means we'd
75+
// need to have loaded it with at least C11's consume
76+
// ordering in order to be guaranteed that the data we read
77+
// from the pointer isn't from before the pointer was
78+
// stored. Rust has no equivalent to memory_order_consume,
79+
// so we use an acquire fence (sorry, ARM).
80+
//
81+
// Now, in practice this likely isn't needed even on CPUs
82+
// where relaxed and consume mean different things. The
83+
// symbols we're loading are probably present (or not) at
84+
// init, and even if they aren't the runtime dynamic loader
85+
// is extremely likely have sufficient barriers internally
86+
// (possibly implicitly, for example the ones provided by
87+
// invoking `mprotect`).
88+
//
89+
// That said, none of that's *guaranteed*, and so we fence.
90+
atomic::fence(Ordering::Acquire);
91+
Some(func)
92+
}
93+
}
94+
}
95+
}
96+
97+
// Cold because it should only happen during first-time initialization.
98+
#[cold]
99+
unsafe fn initialize(&self) -> Option<F> {
100+
let val = fetch(self.name);
101+
// This synchronizes with the acquire fence in `get`.
102+
self.addr.store(val, Ordering::Release);
103+
104+
match val {
105+
NULL => None,
106+
addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)),
107+
}
108+
}
109+
}
110+
111+
unsafe fn fetch(name: &str) -> *mut c_void {
112+
let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
113+
Ok(c_str) => c_str,
114+
Err(..) => return null_mut(),
115+
};
116+
libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast())
117+
}
118+
119+
#[cfg(not(any(target_os = "android", target_os = "linux")))]
120+
macro_rules! syscall {
121+
(fn $name:ident($($arg_name:ident: $t:ty),*) via $_sys_name:ident -> $ret:ty) => (
122+
unsafe fn $name($($arg_name: $t),*) -> $ret {
123+
weak! { fn $name($($t),*) -> $ret }
124+
125+
if let Some(fun) = $name.get() {
126+
fun($($arg_name),*)
127+
} else {
128+
libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
129+
-1
130+
}
131+
}
132+
)
133+
}
134+
135+
#[cfg(any(target_os = "android", target_os = "linux"))]
136+
macro_rules! syscall {
137+
(fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
138+
unsafe fn $name($($arg_name:$t),*) -> $ret {
139+
// This looks like a hack, but concat_idents only accepts idents
140+
// (not paths).
141+
use libc::*;
142+
143+
trait AsSyscallArg {
144+
type SyscallArgType;
145+
fn into_syscall_arg(self) -> Self::SyscallArgType;
146+
}
147+
148+
// Pass pointer types as pointers, to preserve provenance.
149+
impl<T> AsSyscallArg for *mut T {
150+
type SyscallArgType = *mut T;
151+
fn into_syscall_arg(self) -> Self::SyscallArgType { self }
152+
}
153+
impl<T> AsSyscallArg for *const T {
154+
type SyscallArgType = *const T;
155+
fn into_syscall_arg(self) -> Self::SyscallArgType { self }
156+
}
157+
158+
// Pass `BorrowedFd` values as the integer value.
159+
impl AsSyscallArg for $crate::fd::BorrowedFd<'_> {
160+
type SyscallArgType = c::c_long;
161+
fn into_syscall_arg(self) -> Self::SyscallArgType {
162+
$crate::fd::AsRawFd::as_raw_fd(&self) as _
163+
}
164+
}
165+
166+
// Coerce integer values into `c_long`.
167+
impl AsSyscallArg for i32 {
168+
type SyscallArgType = c::c_long;
169+
fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ }
170+
}
171+
impl AsSyscallArg for u32 {
172+
type SyscallArgType = c::c_long;
173+
fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ }
174+
}
175+
impl AsSyscallArg for usize {
176+
type SyscallArgType = c::c_long;
177+
fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ }
178+
}
179+
180+
// `concat_idents is unstable, so we take an extra `sys_name`
181+
// parameter and have our users do the concat for us for now.
182+
/*
183+
syscall(
184+
concat_idents!(SYS_, $name),
185+
$($arg_name.into_syscall_arg()),*
186+
) as $ret
187+
*/
188+
189+
syscall($sys_name, $($arg_name.into_syscall_arg()),*) as $ret
190+
}
191+
)
192+
}
193+
194+
macro_rules! weakcall {
195+
($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => (
196+
$vis unsafe fn $name($($arg_name: $t),*) -> $ret {
197+
weak! { fn $name($($t),*) -> $ret }
198+
199+
// Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
200+
// interposition, but if it's not found just fail.
201+
if let Some(fun) = $name.get() {
202+
fun($($arg_name),*)
203+
} else {
204+
libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS));
205+
-1
206+
}
207+
}
208+
)
209+
}
210+
211+
/// A combination of `weakcall` and `syscall`. Use the libc function if it's
212+
/// available, and fall back to `libc::syscall` otherwise.
213+
macro_rules! weak_or_syscall {
214+
($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => (
215+
$vis unsafe fn $name($($arg_name: $t),*) -> $ret {
216+
weak! { fn $name($($t),*) -> $ret }
217+
218+
// Use a weak symbol from libc when possible, allowing `LD_PRELOAD`
219+
// interposition, but if it's not found just fail.
220+
if let Some(fun) = $name.get() {
221+
fun($($arg_name),*)
222+
} else {
223+
syscall! { fn $name($($arg_name: $t),*) via $sys_name -> $ret }
224+
$name($($arg_name),*)
225+
}
226+
}
227+
)
228+
}

0 commit comments

Comments
 (0)