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
//! Not a test, but the first process of the virtual machine in which
//! `scripts/vm.sh` runs tests: a kernel, this program as `/init`, and the
//! test programs under `/tests`, with nothing else, not even a shell.
//!
//! That is how the architectures no machine at hand runs natively (riscv64,
//! riscv32) get what an emulator of user programs cannot give: a kernel of
//! their own, with `clone3`, namespaces, cgroups and system call filters,
//! and root to use them.
//!
//! As a test program (`harness = false` in `Cargo.toml`) it is built
//! wherever the tests are, for every target, and does nothing: it only acts
//! as process 1 of a system that says so (`OSCALL_VM_INIT`, which the
//! kernel is given on its command line and passes on).

#[cfg(all(feature = "std", any(target_os = "linux", target_os = "fullrust")))]
mod vm {
    use oscall::fs::linux::{MountFlags, chroot, mount, move_mount};
    use oscall::process::{Command, Stdio};
    use oscall::raw::linux::syscall;

    /// What the system needs for the tests: a root that is a mount like
    /// another, and the file systems a distribution mounts at boot.
    fn set_up() -> std::io::Result<()> {
        // What the kernel unpacked this program into is its initial file
        // system, the one mount `pivot_root` refuses to leave. The tests
        // move to a file system of their own, mounted over it: what
        // `switch_root` does on a real system.
        let _ = std::fs::create_dir("/root");
        mount("root", "/root", "tmpfs", MountFlags::empty(), "")?;
        std::fs::create_dir("/root/tests")?;
        for entry in std::fs::read_dir("/tests")? {
            let from = entry?.path();
            std::fs::copy(
                &from,
                std::path::Path::new("/root/tests").join(from.file_name().unwrap()),
            )?;
            std::fs::remove_file(from)?;
        }
        oscall::fs::set_current_dir("/root")?;
        move_mount(".", "/")?;
        chroot(".")?;
        oscall::fs::set_current_dir("/")?;

        let safe = MountFlags::NO_SUID | MountFlags::NO_EXEC | MountFlags::NO_DEV;
        for dir in ["/proc", "/sys", "/dev", "/tmp", "/work"] {
            std::fs::create_dir(dir)?;
        }
        mount("proc", "/proc", "proc", safe, "")?;
        mount("sysfs", "/sys", "sysfs", safe, "")?;
        mount("devtmpfs", "/dev", "devtmpfs", MountFlags::NO_SUID, "")?;
        mount("cgroup2", "/sys/fs/cgroup", "cgroup2", safe, "")?;
        mount("tmpfs", "/tmp", "tmpfs", MountFlags::NO_SUID, "")?;
        loopback_up()?;
        Ok(oscall::fs::set_current_dir("/work")?)
    }

    /// Brings the loopback interface up, which nothing has done on a
    /// system without an `init` of its own: the tests of sockets
    /// (`tests/io_linux.rs`) connect to 127.0.0.1.
    fn loopback_up() -> std::io::Result<()> {
        use oscall::net::{Family, Protocol, Type, socket};
        const SIOCSIFFLAGS: usize = 0x8914;
        const IFF_UP: u8 = 1;
        // `struct ifreq`: the name, 16 bytes, then a union whose first
        // member here is the flags, a `short`. 40 bytes at most.
        let mut request = [0u8; 40];
        request[..2].copy_from_slice(b"lo");
        request[16] = IFF_UP;
        let any = socket(Family::Ipv4, Type::Datagram, Protocol::Default)?;
        // SAFETY: the call reads the structure, which is as large as any
        // `struct ifreq`.
        unsafe { syscall!(IOCTL, any.as_raw(), SIOCSIFFLAGS, request.as_ptr()) }?;
        Ok(())
    }

    /// Runs every program of `/tests`, in the order of their names, and
    /// says whether all passed.
    fn run() -> bool {
        if let Err(error) = set_up() {
            println!("init: cannot set the system up: {error}");
            return false;
        }
        let mut tests: Vec<_> = std::fs::read_dir("/tests")
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .collect();
        tests.sort();
        let env = [
            "OSCALL_REQUIRE_PRIVILEGED=1",
            "OSCALL_REQUIRE_IO_URING=1",
            "RUST_BACKTRACE=1",
            "PATH=/tests",
        ];
        let mut passed = !tests.is_empty();
        for test in tests {
            println!("== test {}", test.display());
            let spawned = Command::new(test.as_os_str().as_encoded_bytes())
                .env(&env)
                .stdin(Stdio::Null)
                .spawn();
            let status = spawned.and_then(|mut child| child.wait());
            match status {
                Ok(status) if status.success() => {}
                Ok(status) => {
                    println!("init: {}: {status}", test.display());
                    passed = false;
                }
                Err(error) => {
                    println!("init: {}: {error}", test.display());
                    passed = false;
                }
            }
        }
        passed
    }

    pub fn main() -> ! {
        // The line `scripts/vm.sh` looks for.
        let verdict = if run() { "passed" } else { "FAILED" };
        println!("== oscall-vm: {verdict}");
        // `reboot(LINUX_REBOOT_CMD_POWER_OFF)`, with its two magic
        // numbers. Process 1 must not return: the kernel would panic.
        loop {
            // SAFETY: the call takes numbers, and switches the machine
            // off: there is nothing to keep, on file systems in memory.
            let _ = unsafe { syscall!(REBOOT, 0xfee1_deadu32, 672_274_793, 0x4321_fedc, 0) };
        }
    }
}

fn main() {
    #[cfg(all(feature = "std", any(target_os = "linux", target_os = "fullrust")))]
    if oscall::process::id() == 1 && std::env::var_os("OSCALL_VM_INIT").is_some() {
        vm::main();
    }
}