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
//! Helpers shared by the integration tests (`mod common;`).
#![allow(dead_code)]

use std::path::PathBuf;

/// A fresh, empty directory for the test `name`, which must be unique among
/// the tests of the crate.
///
/// It is a relative path under `target/`: the only place every platform can
/// write to (on WASI, only the current directory is accessible).
pub fn tmp_dir(name: &str) -> PathBuf {
    let dir = PathBuf::from("target").join("oscall-tests").join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// Borrows the handle of a `std` file, without needing the `std` feature of
/// oscall (the tests also run without it).
pub fn handle_of(file: &std::fs::File) -> oscall::BorrowedHandle<'_> {
    #[cfg(windows)]
    let raw = std::os::windows::io::AsRawHandle::as_raw_handle(file);
    #[cfg(not(windows))]
    let raw = std::os::fd::AsRawFd::as_raw_fd(file);
    // SAFETY: the handle stays open as long as `file` is borrowed.
    unsafe { oscall::BorrowedHandle::borrow_raw(raw) }
}

/// Whether the test runs under qemu-user, which shows by the kernel being
/// of another architecture than the program. (The emulator answers `uname`
/// for the program's sake, but leaves this file alone; a kernel older than
/// 6.1 does not have it, and the name of the process is then the only
/// clue, when the emulator was started by hand.) `OSCALL_TEST_EMULATED=0`
/// says it is not, whatever it looks like, and any other value that it is.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn emulated() -> bool {
    if let Some(forced) = std::env::var_os("OSCALL_TEST_EMULATED") {
        return forced != "0";
    }
    let program = std::env::consts::ARCH;
    if let Ok(kernel) = std::fs::read_to_string("/proc/sys/kernel/arch") {
        let kernel = kernel.trim();
        // A 64-bit kernel runs the 32-bit programs of its family.
        let native = match program {
            "x86" => kernel == "x86_64" || (kernel.starts_with('i') && kernel.ends_with("86")),
            "arm" => kernel.starts_with("arm") || kernel == "aarch64",
            program => kernel == program,
        };
        return !native;
    }
    std::fs::read_to_string("/proc/self/comm").is_ok_and(|name| name.starts_with("qemu"))
}

/// Writes a line to the standard error output of the process, past the
/// capture of the test harness (which only takes what `print!` and its
/// kin write): a test that skips something says so even when it passes.
pub fn note(line: &str) {
    use std::io::Write;
    let _ = writeln!(std::io::stderr().lock(), "{line}");
}

/// What may explain that a process has no use of the capabilities of its
/// user namespace: the switch of Ubuntu's AppArmor restriction, and the
/// AppArmor profile the process runs under. For the message of a test that
/// skips for that reason.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn confinement() -> String {
    let read = |path: &str| match std::fs::read_to_string(path) {
        Ok(text) => text.trim().trim_end_matches('\0').to_owned(),
        Err(_) => "unknown".to_owned(),
    };
    format!(
        "kernel.apparmor_restrict_unprivileged_userns is {}, the profile of the process is {}",
        read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns"),
        read("/proc/self/attr/current"),
    )
}

/// Whether the run is one that must be able to do everything
/// (`OSCALL_REQUIRE_PRIVILEGED`, set to anything but `0`): root, with
/// every capability, namespaces, a writable cgroup hierarchy and no system
/// call filter. `scripts/privileged.sh` and `scripts/vm.sh` make such
/// runs.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn privileged_required() -> bool {
    std::env::var_os("OSCALL_REQUIRE_PRIVILEGED").is_some_and(|value| value != "0")
}

/// Says that the environment does not allow what a test is about, and
/// why. The test then passes having tested nothing, which is the best an
/// environment without the feature can do, unless the run is one that
/// exists to cover such features ([`privileged_required`]): there this is
/// a failure.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn skip(reason: &str) {
    note(&format!("skipped: {reason}"));
    assert!(
        !privileged_required(),
        "skipped in a run that must skip nothing (OSCALL_REQUIRE_PRIVILEGED): {reason}"
    );
}

/// Says that the kernel has no time namespaces, which is the environment's
/// doing ([`skip`]) unless the kernel is one that cannot have them: they
/// need a vDSO with clocks, which 32-bit ARM and 32-bit RISC-V kernels
/// lack (as of Linux 6.18). A 32-bit program on a 64-bit kernel has them.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn no_time_namespaces() {
    let kernel = std::fs::read_to_string("/proc/sys/kernel/arch").unwrap_or_default();
    let kernel = kernel.trim();
    if kernel == "riscv32" || (kernel.starts_with("arm") && !kernel.starts_with("arm64")) {
        note(&format!(
            "skipped: {kernel} kernels have no time namespaces"
        ));
    } else {
        skip("the kernel has no time namespaces");
    }
}

/// A field of the status of the calling thread (`/proc/thread-self/status`,
/// or the one of the process where there is no such file): the word number
/// `index` after `name:`.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn status_field(name: &str, index: usize) -> String {
    let status = std::fs::read_to_string("/proc/thread-self/status")
        .or_else(|_| std::fs::read_to_string("/proc/self/status"))
        .unwrap();
    let line = status
        .lines()
        .find_map(|line| line.strip_prefix(name)?.strip_prefix(':'))
        .unwrap_or_else(|| panic!("no {name} in the status of the process"));
    line.split_whitespace()
        .nth(index)
        .unwrap_or_default()
        .to_owned()
}

/// A capability set of the calling thread, as `/proc` shows it: `name` is
/// `CapEff`, `CapPrm`, `CapInh`, `CapBnd` or `CapAmb`.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn status_capabilities(name: &str) -> u64 {
    u64::from_str_radix(&status_field(name, 0), 16).unwrap()
}

/// Why the environment refused to create a process in new namespaces, if
/// the error is one an environment answers with.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub fn namespace_refusal(error: &oscall::Error) -> Option<&'static str> {
    match error.raw_os_error() {
        // EPERM, EACCES
        1 | 13 => Some(
            "not permitted here (user namespaces restricted, or a container's system call filter)",
        ),
        // ENOSPC
        28 => Some("no user namespace may be created (user.max_user_namespaces)"),
        // ENOSYS
        38 => Some("the system call is missing (an emulator, a system call filter)"),
        // EINVAL
        22 if emulated() => Some("qemu-user does not create a process in new namespaces"),
        _ => None,
    }
}