git clone https://garage44.eu/jeroen/pinnacle.git.. /xtask/src/install.rs
//! Pinnacle on a disk of its own, from the host's side:
//!
//! - `cargo xtask loader [pc]`: Pinnacle's UEFI loader (`boot/`), built.
//! - `cargo xtask installer [pc]`: an install medium, `target/install-arm.img`
//! or `target/install-pc.img`, to write to a USB stick whole (`dd`): a
//! partition table, the boot partition (the loader where UEFI looks, the
//! kernel, its command line) and the system's partition. A firmware
//! starts it as it starts any stick; Settings โ Disks installs from it.
//! - `cargo xtask install-test [pc]`: the medium on a USB stick in QEMU,
//! booted by UEFI's firmware (edk2), installs itself on an empty NVMe disk
//! (`install-to=` on its command line), then the machine starts from that
//! disk alone.
//! - `cargo xtask install-demo [pc]`: the same as a person does it, in
//! Settings, with a USB tablet and keyboard, a screenshot each step.
use super::*;
use pinnacle_disk::gpt::{self, Guid, Partition, Table};
use pinnacle_disk::{Medium, fat};
/// The boot partition's size on a medium (the installer gives a disk the
/// same).
const BOOT_MIB: u64 = 300;
/// The empty disk installed on.
const TARGET_MIB: u64 = 2048;
/// A disk image file as a medium.
struct FileDisk(std::fs::File, u64);
impl Medium for FileDisk {
fn read_at(&mut self, offset: u64, into: &mut [u8]) -> bool {
use std::os::unix::fs::FileExt;
self.0.read_exact_at(into, offset).is_ok()
}
fn write_at(&mut self, offset: u64, from: &[u8]) -> bool {
use std::os::unix::fs::FileExt;
offset + from.len() as u64 <= self.1 && self.0.write_all_at(from, offset).is_ok()
}
fn size(&self) -> u64 {
self.1
}
}
fn open(path: &Path) -> Result<FileDisk> {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(path)
.map_err(|e| format!("{}: {e}", path.display()))?;
let size = file.metadata().map_err(|e| e.to_string())?.len();
Ok(FileDisk(file, size))
}
/// A blank file of `mib` MiB at `path`, made afresh (sparse).
fn blank(path: &Path, mib: u64) -> Result {
let _ = std::fs::remove_file(path);
std::fs::File::create(path)
.and_then(|f| f.set_len(mib << 20))
.map_err(|e| format!("{}: {e}", path.display()))
}
fn random_guid() -> Guid {
let mut bytes = [0u8; 16];
if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
let _ = f.read_exact(&mut bytes);
}
Guid::random(bytes)
}
fn name(arch: Arch) -> &'static str {
match arch {
Arch::Arm => "arm",
Arch::Pc => "pc",
}
}
/// The loader, built for `arch`: its `.efi`.
pub fn loader(arch: Arch) -> Result<PathBuf> {
let target = match arch {
Arch::Arm => "aarch64-unknown-uefi",
Arch::Pc => "x86_64-unknown-uefi",
};
let dir = root().join("target/boot");
let status = Command::new(env!("CARGO"))
.args([
"build",
"--locked",
"--release",
"--manifest-path",
"boot/Cargo.toml",
"--target",
target,
])
.arg("--target-dir")
.arg(&dir)
.current_dir(root())
.status()
.map_err(|e| format!("cargo: {e}"))?;
if !status.success() {
return Err(format!("the loader did not build for {target}"));
}
Ok(dir.join(target).join("release/pinnacle-boot.efi"))
}
/// Where UEFI looks for a loader on a disk it has no entry for.
fn loader_path(arch: Arch) -> &'static str {
match arch {
Arch::Arm => "EFI/BOOT/BOOTAA64.EFI",
Arch::Pc => "EFI/BOOT/BOOTX64.EFI",
}
}
/// The kernel, and the system disk, for `arch`.
fn kernel_and_system(arch: Arch) -> Result<(PathBuf, PathBuf)> {
match arch {
Arch::Arm => {
disks(&serve()?)?;
Ok((image("qemu-virt")?, root().join("target/system.img")))
}
Arch::Pc => {
let kernel = pc_kernel()?;
disks_for(Arch::Pc, &pc_system(), &serve()?, &[], 64)?;
Ok((kernel, pc_system()))
}
}
}
/// The install medium for `arch`, its kernel's command line ending in
/// `words`: `target/install-<arch>.img`.
pub fn medium(arch: Arch, words: &str) -> Result<PathBuf> {
let loader = std::fs::read(loader(arch)?).map_err(|e| format!("the loader: {e}"))?;
let (kernel, system) = kernel_and_system(arch)?;
let kernel = std::fs::read(&kernel).map_err(|e| format!("{}: {e}", kernel.display()))?;
let system_bytes = std::fs::read(&system).map_err(|e| format!("{}: {e}", system.display()))?;
let system_mib = (system_bytes.len() as u64).div_ceil(1 << 20);
let out = root().join(format!("target/install-{}.img", name(arch)));
// A MiB before the first partition, and one after the last for the
// table's copy.
blank(&out, 1 + BOOT_MIB + system_mib + 1)?;
let mut disk = open(&out)?;
let mib = (1 << 20) / 512;
let system_id = random_guid();
let boot_first = mib;
let system_first = boot_first + BOOT_MIB * mib;
let table = Table {
sector: 512,
disk: random_guid(),
partitions: vec![
Partition {
kind: gpt::EFI_SYSTEM,
id: random_guid(),
first: boot_first,
last: system_first - 1,
name: "boot".into(),
},
Partition {
kind: gpt::PINNACLE_SYSTEM,
id: system_id,
first: system_first,
last: system_first + system_mib * mib - 1,
name: "Pinnacle system".into(),
},
],
};
if !gpt::write(&mut disk, &table) {
return Err("the medium's partition table could not be written".into());
}
let line = format!("root={} {words}", system_id.text());
let line = line.trim_end();
fat::format(
&mut disk,
boot_first * 512,
BOOT_MIB << 20,
"PINNACLE",
u32::from_le_bytes(system_id.0[..4].try_into().unwrap()),
&[
(loader_path(arch), &loader),
("PINNACLE/KERNEL", &kernel),
("PINNACLE/CMDLINE", line.as_bytes()),
],
)?;
if !disk.write_at(system_first * 512, &system_bytes) {
return Err("the system could not be written to the medium".into());
}
println!("install medium: {} ({line})", out.display());
Ok(out)
}
/// QEMU's own UEFI firmware (edk2) for `arch`, as arguments: where QEMU
/// keeps it beside itself, else where Linux distributions put it.
/// `PINNACLE_FIRMWARE_ARM` / `_PC` name another.
pub fn firmware(arch: Arch) -> Result<Vec<String>> {
let variable = format!("PINNACLE_FIRMWARE_{}", name(arch).to_uppercase());
let binary = match arch {
Arch::Arm => qemu_binary(),
Arch::Pc => PathBuf::from("qemu-system-x86_64"),
};
// QEMU's data: beside its binary (`../share/qemu`), else the usual places.
let mut shares = vec![];
let found = if binary.is_absolute() {
Some(binary.clone())
} else {
std::env::var_os("PATH").and_then(|path| {
std::env::split_paths(&path)
.map(|p| p.join(&binary))
.find(|p| p.exists())
})
};
if let Some(bin) = found.and_then(|b| b.canonicalize().ok())
&& let Some(prefix) = bin.parent().and_then(Path::parent)
{
shares.push(prefix.join("share/qemu"));
}
for s in [
"/opt/homebrew/share/qemu",
"/usr/local/share/qemu",
"/usr/share/qemu",
] {
shares.push(PathBuf::from(s));
}
let candidates: Vec<PathBuf> = match arch {
Arch::Arm => shares
.iter()
.map(|s| s.join("edk2-aarch64-code.fd"))
.chain(
[
"/usr/share/AAVMF/AAVMF_CODE.fd",
"/usr/share/edk2/aarch64/QEMU_EFI.fd",
"/usr/share/edk2-armvirt/aarch64/QEMU_EFI.fd",
"/usr/share/qemu-efi-aarch64/QEMU_EFI.fd",
]
.map(PathBuf::from),
)
.collect(),
Arch::Pc => shares
.iter()
.map(|s| s.join("edk2-x86_64-code.fd"))
.chain(
[
"/usr/share/edk2/x64/OVMF_CODE.4m.fd",
"/usr/share/OVMF/OVMF_CODE_4M.fd",
"/usr/share/OVMF/OVMF_CODE.fd",
"/usr/share/edk2-ovmf/x64/OVMF_CODE.fd",
]
.map(PathBuf::from),
)
.collect(),
};
let code = std::env::var_os(&variable)
.map(PathBuf::from)
.or_else(|| candidates.into_iter().find(|p| p.exists()))
.ok_or_else(|| {
format!(
"no UEFI firmware for {} found (QEMU's edk2; or set {variable})",
name(arch)
)
})?;
match arch {
// virt takes the firmware as its first flash, from -bios.
Arch::Arm => Ok(vec!["-bios".into(), code.display().to_string()]),
// A PC's OVMF wants its variables beside it, in a second flash: a
// copy of the empty store each run.
Arch::Pc => {
let dir = code.parent().unwrap_or(Path::new("/"));
let vars = [
"edk2-i386-vars.fd",
"OVMF_VARS.4m.fd",
"OVMF_VARS_4M.fd",
"OVMF_VARS.fd",
]
.iter()
.map(|v| dir.join(v))
.find(|p| p.exists())
.ok_or_else(|| format!("no OVMF variable store beside {}", code.display()))?;
let copy = root().join("target/ovmf-vars.fd");
std::fs::copy(&vars, ©).map_err(|e| format!("{}: {e}", vars.display()))?;
Ok(vec![
"-drive".into(),
format!("if=pflash,format=raw,unit=0,readonly=on,file={}", code.display()),
"-drive".into(),
format!("if=pflash,format=raw,unit=1,file={}", copy.display()),
])
}
}
}
/// A machine started by UEFI's firmware: the devices the self-check wants
/// (screen, network, sound, entropy), USB with a keyboard and a tablet (the
/// only input), the NVMe disk `target`, and the install medium `stick`
/// on USB when given, which it then starts from.
fn machine(arch: Arch, stick: Option<&Path>, target: &Path) -> Result<Command> {
let (width, height) = screen();
let mut qemu = match arch {
Arch::Arm => {
let mut q = qemu_command();
// No ACPI: edk2 then hands the kernel QEMU's device tree.
q.args([
"-M",
"virt,gic-version=3,highmem=off,acpi=off",
"-cpu",
"cortex-a72",
])
.args(["-m", &memory(), "-smp", &cores().to_string()])
.args([
"-fw_cfg",
&format!("name=opt/pinnacle/screen,string={width}x{height}"),
])
.args(["-nographic", "-semihosting-config", "enable=on,target=native"])
.args(["-global", "virtio-mmio.force-legacy=false"])
.args([
"-device",
&format!("virtio-gpu-device,xres={width},yres={height}"),
])
.args([
"-netdev",
"user,id=net0",
"-device",
"virtio-net-device,netdev=net0",
])
.args([
"-audiodev",
"none,id=snd0",
"-device",
"virtio-sound-device,audiodev=snd0",
]);
q
}
Arch::Pc => {
let mut q = Command::new("qemu-system-x86_64");
// More memory than the PVH boots: the loader holds the kernel's
// file and its copy at once.
q.args(["-M", "q35", "-cpu", "max", "-m", "1G"])
.args(["-smp", &cores().to_string()])
.args(["-vga", "none", "-display", "none", "-monitor", "none"])
.args(["-serial", "stdio", "-no-reboot"])
.args(["-device", "isa-debug-exit,iobase=0xf4,iosize=0x04"])
.args(["-device", &format!("virtio-gpu-pci,xres={width},yres={height}")])
.args(["-netdev", "user,id=net0", "-device", "virtio-net-pci,netdev=net0"])
.args([
"-audiodev",
"none,id=snd0",
"-device",
"virtio-sound-pci,audiodev=snd0",
]);
q
}
};
qemu.args(firmware(arch)?)
.args(["-device", "virtio-rng-pci"])
.args(["-device", "qemu-xhci,id=xhci"])
.args(["-device", "usb-kbd,bus=xhci.0,id=usbkbd"])
.args(["-device", "usb-tablet,bus=xhci.0,id=usbtablet"])
.args([
"-drive",
&format!("if=none,id=target,format=raw,file={}", target.display()),
"-device",
&format!(
"nvme,serial=pinnacle0,drive=target{}",
if stick.is_none() { ",bootindex=0" } else { "" }
),
]);
if let Some(stick) = stick {
qemu.args([
"-drive",
&format!("if=none,id=stick,format=raw,snapshot=on,file={}", stick.display()),
"-device",
"usb-storage,bus=xhci.0,drive=stick,bootindex=0",
]);
}
Ok(qemu)
}
/// Runs `qemu` until it ends or the line `until` is printed (then ends it), within
/// `limit`; its output.
fn run_until(mut qemu: Command, until: Option<&str>, limit: Duration, label: &str) -> Result<String> {
use std::io::{BufRead, BufReader};
let mut child = qemu
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("qemu: {e}"))?;
let stdout = child.stdout.take().unwrap();
let (send, lines) = std::sync::mpsc::channel();
let prefix = label.to_string();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(|l| l.ok()) {
println!(" [{prefix}] {}", line.trim_end());
if send.send(line).is_err() {
break;
}
}
});
let mut guard = Running(Some(child));
let deadline = Instant::now() + limit;
let mut out = String::new();
loop {
match lines.recv_timeout(Duration::from_millis(200)) {
Ok(line) => {
// The whole line: "running" is also in "6 cores running".
let done = until.is_some_and(|u| line.trim() == u);
out += &line;
out.push('\n');
if done {
return Ok(out);
}
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
let child = guard.0.as_mut().unwrap();
let _ = child.wait();
return Ok(out);
}
Err(_) if Instant::now() > deadline => {
return Err(format!("{label}: nothing more within {}s", limit.as_secs()));
}
Err(_) => {}
}
}
}
fn require(out: &str, what: &str, lines: &[&str]) -> Result {
for line in lines {
if !out.contains(line) {
return Err(format!("{what}: no \"{line}\" in the output"));
}
}
Ok(())
}
/// What the installer must have put on `target`: the table, the boot
/// partition with this checkout's loader and kernel, a command line naming
/// the system partition, and a blank data partition.
fn check_installed(arch: Arch, target: &Path) -> Result {
let mut disk = open(target)?;
let table = gpt::read(&mut disk, 512).ok_or("the disk has no partition table")?;
let kinds: Vec<Guid> = table.partitions.iter().map(|p| p.kind).collect();
if kinds != [gpt::EFI_SYSTEM, gpt::PINNACLE_SYSTEM, gpt::PINNACLE_DATA] {
return Err(format!("the disk's partitions are {:?}", table.partitions));
}
let (boot_at, _) = table.partitions[0].range(512);
let loader = std::fs::read(loader(arch)?).map_err(|e| e.to_string())?;
let (kernel, _) = kernel_and_system(arch)?;
let kernel = std::fs::read(kernel).map_err(|e| e.to_string())?;
if fat::read_file(&mut disk, boot_at, loader_path(arch)).as_deref() != Some(&loader[..]) {
return Err("the boot partition's loader is not this checkout's".into());
}
if fat::read_file(&mut disk, boot_at, "PINNACLE/KERNEL").as_deref() != Some(&kernel[..]) {
return Err("the boot partition's kernel is not this checkout's".into());
}
let line = fat::read_file(&mut disk, boot_at, "PINNACLE/CMDLINE").ok_or("no command line")?;
// The new system named first; the stick's other words (`tone`) kept.
let expected = format!("root={}", table.partitions[1].id.text());
if String::from_utf8_lossy(&line).split(' ').next() != Some(expected.as_str()) {
return Err(format!(
"the command line is {:?}",
String::from_utf8_lossy(&line)
));
}
let (data_at, _) = table.partitions[2].range(512);
let mut first = [0u8; 4096];
disk.read_at(data_at, &mut first);
if first.iter().any(|&b| b != 0) {
return Err("the data partition is not blank".into());
}
println!(
"ok the disk: a partition table, the boot partition ({expected}), the system, a blank data partition"
);
Ok(())
}
/// `cargo xtask install-test [pc]`.
pub fn test(arch: Arch) -> Result {
let what = name(arch);
let medium = medium(arch, "install-to=nvme0n1")?;
let target = root().join(format!("target/installed-{what}.img"));
blank(&target, TARGET_MIB)?;
// From the stick: the firmware starts the loader on it, the system
// finds itself on the stick and installs itself on the NVMe disk.
let out = run_until(
machine(arch, Some(&medium), &target)?,
Some("install ok"),
Duration::from_secs(300),
&format!("{what} stick"),
)?;
require(
&out,
&format!("{what}, from the stick"),
&[
"Pinnacle: loading",
"Pinnacle: starting the kernel",
"keyboard (QEMU USB Keyboard)",
"tablet (QEMU USB Tablet)",
"disk: the system is on usb0, as the loader said",
"nvme0: ",
"install: Pinnacle on nvme0n1",
"install ok",
],
)?;
println!("ok {what}: started from a USB stick by UEFI, installed on NVMe");
check_installed(arch, &target)?;
// From the disk alone: its own loader, its own system.
let out = run_until(
machine(arch, None, &target)?,
Some("running"),
Duration::from_secs(300),
&format!("{what} disk"),
)?;
require(
&out,
&format!("{what}, from the disk"),
&[
"Pinnacle: loading",
"disk: the system is on nvme0n1, as the loader said",
"files ok",
"running",
],
)?;
println!("ok {what}: started from the NVMe disk it was installed on");
Ok(())
}
/// `cargo xtask install-demo [pc]`: Settings โ Disks โ Install, then the
/// machine started from the disk, a screenshot each step, into
/// `target/demo-install-<arch>/`.
pub fn demo(arch: Arch) -> Result {
const BUTTON: &str = "settings: button ";
let what = name(arch);
let dir = demo_dir(&format!("demo-install-{what}"))?;
let medium = medium(arch, "")?;
let target = root().join(format!("target/installed-{what}.img"));
blank(&target, TARGET_MIB)?;
{
let mut s = Session::attach(machine(arch, Some(&medium), &target)?, "[stick] ", false, || {
Ok(())
})?;
s.wait_for(&home_apps(0))?;
s.shot(&dir.join("1-home.png"))?;
s.tap_named("launcher: tile ", "Settings")?;
s.wait_for("display: Settings connected")?;
std::thread::sleep(Duration::from_millis(1500));
s.tap_named(BUTTON, "disks")?;
s.wait_for("settings: disks")?;
std::thread::sleep(Duration::from_millis(1000));
s.shot(&dir.join("2-disks.png"))?;
// The NVMe disk, found first; the stick it runs from has no button.
s.tap_named(BUTTON, "install-0")?;
s.wait_for("settings: install on disk")?;
std::thread::sleep(Duration::from_millis(1000));
s.shot(&dir.join("3-asked.png"))?;
s.tap_named(BUTTON, "install-confirm")?;
s.wait_for("settings: installing on nvme0n1: started")?;
std::thread::sleep(Duration::from_millis(800));
s.shot(&dir.join("4-installing.png"))?;
s.wait_any(&["install: Done"], Duration::from_secs(300))?;
std::thread::sleep(Duration::from_millis(1500));
s.shot(&dir.join("5-installed.png"))?;
}
check_installed(arch, &target)?;
let mut s = Session::attach(machine(arch, None, &target)?, "[disk] ", false, || Ok(()))?;
// Its data partition is blank: the first start asks for the password
// that makes it a vault, typed on the USB keyboard.
s.wait_for("display: choose a password for your data")?;
std::thread::sleep(Duration::from_millis(800));
s.shot(&dir.join("6-first-start.png"))?;
for _ in 0..2 {
s.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
std::thread::sleep(Duration::from_millis(300));
}
s.wait_for("display: data opened")?;
s.wait_for(&home_apps(0))?;
s.shot(&dir.join("7-home-from-disk.png"))?;
println!("ok {what}: installed from Settings, started from the disk");
Ok(())
}
/// A laptop as QEMU can make one, with none of QEMU's own (virtio)
/// devices: UEFI's firmware (OVMF), its screen a plain VGA's framebuffer
/// (GOP), the keyboard and the touchpad on the keyboard controller (PS/2),
/// cores with x2APIC, USB with a hub, Intel's Ethernet (e1000e), Intel HDA
/// sound (an ICH9's controller with an output codec, what it plays written
/// to `wav`), the NVMe disk `target`, and the install medium `stick`
/// behind the hub when given. No `isa-debug-exit`: it turns itself off by
/// ACPI, as a laptop does, and QEMU ends then.
fn laptop_machine(stick: Option<&Path>, target: &Path, wav: &Path) -> Result<Command> {
let mut q = Command::new("qemu-system-x86_64");
q.args(["-M", "q35", "-cpu", "max", "-m", "1G"])
.args(["-smp", &cores().to_string()])
.args(["-vga", "std", "-display", "none", "-monitor", "none"])
.args(["-serial", "stdio", "-no-reboot"])
.args(firmware(Arch::Pc)?)
.args(["-netdev", "user,id=net0", "-device", "e1000e,netdev=net0"])
.args([
"-audiodev",
&format!("wav,id=snd0,path={}", wav.display()),
"-device",
"ich9-intel-hda",
"-device",
"hda-output,audiodev=snd0",
])
.args(["-device", "qemu-xhci,id=xhci"])
.args(["-device", "usb-hub,bus=xhci.0,port=1"]);
let ssdt = root().join("target/laptop-ssdt.aml");
std::fs::write(&ssdt, laptop_ssdt()).map_err(|e| format!("{}: {e}", ssdt.display()))?;
q.args(["-acpitable", &format!("file={}", ssdt.display())]).args([
"-drive",
&format!("if=none,id=target,format=raw,file={}", target.display()),
"-device",
&format!(
"nvme,serial=pinnacle0,drive=target{}",
if stick.is_none() { ",bootindex=0" } else { "" }
),
]);
// Behind the hub, a blank USB disk: what a person plugs into a dock.
let dock = root().join("target/laptop-dock.img");
blank(&dock, 16)?;
q.args([
"-drive",
&format!("if=none,id=dock,format=raw,file={}", dock.display()),
"-device",
"usb-storage,bus=xhci.0,port=1.1,drive=dock",
]);
// The stick on a port of its own: OVMF starts nothing from behind a hub.
if let Some(stick) = stick {
q.args([
"-drive",
&format!("if=none,id=stick,format=raw,snapshot=on,file={}", stick.display()),
"-device",
"usb-storage,bus=xhci.0,port=2,drive=stick,bootindex=0",
]);
}
Ok(q)
}
/// What QEMU's machine has not and a laptop has, given as an SSDT
/// (`-acpitable`), written with `pinnacle_aml::asm`: a battery that loses
/// 50 mWh each time it is asked, a charger unplugged, a lid open. No
/// embedded controller: QEMU has none, so the battery's numbers are the
/// table's own.
fn laptop_ssdt() -> Vec<u8> {
use pinnacle_aml::asm::*;
const LGREATER: u8 = 0x94;
let battery = device(
"BAT0",
&[
name("_HID", &eisa("PNP0C0A")),
name("_UID", &int(1)),
name("BRC0", &int(30_000)),
method("_STA", 0, &[ret(&int(0x1f))]),
method(
"_BIF",
0,
&[ret(&package(&[
int(0),
int(57_000),
int(54_000),
int(1),
int(11_520),
int(5_400),
int(1_000),
int(100),
int(100),
string("Pinnacle Test"),
string("0001"),
string("LION"),
string("QEMU"),
]))],
),
method(
"_BST",
0,
&[
if_(
&compare(LGREATER, &path("BRC0"), &int(1_000)),
&[op2(SUBTRACT, &path("BRC0"), &int(50), &path("BRC0"))],
),
ret(&package(&[int(1), int(9_000), path("BRC0"), int(11_400)])),
],
),
],
);
let charger = device(
"ADP0",
&[
name("_HID", &string("ACPI0003")),
method("_PSR", 0, &[ret(&int(0))]),
],
);
let lid = device(
"LID0",
&[name("_HID", &eisa("PNP0C0D")), method("_LID", 0, &[ret(&int(1))])],
);
table(b"SSDT", &scope("\\_SB", &[battery, charger, lid]))
}
/// The lines a laptop's start must say, from the stick and from the disk.
const LAPTOP_LINES: &[&str] = &[
"Pinnacle: starting the kernel",
"apic: x2APIC mode",
"acpi: a computer, in ACPI mode; off by \\_S5; restart by its reset register; the power button heard",
"(firmware framebuffer)",
"ps2: a keyboard and a mouse or touchpad, with a wheel",
// The firmware's AML run: QEMU's DSDT whole, and the SSDT's battery,
// charger and lid read through their methods.
" 0 statements failed",
"power: ac=0",
"power: lid=open",
"power: battery=0|state=discharging|percent=",
"|full=54000|design=57000|unit=mWh|model=Pinnacle Test|maker=QEMU",
];
/// `cargo xtask laptop`: Pinnacle on a machine with a laptop's hardware
/// and none of QEMU's own (`laptop_machine`), as a person meets it: the
/// stick installs itself on the NVMe disk and
/// turns the machine off by ACPI; the machine started from the disk asks
/// for the data's password, typed on the PS/2 keyboard; the home screen;
/// the power button turns it off. A screenshot each step (the first of the
/// boot log on the screen), into `target/demo-laptop/`.
pub fn laptop() -> Result {
let dir = demo_dir("demo-laptop")?;
let medium = medium(Arch::Pc, "install-to=nvme0n1 tone")?;
let target = root().join("target/installed-laptop.img");
blank(&target, TARGET_MIB)?;
// Not ended when "install ok" is said: the machine must turn itself off.
let out = run_until(
laptop_machine(Some(&medium), &target, &root().join("target/laptop-stick.wav"))?,
None,
Duration::from_secs(300),
"laptop stick",
)?;
let mut lines = LAPTOP_LINES.to_vec();
lines.extend([
"hub (",
"storage usb",
"disk: the system is on usb",
"install: Pinnacle on nvme0n1",
"install ok",
]);
require(&out, "laptop, from the stick", &lines)?;
if out.contains("panic") {
return Err("laptop, from the stick: the kernel panicked".into());
}
println!(
"ok laptop: started from a stick, a disk seen behind a USB hub, installed on NVMe, off by ACPI"
);
check_installed(Arch::Pc, &target)?;
// What it plays: the self-check's 440 Hz tone, through Intel HDA.
let wav = root().join("target/laptop.wav");
let _ = std::fs::remove_file(&wav);
let mut s = Session::attach(
laptop_machine(None, &target, &wav)?,
"[laptop] ",
false,
|| Ok(()),
)?;
// The boot log on the firmware's screen, before the display server.
s.wait_for("smp: ")?;
s.shot(&dir.join("0-boot-log.png"))?;
s.wait_for("display: choose a password for your data")?;
std::thread::sleep(Duration::from_millis(800));
s.shot(&dir.join("1-first-start.png"))?;
for line in LAPTOP_LINES.iter().chain(&[
"random: seeded from the core's generator",
"net: Intel 82574L",
"net: address 10.0.2.15 from DHCP",
"hda: codec 0: ",
"sound: Intel HDA, 1 stream",
"audio ok",
// The firmware's screen through its write-combining window.
"us write-combining, ",
// QEMU's VGA is no Intel GPU and its DSDT has no _BCM: no
// brightness, and Settings shows no slider for it. The backlight
// itself waits for a laptop.
"backlight: none to set",
]) {
if !s.read.iter().any(|l| l.contains(line)) {
return Err(format!("laptop, from the disk: no \"{line}\" in the output"));
}
}
// The password, on the PS/2 keyboard (the only one there is).
for _ in 0..2 {
s.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
std::thread::sleep(Duration::from_millis(300));
}
s.wait_for("display: data opened")?;
s.wait_for(&home_apps(0))?;
// The touchpad moves the pointer.
for _ in 0..10 {
s.call(
r#"{"execute":"input-send-event","arguments":{"events":[{"type":"rel","data":{"axis":"x","value":-30}},{"type":"rel","data":{"axis":"y","value":-20}}]}}"#,
)?;
std::thread::sleep(Duration::from_millis(40));
}
std::thread::sleep(Duration::from_millis(800));
s.shot(&dir.join("2-home.png"))?;
// The power button: ACPI's fixed event, then off by \_S5.
s.call(r#"{"execute":"system_powerdown"}"#)?;
s.wait_for("acpi: the power button")?;
s.wait_for("system: turning off")?;
let deadline = Instant::now() + Duration::from_secs(20);
while s.child.try_wait().map_err(|e| e.to_string())?.is_none() {
if Instant::now() > deadline {
return Err("laptop: still on 20 s after the power button".into());
}
std::thread::sleep(Duration::from_millis(100));
}
// QEMU has ended, so the WAV is whole.
expect_tone(&wav, 440.0, 0.25)?;
println!("ok laptop: started from its disk, typed on PS/2, heard through HDA, off by its power button");
println!("note laptop: brightness untried (QEMU has no Intel GPU); it waits for a laptop");
Ok(())
}