oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `mem::linux`: what is mapped, as `/proc/self/maps` and its `ioctl`
//! say it, and which pages are in memory.

use core::sync::atomic::{AtomicU8, Ordering};

use crate::sys::{errno, syscall};
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};

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

pub(crate) const PROCMAP_QUERY_VMA_READABLE: u64 = 1;
pub(crate) const PROCMAP_QUERY_VMA_WRITABLE: u64 = 2;
pub(crate) const PROCMAP_QUERY_VMA_EXECUTABLE: u64 = 4;
pub(crate) const PROCMAP_QUERY_VMA_SHARED: u64 = 8;

/// `struct procmap_query` (`include/uapi/linux/fs.h`, Linux 6.11): 64-bit
/// members at multiples of eight, one layout everywhere.
#[repr(C)]
#[derive(Default)]
pub(crate) struct ProcmapQuery {
    size: u64,
    query_flags: u64,
    query_addr: u64,
    pub(crate) vma_start: u64,
    pub(crate) vma_end: u64,
    pub(crate) vma_flags: u64,
    vma_page_size: u64,
    pub(crate) vma_offset: u64,
    pub(crate) inode: u64,
    pub(crate) dev_major: u32,
    pub(crate) dev_minor: u32,
    pub(crate) vma_name_size: u32,
    build_id_size: u32,
    vma_name_addr: u64,
    build_id_addr: u64,
}

/// `PROCMAP_QUERY`: `_IOWR('f', 17, struct procmap_query)`, encoded the
/// same way by the six architectures.
const PROCMAP_QUERY: u32 = 3 << 30 | (size_of::<ProcmapQuery>() as u32) << 16 | 0x66 << 8 | 17;

const _: () = assert!(size_of::<ProcmapQuery>() == 104 && PROCMAP_QUERY == 0xc068_6611);

/// Opens `/proc/self/maps`.
pub(crate) fn open() -> Result<OwnedHandle> {
    let path = c"/proc/self/maps";
    // SAFETY: the path is a C string.
    let fd = unsafe { syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_RDONLY | O_CLOEXEC, 0) }?;
    // SAFETY: the descriptor was just opened.
    Ok(unsafe { OwnedHandle::from_raw(fd as i32) })
}

/// Whether the file answers `PROCMAP_QUERY`: 0 while unknown, 1 if it
/// does, 2 if not. A fact about the running kernel, which cannot change.
static HAS_QUERY: AtomicU8 = AtomicU8::new(0);

/// What `PROCMAP_QUERY` says of the mapping that holds `address`, with
/// its name in `name` (unless `name` is empty). `Ok(None)` when the file
/// has no such request: the text is then what there is to read.
/// `Ok(Some(None))` when nothing is mapped there.
pub(crate) fn query(
    maps: BorrowedHandle<'_>,
    address: usize,
    name: &mut [u8],
) -> Result<Option<Option<ProcmapQuery>>> {
    if HAS_QUERY.load(Ordering::Relaxed) == 2 {
        return Ok(None);
    }
    let mut query = ProcmapQuery {
        size: size_of::<ProcmapQuery>() as u64,
        query_addr: address as u64,
        vma_name_size: name.len().min(u32::MAX as usize) as u32,
        vma_name_addr: if name.is_empty() {
            0
        } else {
            name.as_mut_ptr().addr() as u64
        },
        ..ProcmapQuery::default()
    };
    // SAFETY: the kernel reads and writes one structure, and writes at
    // most `vma_name_size` bytes where `vma_name_addr` points.
    match unsafe { syscall!(IOCTL, maps.as_raw(), PROCMAP_QUERY, &raw mut query) } {
        Ok(_) => {
            HAS_QUERY.store(1, Ordering::Relaxed);
            Ok(Some(Some(query)))
        }
        Err(error) => match error.raw_os_error() {
            // A kernel older than the request, or an emulator that has
            // its own idea of the file.
            errno::ENOTTY | errno::ENOSYS => {
                HAS_QUERY.store(2, Ordering::Relaxed);
                Ok(None)
            }
            errno::ENOENT => Ok(Some(None)),
            errno::ENAMETOOLONG => Err(ErrorKind::BufferTooSmall.into()),
            _ => Err(error),
        },
    }
}

/// `mincore`: a byte per page of the range.
pub(crate) fn mincore(ptr: *const u8, len: usize, pages: &mut [u8]) -> Result<()> {
    // SAFETY: the caller checked that `pages` holds a byte for each page
    // of the range, which is what the kernel writes.
    unsafe { syscall!(MINCORE, ptr, len, pages.as_mut_ptr()) }.map(drop)
}