🆕 Make arm64 VMs from an IPSW with reims-ctl, downloading the latest

On an arm64 Mac or arm64 Linux, `reims-ctl create NAME --ipsw latest|PATH`, or
the interface's form, restores macOS from an IPSW onto a new VM's disk with
reims-restore's pipeline, offline: no VM runs and none of Apple's code. The
create saves the VM in the layout Ambrosia's boot reads (disk.img, aux.img,
machine-identifier.bin, and vm.toml with the profile vmapple-arm64 and its aux
and ECID; the ECID as text, since one can pass TOML's integers). A macOS 14 VM
is named with its one step left: a boot that makes its Data volume, then
`reims-restore finish-eacs DIR`.

`latest` is the current macOS in Apple's IPSW catalog, which lists only the
current release, so another is given by its IPSW's path, as the owner chose. The
IPSW downloads into the installers directory and continues after a stop;
`reims-ctl downloads` lists and deletes what is kept, never one a VM uses or one
being downloaded. The space check covers the download and the restore together.
A failed or stopped restore leaves nothing, and its log moves to the cache,
where the error names it.

reims-ctl doesn't start arm64 VMs yet: start, describe, doctor and the USB and
GPU views say so. Windows and Linux x86-64 keep their profile; host.rs adds
vmapple-arm64 for arm64 Macs (HVF) and arm64 Linux (KVM).

On those hosts scripts/install-ctl.sh installs reims-ctl alone: the restore runs
no QEMU and reims-ctl starts no arm64 VM. A Mac needs Xcode's command line
tools; arm64 Linux a C toolchain, git and curl (apt, pacman or dnf).
docs/qemu.md says so.
This commit is contained in:
Anees Iqbal committed 2026-11-16 02:03:39 -08:00
1 parent ad3b37b8e8
commit b5ad91b938
17 files changed
+3521 -269

No files matched your search

