oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! The auxiliary vector: what the kernel told the process at startup (the
//! page size, where the vDSO is...).
//!
//! The vector itself sits above the initial stack, and without a libc
//! nothing in the process has a pointer to it. The kernel serves a copy as
//! `/proc/self/auxv`: pairs of words, type then value. Where `/proc` is not
//! there (a chroot, a sandbox, a process that is not dumpable) there is no
//! vector, and every caller has a fallback.

use crate::sys::syscall;

/// `AT_PAGESZ`: the size of a page.
pub(crate) const AT_PAGESZ: usize = 6;
/// `AT_SYSINFO_EHDR`: the address of the vDSO's ELF header.
pub(crate) const AT_SYSINFO_EHDR: usize = 33;

const AT_FDCWD: i32 = -100;
const O_RDONLY: usize = 0;
/// The same on every architecture oscall supports.
const O_CLOEXEC: usize = 0o2000000;

/// The value of the entry `kind` of the auxiliary vector, read from
/// `/proc/self/auxv`. Every call reads the file: callers keep what they
/// find.
pub(crate) fn get(kind: usize) -> Option<usize> {
    // The kernel passes some twenty entries; 64 leaves room.
    let mut words = [0usize; 128];
    let capacity = size_of_val(&words);
    // SAFETY: the path is NUL-terminated, and opening a file for reading
    // has no effect on the process but the descriptor returned.
    let fd = unsafe {
        syscall!(
            OPENAT,
            AT_FDCWD,
            c"/proc/self/auxv".as_ptr(),
            O_RDONLY | O_CLOEXEC,
            0
        )
    }
    .ok()?;
    let mut filled = 0;
    while filled < capacity {
        // SAFETY: the destination is the unfilled end of `words`, and any
        // bytes make valid `usize`s.
        let read = unsafe {
            syscall!(
                READ,
                fd,
                words.as_mut_ptr().cast::<u8>().add(filled),
                capacity - filled
            )
        };
        match read {
            Ok(0) | Err(_) => break,
            Ok(n) => filled += n,
        }
    }
    // SAFETY: `fd` was opened above and is used by nothing else.
    unsafe { crate::sys::close(fd as i32) };

    words[..filled / size_of::<usize>()]
        .as_chunks::<2>()
        .0
        .iter()
        .find(|entry| entry[0] == kind)
        .map(|entry| entry[1])
}