Debian Codegraph @

debian/rust-vendor/portable-atomic/src/imp/detect/auxv.rs

raw
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 /*
4 Run-time CPU feature detection on AArch64/Arm/PowerPC64 Linux/Android/FreeBSD/OpenBSD by parsing ELF auxiliary vectors.
5
6 Supported platforms:
7 - Linux 6.4+ (through prctl)
8 https://github.com/torvalds/linux/commit/ddc65971bb677aa9f6a4c21f76d3133e106f88eb
9 prctl returns an unsupported error if operation is not supported,
10 so we can safely use this on older versions.
11 - glibc 2.16+ (through getauxval)
12 https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;hb=glibc-2.16#l83
13 Always available on:
14 - aarch64 (glibc 2.17+ https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;hb=glibc-2.17#l36)
15 - powerpc64 (le) (glibc 2.19+ or RHEL/CentOS's patched glibc 2.17+ https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;hb=glibc-2.19#l108)
16 Not always available on:
17 - arm (glibc 2.1+ https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;hb=glibc-2.1#l97)
18 - powerpc64 (be) (glibc 2.3+ https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;hb=glibc-2.3#l56)
19 Since Rust 1.64, std requires glibc 2.17+ https://blog.rust-lang.org/2022/08/01/Increasing-glibc-kernel-requirements
20 - musl 1.1.0+ (through getauxval)
21 https://git.musl-libc.org/cgit/musl/tree/WHATSNEW?h=v1.1.0#n1197
22 Always available on:
23 - aarch64 (musl 1.1.7+ https://git.musl-libc.org/cgit/musl/tree/WHATSNEW?h=v1.1.7#n1422)
24 - powerpc64 (musl 1.1.15+ https://git.musl-libc.org/cgit/musl/tree/WHATSNEW?h=v1.1.15#n1702)
25 Not always available on:
26 - arm (musl 0.8.3+ https://git.musl-libc.org/cgit/musl/tree/WHATSNEW?h=v0.8.3#n354)
27 At least since Rust 1.15, std requires musl 1.1.14+ https://github.com/rust-lang/rust/blob/1.15.0/src/ci/docker/x86_64-musl/build-musl.sh#L15
28 Since Rust 1.18, std requires musl 1.1.16+ https://github.com/rust-lang/rust/pull/41089
29 Since Rust 1.23, std requires musl 1.1.17+ https://github.com/rust-lang/rust/pull/45393
30 Since Rust 1.25, std requires musl 1.1.18+ https://github.com/rust-lang/rust/pull/47283
31 Since Rust 1.29, std requires musl 1.1.19+ https://github.com/rust-lang/rust/pull/52087
32 Since Rust 1.31, std requires musl 1.1.20+ https://github.com/rust-lang/rust/pull/54430
33 Since Rust 1.37, std requires musl 1.1.22+ https://github.com/rust-lang/rust/pull/61252
34 Since Rust 1.46, std requires musl 1.1.24+ https://github.com/rust-lang/rust/pull/73089
35 Since Rust 1.71, std requires musl 1.2.3+ https://blog.rust-lang.org/2023/05/09/Updating-musl-targets
36 Since Rust 1.93, std requires musl 1.2.5+ https://blog.rust-lang.org/2025/12/05/Updating-musl-1.2.5/
37 OpenHarmony uses a fork of musl 1.2 https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/native-lib/musl.md
38 - uClibc-ng 1.0.43+ (through getauxval)
39 https://github.com/wbx-github/uclibc-ng/commit/d869bb1600942c01a77539128f9ba5b5b55ad647
40 Not always available on:
41 - aarch64 (uClibc-ng 1.0.22+ https://github.com/wbx-github/uclibc-ng/commit/dba942c80dc2cfa5768a856fff98e22a755fdd27)
42 - arm (uClibc-ng 1.0.0+ https://github.com/wbx-github/uclibc-ng/tree/v1.0.0/libc/sysdeps/linux)
43 (powerpc64 is not supported https://github.com/wbx-github/uclibc-ng/commit/d4d4f37fda7fa57e57132ff2f0d735ce7cc2178e)
44 - Picolibc 1.4.6+ (through getauxval)
45 https://github.com/picolibc/picolibc/commit/19bfe51d62ad7e32533c7f664b5bca8e26286e31
46 The implementation always return 0 (as of 1.8.12): https://github.com/picolibc/picolibc/blob/1.8.12/libc/misc/getauxval.c
47 - Android 4.3+ (API level 18+) (through getauxval)
48 https://android.googlesource.com/platform/bionic.git/+/2c5153b043b44e9935a334ae9b2d5a4bc5258b40
49 https://android.googlesource.com/platform/bionic.git/+/655e430b28d7404f763e7ebefe84fba5a387666d
50 Always available on:
51 - 64-bit architectures (Android 5.0+ (API level 21+) https://android-developers.googleblog.com/2014/10/whats-new-in-android-50-lollipop.html)
52 Not always available on:
53 - arm
54 Since Rust 1.68, std requires API level 19+ https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25
55 Since Rust 1.82, std requires API level 21+ https://github.com/rust-lang/rust/pull/120593
56 - FreeBSD 12.0+ and 11.4+ (through elf_aux_info)
57 https://github.com/freebsd/freebsd-src/commit/0b08ae2120cdd08c20a2b806e2fcef4d0a36c470
58 https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/sys/auxv.h
59 Always available on:
60 - arm (v7) (FreeBSD 12.0+ https://www.freebsd.org/releases/12.0R/announce, https://man.freebsd.org/cgi/man.cgi?arch)
61 - powerpc64 (le) (FreeBSD 12.4+ https://www.freebsd.org/releases/12.4R/announce, https://man.freebsd.org/cgi/man.cgi?arch)
62 Not always available on:
63 - aarch64 (FreeBSD 11.0+ https://www.freebsd.org/releases/11.0R/announce, https://man.freebsd.org/cgi/man.cgi?arch)
64 - arm (v6) (FreeBSD 10.1+ https://www.freebsd.org/releases/10.1R/announce, https://man.freebsd.org/cgi/man.cgi?arch)
65 - powerpc64 (be) (FreeBSD 9.0+ https://www.freebsd.org/releases/9.0R/announce, https://man.freebsd.org/cgi/man.cgi?arch)
66 Since Rust 1.75, std requires FreeBSD 12+ https://github.com/rust-lang/rust/pull/114521
67 Since Rust 1.97, std requires FreeBSD 14+ https://github.com/rust-lang/rust/pull/156607
68 - OpenBSD 7.6+ (through elf_aux_info)
69 https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d
70 Not always available on:
71 - aarch64 (OpenBSD 6.1+ https://www.openbsd.org/61.html)
72 - arm (OpenBSD 6.0+ https://www.openbsd.org/60.html)
73 - powerpc64 (OpenBSD 6.8+ https://www.openbsd.org/68.html)
74
75 On L4Re which uses uClibc-ng, a dummy getauxval was added first in 2020 that always returns 0 (https://github.com/kernkonzept/l4re-core/commit/e88fa67198074d3e6b4983c5c8af1538e2089ff3),
76 then implemented in 2024 (https://github.com/kernkonzept/l4re-core/commit/3ee2a50dd1b3bc22955e593004990887a0a5b4a3).
77 However, getauxval(AT_HWCAP*) always returns 0 (as of 2025-12-25). (see tests/l4re test)
78 On Redox, getauxval is available since 0.5.0 (https://github.com/redox-os/relibc/commit/f9f752d74c4f1f56a89c0fcdd5cab63d2380fe09),
79 but the implementation always return 0 (as of 2026-08-08): https://github.com/redox-os/relibc/blob/49aeb9470a885030ed43a70d0b708f3caec19478/src/header/sys_auxv/mod.rs
80
81 On platforms that we can assume that getauxval/elf_aux_info is always available, we directly call
82 them on except for musl with static linking. (At this time, we also retain compatibility with
83 versions that reached EoL or no longer supported by `std`, with the exception of AArch64 FreeBSD described below.)
84
85 On musl with static linking, it seems that getauxval is not always available, independent of version
86 requirements: https://github.com/rust-lang/rust/issues/89626
87 (That problem may have been fixed in https://github.com/rust-lang/rust/commit/9a04ae4997493e9260352064163285cddc43de3c,
88 but even in the version containing that patch, [there is report](https://github.com/rust-lang/rust/issues/89626#issuecomment-1242636038)
89 of the same error.)
90 This seems to be due to the fact that compiler-builtins is built before libc (which is a dependency
91 of std) links musl. And the std and its dependent can use getauxval without this problem at least
92 since the rust-lang/rust patch mentioned above:
93 https://github.com/rust-lang/rust/blob/1.85.0/library/std/src/sys/pal/unix/stack_overflow.rs#L268
94 (According to https://github.com/rust-lang/rust/issues/89626#issuecomment-2420469392, this problem
95 may have been fixed in https://github.com/rust-lang/rust/commit/9ed0d11efbec18a1fa4155576a3bcb685676d23c.)
96 See also https://github.com/rust-lang/stdarch/pull/1746.
97 So as for musl with static linking, we assume that getauxval is always available also when `std` feature enabled.
98
99 On platforms that we cannot assume that getauxval/elf_aux_info is always available, so we use dlsym
100 instead of directly calling getauxval/elf_aux_info. (You can force getauxval/elf_aux_info to be
101 called directly instead of using dlsym by `--cfg portable_atomic_outline_atomics`).
102
103 Also, note that dlsym usually not working with static linking.
104
105 # Linux/Android
106
107 As of Rust 1.69, is_aarch64_feature_detected always uses dlsym by default
108 on AArch64 Linux/Android, but on some platforms, we can safely assume
109 getauxval is linked to the binary (see the above).
110
111 See also https://github.com/rust-lang/stdarch/pull/1375
112
113 See tests::test_alternative and aarch64_aa64reg.rs for (test-only) alternative implementations.
114
115 # FreeBSD
116
117 As of Rust 1.94, is_aarch64_feature_detected always uses mrs on
118 AArch64 FreeBSD. However, they do not work on FreeBSD 12 on QEMU (confirmed
119 on FreeBSD 12.{2,3,4}), and we got SIGILL (worked on FreeBSD 13 and 14).
120
121 So use elf_aux_info instead of mrs like compiler-rt does.
122 https://reviews.llvm.org/D109330
123
124 elf_aux_info is available on FreeBSD 12.0+ and 11.4+:
125 https://github.com/freebsd/freebsd-src/commit/0b08ae2120cdd08c20a2b806e2fcef4d0a36c470
126 https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/sys/auxv.h
127 On FreeBSD, [AArch64 support is available on FreeBSD 11.0+](https://www.freebsd.org/releases/11.0R/announce),
128 but FreeBSD 11 (11.4) was EoL on 2021-09-30, and FreeBSD 11.3 was EoL on 2020-09-30:
129 https://www.freebsd.org/security/unsupported
130 See also https://github.com/rust-lang/stdarch/pull/611#issuecomment-445464613
131
132 See tests::test_alternative and aarch64_aa64reg.rs for (test-only) alternative implementations.
133
134 # OpenBSD
135
136 elf_aux_info is available on OpenBSD 7.6+:
137 https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d
138
139 On AArch64, there is an alternative that available on older version,
140 so we use it (see aarch64_aa64reg.rs).
141
142 */
143
144 include!("common.rs");
145
146 use self::os::ffi;
147 #[cfg(any(target_os = "linux", target_os = "android"))]
148 mod os {
149 // libc requires Rust 1.63
150 #[cfg_attr(test, allow(dead_code))]
151 pub(super) mod ffi {
152 pub(crate) use crate::utils::ffi::c_ulong;
153 #[allow(unused_imports)]
154 pub(crate) use crate::utils::ffi::{c_char, c_int, c_void};
155
156 sys_const!({
157 // https://github.com/torvalds/linux/blob/v6.19/include/uapi/linux/auxvec.h
158 pub(crate) const AT_HWCAP: c_ulong = 16;
159 #[cfg(any(
160 test,
161 all(target_arch = "aarch64", target_pointer_width = "64"),
162 target_arch = "powerpc64",
163 ))]
164 pub(crate) const AT_HWCAP2: c_ulong = 26;
165 // Linux 6.9+
166 // https://github.com/torvalds/linux/commit/3281366a8e79a512956382885091565db1036b64
167 #[cfg(test)]
168 #[cfg(not(all(target_arch = "aarch64", target_pointer_width = "32")))]
169 pub(crate) const AT_HWCAP3: c_ulong = 29;
170 #[cfg(test)]
171 #[cfg(not(all(target_arch = "aarch64", target_pointer_width = "32")))]
172 pub(crate) const AT_HWCAP4: c_ulong = 30;
173
174 // Defined in dlfcn.h.
175 // https://sourceware.org/git/?p=glibc.git;a=blob;f=dlfcn/dlfcn.h;hb=glibc-2.43
176 // https://git.musl-libc.org/cgit/musl/tree/include/dlfcn.h?h=v1.2.5
177 // https://github.com/wbx-github/uclibc-ng/blob/v1.0.47/include/dlfcn.h
178 // https://github.com/kernkonzept/l4re-core/blob/r-2026-W07/libc/uclibc-ng/contrib/uclibc/include/dlfcn.h
179 // https://android.googlesource.com/platform/bionic.git/+/refs/tags/android-16.0.0_r1/libc/include/dlfcn.h
180 #[cfg(any(
181 test,
182 not(any(
183 all(
184 target_os = "linux",
185 any(
186 all(
187 target_env = "gnu",
188 any(
189 target_arch = "aarch64",
190 all(target_arch = "powerpc64", target_endian = "little"),
191 ),
192 ),
193 target_env = "musl",
194 target_env = "ohos",
195 ),
196 ),
197 all(target_os = "android", target_pointer_width = "64"),
198 portable_atomic_outline_atomics,
199 )),
200 ))]
201 #[cfg(not(all(target_os = "android", target_pointer_width = "32")))]
202 pub(crate) const RTLD_DEFAULT: *mut c_void = core::ptr::null_mut();
203 #[cfg(all(target_os = "android", target_pointer_width = "32"))]
204 #[allow(clippy::cast_sign_loss)]
205 pub(crate) const RTLD_DEFAULT: *mut c_void =
206 crate::utils::ptr::without_provenance_mut(-1_isize as usize);
207
208 // Defined in sys/system_properties.h.
209 // https://android.googlesource.com/platform/bionic.git/+/refs/tags/android-16.0.0_r1/libc/include/sys/system_properties.h
210 #[cfg(all(target_arch = "aarch64", target_os = "android"))]
211 pub(crate) const PROP_VALUE_MAX: c_int = 92;
212 });
213
214 sys_fn!({
215 extern "C" {
216 // Defined in sys/auxv.h.
217 // https://man7.org/linux/man-pages/man3/getauxval.3.html
218 // https://sourceware.org/git/?p=glibc.git;a=blob;f=misc/sys/auxv.h;hb=glibc-2.43
219 // https://git.musl-libc.org/cgit/musl/tree/include/sys/auxv.h?h=v1.2.5
220 // https://github.com/wbx-github/uclibc-ng/blob/v1.0.47/include/sys/auxv.h
221 // https://github.com/kernkonzept/l4re-core/blob/r-2026-W07/libc/uclibc-ng/contrib/uclibc/include/sys/auxv.h
222 // https://android.googlesource.com/platform/bionic.git/+/refs/tags/android-16.0.0_r1/libc/include/sys/auxv.h
223 // https://github.com/picolibc/picolibc/blob/1.8.12/libc/include/sys/auxv.h
224 #[cfg(any(
225 test,
226 all(
227 target_os = "linux",
228 any(
229 all(
230 target_env = "gnu",
231 any(
232 target_arch = "aarch64",
233 all(target_arch = "powerpc64", target_endian = "little"),
234 ),
235 ),
236 target_env = "musl",
237 target_env = "ohos",
238 ),
239 ),
240 all(target_os = "android", target_pointer_width = "64"),
241 portable_atomic_outline_atomics,
242 ))]
243 pub(crate) fn getauxval(type_: c_ulong) -> c_ulong;
244
245 // Defined in dlfcn.h.
246 // https://man7.org/linux/man-pages/man3/dlsym.3.html
247 // https://sourceware.org/git/?p=glibc.git;a=blob;f=dlfcn/dlfcn.h;hb=glibc-2.43
248 // https://git.musl-libc.org/cgit/musl/tree/include/dlfcn.h?h=v1.2.5
249 // https://github.com/wbx-github/uclibc-ng/blob/v1.0.47/include/dlfcn.h
250 // https://github.com/kernkonzept/l4re-core/blob/r-2026-W07/libc/uclibc-ng/contrib/uclibc/include/dlfcn.h
251 // https://android.googlesource.com/platform/bionic.git/+/refs/tags/android-16.0.0_r1/libc/include/dlfcn.h
252 #[cfg(any(
253 test,
254 not(any(
255 all(
256 target_os = "linux",
257 any(
258 all(
259 target_env = "gnu",
260 any(
261 target_arch = "aarch64",
262 all(target_arch = "powerpc64", target_endian = "little"),
263 ),
264 ),
265 target_env = "musl",
266 target_env = "ohos",
267 ),
268 ),
269 all(target_os = "android", target_pointer_width = "64"),
270 portable_atomic_outline_atomics,
271 )),
272 ))]
273 pub(crate) fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
274
275 // Defined in sys/system_properties.h.
276 // https://android.googlesource.com/platform/bionic.git/+/refs/tags/android-16.0.0_r1/libc/include/sys/system_properties.h
277 #[cfg(all(target_arch = "aarch64", target_os = "android"))]
278 pub(crate) fn __system_property_get(
279 name: *const c_char,
280 value: *mut c_char,
281 ) -> c_int;
282 }
283 });
284 }
285
286 pub(super) type GetauxvalTy = unsafe extern "C" fn(ffi::c_ulong) -> ffi::c_ulong;
287 pub(super) fn getauxval(type_: ffi::c_ulong) -> ffi::c_ulong {
288 cfg_sel!({
289 #[cfg(any(
290 all(
291 target_os = "linux",
292 any(
293 all(
294 target_env = "gnu",
295 any(
296 target_arch = "aarch64",
297 all(target_arch = "powerpc64", target_endian = "little"),
298 ),
299 ),
300 target_env = "musl",
301 target_env = "ohos",
302 ),
303 ),
304 all(target_os = "android", target_pointer_width = "64"),
305 portable_atomic_outline_atomics,
306 ))]
307 {
308 let getauxval: GetauxvalTy = ffi::getauxval;
309 }
310 #[cfg(else)]
311 {
312 // SAFETY: we passed a valid C string to dlsym, and a pointer returned by dlsym
313 // is a valid pointer to the function if it is non-null.
314 let getauxval: GetauxvalTy = unsafe {
315 let ptr = ffi::dlsym(ffi::RTLD_DEFAULT, c!("getauxval").as_ptr());
316 if ptr.is_null() {
317 return 0;
318 }
319 core::mem::transmute::<*mut ffi::c_void, GetauxvalTy>(ptr)
320 };
321 }
322 });
323
324 // SAFETY: `getauxval` is thread-safe.
325 unsafe { getauxval(type_) }
326 }
327 }
328 #[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
329 mod os {
330 use core::mem;
331
332 // libc requires Rust 1.63
333 #[cfg_attr(test, allow(dead_code))]
334 pub(super) mod ffi {
335 #[allow(unused_imports)]
336 pub(crate) use crate::utils::ffi::c_char;
337 pub(crate) use crate::utils::ffi::{c_int, c_ulong, c_void};
338
339 sys_const!({
340 // FreeBSD
341 // Defined in sys/elf_common.h.
342 // https://github.com/freebsd/freebsd-src/blob/release/15.1.0/sys/sys/elf_common.h
343 // OpenBSD
344 // Defined in sys/auxv.h.
345 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/sys/sys/auxv.h
346 pub(crate) const AT_HWCAP: c_int = 25;
347 #[cfg(any(
348 test,
349 all(target_os = "freebsd", target_arch = "aarch64", target_pointer_width = "64"),
350 target_arch = "powerpc64",
351 ))]
352 pub(crate) const AT_HWCAP2: c_int = 26;
353 // FreeBSD 15.0+
354 // https://github.com/freebsd/freebsd-src/commit/85007872d1227006adf2ce119fe30de856cbe12d
355 #[cfg(test)]
356 #[cfg(not(target_os = "openbsd"))]
357 pub(crate) const AT_HWCAP3: c_int = 38;
358 #[cfg(test)]
359 #[cfg(not(target_os = "openbsd"))]
360 pub(crate) const AT_HWCAP4: c_int = 39;
361
362 // FreeBSD
363 // Defined in dlfcn.h.
364 // https://man.freebsd.org/dlsym(3)
365 // https://github.com/freebsd/freebsd-src/blob/release/15.1.0/include/dlfcn.h
366 // OpenBSD
367 // Defined in dlfcn.h.
368 // https://man.openbsd.org/dlsym.3
369 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/include/dlfcn.h
370 #[cfg(any(
371 test,
372 not(any(
373 all(
374 target_os = "freebsd",
375 any(
376 target_arch = "aarch64",
377 all(target_arch = "powerpc64", target_endian = "little"),
378 ),
379 ),
380 portable_atomic_outline_atomics,
381 )),
382 ))]
383 #[allow(clippy::cast_sign_loss)]
384 pub(crate) const RTLD_DEFAULT: *mut c_void =
385 crate::utils::ptr::without_provenance_mut(-2_isize as usize);
386 });
387
388 sys_fn!({
389 extern "C" {
390 // FreeBSD
391 // Defined in sys/auxv.h.
392 // https://man.freebsd.org/elf_aux_info(3)
393 // https://github.com/freebsd/freebsd-src/blob/release/15.1.0/sys/sys/auxv.h
394 // OpenBSD
395 // Defined in sys/auxv.h.
396 // https://man.openbsd.org/elf_aux_info.3
397 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/sys/sys/auxv.h
398 #[cfg(any(
399 test,
400 any(
401 all(
402 target_os = "freebsd",
403 any(
404 target_arch = "aarch64",
405 all(target_arch = "powerpc64", target_endian = "little"),
406 ),
407 ),
408 portable_atomic_outline_atomics,
409 ),
410 ))]
411 pub(crate) fn elf_aux_info(aux: c_int, buf: *mut c_void, buf_len: c_int) -> c_int;
412
413 // FreeBSD
414 // Defined in dlfcn.h.
415 // https://man.freebsd.org/dlsym(3)
416 // https://github.com/freebsd/freebsd-src/blob/release/15.1.0/include/dlfcn.h
417 // OpenBSD
418 // Defined in dlfcn.h.
419 // https://man.openbsd.org/dlsym.3
420 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/include/dlfcn.h
421 #[cfg(any(
422 test,
423 not(any(
424 all(
425 target_os = "freebsd",
426 any(
427 target_arch = "aarch64",
428 all(target_arch = "powerpc64", target_endian = "little"),
429 ),
430 ),
431 portable_atomic_outline_atomics,
432 )),
433 ))]
434 pub(crate) fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
435 }
436 });
437 }
438
439 pub(super) type ElfAuxInfoTy =
440 unsafe extern "C" fn(ffi::c_int, *mut ffi::c_void, ffi::c_int) -> ffi::c_int;
441 pub(super) fn getauxval(aux: ffi::c_int) -> ffi::c_ulong {
442 #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
443 const OUT_LEN: ffi::c_int = mem::size_of::<ffi::c_ulong>() as ffi::c_int;
444
445 cfg_sel!({
446 #[cfg(any(
447 all(
448 target_os = "freebsd",
449 any(
450 target_arch = "aarch64",
451 all(target_arch = "powerpc64", target_endian = "little"),
452 ),
453 ),
454 portable_atomic_outline_atomics,
455 ))]
456 {
457 let elf_aux_info: ElfAuxInfoTy = ffi::elf_aux_info;
458 }
459 #[cfg(else)]
460 {
461 // SAFETY: we passed a valid C string to dlsym, and a pointer returned by dlsym
462 // is a valid pointer to the function if it is non-null.
463 let elf_aux_info: ElfAuxInfoTy = unsafe {
464 let ptr = ffi::dlsym(ffi::RTLD_DEFAULT, c!("elf_aux_info").as_ptr());
465 if ptr.is_null() {
466 return 0;
467 }
468 mem::transmute::<*mut ffi::c_void, ElfAuxInfoTy>(ptr)
469 };
470 }
471 });
472
473 let mut out: ffi::c_ulong = 0;
474 // SAFETY:
475 // - the pointer is valid because we got it from a reference.
476 // - `OUT_LEN` is the same as the size of `out`.
477 // - `elf_aux_info` is thread-safe.
478 let res = unsafe {
479 elf_aux_info(aux, (&mut out as *mut ffi::c_ulong).cast::<ffi::c_void>(), OUT_LEN)
480 };
481 // If elf_aux_info fails, `out` will be left at zero (which is the proper default value).
482 debug_assert!(res == 0 || out == 0);
483 out
484 }
485 }
486
487 // Basically, Linux/FreeBSD/OpenBSD use the same hwcap values.
488 // FreeBSD and OpenBSD usually support a subset of the hwcap values supported by Linux.
489 use self::arch::_detect;
490 #[cfg(target_arch = "aarch64")]
491 mod arch {
492 use super::{CpuInfo, CpuInfoFlag, ffi, os};
493
494 sys_const!({
495 // Linux
496 // https://github.com/torvalds/linux/blob/v6.19/arch/arm64/include/uapi/asm/hwcap.h
497 // https://github.com/torvalds/linux/blob/v6.19/Documentation/arch/arm64/elf_hwcaps.rst
498 // FreeBSD
499 // Defined in machine/elf.h.
500 // https://github.com/freebsd/freebsd-src/blob/release/15.1.0/sys/arm64/include/elf.h
501 // OpenBSD
502 // Defined in machine/elf.h.
503 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/sys/arch/arm64/include/elf.h
504 // Linux 4.3+
505 // https://github.com/torvalds/linux/commit/40a1db2434a1b62332b1af25cfa14d7b8c0301fe
506 // FreeBSD 13.0+/12.2+
507 // https://github.com/freebsd/freebsd-src/blob/release/13.0.0/sys/arm64/include/elf.h
508 // https://github.com/freebsd/freebsd-src/blob/release/12.2.0/sys/arm64/include/elf.h
509 // OpenBSD 7.6+
510 // https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d
511 pub(crate) const HWCAP_ATOMICS: ffi::c_ulong = 1 << 8;
512 // Linux 4.11+
513 // https://github.com/torvalds/linux/commit/77c97b4ee21290f5f083173d957843b615abbff2
514 // FreeBSD 13.0+/12.2+
515 // https://github.com/freebsd/freebsd-src/blob/release/13.0.0/sys/arm64/include/elf.h
516 // https://github.com/freebsd/freebsd-src/blob/release/12.2.0/sys/arm64/include/elf.h
517 // OpenBSD 7.6+
518 // https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d
519 #[cfg(test)]
520 pub(crate) const HWCAP_CPUID: ffi::c_ulong = 1 << 11;
521 // Linux 4.12+
522 // https://github.com/torvalds/linux/commit/c651aae5a7732287c1c9bc974ece4ed798780544
523 // FreeBSD 13.0+/12.2+
524 // https://github.com/freebsd/freebsd-src/blob/release/13.0.0/sys/arm64/include/elf.h
525 // https://github.com/freebsd/freebsd-src/blob/release/12.2.0/sys/arm64/include/elf.h
526 // OpenBSD 7.6+
527 // https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d
528 #[cfg(test)]
529 pub(crate) const HWCAP_LRCPC: ffi::c_ulong = 1 << 15;
530 // Linux 4.17+
531 // https://github.com/torvalds/linux/commit/7206dc93a58fb76421c4411eefa3c003337bcb2d
532 // FreeBSD 13.0+/12.2+
533 // https://github.com/freebsd/freebsd-src/blob/release/13.0.0/sys/arm64/include/elf.h
534 // https://github.com/freebsd/freebsd-src/blob/release/12.2.0/sys/arm64/include/elf.h
535 // OpenBSD 7.6+
536 // https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d
537 pub(crate) const HWCAP_USCAT: ffi::c_ulong = 1 << 25;
538 #[cfg(test)]
539 pub(crate) const HWCAP_ILRCPC: ffi::c_ulong = 1 << 26;
540 // Linux 6.7+
541 // https://github.com/torvalds/linux/commit/338a835f40a849cd89b993e342bd9fbd5684825c
542 // FreeBSD 15.0+
543 // https://github.com/freebsd/freebsd-src/commit/94686b081fdb0c1bb0fc1dfeda14bd53f26ce7c5
544 #[cfg(not(target_os = "openbsd"))]
545 #[cfg(target_pointer_width = "64")]
546 pub(crate) const HWCAP2_LRCPC3: ffi::c_ulong = 1 << 46;
547 // Linux 6.7+
548 // https://github.com/torvalds/linux/commit/94d0657f9f0d311489606589133ebf49e28104d8
549 // FreeBSD 15.0+
550 // https://github.com/freebsd/freebsd-src/commit/94686b081fdb0c1bb0fc1dfeda14bd53f26ce7c5
551 #[cfg(not(target_os = "openbsd"))]
552 #[cfg(target_pointer_width = "64")]
553 pub(crate) const HWCAP2_LSE128: ffi::c_ulong = 1 << 47;
554 // Linux 6.18+
555 // https://github.com/torvalds/linux/commit/220928e52cb03d223b3acad3888baf0687486d21
556 // FreeBSD 16.0+
557 // https://github.com/freebsd/freebsd-src/commit/3a960425df759a7bb8f946d23f035c63f3a5de7a
558 #[cfg(test)]
559 #[cfg(not(target_os = "openbsd"))]
560 #[cfg(target_pointer_width = "64")]
561 pub(crate) const HWCAP3_LSFE: ffi::c_ulong = 1 << 2;
562 });
563
564 #[cold]
565 #[must_use]
566 pub(crate) fn _detect(mut info: CpuInfo) -> CpuInfo {
567 #[cfg(target_os = "android")]
568 {
569 // Samsung Exynos 9810 has a bug that big and little cores have different
570 // ISAs. And on older Android (pre-9), the kernel incorrectly reports
571 // that features available only on some cores are available on all cores.
572 // https://reviews.llvm.org/D114523
573 let mut arch = [0_u8; ffi::PROP_VALUE_MAX as usize];
574 // SAFETY: we've passed a valid C string and a buffer with max length.
575 let len = unsafe {
576 ffi::__system_property_get(
577 c!("ro.arch").as_ptr(),
578 arch.as_mut_ptr().cast::<ffi::c_char>(),
579 )
580 };
581 // On Exynos, ro.arch is not available on Android 12+, but it is fine
582 // because Android 9+ includes the fix.
583 if len > 0 && arch.starts_with(b"exynos9810") {
584 return info;
585 }
586 }
587
588 macro_rules! check {
589 ($x:ident, $flag:ident, $bit:ident) => {
590 if $x & $bit != 0 {
591 info.set(CpuInfoFlag::$flag);
592 }
593 };
594 }
595 let hwcap = os::getauxval(ffi::AT_HWCAP);
596 check!(hwcap, lse, HWCAP_ATOMICS);
597 check!(hwcap, lse2, HWCAP_USCAT);
598 #[cfg(test)]
599 check!(hwcap, rcpc, HWCAP_LRCPC);
600 #[cfg(test)]
601 check!(hwcap, rcpc2, HWCAP_ILRCPC);
602 #[cfg(test)]
603 check!(hwcap, cpuid, HWCAP_CPUID);
604 #[cfg(not(target_os = "openbsd"))]
605 // HWCAP2 is not yet available on ILP32: https://git.kernel.org/pub/scm/linux/kernel/git/arm64/linux.git/tree/arch/arm64/include/uapi/asm/hwcap.h?h=staging/ilp32-5.1
606 #[cfg(target_pointer_width = "64")]
607 {
608 let hwcap2 = os::getauxval(ffi::AT_HWCAP2);
609 check!(hwcap2, rcpc3, HWCAP2_LRCPC3);
610 check!(hwcap2, lse128, HWCAP2_LSE128);
611 #[cfg(test)]
612 {
613 let hwcap3 = os::getauxval(ffi::AT_HWCAP3);
614 check!(hwcap3, lsfe, HWCAP3_LSFE);
615 }
616 }
617 info
618 }
619 }
620 #[cfg(target_arch = "arm")]
621 mod arch {
622 use super::{CpuInfo, CpuInfoFlag, ffi, os};
623
624 sys_const!({
625 // Linux
626 // https://github.com/torvalds/linux/blob/v6.19/arch/arm/include/uapi/asm/hwcap.h
627 // FreeBSD
628 // Defined in machine/elf.h.
629 // https://github.com/freebsd/freebsd-src/blob/release/15.1.0/sys/arm/include/elf.h
630 // OpenBSD
631 // Defined in machine/elf.h.
632 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/sys/arch/arm/include/elf.h
633 // Linux 3.11+
634 // https://github.com/torvalds/linux/commit/a469abd0f868c902b75532579bf87553dcf1b360
635 // FreeBSD 12.0+/11.2+
636 // https://github.com/freebsd/freebsd-src/commit/0cbf724ed03571bc90ed22c3b4bf8c6c7b2da564
637 // https://github.com/freebsd/freebsd-src/blob/release/11.2.0/sys/arm/include/elf.h
638 // OpenBSD 7.6+
639 // https://github.com/openbsd/src/commit/ef873df06dac50249b2dd380dc6100eee3b0d23d
640 #[cfg(test)]
641 pub(crate) const HWCAP_LPAE: ffi::c_ulong = 1 << 20;
642 });
643
644 #[cold]
645 #[must_use]
646 pub(crate) fn _detect(mut info: CpuInfo) -> CpuInfo {
647 macro_rules! check {
648 ($x:ident, $flag:ident, $($bit:ident) ||+) => {
649 if $x & ($($bit) |+) != 0 {
650 info.set(CpuInfoFlag::$flag);
651 }
652 };
653 ($x:ident, $flag:ident, $($bit:ident) &&+) => {
654 if $x & ($($bit) |+) == ($($bit) |+) {
655 info.set(CpuInfoFlag::$flag);
656 }
657 };
658 }
659 let hwcap = os::getauxval(ffi::AT_HWCAP);
660 #[cfg(test)]
661 check!(hwcap, lpae, HWCAP_LPAE);
662 info
663 }
664 }
665 #[cfg(target_arch = "powerpc64")]
666 mod arch {
667 use super::{CpuInfo, CpuInfoFlag, ffi, os};
668
669 sys_const!({
670 // Linux
671 // https://github.com/torvalds/linux/blob/v6.19/arch/powerpc/include/uapi/asm/cputable.h
672 // https://github.com/torvalds/linux/blob/v6.19/Documentation/arch/powerpc/elf_hwcaps.rst
673 // FreeBSD
674 // Defined in machine/cpu.h.
675 // https://github.com/freebsd/freebsd-src/blob/release/15.1.0/sys/powerpc/include/cpu.h
676 // OpenBSD
677 // Defined in machine/elf.h.
678 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/sys/arch/powerpc64/include/elf.h
679 // Linux 2.6.16+
680 // https://github.com/torvalds/linux/commit/80f15dc703b3677d0b025bafd215f1f3664c8978
681 // FreeBSD 11.0+
682 // https://github.com/freebsd/freebsd-src/commit/b0bf7fcd298133457991b27625bbed766e612730
683 // OpenBSD 7.6+
684 // https://github.com/openbsd/src/commit/0b0568a19fc4c197871ceafbabc91fabf17ca152
685 pub(crate) const PPC_FEATURE_BOOKE: ffi::c_ulong = 0x00008000;
686 // Linux 3.10+
687 // https://github.com/torvalds/linux/commit/cbbc6f1b1433ef553d57826eee87a84ca49645ce
688 // FreeBSD 11.0+
689 // https://github.com/freebsd/freebsd-src/commit/b0bf7fcd298133457991b27625bbed766e612730
690 // OpenBSD 7.6+
691 // https://github.com/openbsd/src/commit/0b0568a19fc4c197871ceafbabc91fabf17ca152
692 pub(crate) const PPC_FEATURE2_ARCH_2_07: ffi::c_ulong = 0x80000000;
693 // Linux 4.5+
694 // https://github.com/torvalds/linux/commit/e708c24cd01ce80b1609d8baccee40ccc3608a01
695 // FreeBSD 12.0+
696 // https://github.com/freebsd/freebsd-src/commit/18f48e0c72f91bc2d4373078a3f1ab1bcab4d8b3
697 // OpenBSD 7.6+
698 // https://github.com/openbsd/src/commit/0b0568a19fc4c197871ceafbabc91fabf17ca152
699 pub(crate) const PPC_FEATURE2_ARCH_3_00: ffi::c_ulong = 0x00800000;
700 // Linux 5.8+
701 // https://github.com/torvalds/linux/commit/ee988c11acf6f9464b7b44e9a091bf6afb3b3a49
702 // FreeBSD 15.0+/14.2+
703 // https://github.com/freebsd/freebsd-src/commit/1e434da3b065ef96b389e5e0b604ae05a51e794e
704 // https://github.com/freebsd/freebsd-src/blob/release/14.2.0/sys/powerpc/include/cpu.h
705 // OpenBSD 7.7+
706 // https://github.com/openbsd/src/commit/483a78e15aaa23c010911940770c1c97db5c1287
707 pub(crate) const PPC_FEATURE2_ARCH_3_1: ffi::c_ulong = 0x00040000;
708 });
709
710 #[cold]
711 #[must_use]
712 pub(crate) fn _detect(mut info: CpuInfo) -> CpuInfo {
713 let hwcap = os::getauxval(ffi::AT_HWCAP);
714 if hwcap & PPC_FEATURE_BOOKE != 0 {
715 // quadword-atomics (Load/Store Quadword category in ISA 2.07) is requirement of ISA 2.07
716 // server processors. It is always optional in ISA 2.07 BookE (embedded category)
717 // processors and there is no corresponding HWCAP bit. (Although there are no ISA 2.07
718 // BookE processors that appear to be supported on these platforms.)
719 // Refs: Appendix B "Platform Support Requirements" of Power ISA 2.07B
720 // https://ibm.ent.box.com/s/jd5w15gz301s5b5dt375mshpq9c3lh4u
721 return info;
722 }
723 let hwcap2 = os::getauxval(ffi::AT_HWCAP2);
724 // Check both 2_07 and later ISAs (which are superset of 2_07) because
725 // OpenBSD (as of 8.0-beta) doesn't set 2_07 even when 3_00 is set.
726 // https://github.com/openbsd/src/blob/d2e81eb18e50973c87ae2c9c2ba348ff3ff89cf9/sys/arch/powerpc64/powerpc64/cpu.c#L222-L238
727 // Other OSes should be fine, but check all OSs in the same way just in case.
728 let isa_2_07_or_later =
729 PPC_FEATURE2_ARCH_2_07 | PPC_FEATURE2_ARCH_3_00 | PPC_FEATURE2_ARCH_3_1;
730 if hwcap2 & isa_2_07_or_later != 0 {
731 info.set(CpuInfoFlag::quadword_atomics);
732 }
733 info
734 }
735 }
736
737 #[allow(
738 clippy::alloc_instead_of_core,
739 clippy::std_instead_of_alloc,
740 clippy::std_instead_of_core,
741 clippy::undocumented_unsafe_blocks,
742 clippy::wildcard_imports
743 )]
744 #[cfg(test)]
745 mod tests {
746 use std::mem;
747
748 use super::*;
749
750 #[allow(clippy::cast_sign_loss)]
751 #[cfg(all(target_arch = "aarch64", target_os = "android"))]
752 #[test]
753 fn test_android() {
754 use std::{slice, str};
755 unsafe {
756 let mut arch = [1; ffi::PROP_VALUE_MAX as usize];
757 let len = ffi::__system_property_get(
758 c!("ro.arch").as_ptr(),
759 arch.as_mut_ptr().cast::<ffi::c_char>(),
760 );
761 assert!(len >= 0);
762 test_helper::eprintln_nocapture!("ro.arch=raw={:?},len={}", arch, len);
763 test_helper::eprintln_nocapture!(
764 "ro.arch={:?}",
765 str::from_utf8(slice::from_raw_parts(arch.as_ptr(), len as usize)).unwrap()
766 );
767 }
768 }
769
770 #[cfg(any(target_os = "linux", target_os = "android"))]
771 #[test]
772 fn test_dlsym_getauxval() {
773 unsafe {
774 let ptr = ffi::dlsym(ffi::RTLD_DEFAULT, c!("getauxval").as_ptr());
775 if cfg!(target_feature = "crt-static") {
776 assert!(ptr.is_null());
777 } else if cfg!(any(
778 all(
779 target_os = "linux",
780 any(target_env = "gnu", target_env = "musl", target_env = "ohos"),
781 ),
782 target_os = "android",
783 )) {
784 assert!(!ptr.is_null());
785 } else if option_env!("CI").is_some() {
786 assert!(ptr.is_null());
787 }
788 if ptr.is_null() {
789 return;
790 }
791 let dlsym_getauxval = mem::transmute::<*mut ffi::c_void, os::GetauxvalTy>(ptr);
792 for &at in &[ffi::AT_HWCAP, ffi::AT_HWCAP2] {
793 assert_eq!(dlsym_getauxval(at), ffi::getauxval(at));
794 }
795 #[cfg(not(all(target_arch = "aarch64", target_pointer_width = "32")))]
796 for &at in &[ffi::AT_HWCAP3, ffi::AT_HWCAP4] {
797 assert_eq!(dlsym_getauxval(at), ffi::getauxval(at));
798 }
799 }
800 }
801 #[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
802 #[test]
803 fn test_dlsym_elf_aux_info() {
804 unsafe {
805 let ptr = ffi::dlsym(ffi::RTLD_DEFAULT, c!("elf_aux_info").as_ptr());
806 if cfg!(target_feature = "crt-static") {
807 assert!(ptr.is_null());
808 } else if cfg!(target_os = "freebsd") || option_env!("CI").is_some() {
809 assert!(!ptr.is_null());
810 }
811 if ptr.is_null() {
812 return;
813 }
814 let dlsym_elf_aux_info = mem::transmute::<*mut ffi::c_void, os::ElfAuxInfoTy>(ptr);
815 #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
816 let out_len = mem::size_of::<ffi::c_ulong>() as ffi::c_int;
817 for &at in &[ffi::AT_HWCAP, ffi::AT_HWCAP2] {
818 let mut out: ffi::c_ulong = 0;
819 let mut dlsym_out: ffi::c_ulong = 0;
820 assert_eq!(
821 ffi::elf_aux_info(
822 at,
823 (&mut out as *mut ffi::c_ulong).cast::<ffi::c_void>(),
824 out_len,
825 ),
826 dlsym_elf_aux_info(
827 at,
828 (&mut dlsym_out as *mut ffi::c_ulong).cast::<ffi::c_void>(),
829 out_len,
830 ),
831 );
832 assert_eq!(out, dlsym_out);
833 }
834 #[cfg(not(target_os = "openbsd"))]
835 for &at in &[ffi::AT_HWCAP3, ffi::AT_HWCAP4] {
836 let mut out: ffi::c_ulong = 0;
837 let mut dlsym_out: ffi::c_ulong = 0;
838 assert_eq!(
839 ffi::elf_aux_info(
840 at,
841 (&mut out as *mut ffi::c_ulong).cast::<ffi::c_void>(),
842 out_len,
843 ),
844 dlsym_elf_aux_info(
845 at,
846 (&mut dlsym_out as *mut ffi::c_ulong).cast::<ffi::c_void>(),
847 out_len,
848 ),
849 );
850 assert_eq!(out, dlsym_out);
851 }
852 }
853 }
854
855 #[cfg(any(target_os = "linux", target_os = "android"))]
856 #[cfg(not(all(target_arch = "aarch64", target_pointer_width = "32")))] // no PR_GET_AUXV
857 #[test]
858 fn test_alternative() {
859 use std::{eprintln, str, vec};
860
861 #[cfg(target_pointer_width = "32")]
862 use sys::Elf32_auxv_t as Elf_auxv_t;
863 #[cfg(target_pointer_width = "64")]
864 use sys::Elf64_auxv_t as Elf_auxv_t;
865 use test_helper::sys;
866
867 use crate::utils::ffi::*;
868
869 // Linux kernel 6.4 has added a way to read auxv without depending on either libc or mrs trap.
870 // https://github.com/torvalds/linux/commit/ddc65971bb677aa9f6a4c21f76d3133e106f88eb
871 // (Actually 6.5? https://github.com/torvalds/linux/commit/636e348353a7cc52609fdba5ff3270065da140d5)
872 //
873 // This is currently used only for testing.
874 #[cfg(not(target_os = "android"))]
875 #[cfg(not(portable_atomic_no_asm_syscall))]
876 fn getauxval_pr_get_auxv_no_libc(type_: c_ulong) -> Result<c_ulong, c_int> {
877 use crate::utils::{RegISize, RegSize};
878
879 unsafe fn prctl_get_auxv(out: *mut c_void, len: usize) -> Result<usize, c_int> {
880 #[cfg_attr(target_arch = "arm", allow(unused_variables))]
881 let number = sys::__NR_prctl as RegSize;
882 let arg1 = sys::PR_GET_AUXV as RegSize;
883 let arg2 = ptr_reg!(out);
884 let arg3 = len as RegSize;
885 let arg4: RegSize = 0;
886 let arg5: RegSize = 0;
887 let r: RegISize;
888 // SAFETY: the caller must uphold the safety contract.
889 // we've extended the syscall number and arguments to the register size.
890 unsafe {
891 #[cfg(target_arch = "arm")]
892 asm_syscall!(sys::__NR_prctl, 172, r, arg1, arg2, arg3, arg4, arg5);
893 // POWER9+ has fast syscall using SCV, but since detection is cold path,
894 // there’s no need to consider it here.
895 #[cfg(not(target_arch = "arm"))]
896 asm_syscall!(number, r, arg1, arg2, arg3, arg4, arg5);
897 }
898 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
899 if (r as c_int) < 0 { Err(r as c_int) } else { Ok(r as usize) }
900 }
901
902 let mut auxv = vec![unsafe { mem::zeroed::<Elf_auxv_t>() }; 38];
903
904 let old_len = auxv.len() * mem::size_of::<Elf_auxv_t>();
905
906 // SAFETY:
907 // - `out_len` does not exceed the size of `auxv`.
908 let _len = unsafe { prctl_get_auxv(auxv.as_mut_ptr().cast::<c_void>(), old_len)? };
909
910 for aux in &auxv {
911 if aux.a_type == type_ {
912 // SAFETY: aux.a_un is #[repr(C)] union and all fields have
913 // the same size and can be safely transmuted to integers.
914 return Ok(unsafe { aux.a_un.a_val });
915 }
916 }
917 Err(0)
918 }
919 // Similar to the above, but call libc prctl instead of syscall using asm.
920 //
921 // This is used only for testing.
922 fn getauxval_pr_get_auxv_libc(type_: c_ulong) -> Result<c_ulong, c_int> {
923 unsafe fn prctl_get_auxv(out: *mut c_void, len: usize) -> Result<usize, c_int> {
924 // arg4 and arg5 must be zero.
925 #[allow(clippy::cast_possible_wrap)]
926 let r = unsafe { libc::prctl(sys::PR_GET_AUXV as c_int, out, len, 0, 0) };
927 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
928 if (r as c_int) < 0 { Err(r as c_int) } else { Ok(r as usize) }
929 }
930
931 let mut auxv = vec![unsafe { mem::zeroed::<Elf_auxv_t>() }; 38];
932
933 let old_len = auxv.len() * mem::size_of::<Elf_auxv_t>();
934
935 // SAFETY:
936 // - `out_len` does not exceed the size of `auxv`.
937 let _len = unsafe { prctl_get_auxv(auxv.as_mut_ptr().cast::<c_void>(), old_len)? };
938
939 for aux in &auxv {
940 if aux.a_type == type_ {
941 // SAFETY: aux.a_un is #[repr(C)] union and all fields have
942 // the same size and can be safely transmuted to integers.
943 return Ok(unsafe { aux.a_un.a_val });
944 }
945 }
946 Err(0)
947 }
948
949 unsafe {
950 let mut u = mem::zeroed();
951 assert_eq!(libc::uname(&mut u), 0);
952 let release = std::ffi::CStr::from_ptr(u.release.as_ptr());
953 let release = str::from_utf8(release.to_bytes()).unwrap();
954 let mut digits = release.split('.');
955 let major = digits.next().unwrap().parse::<u32>().unwrap();
956 let minor = digits.next().unwrap().parse::<u32>().unwrap();
957 // TODO: qemu-user bug (fails even on kernel >= 6.4) (as of 9.2)
958 if (major, minor) < (6, 4) || cfg!(qemu) {
959 eprintln!("kernel version: {}.{} (no pr_get_auxv)", major, minor);
960 for &at in &[ffi::AT_HWCAP, ffi::AT_HWCAP2, ffi::AT_HWCAP3, ffi::AT_HWCAP4] {
961 assert_eq!(getauxval_pr_get_auxv_libc(at).unwrap_err(), -1);
962 #[cfg(not(target_os = "android"))]
963 #[cfg(not(portable_atomic_no_asm_syscall))]
964 assert_eq!(getauxval_pr_get_auxv_no_libc(at).unwrap_err(), -libc::EINVAL);
965 }
966 } else {
967 eprintln!("kernel version: {}.{} (has pr_get_auxv)", major, minor);
968 for &at in &[ffi::AT_HWCAP, ffi::AT_HWCAP2] {
969 if cfg!(all(valgrind, target_arch = "powerpc64")) {
970 // TODO: valgrind bug (as of Valgrind 3.26)
971 assert_eq!(getauxval_pr_get_auxv_libc(at).unwrap_err(), -1);
972 #[cfg(not(target_os = "android"))]
973 #[cfg(not(portable_atomic_no_asm_syscall))]
974 assert_eq!(getauxval_pr_get_auxv_no_libc(at).unwrap_err(), -libc::EINVAL);
975 } else if cfg!(all(valgrind, target_arch = "aarch64"))
976 || cfg!(all(valgrind, target_arch = "arm")) && at == ffi::AT_HWCAP2
977 {
978 // TODO: valgrind bug (result value mismatch) (as of Valgrind 3.26)
979 assert_ne!(os::getauxval(at), getauxval_pr_get_auxv_libc(at).unwrap());
980 #[cfg(not(target_os = "android"))]
981 #[cfg(not(portable_atomic_no_asm_syscall))]
982 assert_ne!(os::getauxval(at), getauxval_pr_get_auxv_no_libc(at).unwrap());
983 } else {
984 assert_eq!(os::getauxval(at), getauxval_pr_get_auxv_libc(at).unwrap());
985 #[cfg(not(target_os = "android"))]
986 #[cfg(not(portable_atomic_no_asm_syscall))]
987 assert_eq!(os::getauxval(at), getauxval_pr_get_auxv_no_libc(at).unwrap());
988 }
989 }
990 for &at in &[ffi::AT_HWCAP3, ffi::AT_HWCAP4] {
991 assert_eq!(
992 os::getauxval(at),
993 getauxval_pr_get_auxv_libc(at).unwrap_or_default()
994 );
995 #[cfg(not(target_os = "android"))]
996 #[cfg(not(portable_atomic_no_asm_syscall))]
997 assert_eq!(
998 os::getauxval(at),
999 getauxval_pr_get_auxv_no_libc(at).unwrap_or_default()
1000 );
1001 }
1002 }
1003 }
1004 }
1005 #[allow(clippy::cast_possible_wrap)]
1006 #[cfg(target_os = "freebsd")]
1007 #[test]
1008 fn test_alternative() {
1009 use std::ptr;
1010
1011 use test_helper::sys;
1012
1013 use crate::utils::ffi::*;
1014
1015 // This is almost equivalent to what elf_aux_info does.
1016 // https://man.freebsd.org/elf_aux_info(3)
1017 // On FreeBSD, [AArch64 support is available on FreeBSD 11.0+](https://www.freebsd.org/releases/11.0R/announce),
1018 // but elf_aux_info is available on FreeBSD 12.0+ and 11.4+:
1019 // https://github.com/freebsd/freebsd-src/commit/0b08ae2120cdd08c20a2b806e2fcef4d0a36c470
1020 // https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/sys/auxv.h
1021 // so use sysctl instead of elf_aux_info.
1022 // Note that FreeBSD 11 (11.4) was EoL on 2021-09-30, and FreeBSD 11.3 was EoL on 2020-09-30:
1023 // https://www.freebsd.org/security/unsupported
1024 //
1025 // This is currently used only for testing.
1026 // If you want us to use this implementation for compatibility with the older FreeBSD
1027 // version that came to EoL a few years ago, please open an issue.
1028 fn getauxval_sysctl_libc(type_: ffi::c_int) -> Result<ffi::c_ulong, c_int> {
1029 let mut auxv: [sys::Elf_Auxinfo; sys::AT_COUNT as usize] = unsafe { mem::zeroed() };
1030
1031 let mut len = mem::size_of_val(&auxv) as c_size_t;
1032
1033 // SAFETY: calling getpid is safe.
1034 let pid = unsafe { libc::getpid() };
1035 let mib = [
1036 sys::CTL_KERN as c_int,
1037 sys::KERN_PROC as c_int,
1038 sys::KERN_PROC_AUXV as c_int,
1039 pid,
1040 ];
1041 #[allow(clippy::cast_possible_truncation)]
1042 let mib_len = mib.len() as c_uint;
1043 // SAFETY:
1044 // - `mib_len` does not exceed the size of `mib`.
1045 // - `len` does not exceed the size of `auxv`.
1046 // - `sysctl` is thread-safe.
1047 let res = unsafe {
1048 libc::sysctl(
1049 mib.as_ptr(),
1050 mib_len,
1051 auxv.as_mut_ptr().cast::<c_void>(),
1052 &mut len,
1053 ptr::null_mut(),
1054 0,
1055 )
1056 };
1057 // FreeBSD sysctl returns 0 on success, -1 on failure.
1058 if res != 0 {
1059 return Err(res);
1060 }
1061
1062 for aux in &auxv {
1063 #[allow(clippy::cast_sign_loss)]
1064 if aux.a_type == type_ as c_long {
1065 // SAFETY: aux.a_un is #[repr(C)] union and all fields have
1066 // the same size and can be safely transmuted to integers.
1067 return Ok(unsafe { aux.a_un.a_val as c_ulong });
1068 }
1069 }
1070 Err(0)
1071 }
1072
1073 // AT_HWCAP2 is only available on FreeBSD 13+ on AArch64.
1074 let hwcap2_else = |e| if cfg!(target_arch = "aarch64") { 0 } else { panic!("{:?}", e) };
1075 let at = ffi::AT_HWCAP;
1076 assert_eq!(os::getauxval(at), getauxval_sysctl_libc(at).unwrap());
1077 let at = ffi::AT_HWCAP2;
1078 assert_eq!(os::getauxval(at), getauxval_sysctl_libc(at).unwrap_or_else(hwcap2_else));
1079 for &at in &[ffi::AT_HWCAP3, ffi::AT_HWCAP4] {
1080 assert_eq!(os::getauxval(at), getauxval_sysctl_libc(at).unwrap_or_default());
1081 }
1082 }
1083 }