+1066 -36
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -23,6 +23,9 @@ plist = "1.10.1"
# The viewer's frames for the kitty and iTerm2 image protocols (view/encode.rs).
png = "0.18.1"
ratatui = "0.30.2"
# Restores an arm64 VM's macOS from an IPSW (restore.rs): this repository's crate, its own
# workspace.
reims-restore = { path = "../reims-restore" }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.153"
shlex = "2.0.1"
+174 -36
View File
@@ -111,6 +111,12 @@ pub enum Cmd {
#[arg(long, value_name = "DEVICE")]
remove: Vec<String>,
},
/// List what's downloaded for new VMs (macOS installers and IPSWs) and the space each
/// takes, or delete one
Downloads {
#[command(subcommand)]
action: Option<DownloadsCmd>,
},
/// Print the end of a VM's QEMU log, or its serial console's
Logs {
name: String,
@@ -140,8 +146,9 @@ pub enum Cmd {
RecordInstall {
#[arg(long)]
repo: PathBuf,
/// The QEMU build installed; none on an arm64 host, which makes VMs without one.
#[arg(long)]
qemu: PathBuf,
qemu: Option<PathBuf>,
#[arg(long, default_value = "")]
commit: String,
},
@@ -267,7 +274,85 @@ const CREATE_EXAMPLES: &str = r"
reims-ctl create mac --disk ~/vms/old/disk.qcow2
# Or with the OpenCore image it booted from, copied, which keeps its Mac too
reims-ctl create mac --disk ~/vms/mac.qcow2 --opencore ~/vms/OpenCore.qcow2";
reims-ctl create mac --disk ~/vms/mac.qcow2 --opencore ~/vms/OpenCore.qcow2
An arm64 guest on an arm64 Mac or arm64 Linux:
# Download the current macOS's IPSW from Apple (about 25 GB, kept for the next VM; a
# stopped download continues) and restore it onto a new 128G disk, with tickets Apple
# signs for the VM (reims-ctl doesn't start arm64 VMs yet)
reims-ctl create mac --ipsw latest
# An IPSW of your own, read where it is: Apple offers only the current macOS to download.
# macOS 14 makes its Data volume at the VM's first boot and then resets the VM: after that
# boot, reims-restore finish-eacs DIR makes it ready for Setup Assistant
reims-ctl create mac --ipsw ~/Downloads/UniversalMac_14.6.1_23G93_Restore.ipsw";
#[derive(Subcommand)]
pub enum DownloadsCmd {
/// Delete downloads, by the names the list shows: a later VM of their macOS downloads them
/// again
Delete {
#[arg(required = true, value_name = "NAME")]
names: Vec<String>,
/// Do not ask
#[arg(long, short)]
yes: bool,
},
}
/// `downloads`: what's kept for new VMs, and the space it takes.
fn downloads() {
let items = crate::downloads::list();
let dirs: Vec<String> = crate::downloads::dirs()
.iter()
.filter(|d| d.is_dir())
.map(|d| paths::tilde(d))
.collect();
if items.is_empty() {
println!(
"Nothing is downloaded: a new VM downloads its macOS, and it's kept here for the next."
);
return;
}
let w = items
.iter()
.map(|i| i.name().len())
.max()
.unwrap_or(4)
.max(4);
println!("{:<w$} {:>8} WHAT", "NAME", "SIZE");
for i in &items {
println!(
"{:<w$} {:>8} {}",
i.name(),
crate::downloads::size(i.bytes),
i.what
);
}
let total: u64 = items.iter().map(|i| i.bytes).sum();
println!(
"\n{} in {}. reims-ctl downloads delete NAME deletes one.",
crate::downloads::size(total),
dirs.join(" and ")
);
}
/// `downloads delete`: each of `names`, asking first unless `yes`.
fn delete_downloads(names: &[String], yes: bool) -> Result<()> {
let items = crate::downloads::list();
for n in names {
let Some(i) = items.iter().find(|i| &i.name() == n) else {
bail!("no download is named {n}: reims-ctl downloads lists them");
};
if !yes && !confirm(&format!("Delete {n}, {}?", crate::downloads::size(i.bytes))) {
println!("{n}: not deleted");
continue;
}
println!("{}", crate::downloads::delete(n)?);
}
Ok(())
}
#[derive(Args)]
pub struct CreateArgs {
@@ -310,6 +395,12 @@ pub struct CreateArgs {
/// image's BaseSystem.img, or a DMG, converted to a raw image in the VM's directory
#[arg(long)]
pub installer: Option<PathBuf>,
/// On an arm64 Mac or arm64 Linux: the IPSW to restore an arm64 VM's macOS from: latest,
/// the current macOS, downloaded from Apple once and kept (reims-ctl downloads lists it),
/// or an IPSW's path, read where it is. A macOS 14 VM needs one boot, which makes its Data
/// volume, and then `reims-restore finish-eacs DIR`
#[arg(long, value_name = "latest|PATH", conflicts_with_all = ["macos", "installer", "disk", "opencore"])]
pub ipsw: Option<String>,
/// An OpenCore image of your own to copy, with OVMF_CODE.fd and OVMF_VARS.fd beside it
/// (default: a new one made for the VM, with OVMF, presenting the Mac of the image beside
/// --disk, opencore.qcow2, where there is one and --disk is no copy of the disk of a VM
@@ -513,6 +604,10 @@ pub fn main(cli: Cli) -> Result<i32> {
);
}
Cmd::Gpus => gpus(host),
Cmd::Downloads { action } => match action {
None => downloads(),
Some(DownloadsCmd::Delete { names, yes }) => delete_downloads(&names, yes)?,
},
Cmd::Usb { name, add, remove } => usb(host, name.as_deref(), &add, &remove)?,
Cmd::Logs {
name,
@@ -550,7 +645,7 @@ pub fn main(cli: Cli) -> Result<i32> {
install::Install {
repo: repo.clone(),
commit,
qemu,
qemu: qemu.unwrap_or_default(),
installed_at: runtime::now_stamp("%Y-%m-%d %H:%M:%S %z"),
}
.save()?;
@@ -682,8 +777,15 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
.or(a.name_pos.clone())
.ok_or_else(|| with_create_examples("give the VM a name: reims-ctl create NAME"))?;
// Nothing a VM is made from: whatever create says is missing, the examples show the ways.
let source =
a.macos.is_some() || a.installer.is_some() || a.disk.is_some() || a.opencore.is_some();
let source = a.macos.is_some()
|| a.installer.is_some()
|| a.disk.is_some()
|| a.opencore.is_some()
|| a.ipsw.is_some();
let arm64 = host.default_profile() == Some(Profile::VmappleArm64);
if arm64 && a.start {
bail!("reims-ctl doesn't start arm64 VMs yet: create it without --start");
}
let mut s = Spec::new(&name);
s.dir = a
.dir
@@ -700,7 +802,7 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
mode: ImportMode::parse(&a.disk_mode)?,
}),
(None, None) => Some(DiskSource::New {
size_mib: 128 * 1024,
size_mib: create::DEFAULT_DISK_MIB,
}),
};
let abs = |p: &Option<PathBuf>| p.as_ref().map(|p| paths::absolute(&p.to_string_lossy()));
@@ -710,6 +812,13 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
});
s.opencore = abs(&a.opencore);
s.installer = abs(&a.installer);
s.ipsw = a.ipsw.as_deref().map(|i| {
if crate::ipsw::is_path(i) {
paths::absolute(i).display().to_string()
} else {
i.to_string()
}
});
s.mac = a.mac.clone();
s.graphics = a.graphics.as_deref().map(vm::Graphics::parse).transpose()?;
if let Some(n) = a.displays {
@@ -727,6 +836,10 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
s.audio = a.audio.unwrap_or(true);
s.network = a.network.unwrap_or(true);
s.ssh_port = a.ssh_port;
if arm64 {
// Ctrl-C stops the restore, which removes what it made.
crate::restore::stop_at_interrupt();
}
let vm = create::create(s, host, &mut |p| println!("{name}: {p}")).map_err(|e| {
if source {
e
@@ -897,6 +1010,15 @@ pub fn describe(vm: &Vm, host: Host) -> Vec<(String, String)> {
),
None => add("disk", format!("{disk_name} ({})", c.disk_format.as_str())),
}
if let Some(a) = &c.vmapple {
add("aux", paths::tilde(&vm.path(&a.aux)));
add("ecid", format!("{:#018x}", a.ecid));
}
// Its devices are those of its start, which an arm64 VM doesn't have yet.
if !c.profile.starts() {
add("start", "not yet: reims-ctl doesn't start arm64 VMs".into());
return v;
}
let graphics = c.graphics();
match graphics {
vm::Graphics::VmwareSvga => add(
@@ -1188,9 +1310,12 @@ fn set(a: SetArgs, host: Host) -> Result<()> {
}
fn gpus(host: Host) {
if host.default_profile().is_none() {
println!("{}", crate::host::UNSUPPORTED);
return;
match host.default_profile() {
None => return println!("{}", crate::host::UNSUPPORTED),
Some(p) if !p.gpu_choice(host) => {
return println!("A VM's GPU: {}", crate::host::X86_64_ONLY);
}
Some(_) => {}
}
let list = gpu::list();
if list.is_empty() {
@@ -1220,8 +1345,10 @@ fn gpus(host: Host) {
/// `remove` first.
fn usb(host: Host, name: Option<&str>, add: &[String], remove: &[String]) -> Result<()> {
use crate::usb;
if host.default_profile().is_none() {
bail!("{}", crate::host::UNSUPPORTED);
match host.default_profile() {
None => bail!("{}", crate::host::UNSUPPORTED),
Some(Profile::VmappleArm64) => bail!("USB passthrough: {}", crate::host::X86_64_ONLY),
Some(Profile::Q35X86_64) => {}
}
let devices = usb::host_devices();
let Some(name) = name else {
@@ -1340,7 +1467,11 @@ fn doctor(host: Host) -> Result<i32> {
format!(
"{host}{}",
profile
.map(|p| format!(", runs {p} VMs"))
.map(|p| if p.starts() {
format!(", runs {p} VMs")
} else {
format!(", makes {p} VMs from IPSWs (it doesn't start them yet)")
})
.unwrap_or_else(|| format!(": {}", crate::host::UNSUPPORTED))
),
);
@@ -1354,29 +1485,32 @@ fn doctor(host: Host) -> Result<i32> {
),
);
let Some(profile) = profile else { return Ok(1) };
match install::qemu_binary(profile) {
Ok(q) => {
line(
true,
"qemu",
format!(
"{} ({})",
q.display(),
install::qemu_version(&q).unwrap_or_default()
),
);
let b = install::audio_backends(&q);
line(
true,
"audio backends",
format!(
"{} (default {})",
b.join(", "),
install::default_audio_backend(&b)
),
);
// An arm64 VM is made by a restore, which runs no QEMU, and isn't started.
if profile.starts() {
match install::qemu_binary(profile) {
Ok(q) => {
line(
true,
"qemu",
format!(
"{} ({})",
q.display(),
install::qemu_version(&q).unwrap_or_default()
),
);
let b = install::audio_backends(&q);
line(
true,
"audio backends",
format!(
"{} (default {})",
b.join(", "),
install::default_audio_backend(&b)
),
);
}
Err(e) => line(false, "qemu", format!("{e:#}")),
}
Err(e) => line(false, "qemu", format!("{e:#}")),
}
match install::Install::load() {
Some(i) => line(
@@ -1395,8 +1529,9 @@ fn doctor(host: Host) -> Result<i32> {
"no install record: reims-ctl update needs scripts/install-ctl.sh to have run".into(),
),
}
// KVM and the library's needs, for the x86-64 VMs Linux runs.
match host.os {
crate::host::Os::Linux => {
crate::host::Os::Linux if profile == Profile::Q35X86_64 => {
let kvm = std::fs::OpenOptions::new()
.read(true)
.write(true)
@@ -1529,7 +1664,10 @@ fn doctor(host: Host) -> Result<i32> {
},
);
}
crate::host::Os::Mac | crate::host::Os::Windows | crate::host::Os::Other => {}
crate::host::Os::Linux
| crate::host::Os::Mac
| crate::host::Os::Windows
| crate::host::Os::Other => {}
}
if profile == Profile::Q35X86_64 {
// What makes a new VM's OpenCore image, with its OVMF, and downloads its installer.
+619 -6
View File
@@ -11,13 +11,20 @@
//! no VM half made, or one given. An installer is used in place, except a DMG, which qemu-img
//! converts to a raw image in the VM's directory, saying how far it is ([`installer_media`]). A
//! VM's settings name its graphics: reims-vgpu's own device unless the create chose another.
//!
//! An arm64 VM (`vmapple-arm64`) is macOS restored from an IPSW onto a new raw disk
//! (restore.rs), with the auxiliary storage and ECID the restore leaves beside it. Its IPSW is
//! found, and downloaded where it isn't here (ipsw.rs), before its directory is made; the restore
//! checks the space it writes before it writes anything.
use crate::copy;
use crate::host::{Host, Profile};
use crate::install;
use crate::ipsw;
use crate::opencore::{self, Identity};
use crate::paths;
use crate::reims_util::{self, Download};
use crate::restore::{self, Restorer};
use crate::vm::*;
use anyhow::{Context, Result, bail};
use std::collections::BTreeMap;
@@ -75,6 +82,10 @@ pub struct Spec {
pub macos: Option<Download>,
pub opencore: Option<PathBuf>,
pub installer: Option<PathBuf>,
// vmapple
/// The IPSW an arm64 VM's macOS is restored from: its path, or `latest`, the current macOS,
/// downloaded from Apple (ipsw.rs).
pub ipsw: Option<String>,
}
impl Spec {
@@ -97,6 +108,7 @@ impl Spec {
macos: None,
opencore: None,
installer: None,
ipsw: None,
}
}
}
@@ -127,6 +139,23 @@ pub fn default_dir(name: &str) -> PathBuf {
/// Makes the VM, calling `progress` with each step, and registers it.
pub fn create(spec: Spec, host: Host, progress: &mut dyn FnMut(&str)) -> Result<Vm> {
create_with(
spec,
host,
progress,
&restore::Pipeline,
restore::cancel_flag(),
)
}
/// [`create`], restoring an arm64 VM's macOS with `restorer`, which stops when `cancel` is set.
pub fn create_with(
spec: Spec,
host: Host,
progress: &mut dyn FnMut(&str),
restorer: &dyn Restorer,
cancel: &std::sync::atomic::AtomicBool,
) -> Result<Vm> {
check_name(&spec.name)?;
if let Some(m) = &spec.mac {
check_mac(m)?;
@@ -143,6 +172,12 @@ pub fn create(spec: Spec, host: Host, progress: &mut dyn FnMut(&str)) -> Result<
if !Profile::supported_on(host).contains(&profile) {
bail!("{}", crate::host::UNSUPPORTED);
}
if profile == Profile::VmappleArm64 {
return create_vmapple(spec, progress, restorer, cancel);
}
if spec.ipsw.is_some() {
bail!("an IPSW makes an arm64 VM, which arm64 Macs and arm64 Linux make");
}
// The image reims-util makes holds them.
if graphics == Graphics::ReimsVgpu && spec.opencore.is_none() {
crate::prebuilt::set()?;
@@ -193,15 +228,25 @@ pub fn create(spec: Spec, host: Host, progress: &mut dyn FnMut(&str)) -> Result<
macos = Some(i.version);
}
let made = claim(&dir)?;
let result = match profile {
Profile::Q35X86_64 => make_q35(&spec, graphics, &dir, macos.as_deref(), progress),
};
let result = make_q35(&spec, graphics, &dir, macos.as_deref(), progress);
finish(&spec.name, &dir, made, result, progress)
}
/// Saves and registers the VM made in `dir`, or, where making it failed, removes what was made:
/// `dir` itself where the create made it, else everything in it.
fn finish(
name: &str,
dir: &Path,
made: bool,
result: Result<Vm>,
progress: &mut dyn FnMut(&str),
) -> Result<Vm> {
let vm = match result {
Ok(vm) => vm,
Err(e) => {
if made {
let _ = std::fs::remove_dir_all(&dir);
} else if let Ok(rd) = std::fs::read_dir(&dir) {
let _ = std::fs::remove_dir_all(dir);
} else if let Ok(rd) = std::fs::read_dir(dir) {
for e in rd.flatten() {
let _ = if e.path().is_dir() {
std::fs::remove_dir_all(e.path())
@@ -217,12 +262,174 @@ pub fn create(spec: Spec, host: Host, progress: &mut dyn FnMut(&str)) -> Result<
let _ = std::fs::remove_file(dir.join(CREATING));
// Read again: VMs may have come and gone while this one was made, over a download.
let mut reg = Registry::load()?;
reg.add(&spec.name, &dir)?;
reg.add(name, dir)?;
reg.save()?;
progress("done");
Ok(vm)
}
/// Makes an arm64 VM: macOS restored from the spec's IPSW onto a new raw disk.
fn create_vmapple(
spec: Spec,
progress: &mut dyn FnMut(&str),
restorer: &dyn Restorer,
cancel: &std::sync::atomic::AtomicBool,
) -> Result<Vm> {
// Held until the directory of a failed restore is gone, which the interface waits for as it
// quits.
let _busy = restore::Busy::new();
let Some(want) = spec.ipsw.clone() else {
bail!("an arm64 VM is made from an IPSW: give one with --ipsw, or --ipsw latest");
};
let size_mib = match &spec.disk {
None => DEFAULT_DISK_MIB,
Some(DiskSource::New { size_mib }) => *size_mib,
Some(DiskSource::Existing { .. }) => {
bail!("an arm64 VM's disk is a new one its IPSW is restored onto, not an existing one")
}
};
if spec.macos.is_some() || spec.installer.is_some() || spec.opencore.is_some() {
bail!(
"an arm64 VM's macOS comes from its IPSW: a download, an installer and OpenCore are \
for x86-64 VMs"
);
}
if spec.graphics.is_some() {
bail!("an arm64 VM has no choice of graphics");
}
let dir = spec.dir.clone().unwrap_or_else(|| default_dir(&spec.name));
if dir.exists() && std::fs::read_dir(&dir)?.next().is_some() {
return Err(not_empty(&dir));
}
// The IPSW, downloaded first where it isn't here: a download that stops leaves its part
// for the next, and no VM.
// The space a restore writes is checked by the restore, before it writes anything.
let ipsw = match restorer.ipsws().find(&want)? {
ipsw::Found::Here(p) => p,
ipsw::Found::Download { entry, total, have } => {
let what = format!("macOS {} ({})", entry.version, entry.build);
restore::check_download_space(&what, total, have, &ipsw::dir(), &dir)?;
restorer
.ipsws()
.download(&entry, progress, cancel)
.map_err(|e| {
if cancel.load(std::sync::atomic::Ordering::SeqCst) {
anyhow::anyhow!(
"the download was stopped, and {} was not made: the next create of \
{what} continues the download",
spec.name
)
} else {
e
}
})?
}
};
let made = claim(&dir)?;
let result =
make_vmapple(&spec, &ipsw, size_mib, &dir, progress, restorer, cancel).map_err(|e| {
let kept = keep_restore_log(&dir, &spec.name);
// Stopped (Ctrl-C, or the interface quitting), it is no failure to report.
if cancel.load(std::sync::atomic::Ordering::SeqCst) {
return anyhow::anyhow!("the restore was stopped, and {} was not made", spec.name);
}
match kept {
// The error names the log where the restore wrote it, in the directory that
// goes: it names it where it is kept.
Some(kept) => anyhow::anyhow!(
"{}\nThe restore's log is kept in {}",
format!("{e:#}").replace(&dir.display().to_string(), &paths::tilde(&kept)),
paths::tilde(&kept.join(restore::LOG))
),
None => e,
}
});
finish(&spec.name, &dir, made, result, progress)
}
/// Moves the log of the failed restore in `dir`, which goes, into the restore logs' directory
/// for `name` ([`restore::logs_dir`]), replacing an earlier failure's; that directory, if the
/// log was there.
fn keep_restore_log(dir: &Path, name: &str) -> Option<PathBuf> {
let log = dir.join(restore::LOG);
if !log.is_file() {
return None;
}
let to = restore::logs_dir().join(name);
let _ = std::fs::remove_dir_all(&to);
std::fs::create_dir_all(&to).ok()?;
let dest = to.join(restore::LOG);
if std::fs::rename(&log, &dest).is_err() {
std::fs::copy(&log, &dest).ok()?;
}
Some(to)
}
/// A new disk's size where none is given, as the CLI's default.
pub const DEFAULT_DISK_MIB: u64 = 128 * 1024;
/// The files a restore leaves in an arm64 VM's directory.
pub const VMAPPLE_DISK: &str = "disk.img";
pub const VMAPPLE_AUX: &str = "aux.img";
fn make_vmapple(
spec: &Spec,
ipsw: &Path,
size_mib: u64,
dir: &Path,
progress: &mut dyn FnMut(&str),
restorer: &dyn Restorer,
cancel: &std::sync::atomic::AtomicBool,
) -> Result<Vm> {
let request = restore::Request {
ipsw,
dir,
disk_size: size_mib << 20,
};
let restored = restorer.restore(&request, progress, cancel)?;
for f in [VMAPPLE_DISK, VMAPPLE_AUX] {
if !dir.join(f).is_file() {
bail!("the restore left no {f} in {}", dir.display());
}
}
let mut c = base_config(
spec,
Profile::VmappleArm64,
VMAPPLE_DISK.into(),
ImageFormat::Raw,
);
// Its boot, on Ambrosia, is not reims-ctl's yet: no device is chosen.
c.graphics = None;
c.vmapple = Some(Vmapple {
aux: VMAPPLE_AUX.into(),
ecid: restored.ecid,
});
progress(&format!(
"restored macOS {} ({})",
restored.version, restored.build
));
first_boot(restored.first_boot, dir, progress);
Ok(Vm {
dir: dir.to_path_buf(),
config: c,
})
}
/// What the VM's first boot asks of the create after the restore. For macOS 14
/// ([`restore::FirstBoot::Eacs`]) that is one boot, in which macOS makes its Data volume and
/// resets the VM, and then reims-restore's finish step; reims-ctl starts no arm64 VM yet, so it
/// names the step left.
fn first_boot(first: restore::FirstBoot, dir: &Path, progress: &mut dyn FnMut(&str)) {
if first == restore::FirstBoot::Eacs {
progress(&format!(
"one step is left: macOS 14 makes its Data volume at the VM's first boot and then \
resets the VM, which doesn't start again until it is finished; after that boot, \
run `reims-restore finish-eacs {}`, and the next boot goes to Setup Assistant",
paths::tilde(dir)
));
}
}
/// Marks a directory a VM is being made in, until its vm.toml is written.
const CREATING: &str = ".reims-ctl-creating";
@@ -279,6 +486,7 @@ fn base_config(spec: &Spec, profile: Profile, disk: PathBuf, disk_format: ImageF
..Logs::default()
},
q35: None,
vmapple: None,
extra_env: BTreeMap::new(),
usb: vec![],
}
@@ -1017,4 +1225,409 @@ mod tests {
assert!(!claim(&d).unwrap());
std::fs::remove_dir_all(&d).unwrap();
}
/// What a test's restore does: write files into the VM's directory, then succeed with an
/// ECID past TOML's integers, fail, or wait for its cancel.
enum Fake {
Succeeds,
/// Restores macOS 14, whose first boot makes its Data volume.
SucceedsForEacs,
Fails,
WaitsForCancel,
/// Its download waits for the cancel.
StopsDownloading,
}
/// An IPSW path is taken as it is; `latest` is a download, of an IPSW of 1 MiB.
impl crate::ipsw::Source for Fake {
fn find(&self, want: &str) -> Result<crate::ipsw::Found> {
if crate::ipsw::is_path(want) {
return crate::ipsw::here(want);
}
assert_eq!(want, "latest");
Ok(crate::ipsw::Found::Download {
entry: reims_restore::catalog::Entry {
version: "27.2.1".into(),
build: "26B131".into(),
url: "https://updates.cdn-apple.com/x/UniversalMac_27.2.1_26B131_Restore.ipsw"
.into(),
sha1: None,
},
total: 1 << 20,
have: 0,
})
}
fn download(
&self,
e: &reims_restore::catalog::Entry,
progress: &mut dyn FnMut(&str),
cancel: &std::sync::atomic::AtomicBool,
) -> Result<PathBuf> {
progress("Downloading macOS 27.2.1 (26B131): 0%");
if let Fake::StopsDownloading = self {
while !cancel.load(std::sync::atomic::Ordering::SeqCst) {
std::thread::sleep(std::time::Duration::from_millis(5));
}
bail!("the download was stopped");
}
let path = crate::ipsw::dir().join(e.file_name());
std::fs::create_dir_all(crate::ipsw::dir()).unwrap();
std::fs::File::create(&path)
.unwrap()
.set_len(1 << 20)
.unwrap();
progress("Downloading macOS 27.2.1 (26B131): 100%");
Ok(path)
}
}
impl Restorer for Fake {
fn ipsws(&self) -> &dyn crate::ipsw::Source {
self
}
fn restore(
&self,
r: &restore::Request,
progress: &mut dyn FnMut(&str),
cancel: &std::sync::atomic::AtomicBool,
) -> Result<restore::Restored> {
progress("Restoring");
assert!(r.dir.is_dir());
assert_eq!(r.disk_size, 64 << 30);
std::fs::write(r.dir.join("disk.img.part"), b"partial").unwrap();
std::fs::write(r.dir.join("aux.img"), b"aux").unwrap();
match self {
Fake::Succeeds => {
std::fs::rename(r.dir.join("disk.img.part"), r.dir.join("disk.img")).unwrap();
Ok(restore::Restored {
ecid: 0xc208_f7ea_febd_c581,
version: "27.2.1".into(),
build: "26B131".into(),
first_boot: restore::FirstBoot::SetupAssistant,
})
}
Fake::SucceedsForEacs => {
std::fs::rename(r.dir.join("disk.img.part"), r.dir.join("disk.img")).unwrap();
Ok(restore::Restored {
ecid: 0x1234,
version: "14.6.1".into(),
build: "23G93".into(),
first_boot: restore::FirstBoot::Eacs,
})
}
Fake::Fails => {
let log = r.dir.join(restore::LOG);
std::fs::write(&log, b"what the restore did").unwrap();
Err(
anyhow::anyhow!("Apple's TSS doesn't sign this build for VirtualMac2,1")
.context(format!("the restore failed: its log is {}", log.display())),
)
}
Fake::WaitsForCancel | Fake::StopsDownloading => {
while !cancel.load(std::sync::atomic::Ordering::SeqCst) {
std::thread::sleep(std::time::Duration::from_millis(5));
}
bail!("the restore was stopped")
}
}
}
}
fn arm64() -> Host {
Host {
os: crate::host::Os::Linux,
arch: crate::host::Arch::Aarch64,
}
}
/// An arm64 spec, with an IPSW that exists.
fn arm64_spec(env: &crate::testenv::Env) -> Spec {
let ipsw = env.root.join("UniversalMac_27.2.1_26B131_Restore.ipsw");
std::fs::File::create(&ipsw)
.unwrap()
.set_len(1 << 20)
.unwrap();
Spec {
dir: Some(env.root.join("vms/t")),
ipsw: Some(ipsw.display().to_string()),
disk: Some(DiskSource::New { size_mib: 64 << 10 }),
..Spec::new("t")
}
}
/// A macOS 14 VM is made, and the create names the one step left: its first boot, then
/// reims-restore's finish.
#[test]
fn an_arm64_create_of_macos_14_names_the_step_left() {
let env = crate::testenv::Env::new("create-arm64-eacs");
let cancel = std::sync::atomic::AtomicBool::new(false);
let mut steps = Vec::new();
create_with(
arm64_spec(&env),
arm64(),
&mut |p| steps.push(p.to_string()),
&Fake::SucceedsForEacs,
&cancel,
)
.unwrap();
let dir = paths::tilde(&env.root.join("vms/t"));
let left: Vec<&String> = steps
.iter()
.filter(|s| s.starts_with("one step is left"))
.collect();
assert_eq!(left.len(), 1, "{steps:?}");
assert!(
left[0].contains(&format!("run `reims-restore finish-eacs {dir}`")),
"{}",
left[0]
);
let at = steps
.iter()
.position(|s| s == "restored macOS 14.6.1 (23G93)");
assert_eq!(
at.map(|i| i + 1),
steps.iter().position(|s| s.starts_with("one step is left"))
);
assert!(Registry::load().unwrap().open("t").is_ok());
}
#[test]
fn an_arm64_create_of_a_later_macos_has_no_step_left() {
let env = crate::testenv::Env::new("create-arm64-no-step");
let cancel = std::sync::atomic::AtomicBool::new(false);
let mut steps = Vec::new();
create_with(
arm64_spec(&env),
arm64(),
&mut |p| steps.push(p.to_string()),
&Fake::Succeeds,
&cancel,
)
.unwrap();
assert!(!steps.iter().any(|s| s.starts_with("one step is left")));
}
#[test]
fn an_arm64_vm_is_its_restored_disk_aux_and_ecid() {
let env = crate::testenv::Env::new("create-arm64");
let cancel = std::sync::atomic::AtomicBool::new(false);
let mut steps = Vec::new();
let vm = create_with(
arm64_spec(&env),
arm64(),
&mut |p| steps.push(p.to_string()),
&Fake::Succeeds,
&cancel,
)
.unwrap();
assert_eq!(steps.first().map(String::as_str), Some("Restoring"));
assert!(
steps.contains(&"restored macOS 27.2.1 (26B131)".to_string()),
"{steps:?}"
);
let dir = env.root.join("vms/t");
assert!(!dir.join(CREATING).exists());
let text = std::fs::read_to_string(dir.join(CONFIG_FILE)).unwrap();
assert!(text.contains("profile = \"vmapple-arm64\""), "{text}");
assert!(text.contains("disk = \"disk.img\""), "{text}");
assert!(text.contains("disk_format = \"raw\""), "{text}");
assert!(
text.contains("[vmapple]\naux = \"aux.img\"\necid = \"0xc208f7eafebdc581\""),
"{text}"
);
let saved = Registry::load().unwrap().open("t").unwrap();
assert_eq!(saved.config, vm.config);
assert_eq!(
saved.config.vmapple.as_ref().unwrap().ecid,
0xc208_f7ea_febd_c581
);
assert!(saved.config.graphics.is_none());
let e = crate::runtime::preflight(&saved, arm64())
.unwrap_err()
.to_string();
assert!(
e.starts_with("reims-ctl doesn't start arm64 VMs yet"),
"{e}"
);
}
/// A failed or stopped restore leaves no VM: its directory goes, with what the restore wrote,
/// and the registry doesn't list it.
#[test]
fn a_failed_or_stopped_restore_leaves_nothing() {
let env = crate::testenv::Env::new("create-arm64-fail");
let dir = env.root.join("vms/t");
let cancel = std::sync::atomic::AtomicBool::new(false);
let e = create_with(
arm64_spec(&env),
arm64(),
&mut |_| {},
&Fake::Fails,
&cancel,
)
.unwrap_err();
// It names the log where it is kept, not in the directory that went.
let kept = paths::tilde(&env.root.join("cache/reims-ctl/restore/logs/t"));
assert_eq!(
format!("{e:#}"),
format!(
"the restore failed: its log is {kept}/restore.log: Apple's TSS doesn't sign \
this build for VirtualMac2,1\nThe restore's log is kept in {kept}/restore.log"
)
);
assert!(!dir.exists());
assert!(Registry::load().unwrap().find("t").is_none());
assert_eq!(restore::running(), 0);
// Its log is kept out of the VM's directory.
let kept = env.root.join("cache/reims-ctl/restore/logs/t/restore.log");
assert_eq!(std::fs::read(&kept).unwrap(), b"what the restore did");
let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let stop = {
let cancel = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
cancel.store(true, std::sync::atomic::Ordering::SeqCst);
})
};
let e = create_with(
arm64_spec(&env),
arm64(),
&mut |_| {},
&Fake::WaitsForCancel,
&cancel,
)
.unwrap_err();
stop.join().unwrap();
assert_eq!(
format!("{e:#}"),
"the restore was stopped, and t was not made"
);
assert!(!dir.exists());
assert!(Registry::load().unwrap().find("t").is_none());
// An empty directory given for it stays, emptied.
std::fs::create_dir_all(&dir).unwrap();
create_with(
arm64_spec(&env),
arm64(),
&mut |_| {},
&Fake::Fails,
&cancel,
)
.unwrap_err();
assert!(dir.is_dir());
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
}
/// `latest` downloads the current IPSW into the installers directory first, then restores
/// it; a stopped download makes no VM.
#[test]
fn latest_is_downloaded_then_restored() {
let env = crate::testenv::Env::new("create-arm64-latest");
let dir = env.root.join("vms/t");
let cancel = std::sync::atomic::AtomicBool::new(false);
let mut steps = Vec::new();
create_with(
Spec {
ipsw: Some("latest".into()),
..arm64_spec(&env)
},
arm64(),
&mut |p| steps.push(p.to_string()),
&Fake::Succeeds,
&cancel,
)
.unwrap();
let i = |s: &str| steps.iter().position(|p| p == s).unwrap();
assert!(
i("Downloading macOS 27.2.1 (26B131): 100%") < i("Restoring"),
"{steps:?}"
);
assert!(
crate::ipsw::dir()
.join("UniversalMac_27.2.1_26B131_Restore.ipsw")
.is_file()
);
assert!(dir.join("vm.toml").is_file());
let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let stop = {
let cancel = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
cancel.store(true, std::sync::atomic::Ordering::SeqCst);
})
};
let e = create_with(
Spec {
name: "u".into(),
dir: Some(env.root.join("vms/u")),
ipsw: Some("latest".into()),
..arm64_spec(&env)
},
arm64(),
&mut |_| {},
&Fake::StopsDownloading,
&cancel,
)
.unwrap_err();
stop.join().unwrap();
assert_eq!(
format!("{e:#}"),
"the download was stopped, and u was not made: the next create of macOS 27.2.1 \
(26B131) continues the download"
);
assert!(!env.root.join("vms/u").exists());
assert!(Registry::load().unwrap().find("u").is_none());
assert_eq!(restore::running(), 0);
}
/// What an arm64 create needs is checked before its directory is made.
#[test]
fn an_arm64_create_checks_its_ipsw_and_options_first() {
let env = crate::testenv::Env::new("create-arm64-checks");
let dir = env.root.join("vms/t");
let cancel = std::sync::atomic::AtomicBool::new(false);
let fails = |spec: Spec| {
let e = create_with(spec, arm64(), &mut |_| {}, &Fake::Succeeds, &cancel).unwrap_err();
assert!(!dir.exists(), "{e:#}");
format!("{e:#}")
};
let e = fails(Spec {
ipsw: None,
..arm64_spec(&env)
});
assert!(e.contains("give one with --ipsw"), "{e}");
let e = fails(Spec {
ipsw: Some(env.root.join("missing.ipsw").display().to_string()),
..arm64_spec(&env)
});
assert!(e.contains("missing.ipsw does not exist"), "{e}");
let e = fails(Spec {
installer: Some(env.root.join("BaseSystem.img")),
..arm64_spec(&env)
});
assert!(e.contains("for x86-64 VMs"), "{e}");
let e = fails(Spec {
disk: Some(DiskSource::Existing {
path: env.root.join("disk.img"),
mode: ImportMode::Copy,
}),
..arm64_spec(&env)
});
assert!(e.contains("not an existing one"), "{e}");
// And an x86-64 host takes no IPSW.
let x86 = Host {
os: crate::host::Os::Linux,
arch: crate::host::Arch::X86_64,
};
let e = create_with(arm64_spec(&env), x86, &mut |_| {}, &Fake::Succeeds, &cancel)
.unwrap_err()
.to_string();
assert!(e.starts_with("an IPSW makes an arm64 VM"), "{e}");
assert!(!dir.exists());
}
}
+265
View File
@@ -0,0 +1,265 @@
//! What reims-ctl keeps downloaded for new VMs: macOS installers, which reims-util downloads
//! (reims_util.rs), and IPSWs (ipsw.rs), in the data directory's `installers`, and the IPSWs the
//! previous reims-ctl kept in its `ipsw`. Each is kept for the next VM of its macOS, and a
//! download that stopped leaves its part for the next to continue. `reims-ctl downloads` and the
//! interface's Downloads view list them with the space each takes, and delete one: a later VM
//! of its macOS downloads it again.
//!
//! A file a VM boots from (an offline installer, which a VM uses where it is) isn't deleted, nor
//! one being downloaded.
use crate::ipsw;
use crate::paths;
use crate::vm::{Registry, Vm};
use anyhow::{Context, Result, bail};
use reims_restore::catalog;
use std::path::{Path, PathBuf};
/// A file kept for new VMs.
#[derive(Clone, Debug, PartialEq)]
pub struct Item {
pub path: PathBuf,
/// What it is, as the list says it: "macOS 27.2.1 (26B131) IPSW".
pub what: String,
/// The space it takes on disk.
pub bytes: u64,
}
impl Item {
pub fn name(&self) -> String {
self.path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned()
}
}
/// The directories downloads are kept in.
pub fn dirs() -> [PathBuf; 2] {
[paths::installers_dir(), ipsw::legacy_dir()]
}
/// The files kept, by name.
pub fn list() -> Vec<Item> {
let mut out = Vec::new();
for d in dirs() {
let Ok(rd) = std::fs::read_dir(&d) else {
continue;
};
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
// reims-util's lock, and anything else hidden
if name.starts_with('.') {
continue;
}
let Ok(m) = e.metadata() else { continue };
if !m.is_file() {
continue;
}
use std::os::unix::fs::MetadataExt as _;
out.push(Item {
path: e.path(),
what: what(&name),
// what it takes on disk: a sparse image takes less than its length
bytes: (m.blocks() * 512).min(m.len()),
});
}
}
out.sort_by_key(Item::name);
out
}
/// What the file `name` is, from its name.
pub fn what(name: &str) -> String {
if let Some(base) = name.strip_suffix(".part") {
return format!("{}, partly downloaded", what(base));
}
if let Some((v, b)) = catalog::name_parts(name) {
return format!("macOS {v} ({b}) IPSW");
}
if let Some(n) = name
.strip_prefix("macOS-")
.and_then(|n| n.strip_suffix("-online-installer.dmg"))
{
return format!("macOS {} online installer", n.replace('-', " "));
}
if let Some(n) = name
.strip_prefix("macOS-")
.and_then(|n| n.strip_suffix("-offline-installer.img"))
&& let [build, version, rest] = n.rsplitn(3, '-').collect::<Vec<_>>()[..]
{
return format!(
"macOS {} {version} ({build}) offline installer",
rest.replace('-', " ")
);
}
"a file reims-ctl didn't download".into()
}
/// Space, as the list shows it: "25.6 GB".
pub fn size(bytes: u64) -> String {
if bytes >= 1_000_000_000 {
format!("{:.1} GB", bytes as f64 / 1e9)
} else {
format!("{} MB", bytes.div_ceil(1_000_000))
}
}
/// Deletes the kept file named `name`; what it freed.
pub fn delete(name: &str) -> Result<String> {
let item = list()
.into_iter()
.find(|i| i.name() == name)
.with_context(|| format!("no download is named {name}: reims-ctl downloads lists them"))?;
if let Some(vm) = used_by(&item.path) {
bail!("{vm} boots from {name}: take it out first (reims-ctl eject {vm}), or delete {vm}");
}
if being_downloaded(&item.path) {
bail!("{name} is being downloaded now: delete it once its download ends or is stopped");
}
std::fs::remove_file(&item.path)
.with_context(|| format!("delete {}", paths::tilde(&item.path)))?;
Ok(format!("deleted {name}, freeing {}", size(item.bytes)))
}
/// The VM that boots from `path`, its installer, if any.
fn used_by(path: &Path) -> Option<String> {
let same = |p: &Path| match (p.canonicalize(), path.canonicalize()) {
(Ok(a), Ok(b)) => a == b,
_ => p == path,
};
let reg = Registry::load().ok()?;
reg.vms.iter().find_map(|e| {
let vm = Vm::load(&e.dir).ok()?;
let installer = vm.config.q35.as_ref()?.installer.as_deref()?;
same(&vm.path(installer)).then(|| e.name.clone())
})
}
/// Whether a download is writing `path`: an IPSW's part, whose download holds its lock file
/// (reims-restore's download.rs), or an installer while reims-util downloads into the
/// installers directory, which it locks.
fn being_downloaded(path: &Path) -> bool {
let name = path.file_name().unwrap_or_default().to_string_lossy();
let lock = if let Some(base) = name.strip_suffix(".part") {
reims_restore::download::lock_path(path.parent().unwrap_or(Path::new(".")), base)
} else if catalog::name_parts(&path.file_name().unwrap_or_default().to_string_lossy()).is_some()
{
// a whole IPSW is written no more
return false;
} else {
path.with_file_name(".lock")
};
let Ok(f) = std::fs::OpenOptions::new().read(true).open(&lock) else {
return false;
};
use std::os::fd::AsRawFd as _;
// SAFETY: flock on a descriptor this function holds; closing it lets go.
unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) != 0 }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_download_says_what_it_is() {
assert_eq!(
what("UniversalMac_27.2.1_26B131_Restore.ipsw"),
"macOS 27.2.1 (26B131) IPSW"
);
assert_eq!(
what("UniversalMac_27.2.1_26B131_Restore.ipsw.part"),
"macOS 27.2.1 (26B131) IPSW, partly downloaded"
);
assert_eq!(
what("macOS-Tahoe-online-installer.dmg"),
"macOS Tahoe online installer"
);
assert_eq!(
what("macOS-Tahoe-26.6.2-25G83-offline-installer.img"),
"macOS Tahoe 26.6.2 (25G83) offline installer"
);
assert_eq!(what("notes.txt"), "a file reims-ctl didn't download");
assert_eq!(size(25_595_954_706), "25.6 GB");
assert_eq!(size(950_000_000), "950 MB");
}
/// The list holds both directories' files, but no hidden one; delete removes one, but not
/// one a VM boots from or one being downloaded.
#[test]
fn downloads_are_listed_and_deleted() {
let _env = crate::testenv::Env::new("downloads");
let [inst, old] = dirs();
std::fs::create_dir_all(&inst).unwrap();
std::fs::create_dir_all(&old).unwrap();
let ipsw = "UniversalMac_27.2.1_26B131_Restore.ipsw";
let part = "UniversalMac_28.0_27A100_Restore.ipsw.part";
let offline = "macOS-Tahoe-26.6.2-25G83-offline-installer.img";
std::fs::write(inst.join(ipsw), vec![1u8; 10_000]).unwrap();
std::fs::write(inst.join(part), b"p").unwrap();
std::fs::write(inst.join(offline), b"o").unwrap();
std::fs::write(inst.join(".lock"), b"").unwrap();
std::fs::write(old.join("UniversalMac_14.6.1_23G93_Restore.ipsw"), b"x").unwrap();
let names: Vec<_> = list().iter().map(Item::name).collect();
assert_eq!(
names,
[
"UniversalMac_14.6.1_23G93_Restore.ipsw",
ipsw,
part,
offline
]
);
// a VM boots from the offline installer
let mut c = crate::vm::tests::x86_64_config();
c.q35.as_mut().unwrap().installer = Some(inst.join(offline));
let dir = _env.root.join("vms/t");
std::fs::create_dir_all(&dir).unwrap();
Vm {
dir: dir.clone(),
config: c,
}
.save()
.unwrap();
let mut reg = Registry::load().unwrap();
reg.add("t", &dir).unwrap();
reg.save().unwrap();
let e = delete(offline).unwrap_err().to_string();
assert!(e.starts_with("t boots from"), "{e}");
// a part being downloaded
let base = part.strip_suffix(".part").unwrap();
let held = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(reims_restore::download::lock_path(&inst, base))
.unwrap();
use std::os::fd::AsRawFd as _;
// SAFETY: flock on an open descriptor.
assert_eq!(
unsafe { libc::flock(held.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
0
);
let e = delete(part).unwrap_err().to_string();
assert!(e.contains("is being downloaded now"), "{e}");
drop(held);
assert!(
delete(part)
.unwrap()
.starts_with(&format!("deleted {part}, freeing"))
);
assert!(
delete(ipsw)
.unwrap()
.starts_with(&format!("deleted {ipsw}"))
);
assert!(!inst.join(ipsw).exists());
let e = delete("nothing.ipsw").unwrap_err().to_string();
assert!(e.starts_with("no download is named nothing.ipsw"), "{e}");
}
}
+73 -20
View File
@@ -1,11 +1,15 @@
//! The host reims-ctl runs on, and the machine profiles it can run there.
//!
//! A profile is one QEMU machine for one guest architecture: its binary, accelerator, devices
//! and what it can attach. Each host supports the profiles [`Profile::supported_on`] lists, and
//! only Linux and Windows on x86-64 have one: [`Profile::Q35X86_64`], `q35` booted through
//! OpenCore, with reims-vgpu's own GPU device, on KVM on Linux and on the Windows Hypervisor
//! Platform (WHPX) on Windows. A Mac host runs none ([`UNSUPPORTED`]): reims-ctl makes no arm64
//! VMs, and an arm64 guest boots on Ambrosia without it (docs/qemu.md, "arm64 guests").
//! and what it can attach. Each host supports the profiles [`Profile::supported_on`] lists:
//! - Linux and Windows on x86-64: [`Profile::Q35X86_64`], `q35` booted through OpenCore, with
//! reims-vgpu's own GPU device, on KVM on Linux and on the Windows Hypervisor Platform (WHPX)
//! on Windows;
//! - an arm64 Mac (HVF) and arm64 Linux (KVM): [`Profile::VmappleArm64`], QEMU's `vmapple`, whose
//! VMs reims-ctl makes by restoring macOS from an IPSW (restore.rs) and does not start yet
//! ([`Profile::starts`]).
//!
//! Any other host runs none ([`UNSUPPORTED`]).
//!
//! Another host or guest architecture is another profile (x86-64 guests on an Intel Mac would be
//! `q35` on HVF, without the memfd RAM only Linux has): add it here and in `qemu.rs`.
@@ -15,7 +19,11 @@ use std::collections::BTreeMap;
use std::fmt;
/// What reims-ctl tells a host it runs no VMs on, for a create or a start there.
pub const UNSUPPORTED: &str = "reims-ctl runs VMs on Linux x86-64 hosts";
pub const UNSUPPORTED: &str = "reims-ctl runs VMs on Linux x86-64 hosts, and makes arm64 VMs from \
an IPSW on arm64 Macs and arm64 Linux";
/// What reims-ctl tells an arm64 host of the work only x86-64 VMs have (GPUs, USB devices).
pub const X86_64_ONLY: &str = "that's for x86-64 VMs, which run on Linux x86-64 hosts";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Os {
@@ -113,12 +121,17 @@ impl fmt::Display for Host {
pub enum Profile {
#[serde(rename = "q35-x86_64")]
Q35X86_64,
/// An arm64 macOS guest on QEMU's `vmapple`, the id the arm64 VMs of an earlier reims-ctl
/// and the guests Ambrosia's boot check reads have in their settings.
#[serde(rename = "vmapple-arm64")]
VmappleArm64,
}
impl Profile {
pub fn supported_on(host: Host) -> &'static [Profile] {
match (host.os, host.arch) {
(Os::Linux | Os::Windows, Arch::X86_64) => &[Profile::Q35X86_64],
(Os::Mac | Os::Linux, Arch::Aarch64) => &[Profile::VmappleArm64],
_ => &[],
}
}
@@ -126,6 +139,7 @@ impl Profile {
pub fn id(self) -> &'static str {
match self {
Profile::Q35X86_64 => "q35-x86_64",
Profile::VmappleArm64 => "vmapple-arm64",
}
}
@@ -134,6 +148,7 @@ impl Profile {
match (self, host.os) {
(Profile::Q35X86_64, Os::Windows) => "x86-64 macOS guest (q35 and OpenCore, WHPX)",
(Profile::Q35X86_64, _) => "x86-64 macOS guest (q35 and OpenCore, KVM)",
(Profile::VmappleArm64, _) => "arm64 macOS guest (vmapple), restored from an IPSW",
}
}
@@ -142,17 +157,27 @@ impl Profile {
match self {
Profile::Q35X86_64 if cfg!(windows) => "qemu-system-x86_64.exe",
Profile::Q35X86_64 => "qemu-system-x86_64",
Profile::VmappleArm64 => "qemu-system-aarch64",
}
}
/// The accelerator on `host`: KVM, and on Windows the Windows Hypervisor Platform.
/// The accelerator on `host`: KVM, on Windows the Windows Hypervisor Platform, and for an
/// arm64 guest on a Mac, Hypervisor.framework.
pub fn accel(self, host: Host) -> &'static str {
match (self, host.os) {
(Profile::Q35X86_64, Os::Windows) => "whpx",
(Profile::Q35X86_64, _) => "kvm",
(Profile::VmappleArm64, Os::Mac) => "hvf",
(Profile::VmappleArm64, _) => "kvm",
}
}
/// Whether reims-ctl starts its VMs. An arm64 VM is made, by a restore, and not started:
/// its boot, on Ambrosia with reims-vgpu's device, is not reims-ctl's yet.
pub fn starts(self) -> bool {
self == Profile::Q35X86_64
}
/// Whether the guest's RAM must be a shared memfd: the library on Linux builds its views of
/// guest pages from the file behind the RAM, and refuses RAM without one.
pub fn memfd_ram(self, host: Host) -> bool {
@@ -166,9 +191,10 @@ impl Profile {
host.os == Os::Windows
}
/// Whether a Vulkan GPU can be chosen: the library runs on Vulkan on Linux and Windows.
/// Whether a Vulkan GPU can be chosen: the library runs on Vulkan on Linux and Windows, for
/// the x86-64 VMs it runs.
pub fn gpu_choice(self, host: Host) -> bool {
matches!(host.os, Os::Linux | Os::Windows)
self == Profile::Q35X86_64 && matches!(host.os, Os::Linux | Os::Windows)
}
}
@@ -182,26 +208,53 @@ impl fmt::Display for Profile {
mod tests {
use super::*;
/// Linux on x86-64 runs x86-64 guests on KVM in memfd RAM; a Mac and any other host run
/// none.
/// Linux on x86-64 runs x86-64 guests on KVM in memfd RAM; an arm64 Mac and arm64 Linux
/// make arm64 guests on vmapple, which they don't start; an Intel Mac, Windows on arm64 and
/// any other host run none.
#[test]
fn only_linux_on_x86_64_runs_vms() {
fn each_host_has_its_profile() {
let linux = Host {
os: Os::Linux,
arch: Arch::X86_64,
};
assert_eq!(linux.default_profile(), Some(Profile::Q35X86_64));
for (os, arch) in [
(Os::Mac, Arch::Aarch64),
(Os::Mac, Arch::X86_64),
(Os::Linux, Arch::Aarch64),
(Os::Windows, Arch::Aarch64),
] {
assert_eq!(Host { os, arch }.default_profile(), None, "{os:?} {arch:?}");
}
assert!(Profile::Q35X86_64.memfd_ram(linux));
assert!(!Profile::Q35X86_64.section_ram(linux));
assert_eq!(Profile::Q35X86_64.accel(linux), "kvm");
assert!(Profile::Q35X86_64.starts());
for os in [Os::Mac, Os::Linux] {
let host = Host {
os,
arch: Arch::Aarch64,
};
assert_eq!(
host.default_profile(),
Some(Profile::VmappleArm64),
"{os:?}"
);
assert!(!Profile::VmappleArm64.gpu_choice(host));
}
let (mac, arm_linux) = (
Host {
os: Os::Mac,
arch: Arch::Aarch64,
},
Host {
os: Os::Linux,
arch: Arch::Aarch64,
},
);
assert_eq!(Profile::VmappleArm64.accel(mac), "hvf");
assert_eq!(Profile::VmappleArm64.accel(arm_linux), "kvm");
assert!(!Profile::VmappleArm64.starts());
assert_eq!(Profile::VmappleArm64.qemu_binary(), "qemu-system-aarch64");
for (os, arch) in [
(Os::Mac, Arch::X86_64),
(Os::Windows, Arch::Aarch64),
(Os::Other, Arch::Aarch64),
] {
assert_eq!(Host { os, arch }.default_profile(), None, "{os:?} {arch:?}");
}
}
/// Windows on x86-64 runs x86-64 guests on WHPX, in RAM of a shared section rather than a
+9 -2
View File
@@ -272,8 +272,9 @@ mod tests {
}
/// The installer's --skip-qemu keeps the installed QEMU: with none installed it ends at
/// once, before it builds or installs anything, saying what to do. On a host other than
/// Linux on x86-64 it ends before that, saying where reims-ctl runs VMs.
/// once, before it builds or installs anything, saying what to do, as it does on an arm64
/// host, which has no QEMU. On a host reims-ctl has no VMs for (an Intel Mac) it ends before
/// that, saying where it runs and makes them.
#[test]
fn the_installer_skips_qemu_only_where_one_is_installed() {
let dir = std::env::var_os("CARGO_MANIFEST_DIR")
@@ -299,6 +300,12 @@ mod tests {
&& err.contains("run this without --skip-qemu, which builds it"),
"{err}"
);
} else if cfg!(target_arch = "aarch64") {
assert!(
err.contains("--skip-qemu keeps the installed QEMU, and this host has none")
&& err.contains("run this without --skip-qemu"),
"{err}"
);
} else {
assert!(err.contains(crate::host::UNSUPPORTED), "{err}");
}
+155
View File
@@ -0,0 +1,155 @@
//! The IPSWs arm64 VMs are restored from (restore.rs). A create names its IPSW by its path, or
//! by `latest`, the current macOS Apple's catalog offers (reims-restore's catalog.rs), which is
//! downloaded once into the installers directory (reims-restore's download.rs), where reims-util
//! keeps its installers too (reims_util.rs), and every later VM of that release finds it. A
//! download that stops is continued by the next. Apple offers only its current release: another
//! is given by its IPSW's path. One downloaded before is also found by its version or build,
//! there or in the `ipsw` directory the previous reims-ctl downloaded IPSWs into.
use crate::paths;
use anyhow::{Context, Result};
use reims_restore::catalog::{self, Entry, OnDisk};
use reims_restore::http::Client;
use reims_restore::pipeline::Event;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
/// Where IPSWs are downloaded: the installers directory.
pub fn dir() -> PathBuf {
paths::installers_dir()
}
/// Where the previous reims-ctl downloaded IPSWs, read where they are.
pub fn legacy_dir() -> PathBuf {
paths::data_dir().join("ipsw")
}
/// The IPSWs downloaded, newest first.
pub fn on_disk() -> Vec<OnDisk> {
catalog::on_disk(&[dir(), legacy_dir()])
}
/// Whether a create's `--ipsw` names a file rather than a release: a path, or a name that is
/// there.
pub fn is_path(s: &str) -> bool {
s.contains('/') || s.ends_with(".ipsw") || Path::new(s).exists()
}
/// The IPSW a create named.
#[derive(Clone, Debug, PartialEq)]
pub enum Found {
/// Here: given by its path, or downloaded before.
Here(PathBuf),
/// To download: its file's length, and how much of it a stopped download left.
Download { entry: Entry, total: u64, have: u64 },
}
/// Where a create's IPSW comes from: Apple's catalog and CDN ([`Apple`]), or a test's.
pub trait Source {
/// Finds the IPSW `want` names: a path, `latest`, or a release downloaded before.
fn find(&self, want: &str) -> Result<Found>;
/// Downloads `e`'s IPSW into [`dir`], or continues its download; the file.
fn download(
&self,
e: &Entry,
progress: &mut dyn FnMut(&str),
cancel: &AtomicBool,
) -> Result<PathBuf>;
}
/// Apple's catalog, and its CDN.
pub struct Apple;
impl Source for Apple {
fn find(&self, want: &str) -> Result<Found> {
if is_path(want) {
return here(want);
}
let client = Client::apple();
let (listed, unread) = match catalog::fetch(&client, catalog::URL) {
Ok(l) => (l, None),
Err(e) => (Vec::new(), Some(e)),
};
let found = catalog::pick(want, &on_disk(), &listed).map_err(|e| match unread {
Some(why) => e.context(format!("{why:#}")),
None => e,
})?;
Ok(match found {
catalog::Found::OnDisk(o) => Found::Here(o.path),
catalog::Found::Download(entry) => {
let (total, have) = reims_restore::download::remaining(&client, &entry, &dir())?;
Found::Download { entry, total, have }
}
})
}
fn download(
&self,
e: &Entry,
progress: &mut dyn FnMut(&str),
cancel: &AtomicBool,
) -> Result<PathBuf> {
let mut shown = crate::restore::Shown::default();
reims_restore::download::download(
&Client::apple(),
e,
&dir(),
&mut |ev| match ev {
Event::Step(s) | Event::Note(s) => progress(&s),
Event::Progress { what, done, total } => {
if let Some(line) = shown.line(&what, done, total) {
progress(&line);
}
}
},
cancel,
)
}
}
/// The IPSW at `path`, which must be a file.
pub fn here(path: &str) -> Result<Found> {
let p = PathBuf::from(path);
let m = std::fs::metadata(&p).with_context(|| format!("the IPSW {path} does not exist"))?;
anyhow::ensure!(m.is_file(), "the IPSW {path} is not a file");
Ok(Found::Here(p))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_ipsw_is_named_by_its_path_or_a_release() {
assert!(is_path("~/Downloads/x.ipsw"));
assert!(is_path("./a"));
assert!(is_path("UniversalMac_27.2.1_26B131_Restore.ipsw"));
assert!(!is_path("latest"));
assert!(!is_path("27.2.1"));
assert!(!is_path("26B131"));
}
/// IPSWs downloaded go in the installers directory, and the previous reims-ctl's are found
/// where it kept them.
#[test]
fn ipsws_are_found_in_both_directories() {
let env = crate::testenv::Env::new("ipsw-dirs");
assert_eq!(dir(), paths::installers_dir());
std::fs::create_dir_all(dir()).unwrap();
std::fs::create_dir_all(legacy_dir()).unwrap();
std::fs::write(dir().join("UniversalMac_27.2.1_26B131_Restore.ipsw"), b"a").unwrap();
std::fs::write(
legacy_dir().join("UniversalMac_14.6.1_23G93_Restore.ipsw"),
b"b",
)
.unwrap();
let found: Vec<_> = on_disk().into_iter().map(|o| o.build).collect();
assert_eq!(found, ["26B131", "23G93"]);
assert!(env.root.exists());
// a release downloaded before is found with no network
assert_eq!(
catalog::pick("14.6.1", &on_disk(), &[]).unwrap(),
catalog::Found::OnDisk(on_disk()[1].clone())
);
}
}
+5 -2
View File
@@ -1,14 +1,16 @@
//! reims-ctl: creates, boots and manages x86-64 macOS VMs on Linux, on the QEMU
//! scripts/install-ctl.sh builds with reims-vgpu. With no command it opens its interactive
//! interface.
//! scripts/install-ctl.sh builds with reims-vgpu, and makes arm64 macOS VMs from an IPSW on arm64
//! Macs and arm64 Linux (restore.rs). With no command it opens its interactive interface.
mod cli;
mod copy;
mod create;
mod downloads;
mod form;
mod gpu;
mod host;
mod install;
mod ipsw;
mod logs;
mod macos;
mod migrate;
@@ -19,6 +21,7 @@ mod prebuilt;
mod qemu;
mod qmp;
mod reims_util;
mod restore;
mod runtime;
#[cfg(test)]
mod testenv;
+3 -1
View File
@@ -80,7 +80,7 @@
use crate::host::{Host, Profile};
use crate::vm::{DiskController, Graphics, Vm};
use anyhow::{Context, Result};
use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};
/// The SMC key `isa-applesmc` gives every x86-64 guest.
@@ -126,6 +126,7 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result<Invocation> {
push(&["-name", &c.name]);
match c.profile {
Profile::Q35X86_64 => q35(vm, ctx, &mut a)?,
Profile::VmappleArm64 => bail!("{}", crate::runtime::not_started(vm)),
}
common(vm, ctx, &mut a)?;
a.extend(c.extra_args.iter().cloned());
@@ -519,6 +520,7 @@ mod tests {
disk_controller: DiskController::Ahci,
disk_port: 3,
}),
vmapple: None,
extra_env: BTreeMap::new(),
usb: vec![],
},
+415
View File
@@ -0,0 +1,415 @@
//! Making an arm64 VM: macOS restored from an IPSW onto a new disk, by reims-restore's pipeline
//! (crates/reims-restore). The pipeline writes the disk itself, on any host: it reads the IPSW
//! where it lies, has Apple's signing server (TSS) sign the VM's tickets, and leaves the VM's disk
//! (`disk.img`), its auxiliary storage (`aux.img`) and its ECID (`machine-identifier.bin`) in the
//! VM's directory, as a fresh restore by Virtualization.framework leaves them. No VM runs, and
//! none of Apple's code. reims-ctl gives it the IPSW, the directory and the disk's size, shows
//! its steps and their progress, and writes the VM's settings (create.rs). The pipeline's notes
//! go only to the restore's log, `restore.log` in the VM's directory ([`LOG`]).
//!
//! The pipeline checks the space it writes once the IPSW's OS image is open, before it writes
//! anything. An IPSW to download is checked first, for the download and the restore together
//! ([`check_download_space`]), from an estimate of what the restore writes ([`space_needed`]).
//!
//! A restore stops when it fails, at Ctrl-C in the CLI, and when the interface quits
//! ([`cancel`]): the create removes the VM's directory, so nothing of the VM is left.
use crate::paths;
use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
/// What a restore is given.
pub struct Request<'a> {
pub ipsw: &'a Path,
/// The VM's directory, made and empty but for create's mark.
pub dir: &'a Path,
/// The disk's size, in bytes.
pub disk_size: u64,
}
/// What a restore made.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Restored {
pub ecid: u64,
/// The macOS restored: its version and build, such as 27.2.1 and 26B131.
pub version: String,
pub build: String,
/// What the VM's first boot does: for macOS 14, it makes the Data volume, and reims-restore
/// finishes the VM after it.
pub first_boot: FirstBoot,
}
pub use reims_restore::pipeline::FirstBoot;
/// Restores macOS onto a VM's disk: reims-restore's [`Pipeline`], or a test's.
pub trait Restorer {
/// Where its IPSWs come from.
fn ipsws(&self) -> &dyn crate::ipsw::Source;
fn restore(
&self,
r: &Request,
progress: &mut dyn FnMut(&str),
cancel: &AtomicBool,
) -> Result<Restored>;
}
/// The restore's log in the VM's directory: each step, progress line and note, with the seconds
/// since the restore started.
pub const LOG: &str = "restore.log";
/// reims-restore's pipeline.
pub struct Pipeline;
impl Restorer for Pipeline {
fn ipsws(&self) -> &dyn crate::ipsw::Source {
&crate::ipsw::Apple
}
fn restore(
&self,
r: &Request,
progress: &mut dyn FnMut(&str),
cancel: &AtomicBool,
) -> Result<Restored> {
use reims_restore::pipeline;
let job = pipeline::Restore {
ipsw: r.ipsw.to_path_buf(),
dir: r.dir.to_path_buf(),
disk_size: r.disk_size,
ecid: None,
lp_keys: None,
};
let mut shown = Shown::default();
let mut log = Log::create(&r.dir.join(LOG))?;
let done = pipeline::run(
&job,
&mut |e| on_event(e, &mut shown, &mut log, progress),
cancel,
)?;
Ok(Restored {
ecid: done.ecid,
version: done.version,
build: done.build,
first_boot: done.first_boot,
})
}
}
/// Shows a step, and a progress line a whole percent on, and logs them; a note is only logged.
fn on_event(
e: reims_restore::pipeline::Event,
shown: &mut Shown,
log: &mut Log,
progress: &mut dyn FnMut(&str),
) {
use reims_restore::pipeline::Event;
match e {
Event::Step(s) => {
log.line(&s);
progress(&s);
}
Event::Note(s) => log.line(&s),
Event::Progress { what, done, total } => {
if let Some(line) = shown.line(&what, done, total) {
log.line(&line);
progress(&line);
}
}
}
}
/// The restore's log ([`LOG`]): a write that fails is left out, as the restore goes on.
struct Log {
file: std::io::BufWriter<std::fs::File>,
start: Instant,
}
impl Log {
fn create(path: &Path) -> Result<Log> {
let file = std::fs::File::create(path).with_context(|| format!("{}", path.display()))?;
Ok(Log {
file: std::io::BufWriter::new(file),
start: Instant::now(),
})
}
fn line(&mut self, text: &str) {
use std::io::Write;
let t = self.start.elapsed().as_secs_f64();
let _ = writeln!(self.file, "[{t:8.1}] {text}");
let _ = self.file.flush();
}
}
/// Where the logs of failed restores are kept, a directory for each VM: the cache directory's
/// `restore/logs`.
pub fn logs_dir() -> PathBuf {
paths::cache_dir().join("restore/logs")
}
/// A progress line for each whole percent, so a long step doesn't print a line per read.
#[derive(Default)]
pub struct Shown {
last: Option<(String, u64)>,
}
impl Shown {
pub fn line(&mut self, what: &str, done: u64, total: u64) -> Option<String> {
let percent = (done.min(total) * 100).checked_div(total).unwrap_or(0);
let now = (what.to_string(), percent);
if self.last.as_ref() == Some(&now) {
return None;
}
self.last = Some(now);
Some(format!("{what}: {percent}%"))
}
}
// ------------------------------------------------------------------ space
/// An estimate of the space a restore of `ipsw_len` bytes of IPSW writes, for a download's check
/// before the IPSW is here: its disk takes about what the IPSW holds (measured: a fresh restore
/// of 27.2.1 (26B131) by Virtualization.framework took 25.1 GiB of disk from a 23.8 GiB IPSW), so
/// a quarter more, and the auxiliary storage. The pipeline's own check, once the IPSW is here, is
/// exact; this reads low for an IPSW that keeps its images deflated, as 14's do.
pub fn space_needed(ipsw_len: u64) -> u64 {
ipsw_len + ipsw_len / 4 + (64 << 20)
}
/// Refuses to download an IPSW of `total` bytes, `have` of which a stopped download left in
/// `downloads`, and restore it into `dir`, where the space free is short of what both write.
pub fn check_download_space(
what: &str,
total: u64,
have: u64,
downloads: &Path,
dir: &Path,
) -> Result<()> {
let rest = total.saturating_sub(have) + (64 << 20);
let restore = space_needed(total);
use reims_restore::pipeline::free_space;
let (free_dl, free_vm) = (free_space(downloads)?, free_space(dir)?);
if same_file_system(downloads, dir) {
if free_vm < rest + restore {
bail!(
"downloading {what} and restoring it needs about {} free where the VM goes ({}): \
{} for the rest of its IPSW and {} for the VM, and there are {}: free some \
space, or put the VM on another disk (--dir)",
gib(rest + restore),
paths::tilde(dir),
gib(rest),
gib(restore),
gib(free_vm)
);
}
return Ok(());
}
if free_dl < rest {
bail!(
"downloading {what} needs about {} free in {}, and there are {}: free some space",
gib(rest),
paths::tilde(downloads),
gib(free_dl)
);
}
if free_vm < restore {
bail!(
"restoring {what} needs about {} free where the VM goes ({}), and there are {}: \
free some space, or put the VM on another disk (--dir)",
gib(restore),
paths::tilde(dir),
gib(free_vm)
);
}
Ok(())
}
/// Whether `a` and `b`, or the nearest directories above them that exist, are on one file
/// system.
fn same_file_system(a: &Path, b: &Path) -> bool {
use std::os::unix::fs::MetadataExt as _;
let dev = |p: &Path| {
p.ancestors()
.find_map(|q| std::fs::metadata(q).ok())
.map(|m| m.dev())
};
dev(a).is_some() && dev(a) == dev(b)
}
fn gib(bytes: u64) -> String {
format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64)
}
// ------------------------------------------------------------------ stopping
/// Set to stop every restore of this process: at Ctrl-C ([`stop_at_interrupt`]), or as the
/// interface quits.
static CANCEL: AtomicBool = AtomicBool::new(false);
/// The creates of arm64 VMs running in this process, each from its restore's start to its
/// directory's removal where it fails ([`Busy`]).
static RUNNING: AtomicUsize = AtomicUsize::new(0);
/// The flag a restore watches.
pub fn cancel_flag() -> &'static AtomicBool {
&CANCEL
}
/// Stops every restore of this process.
pub fn cancel() {
CANCEL.store(true, Ordering::SeqCst);
}
/// The arm64 creates running in this process.
pub fn running() -> usize {
RUNNING.load(Ordering::SeqCst)
}
/// Waits up to `timeout` for every arm64 create to end; whether they did.
pub fn wait_stopped(timeout: Duration) -> bool {
let end = Instant::now() + timeout;
while running() > 0 {
if Instant::now() >= end {
return false;
}
std::thread::sleep(Duration::from_millis(100));
}
true
}
/// Held by an arm64 create while it runs, its restore and its cleanup.
pub struct Busy(());
impl Busy {
pub fn new() -> Busy {
RUNNING.fetch_add(1, Ordering::SeqCst);
Busy(())
}
}
impl Drop for Busy {
fn drop(&mut self) {
RUNNING.fetch_sub(1, Ordering::SeqCst);
}
}
/// Ctrl-C (SIGINT) and SIGTERM stop the restores of this process, and the downloads of their
/// IPSWs: a restore's VM directory is removed, a download keeps its part, and the create says the
/// VM was not made.
pub fn stop_at_interrupt() {
extern "C" fn stop(_: libc::c_int) {
// An atomic store is all a signal handler may do here.
CANCEL.store(true, Ordering::SeqCst);
}
let handler = stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
// SAFETY: the handler only stores to an atomic.
unsafe {
libc::signal(libc::SIGINT, handler);
libc::signal(libc::SIGTERM, handler);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn progress_is_a_line_a_percent() {
let mut s = Shown::default();
assert_eq!(
s.line("Installing macOS", 0, 200).as_deref(),
Some("Installing macOS: 0%")
);
assert_eq!(s.line("Installing macOS", 1, 200), None);
assert_eq!(
s.line("Installing macOS", 2, 200).as_deref(),
Some("Installing macOS: 1%")
);
assert_eq!(
s.line("Verifying", 2, 200).as_deref(),
Some("Verifying: 1%")
);
assert_eq!(
s.line("Verifying", 300, 200).as_deref(),
Some("Verifying: 100%")
);
assert_eq!(
s.line("Unknown size", 5, 0).as_deref(),
Some("Unknown size: 0%")
);
}
/// Steps and progress are shown and logged; the pipeline's notes are only logged.
#[test]
fn notes_go_to_the_log_alone() {
use reims_restore::pipeline::Event;
let path = std::env::temp_dir().join(format!("reims-ctl-log-{}", std::process::id()));
let mut log = Log::create(&path).unwrap();
let mut shown = Shown::default();
let mut seen = Vec::new();
for e in [
Event::Step("Signing the VM's tickets".into()),
Event::Note("TSS answered (8 KiB)".into()),
Event::Progress {
what: "Writing the system volume".into(),
done: 1,
total: 2,
},
] {
on_event(e, &mut shown, &mut log, &mut |s| seen.push(s.to_string()));
}
drop(log);
assert_eq!(
seen,
["Signing the VM's tickets", "Writing the system volume: 50%"]
);
let text = std::fs::read_to_string(&path).unwrap();
let _ = std::fs::remove_file(&path);
let lines: Vec<&str> = text
.lines()
.map(|l| &l[l.find("] ").unwrap() + 2..])
.collect();
assert_eq!(
lines,
[
"Signing the VM's tickets",
"TSS answered (8 KiB)",
"Writing the system volume: 50%"
]
);
assert!(text.starts_with("[ 0.0] "), "{text}");
}
/// A download and its restore on one file system need the space of both there.
#[test]
fn a_download_and_its_restore_need_the_space_of_both() {
let dir = std::env::temp_dir().join(format!("reims-ctl-dlspace-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let free = reims_restore::pipeline::free_space(&dir).unwrap();
// more than is free, for the restore alone
let big = free;
let e = check_download_space(
"macOS 31.0 (30A100)",
big,
big,
&dir.join("dl"),
&dir.join("vm"),
)
.unwrap_err()
.to_string();
assert!(
e.starts_with("downloading macOS 31.0 (30A100) and restoring it needs about"),
"{e}"
);
assert!(check_download_space("m", 1 << 20, 0, &dir.join("dl"), &dir.join("vm")).is_ok());
assert!(same_file_system(&dir.join("a/b"), &dir));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_restore_is_estimated_at_the_ipsws_size_and_a_quarter() {
assert_eq!(space_needed(20 << 30), (25 << 30) + (64 << 20));
}
}
+17
View File
@@ -55,6 +55,19 @@ pub fn running(vm: &Vm) -> bool {
pid(vm).is_some()
}
/// What reims-ctl says of a start of a VM it makes and doesn't start, an arm64 VM: where its
/// restored macOS is.
pub fn not_started(vm: &Vm) -> String {
format!(
"reims-ctl doesn't start arm64 VMs yet: {}'s macOS is restored in {} (its disk, {}, and \
its auxiliary storage, aux.img), which boots on QEMU's vmapple with Ambrosia, our arm64 \
firmware",
vm.name(),
crate::paths::tilde(&vm.dir),
vm.config.disk.display()
)
}
/// What is wrong with the host or the VM's files for a start, if anything.
pub fn preflight(vm: &Vm, host: Host) -> Result<()> {
let c = &vm.config;
@@ -62,6 +75,9 @@ pub fn preflight(vm: &Vm, host: Host) -> Result<()> {
if !crate::host::Profile::supported_on(host).contains(&c.profile) {
bail!("{}", crate::host::UNSUPPORTED);
}
if !c.profile.starts() {
bail!("{}", not_started(vm));
}
let need = |p: &Path, what: &str| -> Result<()> {
if !p.exists() {
bail!("{what} {} is missing", p.display());
@@ -86,6 +102,7 @@ pub fn preflight(vm: &Vm, host: Host) -> Result<()> {
);
}
}
Profile::VmappleArm64 => {}
}
if host.os == Os::Linux {
let kvm = std::fs::OpenOptions::new()
+6 -3
View File
@@ -8,15 +8,17 @@ use std::sync::{Mutex, MutexGuard};
static LOCK: Mutex<()> = Mutex::new(());
const VARS: [&str; 4] = [
const VARS: [&str; 5] = [
"REIMS_CTL_CONFIG_DIR",
"REIMS_CTL_DATA_DIR",
"REIMS_CTL_QEMU",
"REIMS_CTL_UTIL",
"XDG_CACHE_HOME",
];
/// A temporary directory holding reims-ctl's config and data directories, `config` and
/// `data`, named in the environment until it drops, with no QEMU or reims-util named.
/// A temporary directory holding reims-ctl's config, data and cache directories, `config`,
/// `data` and `cache`, named in the environment until it drops, with no QEMU or reims-util
/// named.
pub struct Env {
pub root: PathBuf,
saved: Vec<(&'static str, Option<OsString>)>,
@@ -37,6 +39,7 @@ impl Env {
};
env.set("REIMS_CTL_CONFIG_DIR", env.root.join("config"));
env.set("REIMS_CTL_DATA_DIR", env.root.join("data"));
env.set("XDG_CACHE_HOME", env.root.join("cache"));
// SAFETY: the tests that set the environment hold LOCK.
unsafe {
std::env::remove_var("REIMS_CTL_QEMU");
+462 -53
View File
@@ -67,6 +67,7 @@ pub fn run() -> Result<()> {
let result = app.run(&mut terminal);
let _ = app.hand_over();
ratatui::restore();
stop_restores();
result?;
if app.update_requested {
return run_update(app.update_channel);
@@ -74,6 +75,22 @@ pub fn run() -> Result<()> {
Ok(())
}
/// Stops the restores of arm64 VMs still running as the interface ends, and waits while each
/// removes its VM's files, so none is left half made.
fn stop_restores() {
if crate::restore::running() == 0 {
return;
}
println!("Stopping the restore of each arm64 VM being made, which removes its files…");
crate::restore::cancel();
if !crate::restore::wait_stopped(Duration::from_secs(120)) {
eprintln!(
"warning: a restore did not stop within 2 minutes: its VM's directory may be left; \
delete it before you create the VM again"
);
}
}
/// Runs the update in the plain terminal, then reims-ctl again in this process's place: the new
/// one, or the same where the install was already up to date.
fn run_update(channel: Option<Channel>) -> Result<()> {
@@ -99,6 +116,8 @@ enum Msg {
Progress(String, u64, String),
Done(String, u64, Result<String, String>),
Gpus(Vec<GpuInfo>),
/// Apple's catalog of IPSWs, read on an arm64 host as the interface starts.
Ipsws(Result<Vec<reims_restore::catalog::Entry>, String>),
}
enum Overlay {
@@ -115,6 +134,11 @@ enum Overlay {
options: Vec<(&'static str, Action)>,
choice: usize,
},
/// What's downloaded for new VMs (downloads.rs): `choice` is the selected row.
Downloads {
items: Vec<crate::downloads::Item>,
choice: usize,
},
/// The host's USB devices, to give the VM `vm` or take back (usb.rs): `choice` is the
/// selected row of [`usb::rows`].
Usb {
@@ -148,10 +172,17 @@ enum TextKind {
#[derive(Clone)]
enum Action {
None,
Delete { vm: String, keep_files: bool },
Delete {
vm: String,
keep_files: bool,
},
ForceStop(String),
UpdateOpencore(String),
Update(Option<Channel>),
/// Deletes a download by its name, then shows the downloads again.
DeleteDownload(String),
/// Shows the downloads again.
Downloads,
Quit,
}
@@ -231,6 +262,8 @@ struct App {
pending_view: Option<Vm>,
/// The macOS versions reims-util downloads, read when the first x86-64 VM's form opens.
macos_versions: Option<Result<Vec<reims_util::Version>, String>>,
/// Apple's catalog of IPSWs, on an arm64 host, once read.
ipsw_catalog: Option<Result<Vec<reims_restore::catalog::Entry>, String>>,
/// The works `spawn` started: the last one's id.
spawned: u64,
/// The forms closed while the work they started runs, by its id: one whose work fails
@@ -273,6 +306,7 @@ impl App {
pending_page: None,
pending_view: None,
macos_versions: None,
ipsw_catalog: None,
spawned: 0,
closed_forms: BTreeMap::new(),
failed_forms: Vec::new(),
@@ -298,6 +332,14 @@ impl App {
if !app.rows.is_empty() {
app.table.select(Some(0));
}
if host.default_profile() == Some(Profile::VmappleArm64) {
let tx = app.tx.clone();
std::thread::spawn(move || {
let client = reims_restore::http::Client::apple();
let r = reims_restore::catalog::fetch(&client, reims_restore::catalog::URL);
let _ = tx.send(Msg::Ipsws(r.map_err(|e| format!("{e:#}"))));
});
}
if matches!(host.os, Os::Linux | Os::Windows) {
let tx = app.tx.clone();
std::thread::spawn(move || {
@@ -309,7 +351,7 @@ impl App {
&format!("reims-ctl runs no VMs on {host} yet"),
Level::Error,
);
} else if app.qemu.is_none() {
} else if app.qemu.is_none() && host.default_profile().is_some_and(Profile::starts) {
app.say(
"QEMU is not installed: run scripts/install-ctl.sh in your reims-vgpu checkout",
Level::Warn,
@@ -541,6 +583,16 @@ impl App {
f.set_options("gpu", options);
}
}
Msg::Ipsws(r) => {
self.ipsw_catalog = Some(r);
let options = ipsw_options(self.ipsw_catalog.as_ref());
if let Some(Overlay::Form(FormKind::Create, f)) = &mut self.overlay
&& f.is_shown("source")
&& self.host.default_profile() == Some(Profile::VmappleArm64)
{
f.set_options("source", options);
}
}
}
self.open_failed_form();
}
@@ -625,6 +677,7 @@ impl App {
devices,
choice,
}) => self.usb_key(k, vm, devices, choice),
Some(Overlay::Downloads { items, choice }) => self.downloads_key(k, items, choice),
None => self.main_key(k),
}
self.open_failed_form();
@@ -872,7 +925,8 @@ impl App {
body: format!(
"{busy}\n\nQuitting stops this work where it is: a guest asked to shut down still does, \
but is no longer powered off if it does not; a VM being created is left unfinished, \
though a download of macOS picks up where it stopped when you create it again."
though a download of macOS picks up where it stopped when you create it again; an \
arm64 VM being restored is stopped, and its files removed."
),
options: vec![("Keep working", Action::None), ("Quit", Action::Quit)],
choice: 0,
@@ -899,6 +953,7 @@ impl App {
KeyCode::Enter => self.open_menu(None, k.modifiers.contains(KeyModifiers::CONTROL)),
KeyCode::Delete => self.ask_delete(),
KeyCode::Char('u') => self.ask_update(),
KeyCode::Char('D') => self.open_downloads(),
KeyCode::Char('r') => {
let _ = self.reload();
self.say("reloaded", Level::Info);
@@ -942,6 +997,14 @@ impl App {
fn act(&mut self, a: Action) {
match a {
Action::None => {}
Action::Downloads => self.open_downloads(),
Action::DeleteDownload(name) => {
match crate::downloads::delete(&name) {
Ok(s) => self.say(&s, Level::Ok),
Err(e) => self.say(&format!("{e:#}"), Level::Error),
}
self.open_downloads();
}
Action::Quit => self.quit = true,
Action::Update(channel) => {
self.update_requested = true;
@@ -1158,12 +1221,13 @@ impl App {
.and_then(Channel::of);
// __record-install installs reims-util where the host makes x86-64 VMs, or where one is
// beside reims-ctl (cli.rs).
let what = if self.host.default_profile() == Some(Profile::Q35X86_64)
|| reims_util::beside().is_some()
{
"reims-ctl, the library, QEMU and reims-util"
} else {
"reims-ctl, the library and QEMU"
// An arm64 host builds no QEMU (scripts/install-ctl.sh).
let what = match (self.host.default_profile(), reims_util::beside().is_some()) {
(Some(Profile::Q35X86_64), _) => "reims-ctl, the library, QEMU and reims-util",
(Some(Profile::VmappleArm64), true) => "reims-ctl and reims-util",
(Some(Profile::VmappleArm64), false) => "reims-ctl",
(None, true) => "reims-ctl, the library, QEMU and reims-util",
(None, false) => "reims-ctl, the library and QEMU",
};
let mut options = vec![("Cancel", Action::None), ("Update", Action::Update(None))];
for c in Channel::ALL.into_iter().filter(|&c| Some(c) != current) {
@@ -1213,6 +1277,48 @@ impl App {
usb::rows(&chosen, devices)
}
fn open_downloads(&mut self) {
self.overlay = Some(Overlay::Downloads {
items: crate::downloads::list(),
choice: 0,
});
}
fn downloads_key(&mut self, k: KeyEvent, items: Vec<crate::downloads::Item>, choice: usize) {
let last = items.len().saturating_sub(1);
let mut choice = choice.min(last);
match k.code {
KeyCode::Esc | KeyCode::Char('q') => return,
KeyCode::Down | KeyCode::Char('j') | KeyCode::Tab => choice = (choice + 1).min(last),
KeyCode::Up | KeyCode::Char('k') | KeyCode::BackTab => {
choice = choice.saturating_sub(1)
}
KeyCode::Home => choice = 0,
KeyCode::End => choice = last,
KeyCode::Char('r') => return self.open_downloads(),
KeyCode::Char('d') | KeyCode::Delete => {
if let Some(i) = items.get(choice) {
let name = i.name();
self.overlay = Some(Overlay::Confirm {
title: "Delete a download".into(),
body: format!(
"Delete {name}, {}? A later VM of its macOS downloads it again.",
crate::downloads::size(i.bytes)
),
options: vec![
("Delete", Action::DeleteDownload(name)),
("Keep", Action::Downloads),
],
choice: 1,
});
return;
}
}
_ => {}
}
self.overlay = Some(Overlay::Downloads { items, choice });
}
fn usb_key(
&mut self,
k: KeyEvent,
@@ -1442,6 +1548,43 @@ impl App {
self.say(crate::host::UNSUPPORTED, Level::Error);
return;
};
if profile == Profile::VmappleArm64 {
let options = ipsw_options(self.ipsw_catalog.as_ref());
let first = options[0].0.clone();
let mut fields = vec![
Field::text("name", "Name", "", "Letters, digits, '-', '_' and '.'."),
Field::choice(
"source",
"macOS from",
options,
&first,
"The macOS restored onto the VM's new disk, with tickets Apple signs for \
this VM, as a Mac restores one. Apple offers only the current macOS to \
download: reims-ctl downloads its IPSW once (about 25 GB) and keeps it for \
the next VM (D lists what's kept); a stopped download continues. For \
another macOS, give an IPSW of your own. reims-ctl doesn't start arm64 VMs \
yet.",
),
Field::path(
"ipsw",
"IPSW",
"",
"A Mac's IPSW (Tab completes), such as \
UniversalMac_14.6.1_23G93_Restore.ipsw, read where it is.",
)
.show_if("source", &["path"]),
Field::text(
"disk_size",
"Disk size",
&format_mib(create::DEFAULT_DISK_MIB),
"The new disk's size; it takes only what macOS writes, about the IPSW's size.",
),
];
fields.extend(place_fields());
let form = Form::new("New arm64 VM", "create", fields);
self.overlay = Some(Overlay::Form(FormKind::Create, form));
return;
}
let mut fields = vec![
Field::text(
"name",
@@ -1483,33 +1626,7 @@ impl App {
Field::path("opencore", "OpenCore image", "", "Empty makes one for this VM, with OVMF, presenting the Mac of the image beside an existing disk (opencore.qcow2, as a VM's directory holds them), unless the disk is copied from a VM reims-ctl has, else a Mac identity of its own. Or an OpenCore image of yours to copy, with OVMF_CODE.fd and OVMF_VARS.fd beside it, such as the one a disk of macOS booted from, which keeps its Mac's identity.")
.placeholder("made for this VM"),
]);
fields.extend([
Field::path(
"dir",
"Storage directory",
"",
"Where its disks and settings go (Tab completes). Empty for the default.",
)
.placeholder(&format!(
"{}/<name>",
paths::tilde(&paths::default_vms_dir())
)),
Field::text(
"cpus",
"CPU cores",
&create::default_cpus().to_string(),
&format!("vCPUs; this host has {}.", create::host_cpus()),
),
Field::text(
"memory",
"Memory",
&format_mib(create::default_memory_mib()),
&format!(
"Such as 8G; this host has {}.",
format_mib(create::host_memory_mib() / 1024 * 1024)
),
),
]);
fields.extend(place_fields());
fields.push(graphics_field(Graphics::default()));
if profile.gpu_choice(self.host) {
fields.push(
@@ -1559,6 +1676,11 @@ impl App {
),
Field::text("memory", "Memory", &format_mib(c.memory_mib), "Such as 8G."),
];
if !c.profile.starts() {
let form = Form::new(&format!("Edit {}", c.name), "save", fields);
self.overlay = Some(Overlay::Form(FormKind::Edit(c.name.clone()), form));
return;
}
// The displays', the resolution's, borderless's and the GPU's fields are reims-vgpu's.
fields.push(graphics_field(c.graphics()));
fields.extend([
@@ -1707,6 +1829,14 @@ impl App {
let name = spec.name.clone();
self.spawn_for(f, &name, "creating", move |p| {
let vm = create::create(spec, host, p)?;
if !vm.config.profile.starts() {
return Ok(format!(
"created {} in {}: its macOS is restored (reims-ctl doesn't start \
arm64 VMs yet)",
vm.name(),
paths::tilde(&vm.dir)
));
}
let next = if runtime::install_steps(&vm).is_some() {
"; its details say how to install macOS"
} else {
@@ -1822,6 +1952,19 @@ impl App {
}
s.opencore = opt_path("opencore");
}
Some(Profile::VmappleArm64) => {
s.ipsw = Some(match f.choice("source").as_str() {
"path" => opt_path("ipsw")
.context("give the IPSW to restore")?
.display()
.to_string(),
// latest, or the path of an IPSW downloaded before
other => other.to_string(),
});
s.disk = Some(DiskSource::New {
size_mib: parse_size_mib(&f.text("disk_size")).context("disk size")?,
});
}
None => bail!(crate::host::UNSUPPORTED),
}
if f.is_shown("graphics") {
@@ -1832,10 +1975,15 @@ impl App {
s.display.resolution = f.text("resolution");
}
s.display.check()?;
s.logs = f.toggle("logs");
s.network = f.toggle("network");
if s.network {
s.ssh_port = ssh_port_field(f)?;
// The arm64 form has neither: its VM takes the defaults.
if f.is_shown("logs") {
s.logs = f.toggle("logs");
}
if f.is_shown("network") {
s.network = f.toggle("network");
if s.network {
s.ssh_port = ssh_port_field(f)?;
}
}
Ok(s)
}
@@ -1966,6 +2114,7 @@ impl App {
let running = self.rows.iter().any(|r| &r.name == vm && r.pid.is_some());
draw_usb(f, area, vm, running, &rows, devices, *choice);
}
Some(Overlay::Downloads { items, choice }) => draw_downloads(f, area, items, *choice),
// A menu whose VM has left the list closes.
Some(Overlay::Menu {
vm,
@@ -1986,19 +2135,22 @@ impl App {
.default_profile()
.map(|p| p.describe(self.host).to_string())
.unwrap_or_else(|| "no VMs on this host".into());
let qemu = match &self.qemu {
Some(q) => Span::styled(q.clone(), Style::new().fg(Color::Green)),
None => Span::styled("QEMU not installed", Style::new().fg(Color::Red).bold()),
};
let line = Line::from(vec![
let mut spans = vec![
Span::styled(
" reims-ctl ",
Style::new().fg(Color::Black).bg(Color::Cyan).bold(),
),
Span::raw(format!(" {} · {profile} · ", self.host)),
qemu,
]);
f.render_widget(Paragraph::new(line), area);
Span::raw(format!(" {} · {profile}", self.host)),
];
// An arm64 host has no QEMU: its VMs are made by a restore, which runs none.
if self.host.default_profile().is_none_or(Profile::starts) {
spans.push(Span::raw(" · "));
spans.push(match &self.qemu {
Some(q) => Span::styled(q.clone(), Style::new().fg(Color::Green)),
None => Span::styled("QEMU not installed", Style::new().fg(Color::Red).bold()),
});
}
f.render_widget(Paragraph::new(Line::from(spans)), area);
}
fn draw_list(&mut self, f: &mut Frame, area: Rect) {
@@ -2212,8 +2364,12 @@ fn vm_menu(row: &VmRow, all: bool, host: Host) -> Vec<(VmCommand, &'static str)>
/// Whether the VM can be given the host's USB devices: an x86-64 VM on a Linux host. Else why
/// not, to say.
fn usb_available(host: Host, vm: &Vm) -> Result<(), String> {
if host.default_profile().is_none() {
return Err(crate::host::UNSUPPORTED.into());
match host.default_profile() {
None => return Err(crate::host::UNSUPPORTED.into()),
Some(Profile::VmappleArm64) => {
return Err(format!("USB passthrough: {}", crate::host::X86_64_ONLY));
}
Some(Profile::Q35X86_64) => {}
}
if vm.config.q35.is_none() {
return Err(format!(
@@ -2282,6 +2438,37 @@ fn displays_field(current: u32) -> Field {
/// The graphics field's values that show a field of the library's.
const LIBRARY: &[&str] = &["reims-vgpu"];
/// A new VM's directory, vCPUs and memory: the create forms' fields.
fn place_fields() -> Vec<Field> {
vec![
Field::path(
"dir",
"Storage directory",
"",
"Where its disks and settings go (Tab completes). Empty for the default.",
)
.placeholder(&format!(
"{}/<name>",
paths::tilde(&paths::default_vms_dir())
)),
Field::text(
"cpus",
"CPU cores",
&create::default_cpus().to_string(),
&format!("vCPUs; this host has {}.", create::host_cpus()),
),
Field::text(
"memory",
"Memory",
&format_mib(create::default_memory_mib()),
&format!(
"Such as 8G; this host has {}.",
format_mib(create::host_memory_mib() / 1024 * 1024)
),
),
]
}
/// The graphics choice of a VM, at `current`.
fn graphics_field(current: Graphics) -> Field {
let options = Graphics::ALL.map(|g| (g.id().to_string(), g.describe().to_string()));
@@ -2347,6 +2534,10 @@ fn apply_edit(vm: &mut Vm, f: &Form, gpus: Option<&[GpuInfo]>) -> Result<()> {
let c = &mut vm.config;
c.cpus = f.text("cpus").parse().context("CPU cores: a number")?;
c.memory_mib = parse_size_mib(&f.text("memory")).context("memory")?;
// An arm64 VM's form has these two alone: the rest is its start's.
if !c.profile.starts() {
return c.check();
}
if f.is_shown("graphics") {
c.graphics = Some(Graphics::parse(&f.choice("graphics"))?);
}
@@ -2497,7 +2688,10 @@ of its own. A VM runs reims-vgpu's own GPU device unless its settings choose ano
installer from Apple and makes the VM's OpenCore image and disk, and the VM
boots into the installer; its details then say how to install macOS. The form
stays open until the VM is made, and shows what failed, to fix and create again;
Esc closes it meanwhile, and it opens again if the create fails
Esc closes it meanwhile, and it opens again if the create fails. On an arm64
Mac or arm64 Linux, it makes an arm64 VM: from the current macOS, which
reims-ctl downloads from Apple (about 25 GB) and keeps for the next, or an IPSW
you have, restored onto its new disk. reims-ctl doesn't start arm64 VMs yet
s start it
x stop it: the guest is asked to shut down, and powered off if it has not
when its shutdown timeout ends (edit e to change it)
@@ -2528,6 +2722,9 @@ of its own. A VM runs reims-vgpu's own GPU device unless its settings choose ano
same Mac, for its graphics: on reims-vgpu with the macOS drivers of its GPU
device that this reims-ctl carries, which an image an older reims-ctl made
lacks
D downloads: the macOS installers and IPSWs kept for new VMs, and the space
each takes; d deletes the selected one (a later VM of its macOS downloads it
again). Also reims-ctl downloads
u update reims-ctl and QEMU from your reims-vgpu checkout
r reload the list
? this help
@@ -2745,6 +2942,117 @@ fn draw_usb(
);
}
/// The arm64 form's choices of macOS: the current one from Apple (`latest`), as Apple's catalog
/// names it once read, unless it is downloaded already; each IPSW downloaded, by its path; or
/// an IPSW of the user's own (`path`).
fn ipsw_options(
catalog: Option<&Result<Vec<reims_restore::catalog::Entry>, String>>,
) -> Vec<(String, String)> {
let have = crate::ipsw::on_disk();
let mut v = Vec::new();
match catalog
.and_then(|c| c.as_ref().ok())
.and_then(|l| l.first())
{
Some(e) if have.iter().any(|o| o.build == e.build) => {}
Some(e) => v.push((
"latest".into(),
format!("macOS {} ({}), downloaded from Apple", e.version, e.build),
)),
None => v.push((
"latest".into(),
"The current macOS, downloaded from Apple".into(),
)),
}
for o in &have {
v.push((
o.path.display().to_string(),
format!("macOS {} ({}), downloaded", o.version, o.build),
));
}
v.push(("path".into(), "An IPSW of my own".into()));
v
}
/// Draws what's downloaded for new VMs: each of `items` with the space it takes and what it is,
/// `choice` highlighted, and the space they take in all.
fn draw_downloads(f: &mut Frame, area: Rect, items: &[crate::downloads::Item], choice: usize) {
let width = area.width.saturating_sub(4).min(110);
let inner_w = width.saturating_sub(2) as usize;
let mut lines: Vec<Line> = vec![
Line::from(
"What reims-ctl keeps downloaded for new VMs: macOS installers, and IPSWs for arm64 \
VMs. Each is used by the next VM of its macOS; a deleted one is downloaded again \
when a VM needs it.",
)
.dim(),
Line::from(""),
];
let first_row = lines.len();
if items.is_empty() {
lines.push(Line::from("Nothing is downloaded."));
}
let name_w = items
.iter()
.map(|i| i.name().chars().count())
.max()
.unwrap_or(0)
.min(inner_w.saturating_sub(14).max(12));
for (n, i) in items.iter().enumerate() {
let mut name: String = i.name().chars().take(name_w).collect();
if i.name().chars().count() > name_w {
name.pop();
name.push('…');
}
let mut text = format!(
"{} {name:<name_w$} {:>8} {}",
if n == choice { "›" } else { " " },
crate::downloads::size(i.bytes),
i.what
);
// A row a line, cut where it is too long.
if text.chars().count() > inner_w {
text = text.chars().take(inner_w.saturating_sub(1)).collect();
text.push('…');
}
lines.push(if n == choice {
Line::from(text).style(Style::new().fg(Color::Black).bg(Color::Cyan))
} else {
Line::from(text)
});
}
lines.push(Line::from(""));
let total: u64 = items.iter().map(|i| i.bytes).sum();
lines.push(
Line::from(format!(
"{} in all · d delete · r rescan · Esc close",
crate::downloads::size(total)
))
.dim(),
);
let rows_of = |l: &Line| (l.width().max(1)).div_ceil(inner_w.max(1)) as u16;
let need: u16 = lines.iter().map(rows_of).sum::<u16>() + 2;
let height = need.min(area.height);
let popup = area.centered(Constraint::Length(width), Constraint::Length(height));
f.render_widget(Clear, popup);
let block = Block::bordered()
.title(Line::from(" Downloads ").bold())
.border_style(Style::new().fg(Color::Cyan));
let body = block.inner(popup);
let above: u16 = lines[..first_row + choice.min(items.len().saturating_sub(1))]
.iter()
.map(rows_of)
.sum();
let scroll = (above + 1).saturating_sub(body.height);
f.render_widget(
Paragraph::new(lines)
.block(block)
.wrap(Wrap { trim: false })
.scroll((scroll, 0)),
popup,
);
}
/// Draws a VM's menu below the cell `at`, or above it where the screen has no room below,
/// and as far left or up as the screen needs; returns where. Each item shows its key at its
/// right.
@@ -2828,6 +3136,97 @@ mod tests {
}
}
/// D shows the downloads; d asks, and Delete deletes the selected one, and the view shows
/// what is left.
#[test]
fn the_downloads_view_deletes_what_is_chosen() {
let _env = crate::testenv::Env::new("tui-downloads");
let dir = paths::installers_dir();
std::fs::create_dir_all(&dir).unwrap();
let a = "UniversalMac_14.6.1_23G93_Restore.ipsw";
let b = "UniversalMac_27.2.1_26B131_Restore.ipsw";
std::fs::write(dir.join(a), b"a").unwrap();
std::fs::write(dir.join(b), b"b").unwrap();
let mut app = App::with(Host {
os: Os::Linux,
arch: Arch::Aarch64,
});
press(
&mut app,
[KeyCode::Char('D'), KeyCode::Down, KeyCode::Char('d')],
);
assert!(matches!(app.overlay, Some(Overlay::Confirm { .. })));
// Keep, the default, goes back to the list
press(&mut app, [KeyCode::Enter]);
assert!(matches!(app.overlay, Some(Overlay::Downloads { .. })));
press(
&mut app,
[
KeyCode::Down,
KeyCode::Char('d'),
KeyCode::Left,
KeyCode::Enter,
],
);
let Some(Overlay::Downloads { items, .. }) = &app.overlay else {
panic!("the downloads view closed");
};
let left: Vec<_> = items.iter().map(|i| i.name()).collect();
assert_eq!(left, [a]);
assert!(!dir.join(b).exists());
assert!(
app.status
.as_ref()
.unwrap()
.0
.starts_with(&format!("deleted {b}"))
);
}
/// The arm64 form offers the current macOS from Apple once its catalog is read, each IPSW
/// downloaded, and an IPSW of the user's own.
#[test]
fn the_arm64_form_offers_apples_current_macos_and_those_downloaded() {
let _env = crate::testenv::Env::new("tui-ipsws");
let dir = paths::installers_dir();
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("UniversalMac_14.6.1_23G93_Restore.ipsw"), b"a").unwrap();
let entry = |v: &str, b: &str| reims_restore::catalog::Entry {
version: v.into(),
build: b.into(),
url: format!("https://updates.cdn-apple.com/x/UniversalMac_{v}_{b}_Restore.ipsw"),
sha1: None,
};
let labels = |c| -> Vec<String> { ipsw_options(c).into_iter().map(|o| o.1).collect() };
assert_eq!(
labels(None),
[
"The current macOS, downloaded from Apple",
"macOS 14.6.1 (23G93), downloaded",
"An IPSW of my own"
]
);
let read = Ok(vec![entry("27.2.1", "26B131")]);
assert_eq!(
labels(Some(&read))[0],
"macOS 27.2.1 (26B131), downloaded from Apple"
);
// downloaded already: offered once, as downloaded
let read = Ok(vec![entry("14.6.1", "23G93")]);
assert_eq!(
labels(Some(&read)),
["macOS 14.6.1 (23G93), downloaded", "An IPSW of my own"]
);
let mut app = App::with(Host {
os: Os::Mac,
arch: Arch::Aarch64,
});
app.open_create();
assert_eq!(form(&app).choice("source"), "latest");
app.message(Msg::Ipsws(Ok(vec![entry("27.2.1", "26B131")])));
assert_eq!(form(&app).choice("source"), "latest");
}
#[test]
fn a_create_that_fails_keeps_its_form_open_with_the_error() {
// The create and the list it reads again use these VMs, not the user's.
@@ -3048,12 +3447,22 @@ mod tests {
let mut app = App::with(Host {
os: Os::Mac,
arch: Arch::Aarch64,
arch: Arch::X86_64,
});
app.reload().unwrap();
press(&mut app, [KeyCode::Char('p')]);
assert!(app.overlay.is_none());
assert_eq!(app.status.as_ref().unwrap().0, crate::host::UNSUPPORTED);
// An arm64 Mac makes arm64 VMs, which take no USB devices.
let mut app = App::with(Host {
os: Os::Mac,
arch: Arch::Aarch64,
});
app.reload().unwrap();
press(&mut app, [KeyCode::Char('p')]);
assert!(app.overlay.is_none());
let said = &app.status.as_ref().unwrap().0;
assert!(said.ends_with(crate::host::X86_64_ONLY), "{said}");
let mut app = App::with(LINUX);
app.reload().unwrap();
+82 -4
View File
@@ -47,6 +47,9 @@ pub struct VmConfig {
pub logs: Logs,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub q35: Option<Q35>,
/// An arm64 VM's own settings ([`crate::host::Profile::VmappleArm64`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vmapple: Option<Vmapple>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub extra_env: BTreeMap<String, String>,
/// The host's USB devices the guest is given while the VM runs (usb.rs), x86-64 VMs'.
@@ -450,6 +453,49 @@ pub struct Q35 {
pub disk_port: u32,
}
/// An arm64 VM's own settings: what its restore left beside its disk (restore.rs).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Vmapple {
/// The auxiliary storage, in the VM's directory: iBoot's NVRAM and the boot's records, with
/// Virtualization.framework's 16 KiB header; `aux.img.trimmed` beside it is the same without
/// the header, which QEMU attaches.
pub aux: PathBuf,
/// The VM's ECID, which every ticket of its macOS is bound to, and QEMU's `vmapple,uuid`.
/// Saved as text, `0x` and 16 hex digits: TOML's integers stop at 2^63, below many ECIDs.
#[serde(with = "ecid")]
pub ecid: u64,
}
/// An ECID in settings: written as `"0x…"`, and read from that, from decimal text, or from an
/// integer, as settings of an earlier reims-ctl hold it.
mod ecid {
use serde::{Deserialize, Deserializer, Serializer, de::Error};
pub fn serialize<S: Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&format!("{v:#018x}"))
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Ecid {
Int(i64),
Text(String),
}
match Ecid::deserialize(d)? {
Ecid::Int(i) => u64::try_from(i).map_err(D::Error::custom),
Ecid::Text(t) => {
let t = t.trim();
match t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
Some(hex) => u64::from_str_radix(hex, 16),
None => t.parse(),
}
.map_err(|e| D::Error::custom(format!("ecid {t:?}: {e}")))
}
}
}
}
/// Skylake-Client without TSX: macOS boots on it without an OpenCore CPUID spoof, and it has no
/// AVX-512, whose state XNU mishandles on AMD hosts (docs/qemu.md, "x86-64 macOS guests: the CPU
/// model").
@@ -553,8 +599,14 @@ impl VmConfig {
}
check_mac(&self.network.mac)?;
self.check_usb()?;
if self.q35.is_none() {
bail!("{}: no [q35] settings", self.name);
match self.profile {
Profile::Q35X86_64 if self.q35.is_none() => {
bail!("{}: no [q35] settings", self.name)
}
Profile::VmappleArm64 if self.vmapple.is_none() => {
bail!("{}: no [vmapple] settings", self.name)
}
_ => {}
}
Ok(())
}
@@ -791,6 +843,9 @@ impl Vm {
v.extend([&q.opencore, &q.firmware_code, &q.firmware_vars].map(|p| self.path(p)));
v.extend(q.installer.as_deref().map(|p| self.path(p)));
}
if let Some(a) = &self.config.vmapple {
v.push(self.path(&a.aux));
}
v
}
@@ -904,7 +959,7 @@ impl Registry {
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
/// A resolution is the window's first size, `<width>x<height>`; reims-vgpu's window opens
@@ -1055,7 +1110,7 @@ mod tests {
);
}
fn x86_64_config() -> VmConfig {
pub(crate) fn x86_64_config() -> VmConfig {
VmConfig {
name: "t".into(),
profile: Profile::Q35X86_64,
@@ -1091,6 +1146,7 @@ mod tests {
disk_controller: DiskController::Nvme,
disk_port: 3,
}),
vmapple: None,
extra_env: BTreeMap::from([("A".into(), "b".into())]),
usb: vec![],
}
@@ -1374,4 +1430,26 @@ mod tests {
"{w:?}"
);
}
/// An arm64 VM's ECID is saved as hex text, which TOML holds whole where its integers stop at
/// 2^63, and read from that, decimal text, or the integer earlier settings hold.
#[test]
fn an_ecid_past_tomls_integers_is_saved_as_text() {
let a = Vmapple {
aux: "aux.img".into(),
ecid: 13_981_697_631_839_962_497,
};
let text = toml::to_string(&a).unwrap();
assert_eq!(text, "aux = \"aux.img\"\necid = \"0xc208f7eafebdc581\"\n");
assert_eq!(toml::from_str::<Vmapple>(&text).unwrap(), a);
for ecid in ["\"13981697631839962497\"", "\"0xC208F7EAFEBDC581\""] {
let read: Vmapple =
toml::from_str(&format!("aux = \"aux.img\"\necid = {ecid}")).unwrap();
assert_eq!(read, a, "{ecid}");
}
let small: Vmapple =
toml::from_str("aux = \"aux.img\"\necid = 7075345111536996972").unwrap();
assert_eq!(small.ecid, 7_075_345_111_536_996_972);
assert!(toml::from_str::<Vmapple>("aux = \"a\"\necid = \"0xzz\"").is_err());
}
}
+13 -5
View File
@@ -9,10 +9,17 @@ users run them with `reims-ctl`, whose installer,
platform. This file says how QEMU is built and uses the library, and the
measured facts QEMU's side and the guests rely on.
`make qemu` builds no `qemu-system-aarch64`, and `reims-ctl` makes no arm64
VMs. QEMU's `vmapple` machine, without the Apple paravirtualized GPU it once
had, builds again in an `aarch64-softmmu` build, under HVF or TCG, for
Ambrosia, our own arm64 firmware ("arm64 guests", below).
`make qemu` builds no `qemu-system-aarch64`. QEMU's `vmapple` machine,
without the Apple paravirtualized GPU it once had, builds again in an
`aarch64-softmmu` build, under HVF or TCG, for Ambrosia, our own arm64
firmware ("arm64 guests", below). On an arm64 Mac or arm64 Linux,
`reims-ctl` makes arm64 VMs by restoring macOS from an IPSW onto their disk
(`crates/reims-restore`), which runs no QEMU, and doesn't start them;
`scripts/install-ctl.sh` builds no QEMU there. A macOS 14 VM needs one boot
before it is ready: macOS 14 makes its Data volume at its first boot and
resets the VM, and `reims-restore finish-eacs DIR` then makes it bootable for
Setup Assistant (`crates/reims-restore/docs/design.md`, "macOS 14's Data
volume").
No test runs QEMU, so a VM boot is the only check of QEMU's side of the
API ([lessons.md](lessons.md)). Each measurement below names its host and
@@ -1669,7 +1676,8 @@ shared memory.
arm64 macOS guests ran on QEMU's `vmapple` machine on an Apple silicon Mac,
and the machine's display was Apple's paravirtualized GPU. That device is
gone from the library and from QEMU: `make qemu` builds no
`qemu-system-aarch64`, and `reims-ctl` makes no arm64 VMs. `vmapple` builds
`qemu-system-aarch64`, and `reims-ctl` starts no arm64 VMs (it makes them,
by a restore from an IPSW, above). `vmapple` builds
again, without the device, in an `aarch64-softmmu` build, and runs under HVF
or TCG on Ambrosia, our own arm64 firmware, which enters macOS's kernel
itself. Virtualization.framework's firmware, AVPBooter, does not boot on the
+154 -101
View File
@@ -6,11 +6,14 @@
# scripts/install-ctl.sh [--yes] [--update] [--skip-qemu]
#
# Linux on x86-64 (Ubuntu or Debian, Arch or CachyOS; other distributions get
# the list of what to install), where the library runs on Vulkan; reims-ctl
# runs no VMs on another host. It:
# the list of what to install), where the library runs on Vulkan and VMs run;
# and arm64 Macs and arm64 Linux (Ubuntu or Debian, Arch, Fedora), where
# reims-ctl makes arm64 VMs by restoring macOS from an IPSW, which runs no
# QEMU: there it installs reims-ctl alone (step 4). It:
# 1. checks the build's dependencies, and offers to install those missing
# (apt or pacman, through sudo), and rustup through rustup.rs, beside any
# other cargo, whose installer asks its own questions;
# (apt, pacman or dnf, through sudo; on a Mac, Xcode's command line tools
# are needed), and rustup through rustup.rs, beside any other cargo, whose
# installer asks its own questions;
# 2. fetches vendor/qemu, QEMU's source, without QEMU's own submodules (its
# build fetches what it needs); cargo fetches metal2vulkan itself, at the
# commit the library's Cargo.toml names;
@@ -80,14 +83,23 @@ ask() {
}
OS="$(uname -s)" ARCH="$(uname -m)"
[[ $OS/$ARCH == Linux/x86_64 ]] || die "reims-ctl runs VMs on Linux x86-64 hosts; this is $OS on $ARCH"
PLATFORM=linux-x86_64
# libusb (usb-host, USB passthrough) and SPICE (-spice, a display a SPICE
# client connects to) are enabled by name: configure leaves out an optional
# feature whose library it does not find, saying nothing.
QEMU_CONFIGURE=(--target-list=x86_64-softmmu --enable-kvm --disable-sdl --enable-gtk --enable-slirp
--enable-libusb --enable-spice)
QEMU_BINARY=qemu-system-x86_64
# BUILDS_QEMU: whether this host runs VMs, on QEMU built on the library: Linux
# x86-64. An arm64 host makes arm64 VMs by a restore, which runs no QEMU, and
# reims-ctl doesn't start them: it gets reims-ctl alone.
BUILDS_QEMU=1
case "$OS/$ARCH" in
Linux/x86_64)
PLATFORM=linux-x86_64
# libusb (usb-host, USB passthrough) and SPICE (-spice, a display a SPICE
# client connects to) are enabled by name: configure leaves out an
# optional feature whose library it does not find, saying nothing.
QEMU_CONFIGURE=(--target-list=x86_64-softmmu --enable-kvm --disable-sdl --enable-gtk --enable-slirp
--enable-libusb --enable-spice)
QEMU_BINARY=qemu-system-x86_64
;;
Darwin/arm64 | Linux/aarch64) BUILDS_QEMU=0 ;;
*) die "reims-ctl runs VMs on Linux x86-64 hosts, and makes arm64 VMs from an IPSW on arm64 Macs and arm64 Linux; this is $OS on $ARCH" ;;
esac
# The XDG directory VAR names, else ~/FALLBACK: ignored unless absolute (as
# reims-ctl does).
@@ -100,6 +112,9 @@ CACHE="$(xdg XDG_CACHE_HOME .cache)/reims-ctl"
mkdir -p "$DATA" "$CACHE"
# Every VM runs on QEMU: --skip-qemu keeps the installed one, and needs one.
if [[ $SKIP_QEMU == 1 && $BUILDS_QEMU == 0 ]]; then
die "--skip-qemu keeps the installed QEMU, and this host has none: reims-ctl makes arm64 VMs here by a restore, which runs no QEMU; run this without --skip-qemu"
fi
if [[ $SKIP_QEMU == 1 && ! -x "$DATA/qemu/current/bin/$QEMU_BINARY" ]]; then
die "--skip-qemu keeps the installed QEMU, and none is installed ($DATA/qemu/current/bin/$QEMU_BINARY is missing): run this without --skip-qemu, which builds it"
fi
@@ -169,8 +184,13 @@ fi
missing=()
# A Mac's C compiler and linker, which Rust's builds use.
if [[ $OS == Darwin ]]; then
xcode-select -p >/dev/null 2>&1 || die "Xcode's command line tools are missing: run xcode-select --install, then this again"
fi
distro_id="" distro_like=""
if [[ -r /etc/os-release ]]; then
if [[ $OS == Linux && -r /etc/os-release ]]; then
# shellcheck disable=SC1091
distro_id="$(. /etc/os-release && echo "${ID:-}")"
# shellcheck disable=SC1091
@@ -194,7 +214,16 @@ pacman_pkgs=(base-devel git curl python ninja pkgconf flex bison bzip2 cmake
glib2 pixman libslirp zlib dtc pipewire libpulse alsa-lib libusb spice vulkan-icd-loader
libx11 libxext libxrandr libxcursor libxi libxfixes libxss libxtst libxkbcommon
wayland libdecor mesa libdrm dbus systemd-libs gtk3)
case " $distro_id $distro_like " in
dnf_pkgs=()
if [[ $BUILDS_QEMU == 0 ]]; then
# reims-ctl alone, for arm64 Linux: a C compiler and linker for Rust's
# builds, git, and curl for rustup. Fedora is Asahi Linux's own distribution.
apt_pkgs=(build-essential git curl ca-certificates)
pacman_pkgs=(base-devel git curl)
dnf_pkgs=(gcc make git curl)
fi
case "$OS $distro_id $distro_like " in
Darwin*) ;;
*" debian "* | *" ubuntu "*)
for p in "${apt_pkgs[@]}"; do
dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'install ok installed' || missing+=("$p")
@@ -206,6 +235,20 @@ case " $distro_id $distro_like " in
sudo apt-get install -y "${missing[@]}"
fi
;;
*" fedora "*)
if ((${#dnf_pkgs[@]} == 0)); then
warn "$distro_id is neither Debian/Ubuntu nor Arch/CachyOS: install the equivalents of these Ubuntu packages yourself if the build stops: ${apt_pkgs[*]}"
else
for p in "${dnf_pkgs[@]}"; do
rpm -q "$p" >/dev/null 2>&1 || missing+=("$p")
done
if ((${#missing[@]})); then
say "Missing packages: ${missing[*]}"
ask "Install them with sudo dnf?" || die "install them (sudo dnf install ${missing[*]}), then run this again"
sudo dnf install -y "${missing[@]}"
fi
fi
;;
*" arch "* | *" cachyos "*)
for p in "${pacman_pkgs[@]}"; do
pacman -Qq "$p" >/dev/null 2>&1 || pacman -Qqg "$p" >/dev/null 2>&1 || missing+=("$p")
@@ -220,94 +263,98 @@ case " $distro_id $distro_like " in
warn "$distro_id is neither Debian/Ubuntu nor Arch/CachyOS: install the equivalents of these Ubuntu packages yourself if the build stops: ${apt_pkgs[*]}"
;;
esac
if [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then
warn "/dev/kvm is not usable by you: enable virtualization in the firmware and add yourself to the kvm group (sudo usermod -aG kvm \$USER; log in again), or VMs will not start"
fi
# The guest's memory reaches the GPU through /dev/udmabuf, on every GPU: without
# it the library's views of that memory take a kernel mapping per 4 KiB page,
# past vm.max_map_count at 4K even at the guest's desktop (reims-ctl's
# runtime::udmabuf_problem, docs/qemu.md "Linux hosts: vm.max_map_count").
why="the guest's memory reaches the GPU through it, and without it the guest can crash at higher resolutions, at 4K even at its desktop"
udmabuf=0
if [[ ! -e /dev/udmabuf ]]; then
warn "there's no /dev/udmabuf: $why. Load it with sudo modprobe udmabuf, and put udmabuf in a file in /etc/modules-load.d to keep it"
else
group="$(stat -c %G /dev/udmabuf)"
if [[ -r /dev/udmabuf && -w /dev/udmabuf ]]; then
udmabuf=1
if [[ $group != root ]] && ! id -nG | tr ' ' '\n' | grep -qx "$group"; then
say "You can open /dev/udmabuf in this session, but you're not in its $group group: over ssh, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG $group \$USER) to start VMs there"
fi
elif [[ $group == root ]]; then
warn "only root can open /dev/udmabuf: $why. Give it to the kvm group with a udev rule, a file in /etc/udev/rules.d holding KERNEL==\"udmabuf\", GROUP=\"kvm\", MODE=\"0660\", add yourself to kvm (sudo usermod -aG kvm \$USER), and restart"
# The rest of the host's checks are for the VMs it runs: KVM, the library's
# GPU access to the guest's memory, and USB passthrough.
if [[ $BUILDS_QEMU == 1 ]]; then
if [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then
warn "/dev/kvm is not usable by you: enable virtualization in the firmware and add yourself to the kvm group (sudo usermod -aG kvm \$USER; log in again), or VMs will not start"
fi
# The guest's memory reaches the GPU through /dev/udmabuf, on every GPU: without
# it the library's views of that memory take a kernel mapping per 4 KiB page,
# past vm.max_map_count at 4K even at the guest's desktop (reims-ctl's
# runtime::udmabuf_problem, docs/qemu.md "Linux hosts: vm.max_map_count").
why="the guest's memory reaches the GPU through it, and without it the guest can crash at higher resolutions, at 4K even at its desktop"
udmabuf=0
if [[ ! -e /dev/udmabuf ]]; then
warn "there's no /dev/udmabuf: $why. Load it with sudo modprobe udmabuf, and put udmabuf in a file in /etc/modules-load.d to keep it"
else
say "You can't open /dev/udmabuf: $why. You need its $group group"
if ask "Add you to the $group group with sudo usermod?"; then
sudo usermod -aG "$group" "$USER"
say "Added you to $group: log in again for it to take effect"
group="$(stat -c %G /dev/udmabuf)"
if [[ -r /dev/udmabuf && -w /dev/udmabuf ]]; then
udmabuf=1
if [[ $group != root ]] && ! id -nG | tr ' ' '\n' | grep -qx "$group"; then
say "You can open /dev/udmabuf in this session, but you're not in its $group group: over ssh, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG $group \$USER) to start VMs there"
fi
elif [[ $group == root ]]; then
warn "only root can open /dev/udmabuf: $why. Give it to the kvm group with a udev rule, a file in /etc/udev/rules.d holding KERNEL==\"udmabuf\", GROUP=\"kvm\", MODE=\"0660\", add yourself to kvm (sudo usermod -aG kvm \$USER), and restart"
else
warn "add yourself to the $group group (sudo usermod -aG $group \$USER) and log in again, or the guest can crash at higher resolutions"
say "You can't open /dev/udmabuf: $why. You need its $group group"
if ask "Add you to the $group group with sudo usermod?"; then
sudo usermod -aG "$group" "$USER"
say "Added you to $group: log in again for it to take effect"
else
warn "add yourself to the $group group (sudo usermod -aG $group \$USER) and log in again, or the guest can crash at higher resolutions"
fi
fi
fi
fi
# With udmabuf, vm.max_map_count is only a speed-up, on NVIDIA: a view of an
# x86-64 guest's memory takes a mapping per 4 KiB page there, and past the
# library's budget (the limit less 16,384 and 8,192) its buffers are copied,
# which works and is slower (reims-ctl's runtime::max_map_count). A new VM
# gets half the host's memory, 4 to 16 GiB.
maps="$(cat /proc/sys/vm/max_map_count 2>/dev/null || echo 0)"
vm_mib=$(($(awk '/^MemTotal:/ { print $2 }' /proc/meminfo) / 2 / 1048576 * 1024))
vm_mib=$((vm_mib < 4096 ? 4096 : vm_mib > 16384 ? 16384 : vm_mib))
want=$((vm_mib * 256 + 24576))
if ((udmabuf && maps < want)) && grep -qsx 0x10de /sys/class/drm/*/device/vendor; then
raise=1048576
while ((raise < want)); do raise=$((raise * 2)); done
uncopied=$((maps > 24576 ? (maps - 24576) / 256 : 0))
say "vm.max_map_count is $maps: on an NVIDIA GPU, past about $uncopied MiB of a new VM's $((vm_mib / 1024)) GiB the GPU gets copies of its memory, which is slower; sudo sysctl -w vm.max_map_count=$raise, and a file in /etc/sysctl.d to keep it, avoids them"
fi
# MGLRU's thrashing guard (reims-ctl's runtime::MIN_TTL_FILE): above 0, the
# kernel kills a process where it can't keep the pages used in the last that
# many ms, even with RAM free, and a VM's QEMU can be the one. Measured on
# CachyOS hosts at 100, its kernel's default there. Offered off on a terminal
# only, and never required; the tmpfiles.d line keeps it off.
min_ttl_file=/sys/kernel/mm/lru_gen/min_ttl_ms
min_ttl_line='w /sys/kernel/mm/lru_gen/min_ttl_ms - - - - 0'
min_ttl="$(cat "$min_ttl_file" 2>/dev/null || echo 0)"
if [[ $min_ttl =~ ^[0-9]+$ ]] && ((min_ttl > 0)); then
warn "$min_ttl_file is $min_ttl: where the kernel can't keep the pages used in the last $min_ttl ms in memory, it kills a process, which can be a VM's QEMU, even while RAM is free (measured on hosts at 100, killing builds with most RAM free); 0 turns this off"
if [[ -t 0 ]] && ask "Write 0 to $min_ttl_file now with sudo?"; then
echo 0 | sudo tee "$min_ttl_file" >/dev/null || warn "sudo didn't write it"
# With udmabuf, vm.max_map_count is only a speed-up, on NVIDIA: a view of an
# x86-64 guest's memory takes a mapping per 4 KiB page there, and past the
# library's budget (the limit less 16,384 and 8,192) its buffers are copied,
# which works and is slower (reims-ctl's runtime::max_map_count). A new VM
# gets half the host's memory, 4 to 16 GiB.
maps="$(cat /proc/sys/vm/max_map_count 2>/dev/null || echo 0)"
vm_mib=$(($(awk '/^MemTotal:/ { print $2 }' /proc/meminfo) / 2 / 1048576 * 1024))
vm_mib=$((vm_mib < 4096 ? 4096 : vm_mib > 16384 ? 16384 : vm_mib))
want=$((vm_mib * 256 + 24576))
if ((udmabuf && maps < want)) && grep -qsx 0x10de /sys/class/drm/*/device/vendor; then
raise=1048576
while ((raise < want)); do raise=$((raise * 2)); done
uncopied=$((maps > 24576 ? (maps - 24576) / 256 : 0))
say "vm.max_map_count is $maps: on an NVIDIA GPU, past about $uncopied MiB of a new VM's $((vm_mib / 1024)) GiB the GPU gets copies of its memory, which is slower; sudo sysctl -w vm.max_map_count=$raise, and a file in /etc/sysctl.d to keep it, avoids them"
fi
keep="the line $min_ttl_line in a file in /etc/tmpfiles.d, such as /etc/tmpfiles.d/reims-ctl-min-ttl.conf"
if [[ "$(cat "$min_ttl_file" 2>/dev/null)" == 0 ]]; then
say "It's 0 now; $keep, keeps it at 0 after a restart"
else
say "echo 0 | sudo tee $min_ttl_file turns it off now, and $keep, keeps it at 0 after a restart"
# MGLRU's thrashing guard (reims-ctl's runtime::MIN_TTL_FILE): above 0, the
# kernel kills a process where it can't keep the pages used in the last that
# many ms, even with RAM free, and a VM's QEMU can be the one. Measured on
# CachyOS hosts at 100, its kernel's default there. Offered off on a terminal
# only, and never required; the tmpfiles.d line keeps it off.
min_ttl_file=/sys/kernel/mm/lru_gen/min_ttl_ms
min_ttl_line='w /sys/kernel/mm/lru_gen/min_ttl_ms - - - - 0'
min_ttl="$(cat "$min_ttl_file" 2>/dev/null || echo 0)"
if [[ $min_ttl =~ ^[0-9]+$ ]] && ((min_ttl > 0)); then
warn "$min_ttl_file is $min_ttl: where the kernel can't keep the pages used in the last $min_ttl ms in memory, it kills a process, which can be a VM's QEMU, even while RAM is free (measured on hosts at 100, killing builds with most RAM free); 0 turns this off"
if [[ -t 0 ]] && ask "Write 0 to $min_ttl_file now with sudo?"; then
echo 0 | sudo tee "$min_ttl_file" >/dev/null || warn "sudo didn't write it"
fi
keep="the line $min_ttl_line in a file in /etc/tmpfiles.d, such as /etc/tmpfiles.d/reims-ctl-min-ttl.conf"
if [[ "$(cat "$min_ttl_file" 2>/dev/null)" == 0 ]]; then
say "It's 0 now; $keep, keeps it at 0 after a restart"
else
say "echo 0 | sudo tee $min_ttl_file turns it off now, and $keep, keeps it at 0 after a restart"
fi
fi
fi
# USB passthrough (reims-ctl usb): QEMU opens a USB device's file in
# /dev/bus/usb, which only root may write unless a udev rule says otherwise.
# This one gives USB devices other than hubs to the kvm group, over SSH too,
# and to the user at the host's screen (uaccess, which a file sorting before
# systemd's 73-seat-late.rules sets). reims-ctl's usb::UDEV_RULE is the same
# line, which its tests check.
usb_rule_file=/etc/udev/rules.d/70-reims-ctl-usb.rules
usb_rule='SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{bDeviceClass}!="09", GROUP="kvm", MODE="0664", TAG+="uaccess"'
if ! grep -qsxF "$usb_rule" "$usb_rule_file"; then
say "A VM can be given this host's USB devices once QEMU, running as you, may open them"
if ask "Add the udev rule $usb_rule_file, giving USB devices other than hubs to the kvm group and to you at this host's screen, with sudo?"; then
printf '# reims-ctl: USB devices for VMs (reims-ctl usb --help)\n%s\n' "$usb_rule" |
sudo tee "$usb_rule_file" >/dev/null
# Applied to the devices plugged in now, as to those plugged in later.
sudo udevadm control --reload && sudo udevadm trigger --subsystem-match=usb ||
warn "udev did not reload its rules: unplug a USB device and plug it in again, or restart, before giving it to a VM"
else
warn "without the rule, a VM can be given only the USB devices you may open; reims-ctl usb --help shows it"
# USB passthrough (reims-ctl usb): QEMU opens a USB device's file in
# /dev/bus/usb, which only root may write unless a udev rule says otherwise.
# This one gives USB devices other than hubs to the kvm group, over SSH too,
# and to the user at the host's screen (uaccess, which a file sorting before
# systemd's 73-seat-late.rules sets). reims-ctl's usb::UDEV_RULE is the same
# line, which its tests check.
usb_rule_file=/etc/udev/rules.d/70-reims-ctl-usb.rules
usb_rule='SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{bDeviceClass}!="09", GROUP="kvm", MODE="0664", TAG+="uaccess"'
if ! grep -qsxF "$usb_rule" "$usb_rule_file"; then
say "A VM can be given this host's USB devices once QEMU, running as you, may open them"
if ask "Add the udev rule $usb_rule_file, giving USB devices other than hubs to the kvm group and to you at this host's screen, with sudo?"; then
printf '# reims-ctl: USB devices for VMs (reims-ctl usb --help)\n%s\n' "$usb_rule" |
sudo tee "$usb_rule_file" >/dev/null
# Applied to the devices plugged in now, as to those plugged in later.
sudo udevadm control --reload && sudo udevadm trigger --subsystem-match=usb ||
warn "udev did not reload its rules: unplug a USB device and plug it in again, or restart, before giving it to a VM"
else
warn "without the rule, a VM can be given only the USB devices you may open; reims-ctl usb --help shows it"
fi
fi
# Unless /dev/udmabuf's group, kvm, was the one named above.
if [[ ${group:-} != kvm ]] && getent group kvm >/dev/null && ! id -nG | tr ' ' '\n' | grep -qx kvm; then
say "You're not in the kvm group: over SSH, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG kvm \$USER) to give VMs USB devices there"
fi
fi
# Unless /dev/udmabuf's group, kvm, was the one named above.
if [[ ${group:-} != kvm ]] && getent group kvm >/dev/null && ! id -nG | tr ' ' '\n' | grep -qx kvm; then
say "You're not in the kvm group: over SSH, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG kvm \$USER) to give VMs USB devices there"
fi
# The build runs the toolchain rust-toolchain.toml pins, through rustup's proxies in Cargo's
@@ -343,7 +390,7 @@ fetch_qemu() {
die "could not fetch vendor/qemu's commit $(git -C "$ROOT" ls-tree HEAD vendor/qemu | awk '{print $3}') from $(git -C "$ROOT" config -f .gitmodules --get submodule.vendor/qemu.url): check that you can read that repository; a commit it does not have was not pushed to it"
}
if [[ $SKIP_QEMU == 0 ]]; then
if [[ $BUILDS_QEMU == 1 && $SKIP_QEMU == 0 ]]; then
# A linked worktree shares the main checkout's module repository: initialising
# vendor/qemu here would rewrite that repository's core.worktree for every
# worktree (docs/lessons.md).
@@ -402,7 +449,7 @@ COMMIT="$(git -C "$ROOT" rev-parse --short HEAD)"
TARGET="${CARGO_TARGET_DIR:-$ROOT/target}"
DIST="$TARGET/dist-vulkan"
if [[ $SKIP_QEMU == 0 ]]; then
if [[ $BUILDS_QEMU == 1 && $SKIP_QEMU == 0 ]]; then
say "Building the library (cargo xtask dist --platform vulkan)"
(cd "$ROOT" && CARGO_TARGET_DIR="$TARGET" cargo xtask dist --platform vulkan)
[[ -f "$DIST/lib/pkgconfig/reims-vgpu.pc" ]] || die "cargo xtask dist wrote no $DIST/lib/pkgconfig/reims-vgpu.pc"
@@ -457,9 +504,11 @@ if [[ $SKIP_QEMU == 0 ]]; then
ln -sfn "$ID" "$DATA/qemu/current"
prune_qemu "$DATA/qemu"
QEMU_DIR="$DATA/qemu/$ID"
else
elif [[ $BUILDS_QEMU == 1 ]]; then
QEMU_DIR="$(cd "$DATA/qemu/current" && pwd -P)"
kept_qemu "$QEMU_DIR" | while read -r why; do warn "$why"; done
else
QEMU_DIR=""
fi
# ------------------------------------------------------------------ reims-ctl
@@ -468,13 +517,17 @@ say "Installing reims-ctl (cargo install)"
(cd "$ROOT" && CARGO_TARGET_DIR="$CACHE/ctl-target" cargo install --locked --force --quiet --path crates/reims-ctl)
BIN="${CARGO_INSTALL_ROOT:-${CARGO_HOME:-$HOME/.cargo}}/bin/reims-ctl"
[[ -x "$BIN" ]] || die "cargo install left no $BIN"
"$BIN" __record-install --repo "$ROOT" --qemu "$QEMU_DIR" --commit "$COMMIT"
"$BIN" __record-install --repo "$ROOT" ${QEMU_DIR:+--qemu "$QEMU_DIR"} --commit "$COMMIT"
echo
printf '%sreims-ctl is installed.%s\n' "$green$bold" "$off"
echo " reims-ctl the interactive interface: create, start and stop VMs"
if [[ $BUILDS_QEMU == 1 ]]; then
echo " reims-ctl the interactive interface: create, start and stop VMs"
else
echo " reims-ctl the interactive interface: make arm64 VMs from IPSWs"
fi
echo " reims-ctl help the same from a shell"
echo " QEMU $QEMU_DIR"
[[ -z $QEMU_DIR ]] || echo " QEMU $QEMU_DIR"
echo
# By its full path, which works before PATH finds reims-ctl.
echo "Check this host:"