Debian Codegraph @

third_party/rust/rustix/src/backend/linux_raw/param/auxv.rs

raw
1 //! Linux auxv support.
2 //!
3 //! # Safety
4 //!
5 //! This uses raw pointers to locate and read the kernel-provided auxv array.
6 #![allow(unsafe_code)]
7
8 use super::super::conv::{c_int, pass_usize, ret_usize};
9 use crate::backend::c;
10 use crate::fd::OwnedFd;
11 #[cfg(feature = "param")]
12 use crate::ffi::CStr;
13 use crate::fs::{Mode, OFlags};
14 use crate::utils::{as_ptr, check_raw_pointer};
15 #[cfg(feature = "alloc")]
16 use alloc::vec::Vec;
17 use core::mem::size_of;
18 use core::ptr::{null_mut, read_unaligned, NonNull};
19 #[cfg(feature = "runtime")]
20 use core::sync::atomic::AtomicU8;
21 use core::sync::atomic::Ordering::Relaxed;
22 use core::sync::atomic::{AtomicPtr, AtomicUsize};
23 use linux_raw_sys::elf::*;
24 use linux_raw_sys::general::{
25 AT_BASE, AT_CLKTCK, AT_EXECFN, AT_HWCAP, AT_HWCAP2, AT_MINSIGSTKSZ, AT_NULL, AT_PAGESZ,
26 AT_SYSINFO_EHDR,
27 };
28 #[cfg(feature = "runtime")]
29 use linux_raw_sys::general::{
30 AT_EGID, AT_ENTRY, AT_EUID, AT_GID, AT_PHDR, AT_PHENT, AT_PHNUM, AT_RANDOM, AT_SECURE, AT_UID,
31 };
32 #[cfg(feature = "alloc")]
33 use {alloc::borrow::Cow, alloc::vec};
34
35 // TODO: Fix linux-raw-sys to define EM_CURRENT for s390x.
36 #[cfg(target_arch = "s390x")]
37 const EM_CURRENT: u16 = 22; // EM_S390
38
39 #[cfg(feature = "param")]
40 #[inline]
41 pub(crate) fn page_size() -> usize {
42 let mut page_size = PAGE_SIZE.load(Relaxed);
43
44 if page_size == 0 {
45 init_auxv();
46 page_size = PAGE_SIZE.load(Relaxed);
47 }
48
49 page_size
50 }
51
52 #[cfg(feature = "param")]
53 #[inline]
54 pub(crate) fn clock_ticks_per_second() -> u64 {
55 let mut ticks = CLOCK_TICKS_PER_SECOND.load(Relaxed);
56
57 if ticks == 0 {
58 init_auxv();
59 ticks = CLOCK_TICKS_PER_SECOND.load(Relaxed);
60 }
61
62 ticks as u64
63 }
64
65 #[cfg(feature = "param")]
66 #[inline]
67 pub(crate) fn linux_hwcap() -> (usize, usize) {
68 let mut hwcap = HWCAP.load(Relaxed);
69 let mut hwcap2 = HWCAP2.load(Relaxed);
70
71 if hwcap == 0 || hwcap2 == 0 {
72 init_auxv();
73 hwcap = HWCAP.load(Relaxed);
74 hwcap2 = HWCAP2.load(Relaxed);
75 }
76
77 (hwcap, hwcap2)
78 }
79
80 #[cfg(feature = "param")]
81 #[inline]
82 pub(crate) fn linux_minsigstksz() -> usize {
83 let mut minsigstksz = MINSIGSTKSZ.load(Relaxed);
84
85 if minsigstksz == 0 {
86 init_auxv();
87 minsigstksz = MINSIGSTKSZ.load(Relaxed);
88 }
89
90 minsigstksz
91 }
92
93 #[cfg(feature = "param")]
94 #[inline]
95 pub(crate) fn linux_execfn() -> &'static CStr {
96 let mut execfn = EXECFN.load(Relaxed);
97
98 if execfn.is_null() {
99 init_auxv();
100 execfn = EXECFN.load(Relaxed);
101 }
102
103 // SAFETY: We assume the `AT_EXECFN` value provided by the kernel is a
104 // valid pointer to a valid NUL-terminated array of bytes.
105 unsafe { CStr::from_ptr(execfn.cast()) }
106 }
107
108 #[cfg(feature = "runtime")]
109 #[inline]
110 pub(crate) fn linux_secure() -> bool {
111 let mut secure = SECURE.load(Relaxed);
112
113 // 0 means not initialized yet.
114 if secure == 0 {
115 init_auxv();
116 secure = SECURE.load(Relaxed);
117 }
118
119 // 0 means not present. Libc `getauxval(AT_SECURE)` would return 0.
120 // 1 means not in secure mode.
121 // 2 means in secure mode.
122 secure > 1
123 }
124
125 #[cfg(feature = "runtime")]
126 #[inline]
127 pub(crate) fn exe_phdrs() -> (*const c::c_void, usize, usize) {
128 let mut phdr = PHDR.load(Relaxed);
129 let mut phent = PHENT.load(Relaxed);
130 let mut phnum = PHNUM.load(Relaxed);
131
132 if phdr.is_null() || phnum == 0 {
133 init_auxv();
134 phdr = PHDR.load(Relaxed);
135 phent = PHENT.load(Relaxed);
136 phnum = PHNUM.load(Relaxed);
137 }
138
139 (phdr.cast(), phent, phnum)
140 }
141
142 /// `AT_SYSINFO_EHDR` isn't present on all platforms in all configurations, so
143 /// if we don't see it, this function returns a null pointer.
144 ///
145 /// And, this function returns a null pointer, rather than panicking, if the
146 /// auxv records can't be read.
147 #[inline]
148 pub(in super::super) fn sysinfo_ehdr() -> *const Elf_Ehdr {
149 let mut ehdr = SYSINFO_EHDR.load(Relaxed);
150
151 if ehdr.is_null() {
152 // Use `maybe_init_auxv` to read the aux vectors if it can, but do
153 // nothing if it can't. If it can't, then we'll get a null pointer
154 // here, which our callers are prepared to deal with.
155 maybe_init_auxv();
156
157 ehdr = SYSINFO_EHDR.load(Relaxed);
158 }
159
160 ehdr
161 }
162
163 #[cfg(feature = "runtime")]
164 #[inline]
165 pub(crate) fn entry() -> usize {
166 let mut entry = ENTRY.load(Relaxed);
167
168 if entry == 0 {
169 init_auxv();
170 entry = ENTRY.load(Relaxed);
171 }
172
173 entry
174 }
175
176 #[cfg(feature = "runtime")]
177 #[inline]
178 pub(crate) fn random() -> *const [u8; 16] {
179 let mut random = RANDOM.load(Relaxed);
180
181 if random.is_null() {
182 init_auxv();
183 random = RANDOM.load(Relaxed);
184 }
185
186 random
187 }
188
189 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
190 static CLOCK_TICKS_PER_SECOND: AtomicUsize = AtomicUsize::new(0);
191 static HWCAP: AtomicUsize = AtomicUsize::new(0);
192 static HWCAP2: AtomicUsize = AtomicUsize::new(0);
193 static MINSIGSTKSZ: AtomicUsize = AtomicUsize::new(0);
194 static EXECFN: AtomicPtr<c::c_char> = AtomicPtr::new(null_mut());
195 static SYSINFO_EHDR: AtomicPtr<Elf_Ehdr> = AtomicPtr::new(null_mut());
196 #[cfg(feature = "runtime")]
197 static SECURE: AtomicU8 = AtomicU8::new(0);
198 #[cfg(feature = "runtime")]
199 static PHDR: AtomicPtr<Elf_Phdr> = AtomicPtr::new(null_mut());
200 #[cfg(feature = "runtime")]
201 static PHENT: AtomicUsize = AtomicUsize::new(0);
202 #[cfg(feature = "runtime")]
203 static PHNUM: AtomicUsize = AtomicUsize::new(0);
204 #[cfg(feature = "runtime")]
205 static ENTRY: AtomicUsize = AtomicUsize::new(0);
206 #[cfg(feature = "runtime")]
207 static RANDOM: AtomicPtr<[u8; 16]> = AtomicPtr::new(null_mut());
208
209 const PR_GET_AUXV: c::c_int = 0x4155_5856;
210
211 /// Use Linux ≥ 6.4's `PR_GET_AUXV` to read the aux records, into a provided
212 /// statically-sized buffer. Return:
213 /// - `Ok(…)` if the buffer is big enough.
214 /// - `Err(Ok(len))` if we need a buffer of length `len`.
215 /// - `Err(Err(err))` if we failed with `err`.
216 #[cold]
217 fn pr_get_auxv_static(buffer: &mut [u8; 512]) -> Result<&mut [u8], crate::io::Result<usize>> {
218 let len = unsafe {
219 ret_usize(syscall_always_asm!(
220 __NR_prctl,
221 c_int(PR_GET_AUXV),
222 buffer.as_mut_ptr(),
223 pass_usize(buffer.len()),
224 pass_usize(0),
225 pass_usize(0)
226 ))
227 .map_err(Err)?
228 };
229 if len <= buffer.len() {
230 return Ok(&mut buffer[..len]);
231 }
232 Err(Ok(len))
233 }
234
235 /// Use Linux ≥ 6.4's `PR_GET_AUXV` to read the aux records, using a provided
236 /// statically-sized buffer if possible, or a dynamically allocated buffer
237 /// otherwise. Return:
238 /// - Ok(…) on success.
239 /// - Err(err) on failure.
240 #[cfg(feature = "alloc")]
241 #[cold]
242 fn pr_get_auxv_dynamic(buffer: &mut [u8; 512]) -> crate::io::Result<Cow<'_, [u8]>> {
243 // First try use the static buffer.
244 let len = match pr_get_auxv_static(buffer) {
245 Ok(buffer) => return Ok(Cow::Borrowed(buffer)),
246 Err(Ok(len)) => len,
247 Err(Err(err)) => return Err(err),
248 };
249
250 // If that indicates it needs a bigger buffer, allocate one.
251 let mut buffer = vec![0u8; len];
252 let len = unsafe {
253 ret_usize(syscall_always_asm!(
254 __NR_prctl,
255 c_int(PR_GET_AUXV),
256 buffer.as_mut_ptr(),
257 pass_usize(buffer.len()),
258 pass_usize(0),
259 pass_usize(0)
260 ))?
261 };
262 assert_eq!(len, buffer.len());
263 Ok(Cow::Owned(buffer))
264 }
265
266 /// Read the auxv records and initialize the various static variables. Panic
267 /// if an error is encountered.
268 #[cold]
269 fn init_auxv() {
270 init_auxv_impl().unwrap();
271 }
272
273 /// Like `init_auxv`, but don't panic if an error is encountered. The caller
274 /// must be prepared for initialization to be skipped.
275 #[cold]
276 fn maybe_init_auxv() {
277 let _ = init_auxv_impl();
278 }
279
280 /// If we don't have "use-explicitly-provided-auxv" or "use-libc-auxv", we
281 /// read the aux vector via the `prctl` `PR_GET_AUXV`, with a fallback to
282 /// /proc/self/auxv for kernels that don't support `PR_GET_AUXV`.
283 #[cold]
284 fn init_auxv_impl() -> Result<(), ()> {
285 let mut buffer = [0u8; 512];
286
287 // If we don't have "alloc", just try to read into our statically-sized
288 // buffer. This might fail due to the buffer being insufficient; we're
289 // prepared to cope, though we may do suboptimal things.
290 #[cfg(not(feature = "alloc"))]
291 let result = pr_get_auxv_static(&mut buffer);
292
293 // If we do have "alloc" then read into our statically-sized buffer if
294 // it fits, or fall back to a dynamically-allocated buffer.
295 #[cfg(feature = "alloc")]
296 let result = pr_get_auxv_dynamic(&mut buffer);
297
298 if let Ok(buffer) = result {
299 // SAFETY: We assume the kernel returns a valid auxv.
300 unsafe {
301 init_from_aux_iter(AuxPointer(buffer.as_ptr().cast())).unwrap();
302 }
303 return Ok(());
304 }
305
306 // If `PR_GET_AUXV` is unavailable, or if we don't have "alloc" and
307 // the aux records don't fit in our static buffer, then fall back to trying
308 // to open "/proc/self/auxv". We don't use `proc_self_fd` because its extra
309 // checking breaks on QEMU.
310 if let Ok(file) = crate::fs::open("/proc/self/auxv", OFlags::RDONLY, Mode::empty()) {
311 #[cfg(feature = "alloc")]
312 init_from_auxv_file(file).unwrap();
313
314 #[cfg(not(feature = "alloc"))]
315 unsafe {
316 init_from_aux_iter(AuxFile(file)).unwrap();
317 }
318
319 return Ok(());
320 }
321
322 Err(())
323 }
324
325 /// Process auxv entries from the open file `auxv`.
326 #[cfg(feature = "alloc")]
327 #[cold]
328 #[must_use]
329 fn init_from_auxv_file(auxv: OwnedFd) -> Option<()> {
330 let mut buffer = Vec::<u8>::with_capacity(512);
331 loop {
332 let cur = buffer.len();
333
334 // Request one extra byte; `Vec` will often allocate more.
335 buffer.reserve(1);
336
337 // Use all the space it allocated.
338 buffer.resize(buffer.capacity(), 0);
339
340 // Read up to that many bytes.
341 let n = match crate::io::read(&auxv, &mut buffer[cur..]) {
342 Err(crate::io::Errno::INTR) => 0,
343 Err(_err) => panic!(),
344 Ok(0) => break,
345 Ok(n) => n,
346 };
347
348 // Account for the number of bytes actually read.
349 buffer.resize(cur + n, 0_u8);
350 }
351
352 // SAFETY: We loaded from an auxv file into the buffer.
353 unsafe { init_from_aux_iter(AuxPointer(buffer.as_ptr().cast())) }
354 }
355
356 /// Process auxv entries from the auxv array pointed to by `auxp`.
357 ///
358 /// # Safety
359 ///
360 /// This must be passed a pointer to an auxv array.
361 ///
362 /// The buffer contains `Elf_aux_t` elements, though it need not be aligned;
363 /// function uses `read_unaligned` to read from it.
364 #[cold]
365 #[must_use]
366 unsafe fn init_from_aux_iter(aux_iter: impl Iterator<Item = Elf_auxv_t>) -> Option<()> {
367 let mut pagesz = 0;
368 let mut clktck = 0;
369 let mut hwcap = 0;
370 let mut hwcap2 = 0;
371 let mut minsigstksz = 0;
372 let mut execfn = null_mut();
373 let mut sysinfo_ehdr = null_mut();
374 #[cfg(feature = "runtime")]
375 let mut secure = 0;
376 #[cfg(feature = "runtime")]
377 let mut phdr = null_mut();
378 #[cfg(feature = "runtime")]
379 let mut phnum = 0;
380 #[cfg(feature = "runtime")]
381 let mut phent = 0;
382 #[cfg(feature = "runtime")]
383 let mut entry = 0;
384 #[cfg(feature = "runtime")]
385 let mut uid = None;
386 #[cfg(feature = "runtime")]
387 let mut euid = None;
388 #[cfg(feature = "runtime")]
389 let mut gid = None;
390 #[cfg(feature = "runtime")]
391 let mut egid = None;
392 #[cfg(feature = "runtime")]
393 let mut random = null_mut();
394
395 for Elf_auxv_t { a_type, a_val } in aux_iter {
396 match a_type as _ {
397 AT_PAGESZ => pagesz = a_val as usize,
398 AT_CLKTCK => clktck = a_val as usize,
399 AT_HWCAP => hwcap = a_val as usize,
400 AT_HWCAP2 => hwcap2 = a_val as usize,
401 AT_MINSIGSTKSZ => minsigstksz = a_val as usize,
402 AT_EXECFN => execfn = check_raw_pointer::<c::c_char>(a_val as *mut _)?.as_ptr(),
403 AT_SYSINFO_EHDR => sysinfo_ehdr = check_elf_base(a_val as *mut _)?.as_ptr(),
404
405 AT_BASE => {
406 // The `AT_BASE` value can be NULL in a static executable that
407 // doesn't use a dynamic linker. If so, ignore it.
408 if !a_val.is_null() {
409 let _ = check_elf_base(a_val.cast())?;
410 }
411 }
412
413 #[cfg(feature = "runtime")]
414 AT_SECURE => secure = (a_val as usize != 0) as u8 + 1,
415 #[cfg(feature = "runtime")]
416 AT_UID => uid = Some(a_val),
417 #[cfg(feature = "runtime")]
418 AT_EUID => euid = Some(a_val),
419 #[cfg(feature = "runtime")]
420 AT_GID => gid = Some(a_val),
421 #[cfg(feature = "runtime")]
422 AT_EGID => egid = Some(a_val),
423 #[cfg(feature = "runtime")]
424 AT_PHDR => phdr = check_raw_pointer::<Elf_Phdr>(a_val as *mut _)?.as_ptr(),
425 #[cfg(feature = "runtime")]
426 AT_PHNUM => phnum = a_val as usize,
427 #[cfg(feature = "runtime")]
428 AT_PHENT => phent = a_val as usize,
429 #[cfg(feature = "runtime")]
430 AT_ENTRY => entry = a_val as usize,
431 #[cfg(feature = "runtime")]
432 AT_RANDOM => random = check_raw_pointer::<[u8; 16]>(a_val as *mut _)?.as_ptr(),
433
434 AT_NULL => break,
435 _ => (),
436 }
437 }
438
439 #[cfg(feature = "runtime")]
440 assert_eq!(phent, size_of::<Elf_Phdr>());
441
442 // If we're running set-uid or set-gid, enable “secure execution” mode,
443 // which doesn't do much, but users may be depending on the things that
444 // it does do.
445 #[cfg(feature = "runtime")]
446 if uid != euid || gid != egid {
447 secure = 2;
448 }
449
450 // The base and sysinfo_ehdr (if present) matches our platform. Accept the
451 // aux values.
452 PAGE_SIZE.store(pagesz, Relaxed);
453 CLOCK_TICKS_PER_SECOND.store(clktck, Relaxed);
454 HWCAP.store(hwcap, Relaxed);
455 HWCAP2.store(hwcap2, Relaxed);
456 MINSIGSTKSZ.store(minsigstksz, Relaxed);
457 EXECFN.store(execfn, Relaxed);
458 SYSINFO_EHDR.store(sysinfo_ehdr, Relaxed);
459 #[cfg(feature = "runtime")]
460 SECURE.store(secure, Relaxed);
461 #[cfg(feature = "runtime")]
462 PHDR.store(phdr, Relaxed);
463 #[cfg(feature = "runtime")]
464 PHNUM.store(phnum, Relaxed);
465 #[cfg(feature = "runtime")]
466 ENTRY.store(entry, Relaxed);
467 #[cfg(feature = "runtime")]
468 RANDOM.store(random, Relaxed);
469
470 Some(())
471 }
472
473 /// Check that `base` is a valid pointer to the kernel-provided vDSO.
474 ///
475 /// `base` is some value we got from a `AT_SYSINFO_EHDR` aux record somewhere,
476 /// which hopefully holds the value of the kernel-provided vDSO in memory. Do a
477 /// series of checks to be as sure as we can that it's safe to use.
478 #[cold]
479 #[must_use]
480 unsafe fn check_elf_base(base: *const Elf_Ehdr) -> Option<NonNull<Elf_Ehdr>> {
481 // If we're reading a 64-bit auxv on a 32-bit platform, we'll see a zero
482 // `a_val` because `AT_*` values are never greater than `u32::MAX`. Zero is
483 // used by libc's `getauxval` to indicate errors, so it should never be a
484 // valid value.
485 if base.is_null() {
486 return None;
487 }
488
489 let hdr = match check_raw_pointer::<Elf_Ehdr>(base as *mut _) {
490 Some(hdr) => hdr,
491 None => return None,
492 };
493
494 let hdr = hdr.as_ref();
495 if hdr.e_ident[..SELFMAG] != ELFMAG {
496 return None; // Wrong ELF magic
497 }
498 if !matches!(hdr.e_ident[EI_OSABI], ELFOSABI_SYSV | ELFOSABI_LINUX) {
499 return None; // Unrecognized ELF OS ABI
500 }
501 if hdr.e_ident[EI_ABIVERSION] != ELFABIVERSION {
502 return None; // Unrecognized ELF ABI version
503 }
504 if hdr.e_type != ET_DYN {
505 return None; // Wrong ELF type
506 }
507
508 // If ELF is extended, we'll need to adjust.
509 if hdr.e_ident[EI_VERSION] != EV_CURRENT
510 || hdr.e_ehsize as usize != size_of::<Elf_Ehdr>()
511 || hdr.e_phentsize as usize != size_of::<Elf_Phdr>()
512 {
513 return None;
514 }
515 // We don't currently support extra-large numbers of segments.
516 if hdr.e_phnum == PN_XNUM {
517 return None;
518 }
519
520 // If `e_phoff` is zero, it's more likely that we're looking at memory that
521 // has been zeroed than that the kernel has somehow aliased the `Ehdr` and
522 // the `Phdr`.
523 if hdr.e_phoff < size_of::<Elf_Ehdr>() {
524 return None;
525 }
526
527 // Verify that the `EI_CLASS`/`EI_DATA`/`e_machine` fields match the
528 // architecture we're running as. This helps catch cases where we're
529 // running under QEMU.
530 if hdr.e_ident[EI_CLASS] != ELFCLASS {
531 return None; // Wrong ELF class
532 }
533 if hdr.e_ident[EI_DATA] != ELFDATA {
534 return None; // Wrong ELF data
535 }
536 if hdr.e_machine != EM_CURRENT {
537 return None; // Wrong machine type
538 }
539
540 Some(NonNull::new_unchecked(as_ptr(hdr) as *mut _))
541 }
542
543 // Aux reading utilities
544
545 // Read auxv records from an array in memory.
546 struct AuxPointer(*const Elf_auxv_t);
547
548 impl Iterator for AuxPointer {
549 type Item = Elf_auxv_t;
550
551 #[cold]
552 fn next(&mut self) -> Option<Self::Item> {
553 unsafe {
554 let value = read_unaligned(self.0);
555 self.0 = self.0.add(1);
556 Some(value)
557 }
558 }
559 }
560
561 // Read auxv records from a file.
562 #[cfg(not(feature = "alloc"))]
563 struct AuxFile(OwnedFd);
564
565 #[cfg(not(feature = "alloc"))]
566 impl Iterator for AuxFile {
567 type Item = Elf_auxv_t;
568
569 // This implementation does lots of `read`s and it isn't amazing, but
570 // hopefully we won't use it often.
571 #[cold]
572 fn next(&mut self) -> Option<Self::Item> {
573 let mut buf = [0_u8; size_of::<Self::Item>()];
574 let mut slice = &mut buf[..];
575 while !slice.is_empty() {
576 match crate::io::read(&self.0, slice) {
577 Ok(0) => panic!("unexpected end of auxv file"),
578 Ok(n) => slice = &mut slice[n..],
579 Err(crate::io::Errno::INTR) => continue,
580 Err(err) => panic!("{:?}", err),
581 }
582 }
583 Some(unsafe { read_unaligned(buf.as_ptr().cast()) })
584 }
585 }