rustix/backend/linux_raw/param/
auxv.rs
1#![allow(unsafe_code)]
7
8use super::super::conv::{c_int, pass_usize, ret_usize};
9use crate::backend::c;
10use crate::fd::OwnedFd;
11#[cfg(feature = "param")]
12use crate::ffi::CStr;
13use crate::fs::{Mode, OFlags};
14use crate::utils::{as_ptr, check_raw_pointer};
15#[cfg(feature = "alloc")]
16use alloc::vec::Vec;
17use core::mem::size_of;
18use core::ptr::{null_mut, read_unaligned, NonNull};
19#[cfg(feature = "runtime")]
20use core::sync::atomic::AtomicU8;
21use core::sync::atomic::Ordering::Relaxed;
22use core::sync::atomic::{AtomicPtr, AtomicUsize};
23use linux_raw_sys::elf::*;
24use 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")]
29use 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")]
33use {alloc::borrow::Cow, alloc::vec};
34
35#[cfg(feature = "param")]
36#[inline]
37pub(crate) fn page_size() -> usize {
38 let mut page_size = PAGE_SIZE.load(Relaxed);
39
40 if page_size == 0 {
41 init_auxv();
42 page_size = PAGE_SIZE.load(Relaxed);
43 }
44
45 page_size
46}
47
48#[cfg(feature = "param")]
49#[inline]
50pub(crate) fn clock_ticks_per_second() -> u64 {
51 let mut ticks = CLOCK_TICKS_PER_SECOND.load(Relaxed);
52
53 if ticks == 0 {
54 init_auxv();
55 ticks = CLOCK_TICKS_PER_SECOND.load(Relaxed);
56 }
57
58 ticks as u64
59}
60
61#[cfg(feature = "param")]
62#[inline]
63pub(crate) fn linux_hwcap() -> (usize, usize) {
64 let mut hwcap = HWCAP.load(Relaxed);
65 let mut hwcap2 = HWCAP2.load(Relaxed);
66
67 if hwcap == 0 || hwcap2 == 0 {
68 init_auxv();
69 hwcap = HWCAP.load(Relaxed);
70 hwcap2 = HWCAP2.load(Relaxed);
71 }
72
73 (hwcap, hwcap2)
74}
75
76#[cfg(feature = "param")]
77#[inline]
78pub(crate) fn linux_minsigstksz() -> usize {
79 let mut minsigstksz = MINSIGSTKSZ.load(Relaxed);
80
81 if minsigstksz == 0 {
82 init_auxv();
83 minsigstksz = MINSIGSTKSZ.load(Relaxed);
84 }
85
86 minsigstksz
87}
88
89#[cfg(feature = "param")]
90#[inline]
91pub(crate) fn linux_execfn() -> &'static CStr {
92 let mut execfn = EXECFN.load(Relaxed);
93
94 if execfn.is_null() {
95 init_auxv();
96 execfn = EXECFN.load(Relaxed);
97 }
98
99 unsafe { CStr::from_ptr(execfn.cast()) }
102}
103
104#[cfg(feature = "runtime")]
105#[inline]
106pub(crate) fn linux_secure() -> bool {
107 let mut secure = SECURE.load(Relaxed);
108
109 if secure == 0 {
111 init_auxv();
112 secure = SECURE.load(Relaxed);
113 }
114
115 secure > 1
119}
120
121#[cfg(feature = "runtime")]
122#[inline]
123pub(crate) fn exe_phdrs() -> (*const c::c_void, usize, usize) {
124 let mut phdr = PHDR.load(Relaxed);
125 let mut phent = PHENT.load(Relaxed);
126 let mut phnum = PHNUM.load(Relaxed);
127
128 if phdr.is_null() || phnum == 0 {
129 init_auxv();
130 phdr = PHDR.load(Relaxed);
131 phent = PHENT.load(Relaxed);
132 phnum = PHNUM.load(Relaxed);
133 }
134
135 (phdr.cast(), phent, phnum)
136}
137
138#[inline]
144pub(in super::super) fn sysinfo_ehdr() -> *const Elf_Ehdr {
145 let mut ehdr = SYSINFO_EHDR.load(Relaxed);
146
147 if ehdr.is_null() {
148 maybe_init_auxv();
152
153 ehdr = SYSINFO_EHDR.load(Relaxed);
154 }
155
156 ehdr
157}
158
159#[cfg(feature = "runtime")]
160#[inline]
161pub(crate) fn entry() -> usize {
162 let mut entry = ENTRY.load(Relaxed);
163
164 if entry == 0 {
165 init_auxv();
166 entry = ENTRY.load(Relaxed);
167 }
168
169 entry
170}
171
172#[cfg(feature = "runtime")]
173#[inline]
174pub(crate) fn random() -> *const [u8; 16] {
175 let mut random = RANDOM.load(Relaxed);
176
177 if random.is_null() {
178 init_auxv();
179 random = RANDOM.load(Relaxed);
180 }
181
182 random
183}
184
185static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
186static CLOCK_TICKS_PER_SECOND: AtomicUsize = AtomicUsize::new(0);
187static HWCAP: AtomicUsize = AtomicUsize::new(0);
188static HWCAP2: AtomicUsize = AtomicUsize::new(0);
189static MINSIGSTKSZ: AtomicUsize = AtomicUsize::new(0);
190static EXECFN: AtomicPtr<c::c_char> = AtomicPtr::new(null_mut());
191static SYSINFO_EHDR: AtomicPtr<Elf_Ehdr> = AtomicPtr::new(null_mut());
192#[cfg(feature = "runtime")]
193static SECURE: AtomicU8 = AtomicU8::new(0);
194#[cfg(feature = "runtime")]
195static PHDR: AtomicPtr<Elf_Phdr> = AtomicPtr::new(null_mut());
196#[cfg(feature = "runtime")]
197static PHENT: AtomicUsize = AtomicUsize::new(0);
198#[cfg(feature = "runtime")]
199static PHNUM: AtomicUsize = AtomicUsize::new(0);
200#[cfg(feature = "runtime")]
201static ENTRY: AtomicUsize = AtomicUsize::new(0);
202#[cfg(feature = "runtime")]
203static RANDOM: AtomicPtr<[u8; 16]> = AtomicPtr::new(null_mut());
204
205const PR_GET_AUXV: c::c_int = 0x4155_5856;
206
207#[cold]
215fn pr_get_auxv_static(buffer: &mut [u8; 512]) -> Result<&mut [u8], crate::io::Result<usize>> {
216 let len = unsafe {
217 ret_usize(syscall_always_asm!(
218 __NR_prctl,
219 c_int(PR_GET_AUXV),
220 buffer.as_mut_ptr(),
221 pass_usize(buffer.len()),
222 pass_usize(0),
223 pass_usize(0)
224 ))
225 .map_err(Err)?
226 };
227 if len <= buffer.len() {
228 return Ok(&mut buffer[..len]);
229 }
230 Err(Ok(len))
231}
232
233#[cfg(feature = "alloc")]
241#[cold]
242fn pr_get_auxv_dynamic(buffer: &mut [u8; 512]) -> crate::io::Result<Cow<'_, [u8]>> {
243 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 let mut buffer = vec![0_u8; 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#[cold]
269fn init_auxv() {
270 init_auxv_impl().unwrap();
271}
272
273#[cold]
276fn maybe_init_auxv() {
277 let _ = init_auxv_impl();
278}
279
280#[cold]
284fn init_auxv_impl() -> Result<(), ()> {
285 let mut buffer = [0_u8; 512];
287
288 #[cfg(not(feature = "alloc"))]
292 let result = pr_get_auxv_static(&mut buffer);
293
294 #[cfg(feature = "alloc")]
297 let result = pr_get_auxv_dynamic(&mut buffer);
298
299 if let Ok(buffer) = result {
300 unsafe {
302 init_from_aux_iter(AuxPointer(buffer.as_ptr().cast())).unwrap();
303 }
304 return Ok(());
305 }
306
307 if let Ok(file) = crate::fs::open("/proc/self/auxv", OFlags::RDONLY, Mode::empty()) {
312 #[cfg(feature = "alloc")]
313 init_from_auxv_file(file).unwrap();
314
315 #[cfg(not(feature = "alloc"))]
316 unsafe {
317 init_from_aux_iter(AuxFile(file)).unwrap();
318 }
319
320 return Ok(());
321 }
322
323 Err(())
324}
325
326#[cfg(feature = "alloc")]
328#[cold]
329#[must_use]
330fn init_from_auxv_file(auxv: OwnedFd) -> Option<()> {
331 let mut buffer = Vec::<u8>::with_capacity(512);
332 loop {
333 let cur = buffer.len();
334
335 buffer.reserve(1);
337
338 buffer.resize(buffer.capacity(), 0);
340
341 let n = match crate::io::read(&auxv, &mut buffer[cur..]) {
343 Err(crate::io::Errno::INTR) => 0,
344 Err(_err) => panic!(),
345 Ok(0) => break,
346 Ok(n) => n,
347 };
348
349 buffer.resize(cur + n, 0_u8);
351 }
352
353 unsafe { init_from_aux_iter(AuxPointer(buffer.as_ptr().cast())) }
355}
356
357#[cold]
366#[must_use]
367unsafe fn init_from_aux_iter(aux_iter: impl Iterator<Item = Elf_auxv_t>) -> Option<()> {
368 let mut pagesz = 0;
369 let mut clktck = 0;
370 let mut hwcap = 0;
371 let mut hwcap2 = 0;
372 let mut minsigstksz = 0;
373 let mut execfn = null_mut();
374 let mut sysinfo_ehdr = null_mut();
375 #[cfg(feature = "runtime")]
376 let mut secure = 0;
377 #[cfg(feature = "runtime")]
378 let mut phdr = null_mut();
379 #[cfg(feature = "runtime")]
380 let mut phnum = 0;
381 #[cfg(feature = "runtime")]
382 let mut phent = 0;
383 #[cfg(feature = "runtime")]
384 let mut entry = 0;
385 #[cfg(feature = "runtime")]
386 let mut uid = None;
387 #[cfg(feature = "runtime")]
388 let mut euid = None;
389 #[cfg(feature = "runtime")]
390 let mut gid = None;
391 #[cfg(feature = "runtime")]
392 let mut egid = None;
393 #[cfg(feature = "runtime")]
394 let mut random = null_mut();
395
396 for Elf_auxv_t { a_type, a_val } in aux_iter {
397 match a_type as _ {
398 AT_PAGESZ => pagesz = a_val as usize,
399 AT_CLKTCK => clktck = a_val as usize,
400 AT_HWCAP => hwcap = a_val as usize,
401 AT_HWCAP2 => hwcap2 = a_val as usize,
402 AT_MINSIGSTKSZ => minsigstksz = a_val as usize,
403 AT_EXECFN => execfn = check_raw_pointer::<c::c_char>(a_val as *mut _)?.as_ptr(),
404 AT_SYSINFO_EHDR => sysinfo_ehdr = check_elf_base(a_val as *mut _)?.as_ptr(),
405
406 AT_BASE => {
407 if !a_val.is_null() {
410 let _ = check_elf_base(a_val.cast())?;
411 }
412 }
413
414 #[cfg(feature = "runtime")]
415 AT_SECURE => secure = (a_val as usize != 0) as u8 + 1,
416 #[cfg(feature = "runtime")]
417 AT_UID => uid = Some(a_val),
418 #[cfg(feature = "runtime")]
419 AT_EUID => euid = Some(a_val),
420 #[cfg(feature = "runtime")]
421 AT_GID => gid = Some(a_val),
422 #[cfg(feature = "runtime")]
423 AT_EGID => egid = Some(a_val),
424 #[cfg(feature = "runtime")]
425 AT_PHDR => phdr = check_raw_pointer::<Elf_Phdr>(a_val as *mut _)?.as_ptr(),
426 #[cfg(feature = "runtime")]
427 AT_PHNUM => phnum = a_val as usize,
428 #[cfg(feature = "runtime")]
429 AT_PHENT => phent = a_val as usize,
430 #[cfg(feature = "runtime")]
431 AT_ENTRY => entry = a_val as usize,
432 #[cfg(feature = "runtime")]
433 AT_RANDOM => random = check_raw_pointer::<[u8; 16]>(a_val as *mut _)?.as_ptr(),
434
435 AT_NULL => break,
436 _ => (),
437 }
438 }
439
440 #[cfg(feature = "runtime")]
441 assert_eq!(phent, size_of::<Elf_Phdr>());
442
443 #[cfg(feature = "runtime")]
447 if uid != euid || gid != egid {
448 secure = 2;
449 }
450
451 PAGE_SIZE.store(pagesz, Relaxed);
454 CLOCK_TICKS_PER_SECOND.store(clktck, Relaxed);
455 HWCAP.store(hwcap, Relaxed);
456 HWCAP2.store(hwcap2, Relaxed);
457 MINSIGSTKSZ.store(minsigstksz, Relaxed);
458 EXECFN.store(execfn, Relaxed);
459 SYSINFO_EHDR.store(sysinfo_ehdr, Relaxed);
460 #[cfg(feature = "runtime")]
461 SECURE.store(secure, Relaxed);
462 #[cfg(feature = "runtime")]
463 PHDR.store(phdr, Relaxed);
464 #[cfg(feature = "runtime")]
465 PHNUM.store(phnum, Relaxed);
466 #[cfg(feature = "runtime")]
467 ENTRY.store(entry, Relaxed);
468 #[cfg(feature = "runtime")]
469 RANDOM.store(random, Relaxed);
470
471 Some(())
472}
473
474#[cold]
480#[must_use]
481unsafe fn check_elf_base(base: *const Elf_Ehdr) -> Option<NonNull<Elf_Ehdr>> {
482 if base.is_null() {
487 return None;
488 }
489
490 let hdr = check_raw_pointer::<Elf_Ehdr>(base as *mut _)?;
491
492 let hdr = hdr.as_ref();
493 if hdr.e_ident[..SELFMAG] != ELFMAG {
494 return None; }
496 if !matches!(hdr.e_ident[EI_OSABI], ELFOSABI_SYSV | ELFOSABI_LINUX) {
497 return None; }
499 if hdr.e_ident[EI_ABIVERSION] != ELFABIVERSION {
500 return None; }
502 if hdr.e_type != ET_DYN {
503 return None; }
505
506 if hdr.e_ident[EI_VERSION] != EV_CURRENT
508 || hdr.e_ehsize as usize != size_of::<Elf_Ehdr>()
509 || hdr.e_phentsize as usize != size_of::<Elf_Phdr>()
510 {
511 return None;
512 }
513 if hdr.e_phnum == PN_XNUM {
515 return None;
516 }
517
518 if hdr.e_phoff < size_of::<Elf_Ehdr>() {
522 return None;
523 }
524
525 if hdr.e_ident[EI_CLASS] != ELFCLASS {
529 return None; }
531 if hdr.e_ident[EI_DATA] != ELFDATA {
532 return None; }
534 if hdr.e_machine != EM_CURRENT {
535 return None; }
537
538 Some(NonNull::new_unchecked(as_ptr(hdr) as *mut _))
539}
540
541struct AuxPointer(*const Elf_auxv_t);
545
546impl Iterator for AuxPointer {
547 type Item = Elf_auxv_t;
548
549 #[cold]
550 fn next(&mut self) -> Option<Self::Item> {
551 unsafe {
552 let value = read_unaligned(self.0);
553 self.0 = self.0.add(1);
554 Some(value)
555 }
556 }
557}
558
559#[cfg(not(feature = "alloc"))]
561struct AuxFile(OwnedFd);
562
563#[cfg(not(feature = "alloc"))]
564impl Iterator for AuxFile {
565 type Item = Elf_auxv_t;
566
567 #[cold]
570 fn next(&mut self) -> Option<Self::Item> {
571 let mut buf = [0_u8; size_of::<Self::Item>()];
572 let mut slice = &mut buf[..];
573 while !slice.is_empty() {
574 match crate::io::read(&self.0, &mut *slice) {
575 Ok(0) => panic!("unexpected end of auxv file"),
576 Ok(n) => slice = &mut slice[n..],
577 Err(crate::io::Errno::INTR) => continue,
578 Err(err) => panic!("{:?}", err),
579 }
580 }
581 Some(unsafe { read_unaligned(buf.as_ptr().cast()) })
582 }
583}