1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//! 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();
}
}