From ee490a23c7e26df2c9dbd264fdc8d31a21768bdf Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:50:52 +0000 Subject: [PATCH] refactor(setup): remove the USB recoveryOS bundle --- crates/stela-boot/src/choice.rs | 16 +- crates/stela-boot/src/engine.rs | 23 - crates/stela-boot/src/engine/bundle.rs | 8 - crates/stela-boot/src/selection.rs | 86 +- crates/stela-boot/src/system.rs | 8 + crates/stela-cli/src/boot.rs | 270 +--- crates/stela-cli/src/boot/disk.rs | 2 +- crates/stela-cli/src/boot/recovery_volume.rs | 266 ---- .../src/boot/recovery_volume/format.rs | 880 ------------- crates/stela-cli/src/restore.rs | 1 - crates/stela-cli/src/restore/udif.rs | 263 ---- crates/stela-cli/src/setup.rs | 1112 ++++++++--------- crates/stela-cli/src/setup/bundle.rs | 77 +- crates/stela-cli/src/setup/doctor.rs | 111 +- crates/stela-cli/src/setup/installed.rs | 32 +- crates/stela-cli/src/setup/machines.rs | 95 +- crates/stela-cli/src/setup/state.rs | 6 +- crates/stela-cli/src/setup/update.rs | 163 +-- crates/stela-cli/src/setup/wizard.rs | 5 +- .../recovery-volume/make-recovery-volume.sh | 15 - .../recovery-volume/recovery-volume.img.gz | Bin 13301 -> 0 bytes crates/stela-loader/src/boot_bundle.rs | 82 +- crates/stela-loader/src/boot_policy.rs | 3 +- crates/stela-loader/src/boot_selection.rs | 120 +- crates/stela-loader/src/mount_interface.rs | 18 +- crates/stela-loader/src/recovery.rs | 2 +- crates/stela-loader/src/root_selection.rs | 96 -- xtask/src/boot.rs | 2 +- 28 files changed, 786 insertions(+), 2976 deletions(-) delete mode 100644 crates/stela-cli/src/boot/recovery_volume.rs delete mode 100644 crates/stela-cli/src/boot/recovery_volume/format.rs delete mode 100644 crates/stela-cli/src/restore/udif.rs delete mode 100644 crates/stela-cli/tests/fixtures/recovery-volume/make-recovery-volume.sh delete mode 100644 crates/stela-cli/tests/fixtures/recovery-volume/recovery-volume.img.gz diff --git a/crates/stela-boot/src/choice.rs b/crates/stela-boot/src/choice.rs index ea28bad1ba..34dc32244b 100644 --- a/crates/stela-boot/src/choice.rs +++ b/crates/stela-boot/src/choice.rs @@ -2,9 +2,8 @@ //! has `choices.cfg`, `stela.efi` lists on the framebuffer, in Stela's look //! ([`ui`]), the entries that can start now, then the PC firmware's own //! boot entries (`firmware::entries`), with one highlighted. A macOS entry -//! is left out until a macOS is installed, a macOS or recoveryOS entry -//! while Install macOS has not prepared its SSD, and Install macOS once it -//! has (`selection::ready`). Up and Down move the +//! is left out until a macOS is installed or while Install macOS has not +//! prepared its SSD, and Install macOS once it has (`selection::ready`). Up and Down move the //! highlight, Enter starts the highlighted entry, and an entry's key (`1`-`9`, //! then `a`-`z`) starts it at once; a firmware entry restarts the PC into it. //! A countdown from the file's timeout starts the first entry, the one @@ -219,7 +218,7 @@ impl<'a> Menu<'a> { None => Readiness::Unprepared, }) .collect(); - // The SSDs a macOS or recoveryOS choice is known to start from, + // The SSDs a macOS choice is known to start from, // which Install macOS has prepared already. let prepared: Vec> = choices .entries @@ -234,9 +233,7 @@ impl<'a> Menu<'a> { let kind = entry.kind(); let left_out = match (kind, readiness[n]) { (ChoiceKind::Mac, Readiness::NotInstalled) => Some("no macOS is installed"), - (ChoiceKind::Mac | ChoiceKind::Recovery, Readiness::Unprepared) => { - Some("its SSD is not prepared") - } + (ChoiceKind::Mac, Readiness::Unprepared) => Some("its SSD is not prepared"), // Install macOS that chooses its disk is always offered. (ChoiceKind::Setup, _) if !unchosen(entry.options.as_bytes()) @@ -274,10 +271,7 @@ impl<'a> Menu<'a> { None => 0, }; // The countdown starts the first entry when it starts the Mac. - let starts_mac = matches!( - items.first(), - Some(Item::Choice(_, ChoiceKind::Mac | ChoiceKind::Recovery)) - ); + let starts_mac = matches!(items.first(), Some(Item::Choice(_, ChoiceKind::Mac))); Self { choices, disk, diff --git a/crates/stela-boot/src/engine.rs b/crates/stela-boot/src/engine.rs index e64c0d35eb..ac86e902cd 100644 --- a/crates/stela-boot/src/engine.rs +++ b/crates/stela-boot/src/engine.rs @@ -1663,29 +1663,6 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! { options.nor.as_ref().map(|_| services.next().unwrap()), ), }; - // recoveryOS boots on a Mac's internal disk layout: refuse a namespace - // without the iBootSystemContainer it aborts without, before it runs. - let recovery = options.bundle - && bundle::enters_recovery_os(&handoff.files[..handoff.file_count], built.as_deref()) - .unwrap_or_else(|error| { - output::arguments(format_args!("bundle refusal: {error}\n")); - output::fatal("the boot bundle's OS environment could not be read") - }); - let backing = match backing { - Some(namespace) if recovery => { - let mut bytes = bundle::Bytes::new(namespace); - if let Err(error) = stela_runtime::apfs::require_system_container(&mut bytes) { - output::arguments(format_args!("recoveryOS refusal: {error}\n")); - output::fatal( - "recoveryOS needs the internal disk's iBootSystemContainer with its xART \ - volume, which the restore creates", - ); - } - Some(bytes.into_inner()) - } - None if recovery => output::fatal("recoveryOS needs the internal disk (--storage)"), - backing => backing, - }; let nor = nor.map(|device| { crate::status::begin(&format!( "Opening the machine state on {}", diff --git a/crates/stela-boot/src/engine/bundle.rs b/crates/stela-boot/src/engine/bundle.rs index 6b9915087e..0188d5a8d9 100644 --- a/crates/stela-boot/src/engine/bundle.rs +++ b/crates/stela-boot/src/engine/bundle.rs @@ -539,14 +539,6 @@ pub fn dram_base(files: &[File], built: Option<&[(String, Vec)]>) -> Result< Ok(manifest(files, built)?.options.dram_base) } -/// Whether the bundle enters recoveryOS (`osenvironment` `recoveryos`). -pub fn enters_recovery_os( - files: &[File], - built: Option<&[(String, Vec)]>, -) -> Result { - Ok(manifest(files, built)?.options.osenvironment.as_deref() == Some("recoveryos")) -} - /// The guest's DRAM: `backed` bytes of host RAM from `base`, within the /// `installed` bytes the Mac reports. #[derive(Debug, Clone, Copy)] diff --git a/crates/stela-boot/src/selection.rs b/crates/stela-boot/src/selection.rs index f0b952ee5a..5700fc736e 100644 --- a/crates/stela-boot/src/selection.rs +++ b/crates/stela-boot/src/selection.rs @@ -6,11 +6,11 @@ //! before it boots) and hands the engine the options for that boot. A macOS //! boot whose Preboot disk holds no installed system boots System Recovery //! instead (missing boot media), as a Mac with an erased disk does. A -//! recoveryOS boot takes the disk's own copy when it has one, the paired -//! recoveryOS of the Recovery volume and then System Recovery of the -//! RecoveryOSContainer (`stela_loader::recovery::find`), which the engine -//! builds from the disk; otherwise it reads the `--recovery-bundle` -//! directory here, because the ESP is readable only through the firmware. +//! recoveryOS boot takes the disk's own copy, the paired recoveryOS of the +//! Recovery volume and then System Recovery of the RecoveryOSContainer +//! (`stela_loader::recovery::find`), which the engine builds from the disk. +//! A disk that holds neither boots nothing ([`Refusal::NoRecovery`]): Stela +//! has no recoveryOS of its own, and only Install macOS restores the disk's. //! NVRAM that holds the machine in iBoot's recovery mode, as an interrupted //! restore leaves it, boots nothing ([`Refusal::RecoveryMode`]). //! @@ -410,15 +410,16 @@ fn replace(text: &str, name: &str, value: &str) -> String { /// Whether a startup choice can start now ([`ready`]). #[derive(Clone, Copy, PartialEq, Eq)] pub enum Readiness { - /// It starts what it names: macOS from an installed system, or - /// recoveryOS from a prepared SSD. + /// It starts what it names: macOS from an installed system, or the + /// disk's recoveryOS when NVRAM asks for it. Ready, /// A Mac choice whose startup disk holds no installed macOS, which - /// would start recoveryOS instead. + /// would start the disk's System Recovery instead, or nothing without + /// one. NotInstalled, - /// Its SSD has no iBootSystemContainer yet, or NVRAM holds the machine - /// in recovery mode, as an unfinished restore leaves it: only Install - /// macOS starts. + /// Its SSD has no iBootSystemContainer yet, NVRAM holds the machine in + /// recovery mode, as an unfinished restore leaves it, or NVRAM asks for + /// a recoveryOS the disk does not hold: only Install macOS starts. Unprepared, /// The check could not be made; starting the choice reports why. Unknown, @@ -430,41 +431,16 @@ pub fn ready(options: &str, kind: ChoiceKind) -> Readiness { match kind { ChoiceKind::Mac => match route_checked(options.as_bytes().into(), false) { Ok((_, true)) => Readiness::Ready, - Ok((_, false)) => Readiness::NotInstalled, - Err(Refusal::BlankDisk | Refusal::RecoveryMode) => Readiness::Unprepared, + Ok((_, false)) | Err(Refusal::NoRecovery { installed: false }) => { + Readiness::NotInstalled + } + Err( + Refusal::BlankDisk + | Refusal::RecoveryMode + | Refusal::NoRecovery { installed: true }, + ) => Readiness::Unprepared, Err(Refusal::Other(_)) => Readiness::Unknown, }, - ChoiceKind::Recovery => { - let Some(target) = option(options, "--storage").and_then(|s| s.parse::().ok()) - else { - return Readiness::Unknown; - }; - // The engine splits a `--storage` partition that `--nor` also - // names; recoveryOS then reads its namespace. - let in_storage = option(options, "--nor") == option(options, "--storage"); - // NVRAM that an unfinished restore left holding the machine in - // recovery mode waits for Install macOS, as the Mac choice does. - if let Some(nor) = option(options, "--nor").and_then(|s| s.parse::().ok()) { - let state = if in_storage { Part::State } else { Part::Whole }; - match select(&nor, state, false) { - Ok(s) if s.target == boot_selection::Target::RecoveryMode => { - return Readiness::Unprepared; - } - Ok(_) => {} - Err(_) => return Readiness::Unknown, - } - } - let part = if in_storage { - Part::Namespace - } else { - Part::Whole - }; - match blank(&target, part) { - Ok(true) => Readiness::Unprepared, - Ok(false) => Readiness::Ready, - Err(_) => Readiness::Unknown, - } - } _ => Readiness::Unknown, } } @@ -478,6 +454,12 @@ pub enum Refusal { /// The internal SSD has no iBootSystemContainer yet: only Install macOS /// boots. BlankDisk, + /// NVRAM boots recoveryOS, or the boot disk holds no installed system + /// (`installed` false, missing boot media), and the disk holds no + /// recoveryOS to boot: only Install macOS restores one. + NoRecovery { + installed: bool, + }, Other(&'static str), } @@ -553,9 +535,7 @@ fn route_checked(options: Vec, consume: bool) -> Result<(Vec, bool), Ref if retargeted.is_none() && blank(&disk, part).map_err(refuse)? { return Err(Refusal::BlankDisk); } - let recovery = option(text, boot_selection::RECOVERY_BUNDLE_OPTION).is_some(); - if recovery - && matches!(selection.target, boot_selection::Target::MacOs { .. }) + if matches!(selection.target, boot_selection::Target::MacOs { .. }) && !installed(&disk, part, selection.volume.as_ref()).map_err(refuse)? { selection.missing_boot_media(); @@ -576,6 +556,18 @@ fn route_checked(options: Vec, consume: bool) -> Result<(Vec, bool), Ref } _ => {} } + let wants_recovery = matches!( + selection.target, + boot_selection::Target::PairedRecovery | boot_selection::Target::SystemRecovery + ); + if wants_recovery && !selection.paired_on_disk && !selection.system_on_disk { + if let Err(error) = boot_selection::route(text, Some(&selection)) { + output::arguments(format_args!("BOOT {error:#}\n")); + } + return Err(Refusal::NoRecovery { + installed: installed_system, + }); + } Some(selection) } None => None, diff --git a/crates/stela-boot/src/system.rs b/crates/stela-boot/src/system.rs index 10c7c3bd68..28da84dfba 100644 --- a/crates/stela-boot/src/system.rs +++ b/crates/stela-boot/src/system.rs @@ -445,6 +445,13 @@ fn map_devices( fn held(refusal: Refusal) -> &'static str { match refusal { Refusal::BlankDisk => "The Mac's SSD is not prepared yet: choose Install macOS first.", + Refusal::NoRecovery { installed: false } => { + "No macOS is installed and the Mac's SSD holds no System Recovery: choose Install \ + macOS." + } + Refusal::NoRecovery { installed: true } => { + "NVRAM asks for recoveryOS, which the Mac's SSD does not hold: choose Install macOS." + } _ => "The Mac's last install did not finish: choose Install macOS again.", } } @@ -462,6 +469,7 @@ pub fn held_at_start(options: &[u8]) -> Option<&'static str> { let (held, found) = match crate::selection::peek(options.to_vec()) { Err(refusal @ Refusal::BlankDisk) => (Some(held(refusal)), "no macOS installed yet"), Err(refusal @ Refusal::RecoveryMode) => (Some(held(refusal)), "an install did not finish"), + Err(refusal @ Refusal::NoRecovery { .. }) => (Some(held(refusal)), "no recoveryOS to boot"), _ => (None, ""), }; crate::status::done(found); diff --git a/crates/stela-cli/src/boot.rs b/crates/stela-cli/src/boot.rs index 04a74ec24f..ac017c45ca 100644 --- a/crates/stela-cli/src/boot.rs +++ b/crates/stela-cli/src/boot.rs @@ -13,11 +13,10 @@ use stela_loader::boot_policy::{OsEnvironment, SealedVolume, SecurityMode, Secur use stela_loader::handoff::{self, BootCommand as FirmwareBootCommand}; use stela_loader::im4m; use stela_loader::root_selection::Root; -use stela_runtime::{apfs::btree::Seal, payload::Purpose}; +use stela_runtime::payload::Purpose; mod board_firmware; mod disk; -mod recovery_volume; mod ticket; const MANIFEST_FILE: &str = "bundle.json"; @@ -26,9 +25,6 @@ const COMPONENT_LIMIT: u64 = 64 * 1024 * 1024; /// The largest BuildManifest `--tss` reads. const BUILD_MANIFEST_LIMIT: u64 = 64 * 1024 * 1024; const RAMDISK_LIMIT: u64 = 2 * 1024 * 1024 * 1024; -/// The recoveryOS volume holds the whole BaseSystem UDIF image (2.3 GB for -/// 26A434) and its APFS metadata. -const RECOVERY_VOLUME_LIMIT: u64 = 3 * 1024 * 1024 * 1024; /// The OS environment of a restore ramdisk: its `/osenvironments` child /// turns off the SEP firmware load and protected data access and selects /// ephemeral storage. @@ -48,22 +44,6 @@ const RESTORE_MODE_ARGS: &[&str] = &[ "-progress", "-restore", ]; -/// recoveryOS first roots from the volume that holds BaseSystem -/// (`recovery_volume`), which `/chosen` names as iBoot names a Recovery -/// volume, then from BaseSystem as a disk image. No `rd=`: a memory-device -/// root makes APFS take that device for the image root as well -/// (`boot_policy::refuse_ramdisk_image_root`). -const RECOVERY_MODE_ARGS: &[&str] = &[recovery_volume::IMAGE_BOOT_ARG]; -/// The environment J473 iBoot enters for recoveryOS (its table 0x170838). -/// The kernel's APFS reads it (`apfs_is_booted_for_recovery`, which accepts -/// only `recoveryos` and `diagnostics`). The DeviceTree's `recovery` child is -/// one no J473 iBoot caller passes, and its data-volume entry needs a -/// `/filesystems` node this DeviceTree lacks. -const RECOVERY_ENVIRONMENT: OsEnvironment = OsEnvironment::Recoveryos; -const BASE_SYSTEM: &str = "BaseSystem"; -/// The BaseSystem image's APFS partition, whose seal the forwarded root hash -/// must name. -const BASE_SYSTEM_PARTITION: &str = "Apple_APFS"; /// The BuildManifest components, and their IM4P types, a boot mode loads. struct Roles { @@ -73,7 +53,8 @@ struct Roles { sptm: &'static str, txm: &'static str, sep: &'static str, - ramdisk: Option, + /// An IM4P ramdisk component and its type. + ramdisk: Option<(&'static str, &'static str)>, /// The sealed volume the kernel roots from, by its root-hash component. root_hash: Option<(&'static str, SealedVolume)>, /// Whether the identity's global manifest admits every boot object of @@ -82,15 +63,6 @@ struct Roles { manifest_admits_all: bool, } -#[derive(Clone, Copy)] -enum Ramdisk { - /// An IM4P component and its type. - Image4(&'static str, &'static str), - /// The AEA-encrypted BaseSystem UDIF image, decrypted, on the volume - /// recoveryOS first roots from, a RAM disk image DiskImages attaches. - BaseSystem, -} - const INSTALLED: Roles = Roles { kernel: "KernelCache", device_tree: "DeviceTree", @@ -110,26 +82,11 @@ const RESTORE: Roles = Roles { sptm: "Ap,RestoreSecurePageTableMonitor", txm: "Ap,RestoreTrustedExecutionMonitor", sep: "RestoreSEP", - ramdisk: Some(Ramdisk::Image4("RestoreRamDisk", "rdsk")), + ramdisk: Some(("RestoreRamDisk", "rdsk")), root_hash: None, manifest_admits_all: false, }; -/// recoveryOS: the installed system's kernel, monitors and DeviceTree, the -/// BaseSystem trust cache, and the volume holding the BaseSystem image as the -/// RAM disk image the kernel first roots from. -const RECOVERY: Roles = Roles { - kernel: "KernelCache", - device_tree: "DeviceTree", - trust_cache: ("Ap,BaseSystemTrustCache", "bstc"), - sptm: "Ap,SecurePageTableMonitor", - txm: "Ap,TrustedExecutionMonitor", - sep: "SEP", - ramdisk: Some(Ramdisk::BaseSystem), - root_hash: Some(("BaseSystemVolume", SealedVolume::BaseSystem)), - manifest_admits_all: true, -}; - #[derive(Subcommand)] pub(crate) enum BootCommand { /// Lay out a model's kernel collection, SPTM, TXM, DeviceTree and trust @@ -379,7 +336,7 @@ pub(crate) struct Prepare { model: Option, /// Build the bundle from an installed system's Preboot volume on this /// disk image instead of an IPSW. - #[arg(long, conflicts_with_all = ["restore", "recovery", "variant", "cryptex_trust_caches"])] + #[arg(long, conflicts_with_all = ["restore", "variant", "cryptex_trust_caches"])] disk: Option, /// The `boot/` directory to use when the Preboot volume has several. #[arg(long, requires = "disk")] @@ -402,30 +359,21 @@ pub(crate) struct Prepare { output: PathBuf, /// Boot the restore ramdisk with the identity's restore objects instead /// of the installed system. - #[arg(long, conflicts_with = "recovery")] + #[arg(long)] restore: bool, /// With `--restore`: the model's update restore identity (its /// `RestoreBehavior` is `Update`), whose ramdisk runs restored_update /// over the installed system and keeps its data. #[arg(long, requires = "restore", conflicts_with = "variant")] update: bool, - /// Boot recoveryOS with the installed system's kernel: the kernel roots - /// from a volume in memory holding the BaseSystem image, then from that - /// image. - #[arg(long)] - recovery: bool, - /// The public AEA key (PKCS8 PEM) for BaseSystem; fetched from Apple's - /// key server when omitted. - #[arg(long, requires = "recovery")] - aea_key: Option, /// The restore identity by its variant, such as `Customer Upgrade /// Install (IPSW)`; by default the model's erase restore identity with /// `--restore`, and its installed system's otherwise. #[arg(long)] variant: Option, /// The OS environment iBoot enters (`/chosen osenvironment` and its - /// `/osenvironments` child): `darwinos-ramdisk` with `--restore`, - /// `recoveryos` with `--recovery`, none (macOS) otherwise. + /// `/osenvironments` child): `darwinos-ramdisk` with `--restore`, none + /// (macOS) otherwise. #[arg(long, value_parser = |name: &str| OsEnvironment::parse(name).map_err(|e| e.to_string()))] osenvironment: Option, /// Guest DRAM base; the target SoC's by default (0x800000000 on the M1 @@ -442,8 +390,8 @@ pub(crate) struct Prepare { /// Distance of the first region above the physical base. #[arg(long, value_parser = parse_address, default_value = "0")] load_offset: u64, - /// The kernel command line, `-v` by default. `--restore` and - /// `--recovery` add the arguments their boot mode needs. + /// The kernel command line, `-v` by default. `--restore` adds the + /// arguments its boot mode needs. #[arg(long)] boot_args: Option, /// The boot policy expressed to SPTM, TXM and the kernel. @@ -657,64 +605,6 @@ fn check_digests( Ok(outside) } -/// The volume recoveryOS first roots from with its volume's UUID, and the -/// seal of BaseSystem's file system. The AEA member is copied out and -/// decrypted with the public key. Its UDIF image's `Apple_APFS` partition -/// gives the seal, and the image itself goes unchanged onto the volume -/// (`recovery_volume`). -fn base_system( - ipsw: &std::path::Path, - member: &str, - key: Option<&std::path::Path>, - declared_digest: Option, -) -> Result<(Decoded, String, Seal)> { - let work = tempfile::tempdir()?; - let encrypted = work.path().join("BaseSystem.dmg.aea"); - let receipt = restore::archive::extract(ipsw, member, &encrypted, RAMDISK_LIMIT)?; - let container_sha256 = receipt["sha256"] - .as_str() - .context("extraction receipt has no SHA-256")? - .to_owned(); - let key = match key { - Some(key) => key.to_path_buf(), - None => { - let fetched = restore::aea::fetch_public_key(&restore::aea::inspect(&encrypted)?)?; - let path = work.path().join("BaseSystem.pem"); - std::fs::write(&path, &fetched.body)?; - path - } - }; - let image = work.path().join("BaseSystem.dmg"); - restore::aea::decrypt(&encrypted, &key, &image)?; - std::fs::remove_file(&encrypted)?; - let seal = recovery_volume::base_system_seal(restore::udif::partition( - &image, - BASE_SYSTEM_PARTITION, - RAMDISK_LIMIT, - )?)?; - let (_, image_sha256) = restore::payload::file_sha256(&image)?; - let (bytes, volume_uuid) = recovery_volume::build(&image, RECOVERY_VOLUME_LIMIT)?; - let source = Source { - component: BASE_SYSTEM.into(), - member: member.into(), - container_sha256, - payload_type: "apfs".into(), - description: format!( - "unsealed APFS volume {volume_uuid} holding the decrypted UDIF image (SHA-256 \ - {image_sha256}) at /{}", - recovery_volume::IMAGE_PATH - ), - decoded_bytes: bytes.len(), - decoded_sha256: stela_runtime::sha256(&bytes), - }; - let volume = Decoded { - source, - bytes, - declared_digest, - }; - Ok((volume, volume_uuid, seal)) -} - fn parse_id(value: Option<&str>) -> Result> { value .map(|v| { @@ -753,11 +643,10 @@ impl Prepare { // The profile's identities and components, as setup chooses them. let profile = components::Profile::of(&model)?; let report = restore::archive::manifest(&ipsw, None, false)?; - let (roles, purpose) = match (self.restore, self.recovery) { - (true, _) if self.update => (RESTORE, Purpose::Update), - (true, _) => (RESTORE, Purpose::Erase), - (false, true) => (RECOVERY, Purpose::Installed), - (false, false) => (INSTALLED, Purpose::Installed), + let (roles, purpose) = match self.restore { + true if self.update => (RESTORE, Purpose::Update), + true => (RESTORE, Purpose::Erase), + false => (INSTALLED, Purpose::Installed), }; let identity = match self.variant.as_deref() { Some(variant) => components::variant(&report, &profile, variant)?, @@ -811,27 +700,10 @@ impl Prepare { let device_tree = component(roles.device_tree, Some("dtre"), COMPONENT_LIMIT)?; let (trust_cache_name, trust_cache_type) = roles.trust_cache; let trust_cache = component(trust_cache_name, Some(trust_cache_type), COMPONENT_LIMIT)?; - let (ramdisk, recovery_uuid, base_system_seal) = match roles.ramdisk { - None => (None, None, None), - Some(Ramdisk::Image4(name, payload_type)) => ( - Some(component(name, Some(payload_type), RAMDISK_LIMIT)?), - None, - None, - ), - Some(Ramdisk::BaseSystem) => { - let entry = identity - .components - .get(BASE_SYSTEM) - .with_context(|| format!("{} lists no {BASE_SYSTEM}", identity.variant))?; - let (volume, uuid, seal) = base_system( - &ipsw, - &entry.path, - self.aea_key.as_deref(), - entry.declared_digest_hex.clone(), - )?; - (Some(volume), Some(uuid), Some(seal)) - } - }; + let ramdisk = roles + .ramdisk + .map(|(name, payload_type)| component(name, Some(payload_type), RAMDISK_LIMIT)) + .transpose()?; // The root hash stays an IM4P: iBoot forwards it with its manifest. let root_hash = match roles.root_hash { None => None, @@ -844,9 +716,6 @@ impl Prepare { .transpose()?, )), }; - if let (Some(seal), Some((_, Some(root_hash)))) = (&base_system_seal, &root_hash) { - recovery_volume::check_root_hash(seal, &root_hash.bytes)?; - } let sep = owned .iter() .any(|i| i.components.contains_key(roles.sep)) @@ -1014,7 +883,7 @@ impl Prepare { .map(|(name, decoded)| (name.clone(), input(decoded))) .collect(), }; - let options = self.options(inputs.dram_base()?, recovery_uuid.as_deref())?; + let options = self.options(inputs.dram_base()?)?; let mut bundle = boot_bundle::prepare(&inputs, &options)?; let mut unresolved = vec![]; // The board the bundle's DeviceTree describes names its images, each @@ -1075,13 +944,8 @@ impl Prepare { } /// The bundle options from the command line, with the boot-args, OS - /// environment and root of the selected boot mode; `recovery_uuid` is - /// the UUID of the volume a recoveryOS boot first roots from. - fn options( - &self, - board_dram_base: Option, - recovery_uuid: Option<&str>, - ) -> Result { + /// environment and root of the selected boot mode. + fn options(&self, board_dram_base: Option) -> Result { let dram_base = self .dram_base .or(board_dram_base) @@ -1093,39 +957,24 @@ impl Prepare { load_offset: self.load_offset, boot_args: boot_args( self.boot_args.as_deref().unwrap_or(DEFAULT_BOOT_ARGS), - match (self.restore, self.recovery) { - (true, _) => RESTORE_MODE_ARGS, - (false, true) => RECOVERY_MODE_ARGS, - (false, false) => &[], - }, + if self.restore { RESTORE_MODE_ARGS } else { &[] }, ), - osenvironment: self.osenvironment.or(match (self.restore, self.recovery) { - (true, _) => Some(RESTORE_ENVIRONMENT), - (false, true) => Some(RECOVERY_ENVIRONMENT), - (false, false) => None, - }), + osenvironment: self + .osenvironment + .or(self.restore.then_some(RESTORE_ENVIRONMENT)), // --restore replaces the host-received iBEC path, for both // erase and update IPSW identities. Disk updates are assigned // Upgrade by stela_loader::upgrade instead. - boot_command: Some(match (self.restore, self.recovery) { - (true, _) => FirmwareBootCommand::TetheredRestore, - (false, true) => FirmwareBootCommand::RecoverSystem, - (false, false) => handoff::installed_command( + boot_command: Some(match self.restore { + true => FirmwareBootCommand::TetheredRestore, + false => handoff::installed_command( None, self.boot_args.as_deref().unwrap_or(DEFAULT_BOOT_ARGS), )?, }), - // A restore ramdisk roots from itself as `md0`; recoveryOS from - // its RAM disk image's volume; an installed system's root is - // named from its disk (`stela_loader::installed`). - root: match (self.restore, self.recovery, recovery_uuid) { - (true, _, _) => Some(Root::Ramdisk), - (false, true, Some(volume)) => Some(Root::RamImage { - volume: volume.to_owned(), - }), - (false, true, None) => bail!("a recoveryOS boot needs its volume's UUID"), - (false, false, _) => None, - }, + // A restore ramdisk roots from itself as `md0`; an installed + // system's root is named from its disk (`stela_loader::installed`). + root: self.restore.then_some(Root::Ramdisk), ecid: self.ecid, boot_cpu: self.boot_cpu.clone(), timebase_frequency: self.timebase_frequency, @@ -1254,18 +1103,6 @@ mod tests { boot_args(DEFAULT_BOOT_ARGS, RESTORE_MODE_ARGS), "-v serial=3 serial-device-name=uart0 rd=md0 nand-enable-reformat=0x1 -progress -restore" ); - let recovery = boot_args("-v debug=0x8", RECOVERY_MODE_ARGS); - assert_eq!( - recovery, - format!("-v debug=0x8 {}", recovery_volume::IMAGE_BOOT_ARG) - ); - // recoveryOS names no memory-device root, which the loader refuses - // beside an image root. - assert_eq!( - stela_loader::boot_policy::ramdisk_root_device(&recovery), - None - ); - assert!(stela_loader::boot_policy::require_image_boot(&recovery).is_ok()); } #[test] @@ -1274,13 +1111,6 @@ mod tests { boot_args("serial=3 rd=md1 -restore", RESTORE_MODE_ARGS), "serial=3 rd=md1 -restore nand-enable-reformat=0x1 -progress" ); - assert_eq!( - boot_args("", RECOVERY_MODE_ARGS), - recovery_volume::IMAGE_BOOT_ARG - ); - // An explicit `rd=md0` stays, and the loader refuses it. - let explicit = boot_args("rd=md0", RECOVERY_MODE_ARGS); - assert!(stela_loader::boot_policy::require_image_boot(&explicit).is_err()); } #[test] @@ -1296,19 +1126,19 @@ mod tests { ]; let automatic = Line::try_parse_from(base).unwrap().prepare; assert_eq!(automatic.boot_cpu, None); - assert_eq!(automatic.options(None, None).unwrap().boot_cpu, None); + assert_eq!(automatic.options(None).unwrap().boot_cpu, None); let explicit = Line::try_parse_from(base.into_iter().chain(["--boot-cpu", "cpu0"])) .unwrap() .prepare; assert_eq!(explicit.boot_cpu.as_deref(), Some("cpu0")); assert_eq!( - explicit.options(None, None).unwrap().boot_cpu.as_deref(), + explicit.options(None).unwrap().boot_cpu.as_deref(), Some("cpu0") ); } #[test] - fn recovery_roots_from_its_volume_and_restore_from_md0() { + fn restore_roots_from_md0() { use clap::Parser; #[derive(Parser)] struct Line { @@ -1321,30 +1151,13 @@ mod tests { ]) .map(|line| line.prepare) }; - let volume = "11111111-2222-3333-4444-555555555555"; - let recovery = parse("--recovery").unwrap(); - let options = recovery.options(None, Some(volume)).unwrap(); - assert_eq!( - options.boot_command, - Some(FirmwareBootCommand::RecoverSystem) - ); - assert_eq!( - options.root, - Some(Root::RamImage { - volume: volume.into() - }) - ); - assert!(!options.boot_args.contains("rd=")); - assert!(recovery.options(None, None).is_err()); + assert!(parse("--recovery").is_err()); let restore = parse("--restore").unwrap(); assert_eq!( - restore.options(None, None).unwrap().boot_command, + restore.options(None).unwrap().boot_command, Some(FirmwareBootCommand::TetheredRestore) ); - assert_eq!( - restore.options(None, None).unwrap().root, - Some(Root::Ramdisk) - ); + assert_eq!(restore.options(None).unwrap().root, Some(Root::Ramdisk)); // `--update` picks the update restore identity, and only with // `--restore`. assert!(parse("--update").is_err()); @@ -1363,13 +1176,10 @@ mod tests { .prepare; assert!(update.update); assert_eq!( - update.options(None, None).unwrap().boot_command, + update.options(None).unwrap().boot_command, Some(FirmwareBootCommand::TetheredRestore) ); - assert_eq!( - update.options(None, None).unwrap().root, - Some(Root::Ramdisk) - ); + assert_eq!(update.options(None).unwrap().root, Some(Root::Ramdisk)); // Merely overriding the environment and arguments does not claim // that an iBEC image was received from a restore host. let manual = Line::try_parse_from([ @@ -1388,7 +1198,7 @@ mod tests { .unwrap() .prepare; assert_eq!( - manual.options(None, None).unwrap().boot_command, + manual.options(None).unwrap().boot_command, Some(FirmwareBootCommand::Fsboot) ); } diff --git a/crates/stela-cli/src/boot/disk.rs b/crates/stela-cli/src/boot/disk.rs index de632ec624..787274353f 100644 --- a/crates/stela-cli/src/boot/disk.rs +++ b/crates/stela-cli/src/boot/disk.rs @@ -17,7 +17,7 @@ impl Prepare { "output exists; choose a new --output directory" ); let mut image = open_image(path)?; - let options = self.options(None, None)?; + let options = self.options(None)?; let volume = self .boot_volume .as_deref() diff --git a/crates/stela-cli/src/boot/recovery_volume.rs b/crates/stela-cli/src/boot/recovery_volume.rs deleted file mode 100644 index 552e470e7c..0000000000 --- a/crates/stela-cli/src/boot/recovery_volume.rs +++ /dev/null @@ -1,266 +0,0 @@ -//! The volume recoveryOS first roots from, which holds BaseSystem as a disk -//! image. -//! -//! A Mac's iBoot boots recoveryOS from the Recovery volume. It forwards -//! BaseSystem's root hash (`base_system_root_hash.img4`) as `/chosen/ -//! secure-boot-hashes base-system-volume-auth-blob` and passes -//! `rp0=file://` with `/usr/standalone/firmware/arm64eBaseSystem.dmg` (J473 -//! iBoot string table). XNU's imageboot then attaches that image through -//! DiskImages and roots from its BaseSystem volume (`bsd/kern/imageboot.c`). -//! APFS authenticates that volume with the forwarded hash, because the -//! attached container is virtual and an APFS root is already mounted -//! (`stela_loader::boot_policy::require_image_boot`). -//! -//! On a blank disk Stela has no Recovery volume, so the bundle carries one in -//! memory. It is an unsealed APFS volume that holds only the decrypted -//! BaseSystem image, unchanged, at the same path. DiskImages attaches it from -//! `/chosen boot-ramdmg-size` and `boot-ramdmg-extents`, and `/chosen -//! boot-uuid` names its volume as iBoot names a Recovery volume -//! (`stela_loader::root_selection::Root::RamImage`), with no `rd=`: with -//! `rd=md0` APFS would take `md0` again for the image root -//! (`stela_loader::boot_policy::refuse_ramdisk_image_root`). -//! -//! The volume is an APFS container with no partition map, so block zero is -//! the container superblock. DiskImages reads it as a raw read-write image -//! (`KDIReadWriteDiskImage`) whose whole disk an APFS container scheme -//! claims, a case its `findAppropriateIOMediaObject` names ("whole=TRUE, -//! leaf=FALSE AppleAPFSContainerScheme child"). Stela writes it itself -//! (`format`), so every host makes the same volume, and checks it with its -//! own APFS reader before use. -use anyhow::{Context, Result, bail, ensure}; -use std::path::Path; -use stela_runtime::{ - apfs::{self, Container, btree::Seal}, - payload::ReadAt, -}; - -mod format; - -/// The BaseSystem image's path on the volume, as iBoot names it below a -/// Recovery volume's boot objects. -pub const IMAGE_PATH: &str = "usr/standalone/firmware/arm64eBaseSystem.dmg"; -/// The image-boot argument naming [`IMAGE_PATH`] from the volume's root. -pub const IMAGE_BOOT_ARG: &str = "rp0=file:///usr/standalone/firmware/arm64eBaseSystem.dmg"; -const VOLUME_NAME: &str = "Stela recoveryOS"; - -/// The volume for `image`, the decrypted BaseSystem UDIF image, at most -/// `limit` bytes. Returns the volume image and its volume's UUID, which -/// `/chosen boot-uuid` names. -pub fn build(image: &Path, limit: u64) -> Result<(Vec, String)> { - let mut file = - std::fs::File::open(image).with_context(|| format!("cannot read {}", image.display()))?; - let image_bytes = file.metadata()?.len(); - let identity = format::Identity { - volume_uuid: random_uuid()?, - container_uuid: random_uuid()?, - time: std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH)? - .as_nanos() - .try_into()?, - }; - let volume = format::container( - VOLUME_NAME, - IMAGE_PATH, - &mut file, - image_bytes, - &identity, - limit, - ) - .context("cannot write the recoveryOS volume")?; - let uuid = check(&volume, image_bytes)?; - Ok((volume, uuid)) -} - -/// A random (version 4) UUID. -fn random_uuid() -> Result<[u8; 16]> { - let mut uuid = [0u8; 16]; - getrandom::getrandom(&mut uuid).map_err(|error| anyhow::anyhow!("no random bytes: {error}"))?; - uuid[6] = (uuid[6] & 0x0f) | 0x40; - uuid[8] = (uuid[8] & 0x3f) | 0x80; - Ok(uuid) -} - -/// The volume must be one unsealed APFS container at offset zero whose one -/// volume holds the image at [`IMAGE_PATH`] with its full length. Returns -/// the volume's UUID in the upper-case form of its `IOMedia` `UUID`, which -/// AppleFileSystemDriver compares with `boot-uuid`. -fn check(volume_image: &[u8], image_bytes: u64) -> Result { - let mut source = Memory(volume_image); - let offsets = apfs::containers(&mut source)?; - ensure!( - offsets == [0], - "the recoveryOS volume image must start with its container; found containers at {offsets:?}" - ); - let mut container = Container::open(source, 0)?; - let volumes = container.volumes()?; - let [volume] = &volumes[..] else { - bail!( - "the recoveryOS container holds {} volumes, not one", - volumes.len() - ); - }; - // An unsealed first root mounts its live file system. A sealed one would - // need a root snapshot, or BaseSystem's path, which needs an earlier root. - ensure!( - volume.seal(&mut container.device)?.is_none(), - "the recoveryOS volume is sealed; recoveryOS first roots from an unsealed volume" - ); - let inode = volume - .lookup(&mut container.device, IMAGE_PATH, false) - .with_context(|| format!("the recoveryOS volume has no {IMAGE_PATH}"))?; - ensure!( - inode.logical_size() == image_bytes, - "{IMAGE_PATH} holds {} bytes, not the image's {image_bytes}", - inode.logical_size() - ); - Ok(apfs::uuid_text(&volume.uuid)) -} - -/// An image's bytes as a reader source. -struct Memory(B); - -impl> ReadAt for Memory { - type Error = &'static str; - fn len(&self) -> u64 { - self.0.as_ref().len() as u64 - } - fn read_at(&mut self, offset: u64, buffer: &mut [u8]) -> Result<(), Self::Error> { - let start = usize::try_from(offset).map_err(|_| "offset out of range")?; - let bytes = self - .0 - .as_ref() - .get(start..start + buffer.len()) - .ok_or("read past the end")?; - buffer.copy_from_slice(bytes); - Ok(()) - } -} - -/// The seal of the file system BaseSystem roots from, read from its APFS -/// partition: the hash its forwarded root-hash record must name. -pub fn base_system_seal(partition: Vec) -> Result { - let mut container = Container::open(Memory(partition), 0)?; - let volumes = container.volumes()?; - let [volume] = &volumes[..] else { - bail!( - "the BaseSystem container holds {} volumes, not one", - volumes.len() - ); - }; - volume - .root_seal(&mut container.device)? - .context("the BaseSystem volume is not sealed") -} - -/// The forwarded root hash must be the seal of the image the kernel roots -/// from: `im4p` (`BaseSystemVolume`, type `csys`) holds a root-hash record, -/// as an installed system's `isys` does. -pub fn check_root_hash(seal: &Seal, im4p: &[u8]) -> Result<()> { - let object = stela_loader::im4p::parse(im4p)?; - ensure!( - object.payload_type == "csys" && object.compression_algorithm.is_none(), - "the BaseSystem root hash is not an uncompressed csys object" - ); - let (hash, bytes) = stela_loader::installed::root_hash_record(object.payload)?; - ensure!( - hash == seal.hash && bytes == seal.root.as_slice(), - "the BaseSystem root hash {} is not the seal {} of the BaseSystem image", - hex::encode(bytes), - hex::encode(&seal.root) - ); - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_image_boot_argument_names_the_image_path_from_the_root() { - assert_eq!(IMAGE_BOOT_ARG, format!("rp0=file:///{IMAGE_PATH}")); - assert!(stela_loader::boot_policy::require_image_boot(IMAGE_BOOT_ARG).is_ok()); - } - - fn gunzip(data: &[u8]) -> Vec { - // RFC 1952 as `gzip -n` writes it: a 10-byte header, a raw deflate - // stream, then CRC-32 and size. - assert_eq!(&data[..4], &[0x1f, 0x8b, 8, 0]); - miniz_oxide::inflate::decompress_to_vec(&data[10..data.len() - 8]).unwrap() - } - - #[test] - fn the_volume_must_hold_the_whole_image_unsealed_at_its_path() { - // `make-recovery-volume.sh`'s volume from Apple's `hdiutil`, holding - // 4096 bytes as the image. - let volume = gunzip(include_bytes!( - "../../tests/fixtures/recovery-volume/recovery-volume.img.gz" - )); - let uuid = check(&volume, 4096).unwrap(); - // The form `/chosen boot-uuid` takes: 36 characters, upper case. - assert!(stela_loader::boot_selection::parse_uuid(uuid.as_bytes()).is_some()); - assert_eq!((uuid.len(), uuid.to_ascii_uppercase()), (36, uuid.clone())); - assert!(check(&volume, 4095).is_err()); - assert!(check(&[0u8; 8192], 0).is_err()); - } - - #[test] - fn the_written_volume_holds_the_image_as_the_reader_finds_it() { - let work = tempfile::tempdir().unwrap(); - let image = work.path().join("BaseSystem.dmg"); - let content: Vec = (0..3 * 4096 + 100).map(|i| (i * 7 % 251) as u8).collect(); - std::fs::write(&image, &content).unwrap(); - let (volume, uuid) = build(&image, 64 << 20).unwrap(); - assert_eq!(volume.len() % 4096, 0); - assert!(stela_loader::boot_selection::parse_uuid(uuid.as_bytes()).is_some()); - - let mut container = Container::open(Memory(&volume[..]), 0).unwrap(); - let volumes = container.volumes().unwrap(); - assert_eq!(volumes[0].name, VOLUME_NAME); - let inode = volumes[0] - .lookup(&mut container.device, IMAGE_PATH, false) - .unwrap(); - assert_eq!( - volumes[0].read(&mut container.device, &inode).unwrap(), - content - ); - assert!(build(&image, 1 << 20).is_err()); - } - - fn der(tag: u8, body: &[u8]) -> Vec { - let mut out = vec![tag]; - match body.len() { - n if n < 0x80 => out.push(n as u8), - n if n < 0x100 => out.extend([0x81, n as u8]), - n => out.extend([0x82, (n >> 8) as u8, n as u8]), - } - out.extend(body); - out - } - - fn root_hash_object(payload_type: &str, record: &[u8]) -> Vec { - let body = [ - der(0x16, b"IM4P"), - der(0x16, payload_type.as_bytes()), - der(0x16, b"root hash"), - der(0x04, record), - ] - .concat(); - der(0x30, &body) - } - - #[test] - fn the_root_hash_must_name_the_seal_of_the_image() { - // The runtime's sealed fixture and the record Apple's sealer wrote. - let sealed = gunzip(include_bytes!( - "../../../stela-runtime/tests/fixtures/apfs/sealed.img.gz" - )); - let record = include_bytes!("../../../stela-runtime/tests/fixtures/apfs/sealed.root_hash"); - let seal = base_system_seal(sealed).unwrap(); - check_root_hash(&seal, &root_hash_object("csys", record)).unwrap(); - let mut other = record.to_vec(); - other[16] ^= 1; - assert!(check_root_hash(&seal, &root_hash_object("csys", &other)).is_err()); - assert!(check_root_hash(&seal, &root_hash_object("isys", record)).is_err()); - assert!(base_system_seal(vec![0u8; 8192]).is_err()); - } -} diff --git a/crates/stela-cli/src/boot/recovery_volume/format.rs b/crates/stela-cli/src/boot/recovery_volume/format.rs deleted file mode 100644 index f737b4292d..0000000000 --- a/crates/stela-cli/src/boot/recovery_volume/format.rs +++ /dev/null @@ -1,880 +0,0 @@ -//! An APFS container of one unencrypted, case-insensitive volume holding one -//! file below its directories, written directly so any host can make it. -//! -//! The layout is the one checkpoint `mkapfs` (apfsprogs, GPL-2.0, read for -//! its structure only) writes at transaction 1: the container superblock at -//! block zero, the checkpoint descriptor area (the checkpoint map, then the -//! superblock's copy), the checkpoint data area (reaper, space manager and -//! the two free-queue roots), the container object map, the volume -//! superblock and its object map, file-system, extent-reference and -//! snapshot-metadata roots, the sixteen internal-pool bitmaps and the -//! internal pool (one allocation bitmap per chunk, then the chunk-info -//! block). The file's data follows as one extent, and free space after it -//! leaves room for the checkpoints a read-write mount writes. Field layouts -//! are Apple's File System Reference. -use anyhow::{Result, bail, ensure}; -use std::io::Read; -use stela_runtime::apfs::object::fletcher64; - -const BLOCK: usize = 4096; -const BLOCKS_PER_CHUNK: u64 = 8 * BLOCK as u64; -/// Chunk-info entries after a chunk-info block's 40-byte header. -const CHUNKS_PER_CIB: u64 = (BLOCK as u64 - 40) / 32; -/// Chunk-info-block addresses after an address block's 40-byte header. -const CIBS_PER_CAB: u32 = (BLOCK as u32 - 40) / 8; -/// Free blocks after the file, for the checkpoints and object-map nodes a -/// read-write mount writes. -const SLACK_BLOCKS: u64 = 8192; -const XID: u64 = 1; - -const OBJ_VIRTUAL: u32 = 0; -const OBJ_EPHEMERAL: u32 = 0x8000_0000; -const OBJ_PHYSICAL: u32 = 0x4000_0000; -const TYPE_NX_SUPERBLOCK: u32 = 0x01; -const TYPE_BTREE: u32 = 0x02; -const TYPE_SPACEMAN: u32 = 0x05; -const TYPE_SPACEMAN_CIB: u32 = 0x07; -const TYPE_FREE_QUEUE: u32 = 0x09; -const TYPE_OMAP: u32 = 0x0b; -const TYPE_CHECKPOINT_MAP: u32 = 0x0c; -const TYPE_FS: u32 = 0x0d; -const TYPE_FSTREE: u32 = 0x0e; -const TYPE_BLOCKREFTREE: u32 = 0x0f; -const TYPE_SNAPMETATREE: u32 = 0x10; -const TYPE_NX_REAPER: u32 = 0x11; - -/// Ephemeral and virtual object identifiers, after the reserved range. -const SPACEMAN_OID: u64 = 1024; -const REAPER_OID: u64 = SPACEMAN_OID + 1; -const VOLUME_OID: u64 = SPACEMAN_OID + 2; -const FS_ROOT_OID: u64 = SPACEMAN_OID + 3; -const IP_FREE_QUEUE_OID: u64 = SPACEMAN_OID + 4; -const MAIN_FREE_QUEUE_OID: u64 = SPACEMAN_OID + 5; - -const BTNODE_ROOT: u16 = 1; -const BTNODE_LEAF: u16 = 2; -const BTNODE_FIXED_KV_SIZE: u16 = 4; -const BTREE_ALLOW_GHOSTS: u32 = 0x04; -const BTREE_EPHEMERAL: u32 = 0x08; -const BTREE_PHYSICAL: u32 = 0x10; -const BTREE_KV_NONALIGNED: u32 = 0x40; -const BTOFF_INVALID: u16 = 0xffff; -const NODE_HEADER_BYTES: usize = 56; -const INFO_BYTES: usize = 40; - -/// File-system record types, in a key's top four bits. -const TYPE_EXTENT: u64 = 2; -const TYPE_INODE: u64 = 3; -const TYPE_DSTREAM_ID: u64 = 6; -const TYPE_FILE_EXTENT: u64 = 8; -const TYPE_DIR_REC: u64 = 9; -const ROOT_DIR_PARENT: u64 = 1; -const ROOT_DIR_INO: u64 = 2; -const PRIVATE_DIR_INO: u64 = 3; -const MIN_USER_INO: u64 = 16; -const INODE_NO_RSRC_FORK: u64 = 0x8000; -const INO_EXT_TYPE_NAME: u8 = 4; -const INO_EXT_TYPE_DSTREAM: u8 = 8; -const XF_DO_NOT_COPY: u8 = 0x02; -const XF_SYSTEM_FIELD: u8 = 0x20; -const DT_DIR: u16 = 4; -const DT_REG: u16 = 8; -const MODE_DIR: u16 = 0o040755; -const MODE_FILE: u16 = 0o100644; -const EXTENT_KIND_NEW: u64 = 1; - -/// The volume's UUID, the container's and the format time in nanoseconds -/// since 1970. -pub struct Identity { - pub volume_uuid: [u8; 16], - pub container_uuid: [u8; 16], - pub time: u64, -} - -/// A container whose volume, `volume_name`, holds the `bytes` read from -/// `file` at `path` (slash-separated, with directories made for its parent -/// components). At most `limit` bytes. -pub fn container( - volume_name: &str, - path: &str, - file: &mut impl Read, - bytes: u64, - identity: &Identity, - limit: u64, -) -> Result> { - ensure!(bytes > 0, "the volume's file is empty"); - ensure!( - volume_name.len() < 256 && !volume_name.contains('\0'), - "the volume name must be under 256 bytes" - ); - let file_blocks = bytes.div_ceil(BLOCK as u64); - let layout = Layout::new(file_blocks)?; - let total = layout.blocks * BLOCK as u64; - ensure!( - total <= limit, - "the volume is {total} bytes, more than {limit}" - ); - let mut image = vec![0u8; usize::try_from(total)?]; - let data = layout.file_start as usize * BLOCK; - file.read_exact(&mut image[data..data + bytes as usize])?; - - let tree = FileTree::new(path, layout.file_start, bytes, identity.time)?; - layout.write_container(&mut image, identity); - layout.write_spaceman(&mut image); - layout.write_volume(&mut image, volume_name, &tree, identity); - Ok(image) -} - -/// Block numbers and counts of everything the container holds. -struct Layout { - blocks: u64, - chunks: u64, - desc_blocks: u64, - data_blocks: u64, - ip_blocks: u64, - ip_bm_size: u64, - file_start: u64, - file_blocks: u64, -} - -impl Layout { - /// The layout for `file_blocks` of data. The checkpoint areas and the - /// internal pool grow with the container, so the size is iterated to its - /// fixed point; each step only grows it. - fn new(file_blocks: u64) -> Result { - let mut blocks = file_blocks + SLACK_BLOCKS; - for _ in 0..64 { - let chunks = blocks.div_ceil(BLOCKS_PER_CHUNK); - if chunks > CHUNKS_PER_CIB { - bail!( - "UNSUPPORTED APFS container of {blocks} blocks: more than one chunk-info block" - ); - } - let ip_blocks = (chunks + 1) * 3; - let ip_bm_size = ip_blocks.div_ceil(BLOCKS_PER_CHUNK); - let layout = Self { - blocks, - chunks, - desc_blocks: checkpoint_desc_blocks(blocks), - data_blocks: checkpoint_data_blocks(blocks), - ip_blocks, - ip_bm_size, - file_start: 0, - file_blocks, - }; - let file_start = layout.ip_base() + ip_blocks; - let needed = file_start + file_blocks + SLACK_BLOCKS; - if needed == blocks { - return Ok(Self { - file_start, - ..layout - }); - } - blocks = needed; - } - bail!("the APFS layout for {file_blocks} blocks does not settle") - } - - fn data_base(&self) -> u64 { - 1 + self.desc_blocks - } - fn reaper(&self) -> u64 { - self.data_base() - } - fn spaceman(&self) -> u64 { - self.data_base() + 1 - } - fn ip_free_queue(&self) -> u64 { - self.data_base() + 2 - } - fn main_free_queue(&self) -> u64 { - self.data_base() + 3 - } - /// The checkpoint data area's used blocks: reaper, space manager and - /// the two free-queue roots. - const EPHEMERAL_BLOCKS: u32 = 4; - fn data_end(&self) -> u64 { - self.data_base() + self.data_blocks - } - fn container_omap(&self) -> u64 { - self.data_end() - } - fn volume(&self) -> u64 { - self.data_end() + 2 - } - fn volume_omap(&self) -> u64 { - self.data_end() + 3 - } - fn fs_root(&self) -> u64 { - self.data_end() + 5 - } - fn extentref_root(&self) -> u64 { - self.data_end() + 6 - } - fn snap_meta_root(&self) -> u64 { - self.data_end() + 7 - } - fn ip_bm_base(&self) -> u64 { - self.data_end() + 8 - } - fn ip_bm_blocks(&self) -> u64 { - 16 * self.ip_bm_size - } - fn ip_base(&self) -> u64 { - self.ip_bm_base() + self.ip_bm_blocks() - } - /// The chunks' allocation bitmaps open the internal pool, then the - /// chunk-info block. - fn chunk_bitmap(&self, chunk: u64) -> u64 { - self.ip_base() + chunk - } - fn cib(&self) -> u64 { - self.ip_base() + self.chunks - } - /// Every block before the file's end is used: the metadata is packed - /// from block zero and the file follows the internal pool. - fn used_end(&self) -> u64 { - self.file_start + self.file_blocks - } - - fn write_container(&self, image: &mut [u8], identity: &Identity) { - let mut sb = [0u8; BLOCK]; - put32(&mut sb, 0x20, 0x4253_584e); // NXSB - put32(&mut sb, 0x24, BLOCK as u32); - put64(&mut sb, 0x28, self.blocks); - put64(&mut sb, 0x40, 2); // NX_INCOMPAT_VERSION2 - sb[0x48..0x58].copy_from_slice(&identity.container_uuid); - put64(&mut sb, 0x58, SPACEMAN_OID + 100); - put64(&mut sb, 0x60, XID + 1); - put32(&mut sb, 0x68, self.desc_blocks as u32); - put32(&mut sb, 0x6c, self.data_blocks as u32); - put64(&mut sb, 0x70, 1); - put64(&mut sb, 0x78, self.data_base()); - // The descriptor area holds the map and the superblock's copy. - put32(&mut sb, 0x80, 2); - put32(&mut sb, 0x84, Self::EPHEMERAL_BLOCKS); - put32(&mut sb, 0x8c, 2); - put32(&mut sb, 0x94, Self::EPHEMERAL_BLOCKS); - put64(&mut sb, 0x98, SPACEMAN_OID); - put64(&mut sb, 0xa0, self.container_omap()); - put64(&mut sb, 0xa8, REAPER_OID); - let bytes = self.blocks * BLOCK as u64; - put32( - &mut sb, - 0xb4, - bytes.div_ceil(512 << 20).clamp(1, 100) as u32, - ); - put64(&mut sb, 0xb8, VOLUME_OID); - let min_block_count = if bytes < 128 << 20 { - u64::from(main_fq_node_limit(self.blocks)) - } else { - 8 - }; - put64(&mut sb, 0x520, (min_block_count << 32) | (4 << 16) | 1); - seal(&mut sb, 1, OBJ_EPHEMERAL | TYPE_NX_SUPERBLOCK, 0); - block(image, 0).copy_from_slice(&sb); - block(image, 2).copy_from_slice(&sb); - - let map = block(image, 1); - put32(map, 0x20, 1); // CHECKPOINT_MAP_LAST - put32(map, 0x24, Self::EPHEMERAL_BLOCKS); - let mappings = [ - (OBJ_EPHEMERAL | TYPE_NX_REAPER, 0, REAPER_OID, self.reaper()), - ( - OBJ_EPHEMERAL | TYPE_SPACEMAN, - 0, - SPACEMAN_OID, - self.spaceman(), - ), - ( - OBJ_EPHEMERAL | TYPE_BTREE, - TYPE_FREE_QUEUE, - IP_FREE_QUEUE_OID, - self.ip_free_queue(), - ), - ( - OBJ_EPHEMERAL | TYPE_BTREE, - TYPE_FREE_QUEUE, - MAIN_FREE_QUEUE_OID, - self.main_free_queue(), - ), - ]; - for (index, (kind, subtype, oid, paddr)) in mappings.into_iter().enumerate() { - let at = 0x28 + 40 * index; - put32(map, at, kind); - put32(map, at + 4, subtype); - put32(map, at + 8, BLOCK as u32); - put64(map, at + 24, oid); - put64(map, at + 32, paddr); - } - seal(map, 1, OBJ_PHYSICAL | TYPE_CHECKPOINT_MAP, 0); - - let reaper = block(image, self.reaper()); - put64(reaper, 0x20, 1); // next reap id - put32(reaper, 0x40, 1); // NR_BHM_FLAG - put32(reaper, 0x6c, BLOCK as u32 - 0x70); - seal(reaper, REAPER_OID, OBJ_EPHEMERAL | TYPE_NX_REAPER, 0); - - let free_queue = |oid| { - let mut node = root_node( - &[], - Toc::Fixed { key: 16, value: 8 }, - BTREE_EPHEMERAL | BTREE_ALLOW_GHOSTS, - ); - seal(&mut node, oid, OBJ_EPHEMERAL | TYPE_BTREE, TYPE_FREE_QUEUE); - node - }; - block(image, self.ip_free_queue()).copy_from_slice(&free_queue(IP_FREE_QUEUE_OID)); - block(image, self.main_free_queue()).copy_from_slice(&free_queue(MAIN_FREE_QUEUE_OID)); - - write_omap( - image, - self.container_omap(), - true, - VOLUME_OID, - self.volume(), - ); - } - - fn write_spaceman(&self, image: &mut [u8]) { - // Chunk allocation bitmaps and the chunk-info block. - let mut chunk_infos = Vec::new(); - for chunk in 0..self.chunks { - let first = chunk * BLOCKS_PER_CHUNK; - let count = BLOCKS_PER_CHUNK.min(self.blocks - first); - let used = self.used_end().clamp(first, first + count) - first; - mark_used(block(image, self.chunk_bitmap(chunk)), 0, used); - chunk_infos.push((first, count, count - used)); - } - let cib = block(image, self.cib()); - put32(cib, 0x24, self.chunks as u32); - for (index, (first, count, free)) in chunk_infos.into_iter().enumerate() { - let at = 40 + 32 * index; - put64(cib, at, XID); - put64(cib, at + 8, first); - put32(cib, at + 16, count as u32); - put32(cib, at + 20, free as u32); - put64(cib, at + 24, self.chunk_bitmap(index as u64)); - } - let cib_oid = self.cib(); - seal(cib, cib_oid, OBJ_PHYSICAL | TYPE_SPACEMAN_CIB, 0); - - // The internal pool's current bitmap marks the chunk bitmaps and - // the chunk-info block; the other fifteen are free. - mark_used(block(image, self.ip_bm_base()), 0, self.chunks + 1); - - // `mkapfs`'s unversioned space manager: the bitmaps' transaction - // identifiers, their ring offsets, the free list, then the - // chunk-info block's address. - const BITMAP_XID_OFFSET: usize = 0x150; - let ip_bm_size = self.ip_bm_size as usize; - let ip_bm_blocks = self.ip_bm_blocks() as usize; - let bitmap_offset = BITMAP_XID_OFFSET + 8 * ip_bm_size; - let free_next_offset = bitmap_offset + (2 * ip_bm_size).next_multiple_of(8); - let cib_address_offset = free_next_offset + 2 * ip_bm_blocks; - assert!(cib_address_offset + 16 <= BLOCK); - - let sm = block(image, self.spaceman()); - put32(sm, 0x20, BLOCK as u32); - put32(sm, 0x24, BLOCKS_PER_CHUNK as u32); - put32(sm, 0x28, CHUNKS_PER_CIB as u32); - put32(sm, 0x2c, CIBS_PER_CAB); - put64(sm, 0x30, self.blocks); - put64(sm, 0x38, self.chunks); - put32(sm, 0x40, 1); // chunk-info blocks - put64(sm, 0x48, self.blocks - self.used_end()); - put32(sm, 0x50, cib_address_offset as u32); - put32(sm, 0x80, cib_address_offset as u32 + 8); // tier 2, empty - put32(sm, 0x94, 16); // SPACEMAN_IP_BM_TX_MULTIPLIER - put64(sm, 0x98, self.ip_blocks); - put32(sm, 0xa0, ip_bm_size as u32); - put32(sm, 0xa4, ip_bm_blocks as u32); - put64(sm, 0xa8, self.ip_bm_base()); - put64(sm, 0xb0, self.ip_base()); - put64(sm, 0xc8 + 8, IP_FREE_QUEUE_OID); - put16(sm, 0xc8 + 24, ip_fq_node_limit(self.chunks)); - put64(sm, 0xf0 + 8, MAIN_FREE_QUEUE_OID); - put16(sm, 0xf0 + 24, main_fq_node_limit(self.blocks)); - put16(sm, 0x140, ip_bm_size as u16); - put16(sm, 0x142, ip_bm_blocks as u16 - 1); - put32(sm, 0x144, BITMAP_XID_OFFSET as u32); - put32(sm, 0x148, bitmap_offset as u32); - put32(sm, 0x14c, free_next_offset as u32); - for index in 0..ip_bm_size { - put64(sm, BITMAP_XID_OFFSET + 8 * index, XID); - put16(sm, bitmap_offset + 2 * index, index as u16); - } - // Free bitmap blocks link to the next; the in-use ones and the tail - // hold the invalid index. - for index in 0..ip_bm_blocks { - let next = if index < ip_bm_size || index + 1 == ip_bm_blocks { - 0xffff - } else { - index as u16 + 1 - }; - put16(sm, free_next_offset + 2 * index, next); - } - put64(sm, cib_address_offset, self.cib()); - seal(sm, SPACEMAN_OID, OBJ_EPHEMERAL | TYPE_SPACEMAN, 0); - } - - fn write_volume(&self, image: &mut [u8], name: &str, tree: &FileTree, identity: &Identity) { - write_omap( - image, - self.volume_omap(), - false, - FS_ROOT_OID, - self.fs_root(), - ); - - let mut fs_root = root_node(&tree.records, Toc::Variable, BTREE_KV_NONALIGNED); - seal( - &mut fs_root, - FS_ROOT_OID, - OBJ_VIRTUAL | TYPE_BTREE, - TYPE_FSTREE, - ); - block(image, self.fs_root()).copy_from_slice(&fs_root); - - // The one physical extent, owned by the file's data stream. - let mut key = Vec::new(); - key.extend((TYPE_EXTENT << 60 | self.file_start).to_le_bytes()); - let mut value = Vec::new(); - value.extend((EXTENT_KIND_NEW << 60 | self.file_blocks).to_le_bytes()); - value.extend(tree.file_ino.to_le_bytes()); - value.extend(1u32.to_le_bytes()); - let flags = BTREE_PHYSICAL | BTREE_KV_NONALIGNED; - let mut extentref = root_node(&[(key, value)], Toc::Variable, flags); - let oid = self.extentref_root(); - seal( - &mut extentref, - oid, - OBJ_PHYSICAL | TYPE_BTREE, - TYPE_BLOCKREFTREE, - ); - block(image, oid).copy_from_slice(&extentref); - - let mut snap_meta = root_node(&[], Toc::Variable, flags); - let oid = self.snap_meta_root(); - seal( - &mut snap_meta, - oid, - OBJ_PHYSICAL | TYPE_BTREE, - TYPE_SNAPMETATREE, - ); - block(image, oid).copy_from_slice(&snap_meta); - - let vsb = block(image, self.volume()); - put32(vsb, 0x20, 0x4253_5041); // APSB - put64(vsb, 0x28, 2); // FEATURE_HARDLINK_MAP_RECORDS - put64(vsb, 0x38, 1); // INCOMPAT_CASE_INSENSITIVE - // The volume's object map and its four tree roots, then the data. - put64(vsb, 0x58, 5 + self.file_blocks); - // Wrapped meta-crypto state: version 5.0, protection class F, - // key revision 1, as an unencrypted volume records it. - put16(vsb, 0x60, 5); - put32(vsb, 0x68, 6); - put16(vsb, 0x70, 1); - put32(vsb, 0x74, OBJ_VIRTUAL | TYPE_BTREE); - put32(vsb, 0x78, OBJ_PHYSICAL | TYPE_BTREE); - put32(vsb, 0x7c, OBJ_PHYSICAL | TYPE_BTREE); - put64(vsb, 0x80, self.volume_omap()); - put64(vsb, 0x88, FS_ROOT_OID); - put64(vsb, 0x90, self.extentref_root()); - put64(vsb, 0x98, self.snap_meta_root()); - put64(vsb, 0xb0, tree.next_ino); - put64(vsb, 0xb8, 1); - put64(vsb, 0xc0, tree.directories); - put64(vsb, 0xe0, self.file_blocks); - vsb[0xf0..0x100].copy_from_slice(&identity.volume_uuid); - put64(vsb, 0x100, identity.time); - put64(vsb, 0x108, 1); // FS_UNENCRYPTED - let formatter = concat!("stela ", env!("CARGO_PKG_VERSION")); - vsb[0x110..0x110 + formatter.len()].copy_from_slice(formatter.as_bytes()); - put64(vsb, 0x130, identity.time); - put64(vsb, 0x138, XID); - vsb[0x2c0..0x2c0 + name.len()].copy_from_slice(name.as_bytes()); - put32(vsb, 0x3c0, 3); // MIN_DOC_ID - seal(vsb, VOLUME_OID, OBJ_VIRTUAL | TYPE_FS, 0); - } -} - -/// `mkapfs`'s checkpoint descriptor area size, after `newfs_apfs`'s. -fn checkpoint_desc_blocks(blocks: u64) -> u64 { - match blocks { - ..131_072 => 8, - 131_072..262_144 => 12, - 262_144..13_107_200 => 20 + 60 * ((blocks - 262_144) / 131_072) / 23, - _ => 280, - } -} - -/// `mkapfs`'s checkpoint data area size, after `newfs_apfs`'s. -fn checkpoint_data_blocks(blocks: u64) -> u64 { - let b = blocks as i64; - let data = match b { - ..4545 => 52, - 4545..13_633 => 124, - 13_633..36_353 => 160 + 36 * ((b - 13_633) / 4544), - 36_353..131_777 => 308 + 4 * ((b - 36_353) / 4544), - 131_777..262_144 => 648 + 4 * ((b - 131_777) / 4544), - 262_144 => 992, - 262_145..1_048_576 => { - let off = (b - 262_144) / 131_072; - 1248 + 488 * off + 4 * ((b - (261_280 + off * 131_776)) / 2272) - } - 1_048_576..4_063_232 => 4112 + 256 * ((b - 1_048_576) / 131_072), - 4_063_232..13_107_200 => 10_000 + 256 * ((b - 4_063_232) / 131_072), - _ => 27_672, - }; - data as u64 -} - -fn ip_fq_node_limit(chunks: u64) -> u16 { - match (3 * (chunks + 751) / 1127 - 1) as u16 { - 2 => 3, - limit => limit, - } -} - -fn main_fq_node_limit(blocks: u64) -> u16 { - let limit = match blocks { - ..0x4_0000 => 1 + (blocks - 1) / 4544, - 0x4_0000..0x10_0000 => 116 + (blocks - 261_281) / 2272, - _ => 512, - }; - match limit as u16 { - 2 => 3, - limit => limit, - } -} - -/// An object map at `paddr` whose root, the next block, maps `oid` at -/// transaction 1 to `target`. -fn write_omap(image: &mut [u8], paddr: u64, manually_managed: bool, oid: u64, target: u64) { - let omap = block(image, paddr); - put32(omap, 0x20, u32::from(manually_managed)); - put32(omap, 0x28, OBJ_PHYSICAL | TYPE_BTREE); - put32(omap, 0x2c, OBJ_PHYSICAL | TYPE_BTREE); - put64(omap, 0x30, paddr + 1); - seal(omap, paddr, OBJ_PHYSICAL | TYPE_OMAP, 0); - - let key = [oid.to_le_bytes(), XID.to_le_bytes()].concat(); - let value = [0u32.to_le_bytes(), (BLOCK as u32).to_le_bytes()] - .concat() - .into_iter() - .chain(target.to_le_bytes()) - .collect(); - let mut root = root_node( - &[(key, value)], - Toc::Fixed { key: 16, value: 16 }, - BTREE_PHYSICAL, - ); - seal(&mut root, paddr + 1, OBJ_PHYSICAL | TYPE_BTREE, TYPE_OMAP); - block(image, paddr + 1).copy_from_slice(&root); -} - -enum Toc { - Fixed { key: usize, value: usize }, - Variable, -} - -/// A root leaf of sorted `records` with its info footer; the caller seals -/// it. A fixed-size tree's table is preallocated for a full node, as -/// `newfs_apfs` does; a variable one has room for sixteen entries or more. -fn root_node(records: &[(Vec, Vec)], toc: Toc, tree_flags: u32) -> [u8; BLOCK] { - let mut node = [0u8; BLOCK]; - let (toc_len, entry, fixed) = match toc { - Toc::Fixed { key, value } => { - let count = (BLOCK - NODE_HEADER_BYTES) / (key + value + 4); - (count * 4, 4, Some((key, value))) - } - Toc::Variable => (records.len().max(16).next_multiple_of(8) * 8, 8, None), - }; - assert!(records.len() * entry <= toc_len); - let key_area = NODE_HEADER_BYTES + toc_len; - let value_end = BLOCK - INFO_BYTES; - let (mut key_at, mut value_at) = (0, 0); - for (index, (key, value)) in records.iter().enumerate() { - node[key_area + key_at..][..key.len()].copy_from_slice(key); - value_at += value.len(); - node[value_end - value_at..][..value.len()].copy_from_slice(value); - let toc_at = NODE_HEADER_BYTES + entry * index; - if fixed.is_some() { - put16(&mut node, toc_at, key_at as u16); - put16(&mut node, toc_at + 2, value_at as u16); - } else { - put16(&mut node, toc_at, key_at as u16); - put16(&mut node, toc_at + 2, key.len() as u16); - put16(&mut node, toc_at + 4, value_at as u16); - put16(&mut node, toc_at + 6, value.len() as u16); - } - key_at += key.len(); - } - let free = BLOCK - key_area - key_at - value_at - INFO_BYTES; - assert!(key_area + key_at <= value_end - value_at); - let mut flags = BTNODE_ROOT | BTNODE_LEAF; - if fixed.is_some() { - flags |= BTNODE_FIXED_KV_SIZE; - } - put16(&mut node, 0x20, flags); - put32(&mut node, 0x24, records.len() as u32); - put16(&mut node, 0x2a, toc_len as u16); - put16(&mut node, 0x2c, key_at as u16); - put16(&mut node, 0x2e, free as u16); - put16(&mut node, 0x30, BTOFF_INVALID); - put16(&mut node, 0x34, BTOFF_INVALID); - - let (key_size, value_size) = fixed.unwrap_or((0, 0)); - let longest = |pick: fn(&(Vec, Vec)) -> usize, size| { - records.iter().map(pick).max().unwrap_or(0).max(size) - }; - let info = BLOCK - INFO_BYTES; - put32(&mut node, info, tree_flags); - put32(&mut node, info + 4, BLOCK as u32); - put32(&mut node, info + 8, key_size as u32); - put32(&mut node, info + 12, value_size as u32); - put32( - &mut node, - info + 16, - longest(|r| r.0.len(), key_size) as u32, - ); - put32( - &mut node, - info + 20, - longest(|r| r.1.len(), value_size) as u32, - ); - put64(&mut node, info + 24, records.len() as u64); - put64(&mut node, info + 32, 1); - node -} - -/// The file-system tree's records, sorted as APFS compares their keys. -struct FileTree { - records: Vec<(Vec, Vec)>, - file_ino: u64, - next_ino: u64, - directories: u64, -} - -impl FileTree { - fn new(path: &str, file_start: u64, bytes: u64, time: u64) -> Result { - let names: Vec<&str> = path.split('/').collect(); - ensure!( - names - .iter() - .all(|name| !name.is_empty() && name.len() < 256 && name.is_ascii()), - "UNSUPPORTED volume path {path:?}: components must be non-empty ASCII names" - ); - // Records under their order: identifier, type, then a directory - // entry's name hash and name. - type Order = (u64, u64, u32, Vec); - let mut records: Vec<(Order, Vec, Vec)> = Vec::new(); - let mut entry = |parent: u64, name: &str, ino: u64, kind: u16| { - let (key, hash) = directory_key(parent, name); - let value = [ - &ino.to_le_bytes()[..], - &time.to_le_bytes(), - &kind.to_le_bytes(), - ] - .concat(); - let sort = (parent, TYPE_DIR_REC, hash, name.as_bytes().to_vec()); - records.push((sort, key, value)); - }; - entry(ROOT_DIR_PARENT, "root", ROOT_DIR_INO, DT_DIR); - entry(ROOT_DIR_PARENT, "private-dir", PRIVATE_DIR_INO, DT_DIR); - let (directories, file) = names.split_at(names.len() - 1); - let mut parent = ROOT_DIR_INO; - let mut inodes = vec![(ROOT_DIR_INO, ROOT_DIR_PARENT, "root", 1)]; - for (index, name) in directories.iter().enumerate() { - let ino = MIN_USER_INO + index as u64; - entry(parent, name, ino, DT_DIR); - inodes.push((ino, parent, *name, 1)); - parent = ino; - } - let file_ino = MIN_USER_INO + directories.len() as u64; - entry(parent, file[0], file_ino, DT_REG); - inodes.push((PRIVATE_DIR_INO, ROOT_DIR_PARENT, "private-dir", 0)); - - let inode_key = |ino: u64| (TYPE_INODE << 60 | ino).to_le_bytes().to_vec(); - for (ino, parent, name, children) in inodes { - let value = inode_value(parent, ino, name, MODE_DIR, children, time, None); - records.push(((ino, TYPE_INODE, 0, vec![]), inode_key(ino), value)); - } - let allocated = bytes.next_multiple_of(BLOCK as u64); - let value = inode_value(parent, file_ino, file[0], MODE_FILE, 1, time, Some(bytes)); - records.push(( - (file_ino, TYPE_INODE, 0, vec![]), - inode_key(file_ino), - value, - )); - records.push(( - (file_ino, TYPE_DSTREAM_ID, 0, vec![]), - (TYPE_DSTREAM_ID << 60 | file_ino).to_le_bytes().to_vec(), - 1u32.to_le_bytes().to_vec(), - )); - let extent_key = [ - (TYPE_FILE_EXTENT << 60 | file_ino).to_le_bytes(), - 0u64.to_le_bytes(), - ] - .concat(); - let extent_value = [allocated.to_le_bytes(), file_start.to_le_bytes(), [0; 8]].concat(); - records.push(( - (file_ino, TYPE_FILE_EXTENT, 0, vec![]), - extent_key, - extent_value, - )); - records.sort_by(|a, b| a.0.cmp(&b.0)); - Ok(Self { - records: records.into_iter().map(|(_, k, v)| (k, v)).collect(), - file_ino, - next_ino: file_ino + 1, - directories: directories.len() as u64, - }) - } -} - -/// A hashed directory-entry key, `j_drec_hashed_key_t`, and its hash. A -/// case-insensitive volume hashes the case-folded name's UTF-32 code points -/// with CRC-32C, from all ones and without the final inversion; the key -/// keeps 22 bits of it above the name's length with its terminator. -fn directory_key(parent: u64, name: &str) -> (Vec, u32) { - let folded = name.to_ascii_lowercase(); - let code_points: Vec = folded - .chars() - .flat_map(|c| (c as u32).to_le_bytes()) - .collect(); - let hash = crc32c_update(!0, &code_points) & 0x3f_ffff; - let length = name.len() as u32 + 1; - let mut key = (TYPE_DIR_REC << 60 | parent).to_le_bytes().to_vec(); - key.extend((hash << 10 | length).to_le_bytes()); - key.extend(name.as_bytes()); - key.push(0); - (key, hash) -} - -fn crc32c_update(mut state: u32, data: &[u8]) -> u32 { - for &byte in data { - state ^= u32::from(byte); - for _ in 0..8 { - state = (state >> 1) ^ (0x82f6_3b78 & (state & 1).wrapping_neg()); - } - } - state -} - -/// `j_inode_val_t` with its name and, for a file of `size` bytes, its data -/// stream in extended fields. -fn inode_value( - parent: u64, - ino: u64, - name: &str, - mode: u16, - links: u32, - time: u64, - size: Option, -) -> Vec { - let mut value = Vec::new(); - value.extend(parent.to_le_bytes()); - value.extend(ino.to_le_bytes()); // private id: the data stream's - for _ in 0..4 { - value.extend(time.to_le_bytes()); - } - value.extend(INODE_NO_RSRC_FORK.to_le_bytes()); - value.extend(links.to_le_bytes()); // children or links - value.extend([0u8; 4 * 5]); // protection class, write generation, BSD flags, owner, group - value.extend(mode.to_le_bytes()); - value.extend([0u8; 2 + 8]); // pad, uncompressed size - let mut fields = vec![(INO_EXT_TYPE_NAME, XF_DO_NOT_COPY, { - let mut bytes = name.as_bytes().to_vec(); - bytes.push(0); - bytes - })]; - if let Some(size) = size { - let allocated = size.next_multiple_of(BLOCK as u64); - let stream = [size, allocated, 0, size, 0] - .iter() - .flat_map(|field| field.to_le_bytes()) - .collect(); - fields.push((INO_EXT_TYPE_DSTREAM, XF_SYSTEM_FIELD, stream)); - } - let used: usize = fields.iter().map(|f| f.2.len().next_multiple_of(8)).sum(); - value.extend((fields.len() as u16).to_le_bytes()); - value.extend((used as u16).to_le_bytes()); - for (kind, flags, data) in &fields { - value.extend([*kind, *flags]); - value.extend((data.len() as u16).to_le_bytes()); - } - // Each field's data is padded to eight bytes of its own length. - for (_, _, data) in &fields { - value.extend(data); - value.extend(vec![0; data.len().next_multiple_of(8) - data.len()]); - } - value -} - -fn block(image: &mut [u8], number: u64) -> &mut [u8] { - let start = number as usize * BLOCK; - &mut image[start..start + BLOCK] -} - -fn mark_used(bitmap: &mut [u8], first: u64, count: u64) { - for bit in first..first + count { - bitmap[(bit / 8) as usize] |= 1 << (bit % 8); - } -} - -/// Set an object's header at transaction 1 and its checksum, last. -fn seal(object: &mut [u8], oid: u64, kind: u32, subtype: u32) { - put64(object, 8, oid); - put64(object, 16, XID); - put32(object, 24, kind); - put32(object, 28, subtype); - let checksum = fletcher64(object); - put64(object, 0, checksum); -} - -fn put16(bytes: &mut [u8], at: usize, value: u16) { - bytes[at..at + 2].copy_from_slice(&value.to_le_bytes()); -} - -fn put32(bytes: &mut [u8], at: usize, value: u32) { - bytes[at..at + 4].copy_from_slice(&value.to_le_bytes()); -} - -fn put64(bytes: &mut [u8], at: usize, value: u64) { - bytes[at..at + 8].copy_from_slice(&value.to_le_bytes()); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn directory_keys_hash_the_case_folded_name_as_apple_does() { - // The key `hdiutil` wrote for the image in the recovery-volume - // fixture (parent 0x12). - let (key, _) = directory_key(0x12, "arm64eBaseSystem.dmg"); - let expected = "1200000000000090157ceb0761726d3634654261736553797374656d2e646d6700"; - assert_eq!(hex::encode(key), expected); - let (key, _) = directory_key(1, "private-dir"); - assert_eq!(&key[8..12], &0xaca6_8c0cu32.to_le_bytes()); - } - - #[test] - fn the_layout_settles_with_the_file_after_the_internal_pool() { - for file_blocks in [1, 4096, 300_000, 700_000] { - let layout = Layout::new(file_blocks).unwrap(); - assert_eq!( - layout.blocks, - layout.file_start + file_blocks + SLACK_BLOCKS - ); - assert_eq!( - layout.file_start, - layout.cib() + 1 + 2 * (layout.chunks + 1) - ); - assert!(layout.chunks <= CHUNKS_PER_CIB); - } - assert!(Layout::new(126 * BLOCKS_PER_CHUNK).is_err()); - } -} diff --git a/crates/stela-cli/src/restore.rs b/crates/stela-cli/src/restore.rs index a79574beb1..95b68a1fba 100644 --- a/crates/stela-cli/src/restore.rs +++ b/crates/stela-cli/src/restore.rs @@ -7,7 +7,6 @@ mod history; pub mod manifest; pub mod payload; pub mod remote; -pub mod udif; use anyhow::{Context, Result, bail, ensure}; use plist::Value; use reqwest::{Url, blocking::Client, header, redirect::Policy}; diff --git a/crates/stela-cli/src/restore/udif.rs b/crates/stela-cli/src/restore/udif.rs deleted file mode 100644 index d176eac8ab..0000000000 --- a/crates/stela-cli/src/restore/udif.rs +++ /dev/null @@ -1,263 +0,0 @@ -//! Read one partition out of an Apple UDIF disk image (`.dmg`), such as the -//! decrypted BaseSystem image, as raw bytes. -//! -//! A UDIF image ends in a 512-byte `koly` trailer that locates an XML -//! property list. Its `resource-fork` → `blkx` entries describe each -//! partition as a `mish` block table of chunks. Only uncompressed images are -//! read: raw and zero-fill chunks. Compressed chunks are refused explicitly. -use anyhow::{Context, Result, bail, ensure}; -use plist::Value; -use std::{ - fs::File, - io::{Read, Seek, SeekFrom}, - path::Path, -}; - -const TRAILER_BYTES: u64 = 512; -const SECTOR: u64 = 512; -const MISH_HEADER_BYTES: usize = 204; -const CHUNK_BYTES: usize = 40; -const MAX_PLIST_BYTES: u64 = 16 * 1024 * 1024; -const CHUNK_ZERO: u32 = 0x0000_0000; -const CHUNK_RAW: u32 = 0x0000_0001; -const CHUNK_IGNORE: u32 = 0x0000_0002; -const CHUNK_COMMENT: u32 = 0x7fff_fffe; -const CHUNK_END: u32 = 0xffff_ffff; - -fn u32_at(bytes: &[u8], at: usize) -> u32 { - u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) -} - -fn u64_at(bytes: &[u8], at: usize) -> u64 { - u64::from_be_bytes(bytes[at..at + 8].try_into().unwrap()) -} - -/// One partition's table: where it starts and how its chunks fill it. -struct Partition { - name: String, - sectors: u64, - /// The `mish` data offset, added to every chunk's offset. - data_offset: u64, - chunks: Vec<(u32, u64, u64, u64, u64)>, -} - -fn partitions(file: &mut File) -> Result<(u64, Vec)> { - let length = file.metadata()?.len(); - ensure!(length >= TRAILER_BYTES, "too short for a UDIF image"); - file.seek(SeekFrom::Start(length - TRAILER_BYTES))?; - let mut trailer = [0u8; TRAILER_BYTES as usize]; - file.read_exact(&mut trailer)?; - ensure!( - &trailer[..4] == b"koly", - "not a UDIF image: no koly trailer" - ); - let data_fork = u64_at(&trailer, 0x18); - let (plist_offset, plist_bytes) = (u64_at(&trailer, 0xd8), u64_at(&trailer, 0xe0)); - ensure!( - plist_bytes <= MAX_PLIST_BYTES && plist_offset + plist_bytes <= length, - "UDIF property list is out of range" - ); - file.seek(SeekFrom::Start(plist_offset))?; - let mut xml = vec![0u8; plist_bytes as usize]; - file.read_exact(&mut xml)?; - let root = Value::from_reader(std::io::Cursor::new(xml))?; - let blocks = root - .as_dictionary() - .and_then(|r| r.get("resource-fork")) - .and_then(Value::as_dictionary) - .and_then(|r| r.get("blkx")) - .and_then(Value::as_array) - .context("UDIF image has no blkx table")?; - let mut found = Vec::new(); - for block in blocks { - let block = block.as_dictionary().context("bad blkx entry")?; - let name = block - .get("Name") - .or_else(|| block.get("CFName")) - .and_then(Value::as_string) - .unwrap_or_default() - .to_owned(); - let data = block - .get("Data") - .and_then(Value::as_data) - .context("blkx entry has no Data")?; - ensure!( - data.len() >= MISH_HEADER_BYTES && &data[..4] == b"mish", - "blkx {name} is not a mish table" - ); - let count = u32_at(data, 200) as usize; - ensure!( - data.len() >= MISH_HEADER_BYTES + count * CHUNK_BYTES, - "blkx {name} chunk table overruns" - ); - let chunks = (0..count) - .map(|i| { - let c = &data[MISH_HEADER_BYTES + i * CHUNK_BYTES..]; - ( - u32_at(c, 0), - u64_at(c, 8), - u64_at(c, 16), - u64_at(c, 24), - u64_at(c, 32), - ) - }) - .collect(); - found.push(Partition { - name, - sectors: u64_at(data, 16), - data_offset: u64_at(data, 24), - chunks, - }); - } - Ok((data_fork, found)) -} - -/// The bytes of the one partition whose name contains `name`, such as -/// `Apple_APFS`, up to `limit` bytes. -pub fn partition(image: &Path, name: &str, limit: u64) -> Result> { - let mut file = File::open(image).with_context(|| format!("cannot open {}", image.display()))?; - let (data_fork, partitions) = partitions(&mut file)?; - let matching: Vec<&Partition> = partitions - .iter() - .filter(|p| p.name.contains(name)) - .collect(); - let [partition] = matching[..] else { - let names: Vec<_> = partitions.iter().map(|p| p.name.as_str()).collect(); - bail!( - "expected one {name} partition in {}; found {names:?}", - image.display() - ); - }; - let bytes = partition - .sectors - .checked_mul(SECTOR) - .filter(|&b| b <= limit) - .with_context(|| format!("partition {} exceeds {limit} bytes", partition.name))?; - let mut out = vec![0u8; bytes as usize]; - for &(kind, sector, count, offset, length) in &partition.chunks { - let start = sector - .checked_add(count) - .filter(|&end| end <= partition.sectors) - .map(|_| (sector * SECTOR) as usize) - .with_context(|| format!("chunk outside partition {}", partition.name))?; - let span = (count * SECTOR) as usize; - match kind { - CHUNK_ZERO | CHUNK_IGNORE => {} - CHUNK_RAW => { - ensure!( - length as usize == span, - "raw chunk length differs from its sectors" - ); - file.seek(SeekFrom::Start(data_fork + partition.data_offset + offset))?; - file.read_exact(&mut out[start..start + span])?; - } - CHUNK_COMMENT | CHUNK_END => {} - other => bail!( - "partition {} uses compressed UDIF chunks (type {other:#x}); only raw images \ - are read", - partition.name - ), - } - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - fn mish(first: u64, sectors: u64, chunks: &[(u32, u64, u64, u64, u64)]) -> Vec { - let mut d = vec![0u8; MISH_HEADER_BYTES]; - d[..4].copy_from_slice(b"mish"); - d[8..16].copy_from_slice(&first.to_be_bytes()); - d[16..24].copy_from_slice(§ors.to_be_bytes()); - d[200..204].copy_from_slice(&(chunks.len() as u32).to_be_bytes()); - for &(kind, sector, count, offset, length) in chunks { - let mut c = vec![0u8; CHUNK_BYTES]; - c[..4].copy_from_slice(&kind.to_be_bytes()); - c[8..16].copy_from_slice(§or.to_be_bytes()); - c[16..24].copy_from_slice(&count.to_be_bytes()); - c[24..32].copy_from_slice(&offset.to_be_bytes()); - c[32..40].copy_from_slice(&length.to_be_bytes()); - d.extend(c); - } - d - } - - /// A data fork, then the plist, then the trailer. - fn image(data: &[u8], blocks: &[(&str, Vec)]) -> tempfile::NamedTempFile { - let entries: Vec = blocks - .iter() - .map(|(name, table)| { - let mut d = plist::Dictionary::new(); - d.insert("Name".into(), (*name).into()); - d.insert("Data".into(), Value::Data(table.clone())); - d.into() - }) - .collect(); - let mut fork = plist::Dictionary::new(); - fork.insert("blkx".into(), Value::Array(entries)); - let mut root = plist::Dictionary::new(); - root.insert("resource-fork".into(), fork.into()); - let mut xml = Vec::new(); - Value::from(root).to_writer_xml(&mut xml).unwrap(); - let mut trailer = vec![0u8; TRAILER_BYTES as usize]; - trailer[..4].copy_from_slice(b"koly"); - trailer[0x20..0x28].copy_from_slice(&(data.len() as u64).to_be_bytes()); - trailer[0xd8..0xe0].copy_from_slice(&(data.len() as u64).to_be_bytes()); - trailer[0xe0..0xe8].copy_from_slice(&(xml.len() as u64).to_be_bytes()); - let mut file = tempfile::NamedTempFile::new().unwrap(); - file.write_all(data).unwrap(); - file.write_all(&xml).unwrap(); - file.write_all(&trailer).unwrap(); - file - } - - #[test] - fn raw_and_zero_chunks_rebuild_the_named_partition() { - let raw: Vec = (0..1024u32).map(|i| i as u8).collect(); - let data = [vec![0xee; 512], raw.clone()].concat(); - let file = image( - &data, - &[ - ( - "MBR : 0", - mish(0, 1, &[(CHUNK_RAW, 0, 1, 0, 512), (CHUNK_END, 1, 0, 0, 0)]), - ), - ( - "Apple_APFS : 3", - mish( - 34, - 4, - &[ - (CHUNK_RAW, 0, 2, 512, 1024), - (CHUNK_IGNORE, 2, 1, 0, 0), - (CHUNK_ZERO, 3, 1, 0, 0), - (CHUNK_END, 4, 0, 0, 0), - ], - ), - ), - ], - ); - let apfs = partition(file.path(), "Apple_APFS", 1 << 20).unwrap(); - assert_eq!(apfs.len(), 2048); - assert_eq!(&apfs[..1024], &raw[..]); - assert!(apfs[1024..].iter().all(|&b| b == 0)); - assert!(partition(file.path(), "Apple_APFS", 1024).is_err()); - assert!(partition(file.path(), "Missing", 1 << 20).is_err()); - } - - #[test] - fn compressed_chunks_and_non_udif_files_are_refused() { - let file = image( - &[0; 512], - &[("Apple_APFS", mish(0, 1, &[(0x8000_0005, 0, 1, 0, 10)]))], - ); - let error = partition(file.path(), "Apple_APFS", 1 << 20).unwrap_err(); - assert!(error.to_string().contains("compressed"), "{error}"); - let mut plain = tempfile::NamedTempFile::new().unwrap(); - plain.write_all(&[0; 1024]).unwrap(); - assert!(partition(plain.path(), "Apple_APFS", 1 << 20).is_err()); - } -} diff --git a/crates/stela-cli/src/setup.rs b/crates/stela-cli/src/setup.rs index ee2dd49f15..59663d6981 100644 --- a/crates/stela-cli/src/setup.rs +++ b/crates/stela-cli/src/setup.rs @@ -2,39 +2,40 @@ //! a disk of the PC and boot it, and keep it working over the installed //! system's life. //! -//! With `--target`, or with the USB's raw partition as the Mac's internal -//! SSD, setup writes the install medium (`setup::medium`) as -//! `--install-image` says: offline, the whole IPSW on the USB's FAT32 data -//! partition; online, only its inventory, and `stela.efi` streams the IPSW -//! from Apple's servers during the install. It prepares each machine's -//! restore bundle (`stela boot prepare --restore`) and adds an Install macOS -//! startup choice (`stela.efi --install`), which restores macOS and -//! recoveryOS onto the target, as a Mac's restore does. An erase restore -//! needs the macOS system image, so `--fetch`'s recovery members -//! (`restore::payload::trim`) only prepare the boot bundles -//! (`docs/research/small-installer-usb.md`). The macOS choice boots it -//! afterwards. The restore personalizes its root tickets and the recoveryOS -//! LocalPolicy with Apple's signing server, so it needs `--tss`. +//! Setup writes the install medium (`setup::medium`) as `--install-image` +//! says: offline, the whole IPSW on the USB's FAT32 data partition; online, +//! only its inventory, and `stela.efi` streams the IPSW from Apple's servers +//! during the install. It prepares each machine's restore bundle (`stela +//! boot prepare --restore`) and adds an Install macOS startup choice +//! (`stela.efi --install`), which restores macOS and its paired recoveryOS +//! and System Recovery onto the Mac's internal SSD, as a Mac's erase +//! restore does. An erase restore needs the macOS system image, so +//! `--fetch`'s recovery members (`restore::payload::trim`) only prepare the +//! boot bundles (`docs/research/small-installer-usb.md`). The macOS choice +//! boots the installed system afterwards. The restore personalizes its root +//! tickets and the recoveryOS LocalPolicy with Apple's signing server, so +//! setup needs `--tss`. //! //! One command checks the USB and the restore image without writing -//! anything, prepares the recoveryOS boot bundle (`stela boot prepare -//! --recovery`) on this computer, then copies it to a FAT32 volume of the -//! USB, which the PC's firmware can read, installs `stela.efi` as the USB's -//! boot loader (`efi`) with a `stela.cfg` that boots that bundle, and -//! records what it wrote in +//! anything, prepares the restore bundle on this computer, then copies it +//! to a FAT32 volume of the USB, which the PC's firmware can read, installs +//! `stela.efi` as the USB's boot loader (`efi`) with a `stela.cfg` that +//! boots the installed macOS, and records what it wrote in //! `EFI/stela/setup.json`. `--dry-run` stops after the checks; `--uninstall` //! removes everything the record names. //! //! Each Stela machine has its own ECID (`setup::ecid`), drawn once, kept in -//! the record and given to every bundle prepared for it. With `--target`, -//! setup runs on the PC itself and also names the PC's own disk -//! (`setup::installed`): one empty partition becomes the Mac's internal SSD -//! and keeps the machine state (NVRAM, the SEP's state, the boot log) in its -//! last bytes, outside what the guest sees, or `--nor` names a partition of -//! its own for that state. The USB then boots the installed macOS from -//! that disk, or recoveryOS when NVRAM asks for it or the disk holds no -//! system yet, as a Mac does. Further disks become further installs of the same -//! setup (`setup::machines`), each its own machine, chosen at boot from +//! the record and given to every bundle prepared for it. Without `--target`, +//! Install macOS asks for a disk of the PC in `stela.efi`, or a raw +//! partition of the USB is the Mac's internal SSD. With `--target`, setup +//! runs on the PC itself and names the PC's own disk (`setup::installed`): +//! one empty partition becomes the Mac's internal SSD and keeps the machine +//! state (NVRAM, the SEP's state, the boot log) in its last bytes, outside +//! what the guest sees, or `--nor` names a partition of its own for that +//! state. The USB then boots the installed macOS from that disk, or the +//! disk's own recoveryOS when NVRAM asks for it or the disk holds no system, +//! as a Mac does. Further disks become further installs of the same setup +//! (`setup::machines`), each its own machine, chosen at boot from //! `stela.efi`'s startup choices. Setup writes no disk but the USB, except //! fresh machine state with `--initialize-nor` and NVRAM with //! `--next-boot`. @@ -42,12 +43,11 @@ //! An existing setup is updated in place (`setup::update`): `--update-stela` //! installs a new `stela.efi` and prepares the boot bundles again when it //! reads another schema or this `stela` prepares another bundle revision -//! than theirs, `--update-os` a new macOS build's recoveryOS -//! and, for installs, its install medium and restore bundles, and -//! `--rollback` undoes the last update or finishes undoing an -//! interrupted one. Every path takes `--dry-run`. A `stela.efi` whose mount -//! interface (`stela_loader::mount_interface`) differs from this `stela`'s is -//! refused. +//! than theirs, `--update-os` a new macOS build's install medium and +//! restore bundles, and `--rollback` undoes the last update or finishes +//! undoing an interrupted one. Every path takes `--dry-run`. A `stela.efi` +//! whose mount interface (`stela_loader::mount_interface`) differs from this +//! `stela`'s is refused. mod assets; mod bundle; mod doctor; @@ -174,7 +174,7 @@ pub(crate) struct Setup { /// Where `--fetch` keeps the image. #[arg(long)] download_dir: Option, - /// A volume of the USB for the recoveryOS bundle, when the EFI partition + /// A volume of the USB for the restore bundles, when the EFI partition /// is too small. #[arg(long)] volume: Option, @@ -197,7 +197,7 @@ pub(crate) struct Setup { uninstall: bool, /// The PC's partition that becomes the Mac's internal SSD, such as /// disk1s2 on macOS, /dev/nvme0n1p2 on Linux or disk1p2 on Windows: - /// macOS is installed onto it from recoveryOS and booted from it. + /// Install macOS restores macOS onto it, and it is booted from it. /// Without --nor its last 16 MiB keep the machine state (NVRAM, the SEP's /// state and the boot log), which the guest never sees. On an existing /// setup, it adds another install. @@ -239,9 +239,10 @@ pub(crate) struct Setup { /// Opt in to Apple's signing server: the restore host sends the /// machine's ECID, the restore's nonces and the build's component hashes /// to gs.apple.com for the restore's personalized root tickets and the - /// recoveryOS LocalPolicy. Off by default; on an existing setup it turns - /// the opt-in on. Required for installation: a local IPSW supplies the - /// image files, but boot firmware still needs personalized tickets. + /// recoveryOS LocalPolicy. Required for a new setup, which installs + /// macOS: a local IPSW supplies the image files, but boot firmware still + /// needs personalized tickets. On an existing setup it turns the opt-in + /// on. #[arg(long, conflicts_with = "no_tss")] tss: bool, /// Turn the Apple signing server opt-in off on an existing setup. @@ -281,8 +282,8 @@ pub(crate) struct Setup { /// bundle schema or this `stela` prepares a new bundle revision. #[arg(long)] update_stela: bool, - /// Add a new macOS build's recoveryOS (`--ipsw` or `--fetch`) to an - /// existing setup for System Recovery and Reinstall macOS. + /// Add a new macOS build's install medium and restore bundles (`--ipsw` + /// or `--fetch`) to an existing setup for Install macOS. #[arg(long)] update_os: bool, /// Undo the last update, or an interrupted one. @@ -297,7 +298,7 @@ pub(crate) struct Setup { status: bool, /// Put back what the setup record says (stela.efi, the entry, /// stela.cfg, the startup choices); with `--ipsw` or `--fetch`, prepare - /// the active build's recoveryOS bundles again. + /// the active build's restore bundles again. #[arg(long)] repair: bool, /// Write a fresh NVRAM to the install's NOR partition (named again with @@ -400,13 +401,13 @@ impl InstallMedium { } /// What setup writes, recorded on the ESP so `--uninstall` can remove it. -/// Schema 1 setups also wrote a restore payload and named a target disk; -/// schema 3 ones named at most one installed disk and no ECIDs. +/// Records before schema 8 also named a recoveryOS bundle on the USB; this +/// `stela` reads them only to uninstall them. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] struct Record { schema_version: u32, kind: String, - /// The active macOS build, whose recoveryOS boots. + /// The active macOS build, which Install macOS restores. build: String, model: String, esp: PathBuf, @@ -431,20 +432,16 @@ struct Record { stela_version: Option, #[serde(default)] stela_versions: Vec, - /// Schema 3: the recoveryOS builds kept, oldest first; `build` is the - /// active one. - #[serde(default)] - recovery_builds: Vec, + /// Schema 3: the macOS builds kept for rollback, oldest first; `build` + /// is the active one. + #[serde(default, alias = "recovery_builds")] + builds: Vec, /// Schema 3: an update that started and has not finished. #[serde(default, skip_serializing_if = "Option::is_none")] pending: Option, /// Schema 3: finished updates, for `--rollback`. #[serde(default)] history: Vec, - /// Schema 4: the ECID of the machine without an installed disk, which - /// the first install takes over. - #[serde(default, skip_serializing_if = "Option::is_none")] - ecid: Option, /// Schema 4: the PC disks macOS installs onto, each its own machine. #[serde(default)] installs: Vec, @@ -457,7 +454,7 @@ struct Record { /// that prepared them (`stela_loader::boot_bundle::REVISION`); 0 before. #[serde(default)] bundle_revision: u32, - /// Schema 4: every recoveryOS bundle setup wrote. + /// Schema 4: every boot bundle setup wrote. #[serde(default)] bundles: Vec, /// Schema 4: the Apple signing server opt-in (`--tss`). @@ -495,7 +492,8 @@ fn first_schema() -> u32 { } const RECORD_KIND: &str = "stela_setup"; -const RECORD_SCHEMA: u32 = 7; +/// Schema 8: no recoveryOS bundle; every setup has an install. +const RECORD_SCHEMA: u32 = 8; impl Record { /// Whether installs stream `ipsw`'s build from Apple's servers @@ -509,9 +507,9 @@ impl Record { image_is_remote(ipsw, self.install_image) } - /// Bring an older schema's record to this one: its installed disk - /// becomes the first install, its bundles (one per build, without an - /// ECID) are listed. + /// Bring an older schema's record to one `--uninstall` reads: its + /// install medium is listed and its installed disk becomes the first + /// install. fn migrate(&mut self) { if let Some(medium) = self.medium.take() && !self.media.iter().any(|m| m.build == medium.build) @@ -525,41 +523,6 @@ impl Record { disk, }); } - if self.bundles.is_empty() { - let mut builds = self.recovery_builds.clone(); - if !builds.contains(&self.build) { - builds.push(self.build.clone()); - } - for build in builds { - let first = bundle::Generation::FIRST; - if bundle::directory(&self.volume, &build, None, first).is_dir() { - self.bundles.push(bundle::Bundle { - build, - ecid: None, - schema: first.schema, - revision: first.revision, - manifest_sha256: String::new(), - kind: Kind::Recovery, - personalized: false, - }); - } - } - } - } - - /// The ECIDs of the machines whose bundles the active build needs: one - /// per install, or the setup's own without one. - fn machines(&self) -> Vec> { - if self.installs.is_empty() { - return vec![self.ecid]; - } - let mut machines: Vec> = Vec::new(); - for install in &self.installs { - if !machines.contains(&install.ecid) { - machines.push(install.ecid); - } - } - machines } /// The install `stela.cfg` boots. @@ -595,32 +558,23 @@ impl Record { } } - /// The recoveryOS bundle of `ecid`'s machine for the active build. - fn recovery(&self, ecid: Option) -> String { - bundle::firmware_path(&self.build, ecid, self.generation()) - } - fn line(&self, text: String) -> String { let tss = if self.tss { " --tss" } else { "" }; let profile = if self.profile { " --profile" } else { "" }; format!("{text}{tss}{profile}\n") } - /// The option line that boots `install`, or the setup's own recoveryOS. - fn boot_line(&self, install: Option<&machines::Install>) -> String { - match install { - Some(install) => self.line( - install - .disk - .options(&self.recovery(install.ecid), install.ecid), - ), - None => self.line(format!("--system --bundle {}", self.recovery(self.ecid))), - } + /// The option line that boots `install`. + fn boot_line(&self, install: &machines::Install) -> String { + self.line(install.disk.options(install.ecid)) } - /// `stela.cfg`: the default install, or recoveryOS alone. + /// `stela.cfg`: the default install. Every setup this `stela` reads + /// has one ([`read_record`]). fn options_text(&self) -> String { - self.boot_line(self.default()) + self.default() + .map(|install| self.boot_line(install)) + .unwrap_or_default() } /// The restore bundle of `kind` (erase or update) of `ecid`'s machine @@ -657,11 +611,9 @@ impl Record { } /// Whether the installs restore from install media: the setup has - /// written a medium or a restore bundle, as every setup with installs - /// since media were introduced has. + /// written a medium or a restore bundle, as every setup does. fn installs_media(&self) -> bool { - !self.installs.is_empty() - && (!self.media.is_empty() || self.bundles.iter().any(|b| b.kind != Kind::Recovery)) + !self.installs.is_empty() && (!self.media.is_empty() || !self.bundles.is_empty()) } /// The machines of the installs, each once. @@ -687,7 +639,7 @@ impl Record { return None; } let restore = bundle::firmware_path_of(kind, &self.build, install.ecid, self.generation()); - let base = install.disk.recovery_options(&restore, install.ecid); + let base = install.disk.bundle_options(&restore, install.ecid); let update = if kind == Kind::Update { format!(" {UPDATE_RESTORE}") } else { @@ -748,9 +700,8 @@ impl Record { missing } - /// The startup choices: each install, default first, its System - /// Recovery and its Install macOS. - /// None without an installed disk. + /// The startup choices: each install, default first, and its Install + /// macOS. None without an installed disk. fn choices(&self) -> Option { let default = self.default()?; let mut entries = Vec::new(); @@ -758,18 +709,7 @@ impl Record { for install in std::iter::once(default).chain(others) { entries.push(Choice { name: install.name.clone(), - options: self.boot_line(Some(install)).trim().into(), - }); - entries.push(Choice { - name: format!("{} Recovery", install.name), - options: self - .line( - install - .disk - .recovery_options(&self.recovery(install.ecid), install.ecid), - ) - .trim() - .into(), + options: self.boot_line(install).trim().into(), }); for kind in bundle::RESTORE_KINDS { if let Some(line) = self.restore_line(kind, install) { @@ -800,31 +740,10 @@ impl Record { .transpose() } - /// The bundle of `build` for `ecid`'s machine of the active generation. - fn bundle(&self, build: &str, ecid: Option) -> Option<&bundle::Bundle> { - self.bundles - .iter() - .find(|b| b.same(build, ecid, self.generation())) - } - - /// Bundle keys of `build` that the machines need and the record or the - /// volume lacks. - fn missing_bundles(&self, build: &str) -> Vec> { - self.machines() - .into_iter() - .filter(|&ecid| { - self.bundle(build, ecid).is_none() - || !bundle::directory(&self.volume, build, ecid, self.generation()) - .join(bundle::MANIFEST) - .is_file() - }) - .collect() - } - /// Forget the bundles of machines the setup no longer has; returns /// them for [`remove_bundles`] once the record no longer names them. fn drop_stale_bundles(&mut self) -> Vec { - let machines = self.machines(); + let machines = self.install_machines(); let (kept, stale) = self .bundles .drain(..) @@ -835,7 +754,7 @@ impl Record { /// Every build directory a bundle or the history names. fn build_directories(&self) -> Vec { - let mut builds: Vec<&String> = self.recovery_builds.iter().collect(); + let mut builds: Vec<&String> = self.builds.iter().collect(); builds.push(&self.build); builds.extend(self.bundles.iter().map(|b| &b.build)); let mut directories = Vec::new(); @@ -884,18 +803,57 @@ fn read_record(environment: &Environment<'_>, usb: &Path) -> Result { "{} has no setup; run `stela setup` first", esp.display() ); - let mut record: Record = stela_runtime::read_json(&path)?; + let header: serde_json::Value = stela_runtime::read_json(&path)?; + let schema = header["schema_version"].as_u64().unwrap_or(0); ensure!( - record.kind == RECORD_KIND && (1..=RECORD_SCHEMA).contains(&record.schema_version), + header["kind"] == RECORD_KIND && schema <= u64::from(RECORD_SCHEMA), "{} is not a setup record this version understands; it may come from a newer stela", path.display() ); ensure!( - record.payload_directory.is_none(), - "{} is a schema 1 setup, which installs from a restore payload; run `stela setup \ - --uninstall` and set up again", - esp.display() + schema == u64::from(RECORD_SCHEMA), + "{} is a schema {schema} setup, which this stela no longer reads: it booted a \ + recoveryOS bundle from the USB. Run `stela setup --uninstall --usb {}` and set the \ + USB up again", + path.display(), + usb.display() ); + let record: Record = stela_runtime::read_json(&path)?; + ensure!( + !record.installs.is_empty(), + "{} names no install; run `stela setup --uninstall --usb {}` and set the USB up again", + path.display(), + usb.display() + ); + Ok(record) +} + +/// Any schema's record, for `--uninstall`: the bundles of an older +/// schema's record that name no kind or `recovery` are recoveryOS bundles, +/// which this `stela` has no kind for; their build directories are removed +/// with the rest. +fn read_any_record(path: &Path) -> Result { + let mut value: serde_json::Value = stela_runtime::read_json(path)?; + let schema = value["schema_version"].as_u64().unwrap_or(0); + ensure!( + value["kind"] == RECORD_KIND && (1..=u64::from(RECORD_SCHEMA)).contains(&schema), + "{} is not a setup record this version understands", + path.display() + ); + if schema < 8 + && let Some(bundles) = value + .get_mut("bundles") + .and_then(serde_json::Value::as_array_mut) + { + bundles.retain(|bundle| { + bundle + .get("kind") + .and_then(serde_json::Value::as_str) + .is_some_and(|kind| kind != "recovery") + }); + } + let mut record: Record = serde_json::from_value(value) + .with_context(|| format!("{} cannot be read", path.display()))?; record.migrate(); Ok(record) } @@ -913,9 +871,8 @@ fn write_record(esp: &Path, record: &Record) -> Result<()> { efi::write_atomic(&path, &bytes, false) } -/// Writes a boot bundle for an IPSW, model and machine into a directory; -/// a restore bundle under Apple's personalized ticket when the `bool` says -/// so (recoveryOS bundles always boot under the global one). +/// Writes a restore bundle for an IPSW, model and machine into a +/// directory, under Apple's personalized ticket when the `bool` says so. type Prepare = dyn Fn(&Path, &str, Option, bool, &Path) -> Result<()>; /// An IPSW's restore inventory for a model. @@ -926,10 +883,8 @@ type InventoryOf = dyn Fn(&Path, &str) -> Result; struct Environment<'a> { host: &'a dyn Host, download: Option<&'a medium::download::Download>, - /// `stela boot prepare --recovery`; tests use synthetic IPSWs, which + /// `stela boot prepare --restore`; tests use synthetic IPSWs, which /// have no kernel, and write a stand-in. - prepare: &'a Prepare, - /// `stela boot prepare --restore`, likewise. prepare_restore: &'a Prepare, /// `stela boot prepare --restore --update`, likewise. prepare_update: &'a Prepare, @@ -1043,32 +998,42 @@ type PreparedSetup = (String, String, Vec); impl Prepared { fn path(&self) -> PathBuf { - self.directory.path().join("recovery") + self.directory.path().join(BUNDLE_LEAF) } } -/// Prepare `ipsw`'s recoveryOS for each machine of `ecids`; the image must -/// be `build`, when given. Returns the image's version and build too. -fn prepare_bundles( +/// The directory a bundle is prepared into, inside its temporary one. +const BUNDLE_LEAF: &str = "bundle"; + +/// Prepare `ipsw`'s restore bundles of every kind setup writes +/// ([`bundle::RESTORE_KINDS`]) for the machine `ecid`, under Apple's +/// personalized ticket. Returns the image's version and build too. +fn prepare_restore_bundles( environment: &Environment<'_>, ipsw: &Path, model: &str, - build: Option<&str>, - ecids: &[Option], -) -> Result<(String, String, Vec)> { - prepare_kind( - environment, - Kind::Recovery, - false, - ipsw, - model, - build, - ecids, - ) + ecid: Ecid, +) -> Result { + let (product_version, build) = restore::payload::identity(ipsw, model)?; + let mut prepared = Vec::new(); + for kind in bundle::RESTORE_KINDS { + let (_, _, bundles) = prepare_kind( + environment, + kind, + true, + ipsw, + model, + Some(&build), + &[Some(ecid)], + )?; + prepared.extend(bundles); + } + Ok((product_version, build, prepared)) } -/// [`prepare_bundles`] for bundles of `kind`; restore bundles under Apple's -/// personalized ticket with the TSS opt-in `tss`. +/// Prepare `ipsw`'s bundles of `kind` for each machine of `ecids`, under +/// Apple's personalized ticket with the TSS opt-in `tss`; the image must be +/// `build`, when given. Returns the image's version and build too. fn prepare_kind( environment: &Environment<'_>, kind: Kind, @@ -1089,13 +1054,12 @@ fn prepare_kind( let mut prepared = Vec::new(); for &ecid in ecids { let directory = tempfile::tempdir()?; - let output = directory.path().join("recovery"); + let output = directory.path().join(BUNDLE_LEAF); let prepare = match kind { - Kind::Recovery => environment.prepare, Kind::Restore => environment.prepare_restore, Kind::Update => environment.prepare_update, }; - let personalized = tss && kind != Kind::Recovery; + let personalized = tss; let progress = crate::progress::Phase::spinner(format!("Preparing {} boot files", kind.label())); prepare(ipsw, model, ecid, personalized, &output) @@ -1192,7 +1156,6 @@ impl Setup { let environment = Environment { host: &host::System, download: None, - prepare: &prepare_recovery, prepare_restore: &prepare_restore, prepare_update: &prepare_update, inventory: &|ipsw, model| restore::payload::inventory(ipsw, model, true, None, None), @@ -1616,7 +1579,7 @@ fn choose_volume( if info.free_bytes < need { writeln!( reasons, - " {} ({}) has {:.1} GB free; the recoveryOS bundle needs {:.1} GB", + " {} ({}) has {:.1} GB free; the restore bundles need {:.1} GB", volume.display(), info.filesystem, info.free_bytes as f64 / 1e9, @@ -1627,7 +1590,7 @@ fn choose_volume( return Ok(volume); } bail!( - "No volume of the USB can hold the recoveryOS bundle:\n{reasons}Add a FAT32 data \ + "No volume of the USB can hold the restore bundles:\n{reasons}Add a FAT32 data \ partition of at least 4 GB beside the EFI partition, then pass it with --volume." ) } @@ -1719,39 +1682,6 @@ pub(crate) fn fetch_image(directory: &Path, build: &str, model: &str) -> Result< /// the boot log as `GUEST|` lines, so a run on a PC can be read afterwards. const CONSOLE_BOOT_ARGS: &str = "--boot-args=-v serial=3 serial-device-name=uart0"; -/// `stela boot prepare --recovery` for the IPSW, model and machine into -/// `output`, then the engine's own board check of the prepared DeviceTree -/// (`machine::soc::board`), so a model the engine cannot run is refused -/// before the USB changes rather than when the PC boots it. -fn prepare_recovery( - ipsw: &Path, - model: &str, - ecid: Option, - _: bool, - output: &Path, -) -> Result<()> { - let mut line: Vec = [ - "--ipsw", - ipsw.to_str().context("IPSW path is not UTF-8")?, - "--model", - model, - "--recovery", - "--output", - output.to_str().context("temporary path is not UTF-8")?, - CONSOLE_BOOT_ARGS, - ] - .map(str::to_owned) - .into(); - if let Some(ecid) = ecid { - line.extend(["--ecid".into(), ecid.to_string()]); - } - boot::prepare(&line)?; - let tree = fs::read(output.join("devicetree.adt"))?; - stela_runtime::machine::soc::board(&tree) - .map_err(|reason| anyhow::anyhow!("Stela cannot run {model} yet: {reason}"))?; - Ok(()) -} - /// `stela boot prepare --restore` for the IPSW, model and machine into /// `output`: the restore bundle the Install macOS choice boots. fn prepare_restore( @@ -1778,7 +1708,10 @@ fn prepare_update( /// A restore bundle of the model's erase or, with `update`, update restore /// identity; `personalized`, under the AP ticket Apple's signing service -/// issues for the machine, which the restore's `--tss` choice needs. +/// issues for the machine, which the restore's `--tss` choice needs. Then +/// the engine's own board check of the prepared DeviceTree +/// (`machine::soc::board`), so a model the engine cannot run is refused +/// before the USB changes rather than when the PC boots it. fn prepare_ramdisk( ipsw: &Path, model: &str, @@ -1812,7 +1745,11 @@ fn prepare_ramdisk( ); line.push("--tss".into()); } - boot::prepare(&line) + boot::prepare(&line)?; + let tree = fs::read(output.join("devicetree.adt"))?; + stela_runtime::machine::soc::board(&tree) + .map_err(|reason| anyhow::anyhow!("Stela cannot run {model} yet: {reason}"))?; + Ok(()) } /// The install medium setup writes. @@ -1829,9 +1766,8 @@ struct MediumPlan { created: Vec, } -/// What installing macOS needs besides the recoveryOS bundles: each -/// machine's restore bundles and, unless the USB holds the build's intact -/// medium, the install medium. +/// What installing macOS needs: each machine's restore bundles and, unless +/// the USB holds the build's intact medium, the install medium. struct InstallPlan { /// The macOS build it installs. build: String, @@ -2093,24 +2029,26 @@ fn remove_replaced(record: &Record, build: &str, previous: Option<&medium::Mediu } } -/// Why installing to a target needs the explicit signing-service choice. -const TSS_REQUIRED: &str = "installing macOS onto the Mac's internal SSD (--target, or the \ - USB's raw partition) needs --tss: required boot firmware needs personalized tickets \ - from Apple's signing server (gs.apple.com), which receives this machine's ECID, \ - the restore's nonces and its boot components' hashes. Add --tss to opt in."; +/// Why a setup, which installs macOS, needs the explicit signing-service +/// choice. +const TSS_REQUIRED: &str = "Stela setup installs macOS onto the Mac's internal SSD, which \ + needs --tss: required boot firmware needs personalized tickets from Apple's signing \ + server (gs.apple.com), which receives this machine's ECID, the restore's nonces and its \ + boot components' hashes. Add --tss to opt in."; /// The checks' result: everything setup will write, and where. struct Plan { record: Record, ipsw: PathBuf, product_version: String, - /// The prepared bundle, in a host directory until setup copies it. + /// The prepared restore bundles, in a host directory until setup + /// copies them. prepared: Vec, efi_image: Vec, - /// The PC's own disk, and the NOR image setup writes to it. - installed: Option, - /// With an installed disk: its restore bundle and the install medium. - install: Option, + /// The install's disk, and the NOR image setup writes to it. + installed: installed::Checked, + /// The install medium. + install: InstallPlan, notes: Vec, } @@ -2146,18 +2084,18 @@ fn plan( None => stick_ssd(host, usb_disk.as_deref())?, }; let target = command.target.clone().or(stick.clone()); - ensure!(target.is_none() || command.tss, TSS_REQUIRED); - // With the signing server opt-in and no disk named here, Install macOS - // chooses the PC's disk in stela.efi. + ensure!(command.tss, TSS_REQUIRED); + // With no disk named here, Install macOS chooses the PC's disk in + // stela.efi. let installed = match &target { - None if command.tss => Some(installed::Checked { + None => installed::Checked { disk: installed::InstalledDisk::chosen(), nor_image: None, sep_provisioned: false, foreign: None, notes: Vec::new(), - }), - Some(target) => Some(installed::check( + }, + Some(target) => installed::check( host, &installed::Request { apple_region: target, @@ -2168,50 +2106,39 @@ fn plan( usb_disk: usb_disk.as_deref(), external_disks: stick.is_some(), }, - )?), - None => None, + )?, }; let mut notes = Vec::new(); - let ecid = match &installed { - Some(checked) => machines::machine_ecid( - command.ecid, - None, - checked.sep_provisioned, - command.new_ecid, - &mut notes, - )?, - None => command.ecid.map_or_else(Ecid::generate, Ok)?, - }; + let ecid = machines::machine_ecid( + command.ecid, + None, + installed.sep_provisioned, + command.new_ecid, + &mut notes, + )?; let efi_path = match &command.efi { Some(path) => path.clone(), None => assets::resolve()?, }; let efi_image = read_efi(environment, &efi_path)?; update::check_firmware_support(&esp, &efi_image)?; - // The bundle is prepared on this computer before the USB changes, which - // also measures it for the space check. + // The restore bundles are prepared on this computer before the USB + // changes, which also measures them for the space check. let (product_version, build, prepared) = match early { Some(prepared) => prepared, - None => prepare_bundles(environment, &ipsw, command.model(), None, &[Some(ecid)])?, + None => prepare_restore_bundles(environment, &ipsw, command.model(), ecid)?, }; - // With an installed disk, its two restore bundles (each smaller than - // the recoveryOS one) go on the same volume. let bundles: u64 = prepared.iter().map(|bundle| bundle.bytes).sum(); let volume = choose_volume(host, &esp, &command.usb, command.volume.as_deref(), bundles)?; - let installs = installed - .iter() - .map(|checked| machines::Install { - name: command - .install - .clone() - .unwrap_or_else(|| machines::FIRST_NAME.into()), - ecid: Some(ecid), - disk: checked.disk.clone(), - }) - .collect::>(); - if let Some(install) = installs.first() { - machines::check_name(&install.name)?; - } + let install = machines::Install { + name: command + .install + .clone() + .unwrap_or_else(|| machines::FIRST_NAME.into()), + ecid: Some(ecid), + disk: installed.disk.clone(), + }; + machines::check_name(&install.name)?; let mut record = Record { schema_version: RECORD_SCHEMA, kind: RECORD_KIND.into(), @@ -2230,11 +2157,10 @@ fn plan( installed: None, stela_version: Some(update::version_id(&efi_image)), stela_versions: vec![update::version_id(&efi_image)], - recovery_builds: vec![build], + builds: vec![build], pending: None, history: Vec::new(), - ecid: Some(ecid), - installs, + installs: vec![install], default_install: None, bundle_schema: environment.interface.bundle_schema, bundle_revision: environment.bundle_revision, @@ -2248,25 +2174,20 @@ fn plan( install_image: command.install_image, translations: None, }; - let missing_restore: Vec<_> = restore_bundles(&[Some(ecid)]) - .into_iter() - .filter(|&(kind, ecid)| !prepared.iter().any(|b| b.kind == kind && b.ecid == ecid)) - .collect(); - let install = match &installed { - Some(_) => Some(plan_install( - environment, - &record, - &record.build, - command.install_volume.as_deref(), - &ipsw, - &missing_restore, - bundles, - )?), - None => None, - }; + // The restore bundles are prepared above: the install plan adds the + // install medium. + let install = plan_install( + environment, + &record, + &record.build, + command.install_volume.as_deref(), + &ipsw, + &[], + bundles, + )?; // The translation store takes what the USB's FAT32 volumes have left // after everything above. - let medium = install.as_ref().and_then(|plan| plan.medium.as_ref()); + let medium = install.medium.as_ref(); let mut candidates: Vec<&Path> = medium.iter().map(|m| m.volume.as_path()).collect(); candidates.extend([record.volume.as_path(), esp.as_path()]); let planned = |volume: &Path| { @@ -2288,43 +2209,28 @@ fn plan( record.translations = store; record.options = record.options_text(); record.choices_text()?; - let source = match install - .as_ref() - .and_then(|plan| plan.medium.as_ref()) - .is_some_and(|medium| medium.remote) - { + let source = match install.medium.as_ref().is_some_and(|medium| medium.remote) { true => { "streaming the restore image from Apple's servers (about 27 GB) over the PC's \ wired network" } false => "from the install medium on this USB (TSS still needs network)", }; - notes.push(match &installed { - Some(checked) if checked.disk.is_chosen() => format!( + notes.push(match installed.disk.is_chosen() { + true => format!( "The Install macOS startup choice asks for a disk of the PC and the space macOS gets \ there, then Apple's restore installs macOS onto it as the Mac's internal SSD \ (ANS2), {source}. An install may not finish yet." ), - Some(checked) => format!( + false => format!( "The Install macOS startup choice restores macOS onto {} as the Mac's internal SSD \ (ANS2), {source}. An install may not finish yet.", - checked.disk.apple_region + installed.disk.apple_region ), - None => "recoveryOS's Reinstall macOS downloads the installer from Apple and \ - personalizes it with Apple's signing server and the Secure Enclave, which \ - Stela does not complete yet; add an installed disk with --target to install \ - from the IPSW, with --tss for personalized boot firmware." - .into(), }); - if command.tss { - notes.push(tss_note()); - } - if installed.is_some() { - notes.push("Erase installs retain the original development-board FDR failure policy: FDR connectivity is disabled and factory data remains unprovisioned.".into()); - } - if let Some(checked) = &installed { - notes.extend(checked.notes.iter().cloned()); - } + notes.push(tss_note()); + notes.push("Erase installs retain the original development-board FDR failure policy: FDR connectivity is disabled and factory data remains unprovisioned.".into()); + notes.extend(installed.notes.iter().cloned()); Ok(Plan { record, ipsw, @@ -2356,10 +2262,11 @@ fn describe(plan: &Plan) -> Result { )?; writeln!(text, " restore image {}", plan.ipsw.display())?; writeln!(text, " EFI partition {}", record.esp.display())?; + let install = &record.installs[0]; writeln!( text, " ECID {}", - record.ecid.expect("a new setup has an ECID") + install.ecid.expect("a new setup's install has an ECID") )?; for prepared in &plan.prepared { writeln!( @@ -2385,57 +2292,43 @@ fn describe(plan: &Plan) -> Result { " boot loader {}: stela.efi", record.esp.join(LOADER_PATH).display() )?; - match (&plan.installed, record.installs.first()) { - (Some(checked), Some(install)) => { - let disk = &checked.disk; - writeln!( - text, - " stela.cfg {}: boots macOS from {}, or recoveryOS when NVRAM asks or \ - the disk holds no system", - record.esp.join("EFI/stela/stela.cfg").display(), - disk.apple_region - )?; - writeln!( - text, - " choices.cfg {}: \"{}\", its System Recovery and \"{INSTALL_CHOICE}\", \ - listed for {CHOOSER_SECONDS} seconds at startup", - record.esp.join(CHOICES_PATH).display(), - install.name - )?; - if let Some(install) = &plan.install { - describe_install(record, install, &mut text)?; - } - match disk.is_chosen() { - true => writeln!( - text, - " Apple region a partition stela.efi's {INSTALL_CHOICE} makes on the PC \ - disk you choose" - )?, - false => writeln!( - text, - " Apple region {} (serial {}, partition {})", - disk.apple_region, disk.apple_region_serial, disk.apple_region_guid - )?, - } - writeln!(text, " {}", state_line(disk))?; - match checked.nor_image { - Some(_) => writeln!( - text, - " disks this USB, and fresh machine state (NOR image or SEP area) \ - on {}", - disk.state_description() - )?, - None => writeln!(text, " disks none are written but this USB")?, - } - } - _ => { - writeln!( - text, - " stela.cfg {}: boots recoveryOS", - record.esp.join("EFI/stela/stela.cfg").display() - )?; - writeln!(text, " disks none are written but this USB")?; - } + let checked = &plan.installed; + let disk = &checked.disk; + writeln!( + text, + " stela.cfg {}: boots macOS from {}, or the disk's own recoveryOS when NVRAM \ + asks or the disk holds no system", + record.esp.join("EFI/stela/stela.cfg").display(), + disk.apple_region + )?; + writeln!( + text, + " choices.cfg {}: \"{}\" and \"{INSTALL_CHOICE}\", listed for {CHOOSER_SECONDS} \ + seconds at startup", + record.esp.join(CHOICES_PATH).display(), + install.name + )?; + describe_install(record, &plan.install, &mut text)?; + match disk.is_chosen() { + true => writeln!( + text, + " Apple region a partition stela.efi's {INSTALL_CHOICE} makes on the PC disk you \ + choose" + )?, + false => writeln!( + text, + " Apple region {} (serial {}, partition {})", + disk.apple_region, disk.apple_region_serial, disk.apple_region_guid + )?, + } + writeln!(text, " {}", state_line(disk))?; + match checked.nor_image { + Some(_) => writeln!( + text, + " disks this USB, and fresh machine state (NOR image or SEP area) on {}", + disk.state_description() + )?, + None => writeln!(text, " disks none are written but this USB")?, } for note in &plan.notes { writeln!(text, " note {note}")?; @@ -2455,6 +2348,7 @@ fn state_line(disk: &installed::InstalledDisk) -> String { fn setup(environment: &Environment<'_>, mut command: Setup) -> Result { let host = environment.host; + ensure!(command.tss, TSS_REQUIRED); let mut erase = None; if let Some(disk) = host.whole_disk(&command.usb)? { let found = host.disks()?.into_iter().find(|d| d.identifier == disk); @@ -2528,25 +2422,11 @@ fn setup(environment: &Environment<'_>, mut command: Setup) -> Result { let remote = download.is_none() && image_is_remote(&ipsw, command.install_image)?; // The portable installer knows its identity before the target PC is // connected. Prepare and sign once, and measure it before erasing USB. - if command.target.is_none() && command.tss { + if command.target.is_none() { let ecid = command.ecid.map_or_else(Ecid::generate, Ok)?; command.ecid = Some(ecid); - let (version, build, mut prepared) = - prepare_bundles(environment, &ipsw, command.model(), None, &[Some(ecid)])?; - for kind in bundle::RESTORE_KINDS { - prepared.extend( - prepare_kind( - environment, - kind, - true, - &ipsw, - command.model(), - Some(&build), - &[Some(ecid)], - )? - .2, - ); - } + let (version, build, prepared) = + prepare_restore_bundles(environment, &ipsw, command.model(), ecid)?; let image_bytes = if remote { 0 } else { @@ -2586,30 +2466,27 @@ fn setup(environment: &Environment<'_>, mut command: Setup) -> Result { report.push_str("Dry run: nothing was changed.\n"); return Ok(report); } - let disk = plan.installed.as_ref().map(|checked| checked.disk.clone()); + let disk = plan.installed.disk.clone(); apply(environment, plan)?; let start = match disk { - Some(disk) if disk.is_chosen() => format!( + disk if disk.is_chosen() => format!( "choose \"{INSTALL_CHOICE}\" in Stela's startup choices, pick the PC disk and the \ space macOS gets, and the install restores macOS onto it; Stela then starts the \ installed macOS from that disk" ), - Some(disk) if disk.external_disks => format!( + disk if disk.external_disks => format!( "boot the PC from the USB: its internal SSD ({}) is blank, so Stela offers \ \"{INSTALL_CHOICE}\", which restores it. Then recoveryOS's Disk Utility \ partitions and formats the PC's disks, which macOS sees as external drives, and \ Reinstall macOS installs onto one, as on a Mac", disk.apple_region ), - Some(disk) => format!( + disk => format!( "choose \"{INSTALL_CHOICE}\" in Stela's startup choices to install macOS onto \ - {target}, then boot from the USB again, which boots the installed macOS (or \ - recoveryOS while {target} holds none, or when NVRAM asks)", + {target}, then boot from the USB again, which boots the installed macOS (or its \ + recoveryOS when NVRAM asks)", target = disk.apple_region ), - None => "stela.efi starts recoveryOS, where Disk Utility prepares a disk and Reinstall \ - macOS installs onto it, as on a Mac" - .into(), }; writeln!( report, @@ -2648,16 +2525,13 @@ fn apply(environment: &Environment<'_>, plan: Plan) -> Result<()> { if let Some(store) = &record.translations { store.publish()?; } - if let Some(install) = plan.install { - apply_install(environment, &mut record, &plan.ipsw, install)?; + apply_install(environment, &mut record, &plan.ipsw, plan.install)?; + let checked = &plan.installed; + if let Some(region) = &checked.foreign { + installed::erase_foreign(environment.host, region)?; } - if let Some(checked) = &plan.installed { - if let Some(region) = &checked.foreign { - installed::erase_foreign(environment.host, region)?; - } - if let Some(nor) = &checked.nor_image { - installed::initialize_nor(environment.host, &checked.disk, nor)?; - } + if let Some(nor) = &checked.nor_image { + installed::initialize_nor(environment.host, &checked.disk, nor)?; } // The version is kept first, so `--rollback` of a later update finds it. let version = update::store_version(&esp, &plan.efi_image)?; @@ -2674,18 +2548,11 @@ fn uninstall(environment: &Environment<'_>, usb: &Path, dry_run: bool) -> Result let record: Option = esp .join(RECORD) .is_file() - .then(|| stela_runtime::read_json(&esp.join(RECORD))) + .then(|| read_any_record(&esp.join(RECORD))) .transpose()?; let mut text = String::new(); let mut removals: Vec = Vec::new(); if let Some(record) = &record { - ensure!( - record.kind == RECORD_KIND && (1..=RECORD_SCHEMA).contains(&record.schema_version), - "{} is not a setup record this version understands", - esp.join(RECORD).display() - ); - let mut record = record.clone(); - record.migrate(); let directories: Vec = record .payload_directory .iter() @@ -2738,11 +2605,7 @@ fn uninstall(environment: &Environment<'_>, usb: &Path, dry_run: bool) -> Result writeln!(text, " remove {}", esp.join(file).display())?; } } - for install in record.iter().flat_map(|r| { - let mut r = r.clone(); - r.migrate(); - r.installs - }) { + for install in record.iter().flat_map(|r| r.installs.iter()) { writeln!( text, " keep install \"{}\": {} keep macOS, its NVRAM and SEP state{}; delete them \ @@ -3030,7 +2893,8 @@ mod tests { install: None, ecid: None, new_ecid: false, - tss: false, + // Every setup installs macOS, which needs the opt-in. + tss: true, no_tss: false, profile: false, no_profile: false, @@ -3067,14 +2931,8 @@ mod tests { } } - /// A stand-in for `boot prepare --recovery`: the synthetic IPSW has no + /// A stand-in for `boot prepare --restore`: the synthetic IPSW has no /// kernel to prepare. The bundle's byte names the machine. - fn fake_prepare(_: &Path, _: &str, ecid: Option, _: bool, output: &Path) -> Result<()> { - let byte = ecid.map_or(0x5a, |e| e.0 as u8); - bundle::tests::write(output, current(), &[byte; 4096]) - } - - /// A stand-in for `boot prepare --restore`. fn fake_prepare_restore( _: &Path, _: &str, @@ -3118,7 +2976,6 @@ mod tests { Environment { host, download: None, - prepare: &fake_prepare, prepare_restore: &fake_prepare_restore, prepare_update: &fake_prepare_update, inventory: &fake_inventory, @@ -3129,10 +2986,10 @@ mod tests { } } - /// Stand-ins for the recoveryOS, restore and update restore `boot - /// prepare` of a stela whose loader prepares `revision`; each bundle's - /// byte names its machine, kind and revision. - fn preparers(revision: u32) -> [Box; 3] { + /// Stand-ins for the restore and update restore `boot prepare` of a + /// stela whose loader prepares `revision`; each bundle's byte names its + /// machine, kind and revision. + fn preparers(revision: u32) -> [Box; 2] { let of = |kind: u8, bytes: usize| -> Box { Box::new( move |_: &Path, _: &str, ecid: Option, _: bool, output: &Path| { @@ -3145,19 +3002,18 @@ mod tests { }, ) }; - [of(0, 4096), of(0xa5, 2048), of(0x3c, 1024)] + [of(0xa5, 2048), of(0x3c, 1024)] } /// The environment of a stela whose loader prepares `revision`. fn environment_at<'a>( host: &'a FakeHost, - preparers: &'a [Box; 3], + preparers: &'a [Box; 2], revision: u32, ) -> Environment<'a> { Environment { - prepare: &*preparers[0], - prepare_restore: &*preparers[1], - prepare_update: &*preparers[2], + prepare_restore: &*preparers[0], + prepare_update: &*preparers[1], bundle_revision: revision, ..environment(host) } @@ -3181,54 +3037,82 @@ mod tests { } fn record(f: &Fixture) -> Record { - let mut record: Record = stela_runtime::read_json(&f.esp.join(RECORD)).unwrap(); - record.migrate(); - record + stela_runtime::read_json(&f.esp.join(RECORD)).unwrap() } - /// The active build's bundle of `ecid`'s machine. + /// The active build's restore bundle of `ecid`'s machine. fn bundle_of(f: &Fixture, ecid: Option) -> PathBuf { let record = record(f); - bundle::directory(&record.volume, &record.build, ecid, record.generation()) + bundle::directory_of( + Kind::Restore, + &record.volume, + &record.build, + ecid, + record.generation(), + ) } #[test] - fn setup_boots_recovery_from_the_usb_and_uninstall_restores_it() { - let f = fixture(64 * GIB, false); - let before = (snapshot(&f.esp), snapshot(&f.data)); + fn setup_installs_from_the_usb_and_uninstall_restores_it() { + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); + let volume = stela_volume(&f); + let before = (snapshot(&f.esp), snapshot(&f.data), snapshot(&volume)); let host = &f.host; + // A setup installs macOS, which needs the signing opt-in. + let mut no_tss = command(&f, &f.esp); + no_tss.tss = false; + let error = setup(&environment(host), no_tss).unwrap_err().to_string(); + assert!(error.contains("needs --tss"), "{error}"); + assert!(error.contains("gs.apple.com"), "{error}"); + assert_eq!( + (snapshot(&f.esp), snapshot(&f.data), snapshot(&volume)), + before + ); + let mut dry = command(&f, &f.esp); dry.dry_run = true; let plan = setup(&environment(host), dry).unwrap(); assert!(plan.contains("Dry run: nothing was changed."), "{plan}"); - assert!(plan.contains("boots recoveryOS"), "{plan}"); + assert!(plan.contains("the disk's own recoveryOS"), "{plan}"); assert!(plan.contains("ECID 0x"), "{plan}"); - assert!(plan.contains("Reinstall macOS downloads"), "{plan}"); - assert_eq!((snapshot(&f.esp), snapshot(&f.data)), before); + assert!(plan.contains("restore "), "{plan}"); + assert!(!plan.contains("recoveryOS "), "{plan}"); + assert_eq!( + (snapshot(&f.esp), snapshot(&f.data), snapshot(&volume)), + before + ); let report = setup(&environment(host), command(&f, &f.esp)).unwrap(); assert!(report.contains("stela setup --uninstall"), "{report}"); - assert!(report.contains("Reinstall macOS"), "{report}"); + assert!(report.contains("pick the PC disk"), "{report}"); let record = record(&f); - let ecid = record.ecid.unwrap(); + let ecid = record.installs[0].ecid.unwrap(); assert_ne!(ecid.0, 0); + let options = fs::read_to_string(f.esp.join("EFI/stela/stela.cfg")).unwrap(); assert_eq!( - fs::read_to_string(f.esp.join("EFI/stela/stela.cfg")).unwrap(), + options, format!( - "--system --bundle \\EFI\\stela\\boot\\{}\\{}\n", - restore::payload::SYNTHETIC_BUILD, - bundle::leaf(Some(ecid), current()) + "--system --storage @disk --nor @disk --preboot @disk --ecid {ecid} \ + --external-disks --guest-network --tss\n" ) ); + assert!(!options.contains("--bundle"), "{options}"); + // The only bundle is the machine's restore bundle. + assert_eq!(record.bundles.len(), 1); + assert_eq!(record.bundles[0].kind, Kind::Restore); let bundle = bundle_of(&f, Some(ecid)); assert_eq!( fs::read(bundle.join("ramdisk.img")).unwrap(), - vec![ecid.0 as u8; 4096] + vec![ecid.0 as u8 ^ 0xa5; 2048] ); assert!(bundle::verify(&bundle, &record.bundles[0].manifest_sha256).is_empty()); assert!(!f.esp.join("EFI/stela/source.bin").exists()); - assert!(!f.esp.join(CHOICES_PATH).exists()); + let choices = + Choices::parse(&fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap()).unwrap(); + let names: Vec<&str> = choices.entries.iter().map(|e| e.name.as_str()).collect(); + assert_eq!(names, ["macOS", INSTALL_CHOICE]); assert_eq!( fs::read(f.esp.join(efi::LOADER)).unwrap(), efi_image(b"stela") @@ -3238,13 +3122,21 @@ mod tests { // A second setup is refused until the first is undone. let again = setup(&environment(host), command(&f, &f.esp)); assert!(again.unwrap_err().to_string().contains("--uninstall")); + // The only install is not removed alone. + let error = rerun(&f, |c| c.remove_install = Some("macOS".into())) + .unwrap_err() + .to_string(); + assert!(error.contains("only one"), "{error}"); let dry = uninstall(&environment(host), &f.esp, true).unwrap(); assert!(dry.contains("Dry run")); assert!(bundle.is_dir()); let done = uninstall(&environment(host), &f.esp, false).unwrap(); assert!(done.contains("Done.")); - assert_eq!((snapshot(&f.esp), snapshot(&f.data)), before); + assert_eq!( + (snapshot(&f.esp), snapshot(&f.data), snapshot(&volume)), + before + ); } #[test] @@ -3277,12 +3169,15 @@ mod tests { .unwrap_err() .to_string(); assert!(error.contains("use FAT32"), "{error}"); - assert!(error.contains("recoveryOS bundle needs"), "{error}"); - // A FAT data volume holds the bundle; the EFI partition keeps only - // the boot loader and stela.cfg. + assert!(error.contains("restore bundles need"), "{error}"); + // A FAT data volume holds the bundle and the online install's + // inventory; the EFI partition keeps only the boot loader and its + // configuration. let f = fixture(GIB / 32, true); - setup(&environment(&f.host), command(&f, &f.data)).unwrap(); - let ecid = record(&f).ecid; + let mut online = command(&f, &f.data); + online.install_image = Some(InstallImage::Online); + setup(&environment(&f.host), online).unwrap(); + let ecid = record(&f).installs[0].ecid; assert!(bundle_of(&f, ecid).join("ramdisk.img").is_file()); assert!(bundle_of(&f, ecid).starts_with(&f.data)); assert!(!f.esp.join("EFI/stela/boot").exists()); @@ -3293,7 +3188,8 @@ mod tests { #[test] fn usbs_setup_cannot_boot_from_are_explained_and_left_unchanged() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); // A USB without an EFI partition, one whose partition is not // mounted, and one that already boots another loader. let dir = tempfile::tempdir().unwrap(); @@ -3305,6 +3201,7 @@ mod tests { .to_string(); assert!(error.contains("names its whole disk"), "{error}"); let mut host = FakeHost::new(f.host.volumes.clone(), f.host.disks.clone()); + host.partitions = f.host.partitions.clone(); // An unmounted EFI partition is mounted, or the error says why not. host.disks[1].partitions[0].mount = None; let error = setup(&environment(&host), command(&f, &f.data)) @@ -3373,15 +3270,16 @@ mod tests { uninstall(&environment(&f.host), &f.esp, false).unwrap(); assert_eq!(snapshot(&f.esp), before); - // Schema 3, with one installed disk and a bundle without an ECID: - // the disk becomes the first install, the bundle is listed. + // Schema 7, with a recoveryOS bundle on the USB: this stela no longer + // reads it, and uninstalls it. let f = fixture(64 * GIB, false); let before = snapshot(&f.esp); - // A schema 3 setup's stela.efi has no interface marker. efi::add_mount(&f.esp, &f.efi, None, Some("--system\n")).unwrap(); - fs::write(f.esp.join(efi::LOADER), b"MZstela-old").unwrap(); - let legacy = f.esp.join("EFI/stela/boot/STELA1/recovery"); - bundle::tests::write(&legacy, bundle::Generation::FIRST, b"old").unwrap(); + let build = f.esp.join("EFI/stela/boot/STELA1"); + let recovery = build.join("recovery-0000000000000001"); + let restore = build.join("restore-0000000000000001"); + bundle::tests::write(&recovery, bundle::Generation::FIRST, b"old").unwrap(); + bundle::tests::write(&restore, bundle::Generation::FIRST, b"old").unwrap(); let disk = installed::InstalledDisk { apple_region: REGION.into(), apple_region_serial: SERIAL.into(), @@ -3392,36 +3290,39 @@ mod tests { machine_state_offset: None, external_disks: false, }; + let mut install = serde_json::to_value(&disk).unwrap(); + install["name"] = "macOS".into(); + install["ecid"] = "0x1".into(); let record = serde_json::json!({ - "schema_version": 3, + "schema_version": 7, "kind": RECORD_KIND, "build": "STELA1", "model": "Mac14,3", "esp": f.esp, "volume": f.esp, - "bundle_directory": f.esp.join("EFI/stela/boot/STELA1"), - "created_directories": [f.esp.join("EFI/stela/boot/STELA1"), f.esp.join("EFI/stela/boot")], + "bundle_directory": build, + "created_directories": [build, f.esp.join("EFI/stela/boot")], "options": "--system\n", "complete": true, - "installed": disk, "recovery_builds": ["STELA1"], + "ecid": "0x1", + "installs": [install], + "bundles": [ + {"build": "STELA1", "ecid": "0x1", "schema": 1, "manifest_sha256": ""}, + {"build": "STELA1", "ecid": "0x1", "schema": 1, "manifest_sha256": "", + "kind": "restore", "personalized": true}, + ], }); stela_runtime::write_json(&f.esp.join(RECORD), &record).unwrap(); - let migrated = read_record(&environment(&f.host), &f.esp).unwrap(); - assert_eq!(migrated.installs.len(), 1); - assert_eq!(migrated.installs[0].disk, disk); - assert_eq!(migrated.installs[0].ecid, None); - assert_eq!(migrated.bundles.len(), 1); - assert_eq!(migrated.missing_bundles("STELA1"), Vec::new()); - assert!( - migrated - .options_text() - .split_ascii_whitespace() - .any(|word| word.ends_with("\\boot\\STELA1\\recovery")) - ); - // The markerless stela.efi it has must be updated before changes. - let error = rerun(&f, |c| c.no_tss = true).unwrap_err().to_string(); - assert!(error.contains("--update-stela"), "{error}"); + let error = read_record(&environment(&f.host), &f.esp) + .unwrap_err() + .to_string(); + assert!(error.contains("schema 7 setup"), "{error}"); + assert!(error.contains("--uninstall"), "{error}"); + let error = rerun(&f, |c| c.status = true).unwrap_err().to_string(); + assert!(error.contains("no longer reads"), "{error}"); + let dry = uninstall(&environment(&f.host), &f.esp, true).unwrap(); + assert!(dry.contains("keep install \"macOS\""), "{dry}"); uninstall(&environment(&f.host), &f.esp, false).unwrap(); assert_eq!(snapshot(&f.esp), before); } @@ -3583,7 +3484,9 @@ mod tests { fn a_raw_partition_of_the_usb_is_the_macs_ssd_and_the_pc_disks_external() { let mut f = fixture(64 * GIB, false); add_stick_ssd(&mut f, "disk5s4", REGION_GUID); - let error = setup(&environment(&f.host), command(&f, &f.esp)) + let mut no_tss = command(&f, &f.esp); + no_tss.tss = false; + let error = setup(&environment(&f.host), no_tss) .unwrap_err() .to_string(); assert!(error.contains("needs --tss"), "{error}"); @@ -3746,6 +3649,8 @@ mod tests { let mut command = command(f, &f.esp); command.ipsw = None; command.model = None; + // Commands on an existing setup leave the opt-in as it is. + command.tss = false; configure(&mut command); command.dispatch(&environment(&f.host)) } @@ -3924,7 +3829,6 @@ mod tests { assert!(report.contains("gs.apple.com"), "{report}"); let record = record(&f); let ecid = record.installs[0].ecid.unwrap(); - assert_eq!(record.ecid, Some(ecid)); // The restore boots under the ticket Apple personalized for it. assert!( record @@ -3932,55 +3836,40 @@ mod tests { .is_some_and(|b| b.personalized) ); let region = format!("{SERIAL}:{REGION_GUID}"); - let recovery = format!( - "\\EFI\\stela\\boot\\{}\\{}", - restore::payload::SYNTHETIC_BUILD, - bundle::leaf(Some(ecid), current()) - ); let line = format!( "--system --storage {region} --nor {SERIAL}:{NOR_GUID} --preboot {region} \ - --recovery-bundle {recovery} --ecid {ecid} --tss" + --ecid {ecid} --tss" ); assert_eq!( fs::read_to_string(f.esp.join("EFI/stela/stela.cfg")).unwrap(), format!("{line}\n") ); - // The startup choices hold the install, its System Recovery and - // Install macOS, and open on their own. + // The startup choices hold the install and Install macOS, and open + // on their own. let choices = Choices::parse(&fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap()).unwrap(); assert_eq!(choices.timeout_seconds, CHOOSER_SECONDS); + assert_eq!(choices.entries.len(), 2); assert_eq!(choices.entries[0].name, "macOS"); assert_eq!(choices.entries[0].options, line); - assert_eq!(choices.entries[1].name, "macOS Recovery"); - assert_eq!( - choices.entries[1].options, - format!( - "--system --storage {region} --nor {SERIAL}:{NOR_GUID} --bundle {recovery} \ - --ecid {ecid} --tss" - ) - ); - // That line is what stela.efi routes a System Recovery choice to. + // stela.efi routes a disk without an installed system to the disk's + // System Recovery, and refuses one that holds none. let mut selection = stela_loader::boot_selection::select( &Variables::parse(&stela_runtime::machine::apple::nor::nvram::empty_bank()).unwrap(), ) .unwrap(); selection.missing_boot_media(); + assert!(stela_loader::boot_selection::route(&line, Some(&selection)).is_err()); + selection.system_on_disk = true; let (routed, _) = stela_loader::boot_selection::route(&line, Some(&selection)).unwrap(); - let mut routed: Vec<&str> = routed.split_ascii_whitespace().collect(); - let mut expected: Vec<&str> = choices.entries[1] - .options - .split_ascii_whitespace() - .collect(); - routed.sort_unstable(); - expected.sort_unstable(); - assert_eq!(routed, expected); + assert!(routed.contains(&format!("--preboot {region}")), "{routed}"); + assert!(routed.ends_with("--system-recovery"), "{routed}"); // Install macOS restores the install medium onto the disk // with the machine's restore bundle. let build = restore::payload::SYNTHETIC_BUILD; - assert_eq!(choices.entries[2].name, INSTALL_CHOICE); + assert_eq!(choices.entries[1].name, INSTALL_CHOICE); assert_eq!( - choices.entries[2].options, + choices.entries[1].options, format!( "--system --storage {region} --nor {SERIAL}:{NOR_GUID} --bundle \ \\EFI\\stela\\boot\\{build}\\{} --ecid {ecid} \ @@ -4047,7 +3936,7 @@ mod tests { ); let choices = Choices::parse(&fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap()).unwrap(); - assert_eq!(choices.entries.len(), 2); + assert_eq!(choices.entries.len(), 1); // Its personalized restore bundle no longer serves the setup. let off = self::record(&f); assert_eq!( @@ -4249,10 +4138,12 @@ mod tests { let mut f = fixture(64 * GIB, false); add_installed_disk(&mut f, &[], &[]); add_disk(&mut f, true, &[], &[]); - // Set up without a disk first; the first install takes over the - // setup's machine and its bundle. - setup(&environment(&f.host), command(&f, &f.esp)).unwrap(); - let first = record(&f).ecid.unwrap(); + setup(&environment(&f.host), installed_command(&f)).unwrap(); + let record1 = record(&f); + let first = record1.installs[0].ecid.unwrap(); + let kinds: Vec = record1.bundles.iter().map(|b| b.kind).collect(); + assert_eq!(kinds, [Kind::Restore]); + assert!(record1.active_medium().unwrap().problems().is_empty()); let add = |target: &str, nor: &str, ipsw: bool, dry_run: bool| { rerun(&f, |c| { c.target = Some(target.into()); @@ -4262,25 +4153,8 @@ mod tests { c.tss = true; }) }; - // An install restores from the IPSW, which it needs. - let error = add(REGION, NOR, false, false).unwrap_err().to_string(); - assert!(error.contains("is installed from the macOS"), "{error}"); - // A fresh install requires the signing-service opt-in. - let error = rerun(&f, |c| { - c.target = Some(REGION.into()); - c.nor = Some(NOR.into()); - c.ipsw = Some(f.ipsw.clone()); - }) - .unwrap_err() - .to_string(); - assert!(error.contains("needs --tss"), "{error}"); - add(REGION, NOR, true, false).unwrap(); - let record1 = record(&f); - assert_eq!(record1.installs[0].ecid, Some(first)); - let kinds: Vec = record1.bundles.iter().map(|b| b.kind).collect(); - assert_eq!(kinds, [Kind::Recovery, Kind::Restore]); - assert!(record1.active_medium().unwrap().problems().is_empty()); - // The second is a new machine and needs its own bundles. + // The second is a new machine and needs its own bundle, which it + // restores with from the IPSW. let error = add(REGION2, NOR2, false, false).unwrap_err().to_string(); assert!(error.contains("is installed from the macOS"), "{error}"); let before = snapshot(&f.esp); @@ -4293,7 +4167,7 @@ mod tests { assert_eq!(record2.installs[1].name, "macOS 2"); assert_eq!( fs::read(bundle_of(&f, Some(second)).join("ramdisk.img")).unwrap(), - vec![second.0 as u8; 4096] + vec![second.0 as u8 ^ 0xa5; 2048] ); // The same partitions are not added twice. assert!( @@ -4310,10 +4184,8 @@ mod tests { names, [ "macOS", - "macOS Recovery", "macOS - Install macOS", "macOS 2", - "macOS 2 Recovery", "macOS 2 - Install macOS" ] ); @@ -4325,7 +4197,7 @@ mod tests { Some(second), record2.generation(), ); - assert!(choices().entries[5].options.contains(&format!( + assert!(choices().entries[3].options.contains(&format!( "--bundle \\EFI\\stela\\boot\\{}\\restore-{}", record2.build, second.digits() @@ -4369,7 +4241,7 @@ mod tests { assert_eq!(partition_bytes(&f, NOR2), nor2); // The list still opens on its own while the USB can install macOS. assert_eq!(choices().timeout_seconds, CHOOSER_SECONDS); - assert_eq!(choices().entries[2].name, INSTALL_CHOICE); + assert_eq!(choices().entries[1].name, INSTALL_CHOICE); assert_eq!(record(&f).installs.len(), 1); uninstall(&environment(&f.host), &f.esp, false).unwrap(); assert!(!f.esp.join("EFI/stela").exists()); @@ -4377,7 +4249,8 @@ mod tests { #[test] fn same_stela_update_replenishes_only_the_cache_and_preserves_custom_options() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); let mut first = command(&f, &f.esp); first.translation_store_bytes = Some(translations::MIN_PACK_BYTES); setup(&environment(&f.host), first).unwrap(); @@ -4419,7 +4292,8 @@ mod tests { #[test] fn cache_spare_failure_blocks_efi_activation_and_update_or_rollback_can_retry() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); let mut first = command(&f, &f.esp); first.translation_store_bytes = Some(translations::MIN_PACK_BYTES); setup(&environment(&f.host), first).unwrap(); @@ -4476,7 +4350,8 @@ mod tests { #[test] fn stela_update_and_rollback_with_disabled_cache_create_no_store() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); let mut first = command(&f, &f.esp); first.translation_store_bytes = Some(0); setup(&environment(&f.host), first).unwrap(); @@ -4499,7 +4374,8 @@ mod tests { #[test] fn stela_updates_keep_the_old_version_and_roll_back() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); let before = snapshot(&f.esp); setup(&environment(&f.host), command(&f, &f.esp)).unwrap(); let tool = f.esp.join(efi::LOADER); @@ -4517,7 +4393,7 @@ mod tests { assert_eq!(fs::read(&tool).unwrap(), efi_image(b"stela")); // Packs of four translators and a damaged one: the update keeps the // three newest intact ones. - let packs = f.esp.join(translations::DIRECTORY); + let packs = record(&f).translations.unwrap().directory(); assert!(packs.join(translations::CONFIG).is_file()); let written: Vec = (0..4u8) .map(|n| { @@ -4582,13 +4458,15 @@ mod tests { #[test] fn a_stela_update_to_a_new_bundle_schema_prepares_new_bundles_and_rolls_back() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); setup(&environment(&f.host), command(&f, &f.esp)).unwrap(); let old_schema = record(&f).bundle_schema; let next_schema = old_schema.checked_add(1).unwrap(); - let ecid = record(&f).ecid; + let ecid = record(&f).installs[0].ecid; let old = bundle_of(&f, ecid); - let options = || fs::read_to_string(f.esp.join("EFI/stela/stela.cfg")).unwrap(); + // The Install macOS choice names the restore bundle. + let options = || fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap(); let first = options(); // A later stela and stela.efi read the next schema. let newer = mount_interface::Interface { @@ -4607,7 +4485,7 @@ mod tests { ) }; let environment = Environment { - prepare: &prepare, + prepare_restore: &prepare, interface: newer, ..environment(&f.host) }; @@ -4630,7 +4508,7 @@ mod tests { let record2 = record(&f); assert_eq!(record2.bundle_schema, next_schema); let migrated = bundle_of(&f, ecid); - let leaf = bundle::leaf(ecid, next_generation); + let leaf = bundle::leaf_of(Kind::Restore, ecid, next_generation); assert!( migrated.ends_with(&leaf) && leaf.contains(&format!("-s{next_schema}")), "{leaf}" @@ -4660,7 +4538,6 @@ mod tests { setup(&old, installed_command(&f)).unwrap(); let path = f.esp.join(RECORD); let mut json: serde_json::Value = stela_runtime::read_json(&path).unwrap(); - json["schema_version"] = 6.into(); json.as_object_mut().unwrap().remove("bundle_revision"); for kept in json["bundles"].as_array_mut().unwrap() { kept.as_object_mut().unwrap().remove("revision"); @@ -4677,11 +4554,13 @@ mod tests { revision, ..current() }; - [Kind::Recovery, Kind::Restore] - .map(|kind| { - bundle::directory_of(kind, &first.volume, &first.build, ecid, generation) - }) - .into() + vec![bundle::directory_of( + Kind::Restore, + &first.volume, + &first.build, + ecid, + generation, + )] }; // A later stela prepares revision 1, with the same stela.efi. let new = environment_at(&f.host, &newer, 1); @@ -4736,22 +4615,11 @@ mod tests { // The revision 0 bundles stay for the rollback. assert_eq!(bundle::generation(old).unwrap().revision, 0); } - let [recovery, restore] = &directories(1)[..] else { + let [restore] = &directories(1)[..] else { unreachable!() }; - let leaf = |directory: &Path| { - directory - .file_name() - .unwrap() - .to_string_lossy() - .into_owned() - }; - assert!( - options().contains(&format!("{} ", leaf(recovery))), - "{}", - options() - ); - assert!(choices().contains(&leaf(restore)), "{}", choices()); + let leaf = restore.file_name().unwrap().to_string_lossy().into_owned(); + assert!(choices().contains(&leaf), "{}", choices()); assert!( run(&|c| c.status = true) .unwrap() @@ -4809,21 +4677,28 @@ mod tests { #[test] fn stela_updates_remove_bundles_no_kept_version_boots() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); let preparers: Vec<_> = (0..4).map(preparers).collect(); setup( &environment_at(&f.host, &preparers[0], 0), command(&f, &f.esp), ) .unwrap(); - let ecid = record(&f).ecid; + let ecid = record(&f).installs[0].ecid; let directory = |revision: u32| { let record = record(&f); let generation = bundle::Generation { revision, ..current() }; - bundle::directory(&record.volume, &record.build, ecid, generation) + bundle::directory_of( + Kind::Restore, + &record.volume, + &record.build, + ecid, + generation, + ) }; for revision in 1..4 { let image = f._dir.path().join(format!("stela-{revision}.efi")); @@ -4847,11 +4722,12 @@ mod tests { } #[test] - fn os_updates_add_recoveryos_and_interrupted_updates_finish_or_roll_back() { - let f = fixture(64 * GIB, false); + fn os_updates_add_restore_bundles_and_interrupted_updates_finish_or_roll_back() { + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); let before = snapshot(&f.esp); setup(&environment(&f.host), command(&f, &f.esp)).unwrap(); - let ecid = record(&f).ecid; + let ecid = record(&f).installs[0].ecid; let newer = f._dir.path().join("Newer.ipsw"); restore::payload::synthetic_ipsw_of(&newer, "STELA2").unwrap(); let update = |dry_run: bool| { @@ -4861,22 +4737,29 @@ mod tests { c.dry_run = dry_run; }) }; - let options = || fs::read_to_string(f.esp.join("EFI/stela/stela.cfg")).unwrap(); + // The Install macOS choice names the build's restore bundle. + let options = || fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap(); let first = options(); assert!(update(true).unwrap().contains("Dry run")); assert_eq!(options(), first); let report = update(false).unwrap(); - assert!(report.contains("Reinstall macOS"), "{report}"); + assert!(report.contains("choose Install macOS"), "{report}"); assert!(report.contains("Update volume"), "{report}"); - assert!(options().contains("\\boot\\STELA2\\recovery-")); - let leaf = bundle::leaf(ecid, current()); + assert!(options().contains("\\boot\\STELA2\\restore-")); + let leaf = bundle::leaf_of(Kind::Restore, ecid, current()); assert!( f.esp .join(format!("EFI/stela/boot/STELA2/{leaf}/bundle.json")) .is_file() ); // The old build stays for rollback. - let old = bundle::directory(&f.esp, restore::payload::SYNTHETIC_BUILD, ecid, current()); + let old = bundle::directory_of( + Kind::Restore, + &f.esp, + restore::payload::SYNTHETIC_BUILD, + ecid, + current(), + ); assert!(old.join("bundle.json").is_file()); rerun(&f, |c| c.rollback = true).unwrap(); assert_eq!(options(), first); @@ -4917,14 +4800,6 @@ mod tests { add_installed_disk(&mut f, &[], &[]); setup(&environment(&f.host), installed_command(&f)).unwrap(); let ecid = record(&f).installs[0].ecid.unwrap(); - // A schema 5 record names its one medium as `medium`. - let path = f.esp.join(RECORD); - let mut json: serde_json::Value = stela_runtime::read_json(&path).unwrap(); - let medium = json["media"][0].clone(); - json["schema_version"] = 5.into(); - json["medium"] = medium; - json.as_object_mut().unwrap().remove("media"); - fs::write(&path, serde_json::to_vec(&json).unwrap()).unwrap(); assert_eq!(record(&f).media.len(), 1); assert!( rerun(&f, |c| c.status = true) @@ -4935,7 +4810,7 @@ mod tests { let choices = || Choices::parse(&fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap()).unwrap(); let names: Vec = choices().entries.into_iter().map(|e| e.name).collect(); - assert_eq!(names, ["macOS", "macOS Recovery", INSTALL_CHOICE]); + assert_eq!(names, ["macOS", INSTALL_CHOICE]); let first = restore::payload::SYNTHETIC_BUILD; let newer = f._dir.path().join("Newer.ipsw"); restore::payload::synthetic_ipsw_of(&newer, "STELA2").unwrap(); @@ -4958,7 +4833,7 @@ mod tests { assert_eq!(media, [first, "STELA2"], "the old medium is kept"); assert!(record1.active_medium().unwrap().problems().is_empty()); assert!(record1.restore_bundle(Kind::Restore, Some(ecid)).is_some()); - for entry in &choices().entries[2..3] { + for entry in &choices().entries[1..2] { assert!( entry.options.contains("\\boot\\STELA2\\") && entry.options.contains("\\install\\STELA2\\payload.json"), @@ -4981,7 +4856,7 @@ mod tests { assert_eq!(media, [first]); assert!(!medium::directory(&stela_volume(&f), "STELA2").exists()); assert!( - choices().entries[2] + choices().entries[1] .options .contains(&format!("\\boot\\{first}\\")) ); @@ -5027,7 +4902,7 @@ mod tests { assert_eq!(snapshot(&f.esp), before); // A damaged bundle, tool and stela.cfg are found ... - let ecid = record(&f).ecid; + let ecid = record(&f).installs[0].ecid; let ramdisk = bundle_of(&f, ecid).join("ramdisk.img"); fs::write(&ramdisk, [0u8; 10]).unwrap(); fs::write(f.esp.join(LOADER_PATH), b"MZ damaged").unwrap(); @@ -5054,10 +4929,10 @@ mod tests { }) .unwrap(); // The bundle is the machine's own again, with its ECID. - assert_eq!(record(&f).ecid, ecid); + assert_eq!(record(&f).installs[0].ecid, ecid); assert_eq!( fs::read(&ramdisk).unwrap(), - vec![ecid.unwrap().0 as u8; 4096] + vec![ecid.unwrap().0 as u8 ^ 0xa5; 2048] ); assert_eq!(snapshot(&f.esp), before); status().unwrap(); @@ -5065,7 +4940,6 @@ mod tests { // A machine an older setup made without an ECID gets one. let mut old = record(&f); old.installs[0].ecid = None; - old.ecid = None; write_record(&f.esp, &old).unwrap(); let error = status().unwrap_err().to_string(); assert!(error.contains("has no ECID"), "{error}"); @@ -5076,7 +4950,6 @@ mod tests { .unwrap(); let repaired = record(&f); let new = repaired.installs[0].ecid.unwrap(); - assert_eq!(repaired.ecid, Some(new)); assert!(bundle_of(&f, Some(new)).join("bundle.json").is_file()); status().unwrap(); } @@ -5159,7 +5032,7 @@ mod tests { add_installed_disk(&mut f, &[], &[]); setup(&environment(&f.host), installed_command(&f)).unwrap(); let before = snapshot(&f.esp); - let directory = bundle_of(&f, record(&f).ecid); + let directory = bundle_of(&f, record(&f).installs[0].ecid); // The stop came after the old bundle was set aside, before the new // copy was renamed into place. let (partial, previous) = bundle::siblings(&directory).unwrap(); @@ -5474,26 +5347,26 @@ mod tests { ); let ecid = record.installs[0].ecid.unwrap(); let region = format!("{SERIAL}:{REGION_GUID}"); - let recovery = format!( + let restore = format!( "\\EFI\\stela\\boot\\{}\\{}", restore::payload::SYNTHETIC_BUILD, - bundle::leaf(Some(ecid), current()) + bundle::leaf_of(Kind::Restore, Some(ecid), current()) ); assert_eq!( fs::read_to_string(f.esp.join("EFI/stela/stela.cfg")).unwrap(), format!( - "--system --storage {region} --nor {region} --preboot {region} \ - --recovery-bundle {recovery} --ecid {ecid} --tss\n" + "--system --storage {region} --nor {region} --preboot {region} --ecid {ecid} \ + --tss\n" ) ); let choices = Choices::parse(&fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap()).unwrap(); - assert_eq!( - choices.entries[1].options, - format!( - "--system --storage {region} --nor {region} --bundle {recovery} \ - --ecid {ecid} --tss" - ) + assert!( + choices.entries[1].options.starts_with(&format!( + "--system --storage {region} --nor {region} --bundle {restore} --ecid {ecid} " + )), + "{}", + choices.entries[1].options ); // Setup itself wrote neither the SSD nor the machine state. assert!( @@ -5719,15 +5592,15 @@ mod tests { Choices::parse(&fs::read_to_string(f.esp.join(CHOICES_PATH)).unwrap()).unwrap(); let region2 = format!("{SERIAL2}:{REGION2_GUID}"); assert!( - choices.entries[3] + choices.entries[2] .options .contains(&format!("--storage {region2} --nor {region2}")), "{}", - choices.entries[3].options + choices.entries[2].options ); // Its Install choice restores onto the region with the tail kept. - assert_eq!(choices.entries[5].name, "Other - Install macOS"); - for entry in &choices.entries[5..6] { + assert_eq!(choices.entries[3].name, "Other - Install macOS"); + for entry in &choices.entries[3..4] { assert!( entry .options @@ -5739,7 +5612,8 @@ mod tests { } #[test] fn observed_firmware_setup_action_requires_capability_and_preserves_dry_run() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); setup(&environment(&f.host), command(&f, &f.esp)).unwrap(); let inventory = f._dir.path().join("observed-firmware.json"); fs::write(&inventory, br#"{"schema":1,"complete":true,"requirements":[{"name":"rtl_nic/rtl8168e-3.fw","target":{"driver":"realtek","hardware":"10ec:8168","revision":"xid-2c8","board":null},"minimum_bytes":4}]}"#).unwrap(); @@ -5791,7 +5665,8 @@ mod tests { fn large_firmware_refuses_legacy_install_update_rollback_and_reinstall_before_writes() { use sha2::{Digest, Sha256}; use stela_loader::host_firmware::{DIRECTORY, MOUNT_CAPABILITY, Package}; - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); setup(&environment(&f.host), command(&f, &f.esp)).unwrap(); let legacy = f._dir.path().join("firmware-v1.efi"); let mut marker = MOUNT_CAPABILITY; @@ -5897,7 +5772,8 @@ mod tests { #[test] fn host_firmware_action_validates_dry_run_and_publishes_separately_from_guest_bundles() { - let f = fixture(64 * GIB, false); + let mut f = fixture(64 * GIB, false); + add_stela(&mut f); setup(&environment(&f.host), command(&f, &f.esp)).unwrap(); let source = f._dir.path().join("firmware-package"); fs::create_dir(&source).unwrap(); diff --git a/crates/stela-cli/src/setup/bundle.rs b/crates/stela-cli/src/setup/bundle.rs index 9e0450a9f5..401732c0c9 100644 --- a/crates/stela-cli/src/setup/bundle.rs +++ b/crates/stela-cli/src/setup/bundle.rs @@ -4,9 +4,6 @@ //! the loader that prepared it) and [`Kind`], in //! `EFI/stela/boot//` of the bundle volume: //! -//! - `recovery`: a recoveryOS bundle from before machines had ECIDs, schema -//! 1, revision 0; -//! - `recovery-`: a machine's recoveryOS bundle, schema 1, revision 0; //! - `restore-`: a machine's restore bundle (`stela boot prepare //! --restore`), which the Install macOS choice boots; //! - `update-`: a machine's update restore bundle (`stela boot @@ -34,7 +31,6 @@ use std::{ }; pub(super) const MANIFEST: &str = "bundle.json"; -const LEGACY_LEAF: &str = "recovery"; /// The schema bundles without a suffix have. const FIRST_SCHEMA: u32 = 1; /// The revision bundles without a suffix have, and that of a `bundle.json` @@ -51,6 +47,7 @@ pub(super) struct Generation { pub(super) revision: u32, } +#[cfg(test)] impl Generation { /// Schema 1, revision 0: every bundle from before setups recorded /// revisions. @@ -70,12 +67,11 @@ impl std::fmt::Display for Generation { #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub(super) enum Kind { - /// recoveryOS (`boot prepare --recovery`). - #[default] - Recovery, /// The restore ramdisk (`boot prepare --restore`). + #[default] Restore, - /// The update restore ramdisk (`boot prepare --restore --update`). + /// The update restore ramdisk (`boot prepare --restore --update`), + /// which earlier setups prepared. Update, } @@ -86,13 +82,12 @@ pub(super) enum Kind { pub(super) const RESTORE_KINDS: [Kind; 1] = [Kind::Restore]; impl Kind { - fn is_recovery(&self) -> bool { - *self == Self::Recovery + fn is_restore(&self) -> bool { + *self == Self::Restore } fn prefix(self) -> &'static str { match self { - Self::Recovery => LEGACY_LEAF, Self::Restore => "restore", Self::Update => "update", } @@ -101,7 +96,6 @@ impl Kind { /// What it is called in reports. pub(super) fn label(self) -> &'static str { match self { - Self::Recovery => "recoveryOS", Self::Restore => "restore", Self::Update => "update restore", } @@ -122,7 +116,7 @@ pub(super) struct Bundle { /// wrote without recording it. #[serde(default)] pub(super) manifest_sha256: String, - #[serde(default, skip_serializing_if = "Kind::is_recovery")] + #[serde(default, skip_serializing_if = "Kind::is_restore")] pub(super) kind: Kind, /// A restore bundle that boots under the AP ticket Apple's signing /// service personalized for its machine (`boot prepare --tss`), not the @@ -139,12 +133,6 @@ impl Bundle { } } - /// Whether it is the recoveryOS bundle of `build`, `ecid` and - /// `generation`. - pub(super) fn same(&self, build: &str, ecid: Option, generation: Generation) -> bool { - self.same_kind(Kind::Recovery, build, ecid, generation) - } - pub(super) fn same_kind( &self, kind: Kind, @@ -164,12 +152,6 @@ impl Bundle { } } -/// A recoveryOS bundle's leaf. -#[cfg(test)] -pub(super) fn leaf(ecid: Option, generation: Generation) -> String { - leaf_of(Kind::Recovery, ecid, generation) -} - pub(super) fn leaf_of(kind: Kind, ecid: Option, generation: Generation) -> String { let prefix = kind.prefix(); let mut leaf = match ecid { @@ -190,16 +172,6 @@ pub(super) fn build_directory(volume: &Path, build: &str) -> PathBuf { volume.join(format!("EFI/stela/boot/{build}")) } -/// The recoveryOS bundle's directory on `volume`. -pub(super) fn directory( - volume: &Path, - build: &str, - ecid: Option, - generation: Generation, -) -> PathBuf { - directory_of(Kind::Recovery, volume, build, ecid, generation) -} - pub(super) fn directory_of( kind: Kind, volume: &Path, @@ -210,12 +182,6 @@ pub(super) fn directory_of( build_directory(volume, build).join(leaf_of(kind, ecid, generation)) } -/// The recoveryOS bundle's directory as `stela.cfg` names it on the -/// firmware's volume. -pub(super) fn firmware_path(build: &str, ecid: Option, generation: Generation) -> String { - firmware_path_of(Kind::Recovery, build, ecid, generation) -} - pub(super) fn firmware_path_of( kind: Kind, build: &str, @@ -487,21 +453,18 @@ pub(super) mod tests { #[test] fn bundles_are_named_by_machine_schema_and_revision() { - assert_eq!(leaf(None, Generation::FIRST), "recovery"); + let restore = |ecid, generation| leaf_of(Kind::Restore, ecid, generation); + assert_eq!(restore(None, Generation::FIRST), "restore"); assert_eq!( - leaf(Some(Ecid(0xab)), Generation::FIRST), - "recovery-00000000000000AB" + restore(Some(Ecid(0xab)), Generation::FIRST), + "restore-00000000000000AB" ); + assert_eq!(restore(None, of(3, 0)), "restore-s3"); assert_eq!( - leaf(Some(Ecid(0xab)), of(2, 0)), - "recovery-00000000000000AB-s2" + restore(Some(Ecid(0xab)), of(1, 4)), + "restore-00000000000000AB-r4" ); - assert_eq!(leaf(None, of(3, 0)), "recovery-s3"); - assert_eq!( - leaf(Some(Ecid(0xab)), of(1, 4)), - "recovery-00000000000000AB-r4" - ); - assert_eq!(leaf(None, of(2, 1)), "recovery-s2-r1"); + assert_eq!(restore(None, of(2, 1)), "restore-s2-r1"); assert_eq!( leaf_of(Kind::Restore, Some(Ecid(0xab)), of(2, 0)), "restore-00000000000000AB-s2" @@ -514,10 +477,6 @@ pub(super) mod tests { firmware_path_of(Kind::Update, "26A434", Some(Ecid(1)), of(1, 2)), "\\EFI\\stela\\boot\\26A434\\update-0000000000000001-r2" ); - assert_eq!( - firmware_path("26A434", Some(Ecid(1)), Generation::FIRST), - "\\EFI\\stela\\boot\\26A434\\recovery-0000000000000001" - ); } #[test] @@ -541,7 +500,7 @@ pub(super) mod tests { let dir = tempfile::tempdir().unwrap(); let prepared = dir.path().join("prepared"); write(&prepared, Generation::FIRST, &[0x5a; 4096]).unwrap(); - let destination = dir.path().join("boot/B/recovery"); + let destination = dir.path().join("boot/B/restore"); fs::create_dir_all(destination.parent().unwrap()).unwrap(); let digest = install(&prepared, &destination).unwrap(); assert!(verify(&destination, &digest).is_empty()); @@ -551,7 +510,7 @@ pub(super) mod tests { let second = install(&prepared, &destination).unwrap(); assert_ne!(second, digest); assert_eq!(generation(&destination).unwrap(), of(2, 1)); - assert!(!dir.path().join("boot/B/recovery.partial").exists()); + assert!(!dir.path().join("boot/B/restore.partial").exists()); assert!(!verify(&destination, &digest).is_empty()); fs::write(destination.join("ramdisk.img"), [0x34; 100]).unwrap(); let problems = verify(&destination, &second); @@ -568,7 +527,7 @@ pub(super) mod tests { let dir = tempfile::tempdir().unwrap(); let prepared = dir.path().join("prepared"); let build = dir.path().join("boot/B"); - let destination = build.join("recovery"); + let destination = build.join("restore"); fs::create_dir_all(&build).unwrap(); write(&prepared, Generation::FIRST, &[0x5a; 4096]).unwrap(); let first = install(&prepared, &destination).unwrap(); diff --git a/crates/stela-cli/src/setup/doctor.rs b/crates/stela-cli/src/setup/doctor.rs index 1298c300d9..6e253371d9 100644 --- a/crates/stela-cli/src/setup/doctor.rs +++ b/crates/stela-cli/src/setup/doctor.rs @@ -3,8 +3,8 @@ //! Status reads everything a setup consists of and changes nothing: the //! record and any pending update, the installed `stela.efi` against its //! kept version and this `stela`'s mount interface, the USB's boot loader, -//! `stela.cfg` and the startup choices against the record, every recoveryOS -//! and restore bundle file against its `bundle.json` and the active ones' +//! `stela.cfg` and the startup choices against the record, every restore +//! bundle file against its `bundle.json` and the active ones' //! revision against the one this `stela` prepares, the install medium's //! manifest and pieces, and for each install its //! partitions (still the recorded ones), the systems on its Apple region, @@ -15,15 +15,14 @@ //! Repair puts back what the record says: the active `stela.efi` from its //! kept copy, the entry, `stela.cfg` and the startup choices, and, from the //! active build's restore image (`--ipsw` or `--fetch`), every damaged or -//! missing recoveryOS or restore bundle and a damaged install medium; with -//! an image it prepares every bundle of the active build again, with each -//! machine's own ECID, and gives a machine of an older setup without one its -//! ECID (`machines::machine_ecid`). +//! missing restore bundle and a damaged install medium; with an image it +//! prepares every restore bundle of the active build again, with each +//! machine's own ECID, and gives an install without one its ECID +//! (`machines::machine_ecid`). use super::{ CHOICES_PATH, Environment, LOADER_PATH, RECORD, Record, Setup, apply_install, bundle, - check_bundle_revision, check_space, copy_bundles, describe_install, ecid::Ecid, host::Host, - installed, machines, plan_install, prepare_bundles, publish, read_record, revision_mismatch, - state, update, write_record, + check_bundle_revision, describe_install, ecid::Ecid, host::Host, installed, machines, + plan_install, publish, read_record, revision_mismatch, state, update, write_record, }; use crate::efi; use anyhow::{Result, bail}; @@ -98,7 +97,7 @@ fn systems(host: &dyn Host, identifier: &str, bytes: u64) -> Vec { )), } } - // The recoveryOS copies stela.efi boots before Stela's own bundle. + // The recoveryOS copies stela.efi boots when NVRAM asks for one. for kind in [recovery::Kind::Paired, recovery::Kind::System] { match recovery::find(&mut disk, kind, None) { Ok(copies) => { @@ -263,13 +262,6 @@ fn bundle_status(environment: &Environment<'_>, record: &Record, report: &mut Re if let Some(reason) = revision_mismatch(environment, record) { report.problem(reason); } - for ecid in record.missing_bundles(&record.build) { - report.problem(format!( - "the active build {} has no recoveryOS bundle for {}: `stela setup --repair --ipsw`", - record.build, - ecid.map_or_else(|| "the setup".into(), |e| format!("ECID {e}")) - )); - } for (kind, ecid) in record.missing_restore_bundles() { report.problem(format!( "the active build {} has no {} bundle for {}, so its {} choice is missing: `stela \ @@ -346,6 +338,15 @@ fn install_status( )), } let disk = &install.disk; + // A portable installer's disk is chosen in stela.efi, out of this + // computer's reach. + if disk.is_chosen() { + report.line( + "Apple region", + "chosen in stela.efi on the PC when Install macOS starts", + ); + return; + } match installed::confirm(host, disk, installed::Role::AppleRegion, None) { Ok(region) => { let bytes = host.partition(®ion).map(|p| p.bytes).unwrap_or(0); @@ -359,7 +360,7 @@ fn install_status( disk.apple_region_serial, disk.apple_region_guid, if systems.is_empty() { - "no installed macOS yet; stela.efi boots System Recovery" + "no installed macOS yet; choose Install macOS" } else { "macOS installed" } @@ -472,18 +473,11 @@ pub(super) fn status(environment: &Environment<'_>, usb: &Path) -> Result report.line("ECID", ecid), - None => report.problem( - "the setup's machine has no ECID (an older setup made it): `stela setup --repair \ - --ipsw`" - .into(), - ), - } - } + report.line( + "macOS build", + format!("{} (Install macOS restores it)", record.build), + ); + report.line("kept builds", record.builds.join(", ")); report.line( "TSS", if record.tss { @@ -578,12 +572,6 @@ pub(super) fn repair(environment: &Environment<'_>, command: &Setup) -> Result install.ecid, - None => Some(command.ecid.map_or_else(Ecid::generate, Ok)?), - }; - } } for (name, ecid) in &assigned { writeln!(text, " ECID install \"{name}\" is now {ecid}")?; @@ -602,53 +590,6 @@ pub(super) fn repair(environment: &Environment<'_>, command: &Setup) -> Result> = Vec::new(); - for ecid in record.machines() { - let directory = bundle::directory(&record.volume, &record.build, ecid, record.generation()); - let digest = record - .bundle(&record.build, ecid) - .map(|b| b.manifest_sha256.clone()); - let intact = digest.is_some_and(|digest| { - bundle::verify(&bundle::in_place(&directory), &digest).is_empty() - }); - if ipsw.is_some() || !intact { - needed.push(ecid); - } - } - let prepared = match (&ipsw, needed.is_empty()) { - (_, true) => Vec::new(), - (Some(ipsw), false) => { - let (_, _, prepared) = prepare_bundles( - environment, - ipsw, - &record.model, - Some(&record.build), - &needed, - )?; - check_space(environment.host, &record.volume, &prepared)?; - prepared - } - (None, false) => bail!( - "{text} recoveryOS {} bundles of macOS {} are damaged or missing: pass its \ - restore image with --ipsw or --fetch", - needed.len(), - record.build - ), - }; - for bundle in &prepared { - writeln!( - text, - " recoveryOS prepare {} again", - bundle::directory( - &record.volume, - &bundle.build, - bundle.ecid, - record.generation() - ) - .display() - )?; - } for old in &stale { writeln!( text, @@ -689,7 +630,7 @@ pub(super) fn repair(environment: &Environment<'_>, command: &Setup) -> Result, command: &Setup) -> Result) -> String { + /// the disk's own recoveryOS as NVRAM chooses (`boot_selection::route`). + /// The bundle `stela.efi` builds from the disk carries the machine's + /// `ecid`. + pub(super) fn options(&self, ecid: Option) -> String { let region = self.region_target(); let ecid = ecid .map(|ecid| format!(" --ecid {ecid}")) .unwrap_or_default(); format!( - "--system --storage {region} --nor {} --preboot {region} --recovery-bundle \ - {recovery}{ecid}{}", + "--system --storage {region} --nor {} --preboot {region}{ecid}{}", self.nor_target(), self.external() ) } - /// The options of its System Recovery, as `stela.efi` routes a - /// recoveryOS choice of NVRAM (`boot_selection::route`): the disk and - /// NVRAM stay, `--bundle` replaces `--preboot`. - pub(super) fn recovery_options(&self, recovery: &str, ecid: Option) -> String { + /// The options that boot the USB's bundle `bundle`, such as a restore + /// bundle, with this disk and its NVRAM. + pub(super) fn bundle_options(&self, bundle: &str, ecid: Option) -> String { let ecid = ecid .map(|ecid| format!(" --ecid {ecid}")) .unwrap_or_default(); format!( - "--system --storage {} --nor {} --bundle {recovery}{ecid}{}", + "--system --storage {} --nor {} --bundle {bundle}{ecid}{}", self.region_target(), self.nor_target(), self.external() @@ -668,8 +668,12 @@ pub(super) fn check(host: &dyn Host, request: &Request) -> Result { /// The Apple region of `disk`, when it holds another file system than a /// guest disk: the PC's own OS mounts it and clears its free space, Stela's -/// machine state included. +/// machine state included. A disk Install macOS chooses in `stela.efi` has +/// none on this computer. pub(super) fn foreign(host: &dyn Host, disk: &InstalledDisk) -> Result> { + if disk.is_chosen() { + return Ok(None); + } let identifier = confirm(host, disk, Role::AppleRegion, None)?; Ok(match contents(host, &identifier)? { Contents::Other => Some(host.partition(&identifier)?), @@ -698,7 +702,7 @@ pub(super) fn initialize_nor(host: &dyn Host, disk: &InstalledDisk, image: &[u8] /// What the next boot is. #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub(crate) enum NextBoot { - /// System Recovery: Stela's recoveryOS bundle. + /// System Recovery: the disk's RecoveryOSContainer. Recovery, /// macOS, clearing a pending recovery request. Macos, diff --git a/crates/stela-cli/src/setup/machines.rs b/crates/stela-cli/src/setup/machines.rs index 98752dbdff..99a0044b3b 100644 --- a/crates/stela-cli/src/setup/machines.rs +++ b/crates/stela-cli/src/setup/machines.rs @@ -2,23 +2,20 @@ //! tail holds the machine state, or an Apple region and a machine-state //! partition) that is its own Stela machine with its own ECID, //! NVRAM and SEP state, as two Macs are. One is the default `stela.cfg` -//! boots; `stela.efi`'s startup choices (`choices.cfg`) list every install, -//! its System Recovery and its Install macOS, which restores the -//! USB's install medium onto it with the machine's own restore bundle. They -//! open on their own with several installs or an install medium, and when a -//! key is held otherwise. +//! boots; `stela.efi`'s startup choices (`choices.cfg`) list every install +//! and its Install macOS, which restores the USB's install medium onto it +//! with the machine's own restore bundle. They open on their own with +//! several installs or an install medium, and when a key is held otherwise. //! //! A machine's ECID is kept for its life: an install whose machine-state //! partition already holds SEP state takes the ECID given with `--ecid`, and //! a new one only with `--new-ecid`, since its LocalPolicy and SEP state are -//! bound to the old one. The first install takes over the setup's own -//! machine (recoveryOS without a disk keeps no state), so its recoveryOS -//! bundle serves it; every further install needs its own bundle, prepared -//! from the active build's restore image. +//! bound to the old one. Every install needs its own restore bundle, +//! prepared from the active build's restore image. use super::{ - Environment, Prepared, Setup, TSS_REQUIRED, apply_install, bundle, check_bundle_revision, - check_installed_efi, check_space, copy_bundles, describe_install, ecid::Ecid, installed, - plan_install, prepare_bundles, publish, read_record, tss_note, write_record, + Environment, Setup, TSS_REQUIRED, apply_install, bundle, check_bundle_revision, + check_installed_efi, describe_install, ecid::Ecid, installed, plan_install, publish, + read_record, tss_note, write_record, }; use anyhow::{Result, bail, ensure}; use serde::{Deserialize, Serialize}; @@ -27,9 +24,9 @@ use stela_loader::mount_interface::MAX_CHOICES; /// The first install's name unless `--install` gives one. pub(super) const FIRST_NAME: &str = "macOS"; -/// Each install has four startup choices: itself, its System Recovery, -/// Install macOS and Update macOS. -const MAX_INSTALLS: usize = MAX_CHOICES / 4; +/// Each install has up to three startup choices: itself, Install macOS and +/// Update macOS. +const MAX_INSTALLS: usize = MAX_CHOICES / 3; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub(super) struct Install { @@ -41,16 +38,17 @@ pub(super) struct Install { pub(super) disk: installed::InstalledDisk, } -/// A name the startup choices can show, with room for " Recovery". +/// A name the startup choices can show, with room for the longest suffix +/// of its choices, " - Install macOS". pub(super) fn check_name(name: &str) -> Result<()> { - const RECOVERY_SUFFIX: usize = " Recovery".len(); + const SUFFIX: usize = " - Install macOS".len(); ensure!( !name.is_empty() - && name.len() + RECOVERY_SUFFIX <= stela_loader::mount_interface::MAX_NAME + && name.len() + SUFFIX <= stela_loader::mount_interface::MAX_NAME && name.bytes().all(|b| b.is_ascii_graphic() || b == b' ') && name.trim() == name, "an install name is 1 to {} printable ASCII characters", - stela_loader::mount_interface::MAX_NAME - RECOVERY_SUFFIX + stela_loader::mount_interface::MAX_NAME - SUFFIX ); Ok(()) } @@ -169,17 +167,9 @@ pub(super) fn add(environment: &Environment<'_>, command: &Setup) -> Result, command: &Setup) -> Result, command: &Setup) -> Result = if missing.is_empty() { - Vec::new() - } else { - let (_, _, prepared) = prepare_bundles( - environment, - &ipsw, - &record.model, - Some(&record.build), - &missing, - )?; - check_space(host, &record.volume, &prepared)?; - prepared - }; let restore: Vec<(bundle::Kind, Option)> = super::restore_bundles(&next.install_machines()) .into_iter() @@ -236,7 +209,7 @@ pub(super) fn add(environment: &Environment<'_>, command: &Setup) -> Result, command: &Setup) -> Result, command: &Setup) -> Result, command: &Setup) -> Resul let mut removed_bundles = Vec::new(); if let Some(name) = &command.remove_install { let install = record.install(Some(name))?.clone(); + ensure!( + record.installs.len() > 1, + "install \"{name}\" is this setup's only one; `stela setup --uninstall` removes the \ + setup" + ); record.installs.retain(|i| i.name != *name); if record.default_install.as_deref() == Some(name.as_str()) { record.default_install = None; } - if record.installs.is_empty() { - record.ecid = install.ecid.or(record.ecid); - } writeln!( text, " remove install \"{name}\"; {} keep macOS, its NVRAM and SEP state{}", @@ -420,7 +380,8 @@ mod tests { machine_ecid(None, None, true, true, &mut notes).unwrap(); assert!(notes[0].contains("orphaned")); assert!(check_name("macOS 2").is_ok()); - for bad in ["", " macOS", "a\tb", &"x".repeat(32)] { + assert!(check_name(&"x".repeat(24)).is_ok()); + for bad in ["", " macOS", "a\tb", &"x".repeat(25)] { assert!(check_name(bad).is_err(), "{bad:?}"); } } diff --git a/crates/stela-cli/src/setup/state.rs b/crates/stela-cli/src/setup/state.rs index 2ae5eec54e..22db405367 100644 --- a/crates/stela-cli/src/setup/state.rs +++ b/crates/stela-cli/src/setup/state.rs @@ -92,9 +92,9 @@ pub(super) fn next_boot(variables: &Variables) -> String { boot_selection::Target::PairedRecovery => "the paired recoveryOS (the Recovery \ volume's, else System Recovery)" .into(), - boot_selection::Target::SystemRecovery => "System Recovery (the \ - RecoveryOSContainer's, else Stela's bundle)" - .into(), + boot_selection::Target::SystemRecovery => { + "System Recovery (the RecoveryOSContainer's)".into() + } boot_selection::Target::Upgrade => { "the macOS update staged on the Update volume".to_string() } diff --git a/crates/stela-cli/src/setup/update.rs b/crates/stela-cli/src/setup/update.rs index fca823159e..491cbab003 100644 --- a/crates/stela-cli/src/setup/update.rs +++ b/crates/stela-cli/src/setup/update.rs @@ -1,6 +1,7 @@ //! Updates of an existing setup, each one a transaction in the setup //! record: Stela updates replace `stela.efi`, macOS updates add the new -//! build's recoveryOS bundles and point `stela.cfg` at them. Both keep what +//! build's install medium and restore bundles and point Install macOS at +//! them. Both keep what //! they replace, so `--rollback` undoes the last one; an update that was //! interrupted is finished by running it again or undone by `--rollback`. //! @@ -11,9 +12,9 @@ //! mount interface. When it reads another boot-bundle schema than the //! setup's bundles have, or this `stela` prepares another bundle revision //! (`stela_loader::boot_bundle::REVISION`) than theirs, the update -//! prepares the active build's bundles for every machine again (the -//! recoveryOS ones, and the restore ones while the setup has the build's -//! install medium) at the new schema and revision, from `--ipsw` or +//! prepares the active build's restore bundles for every machine again +//! (while the setup has the build's install medium) at the new schema and +//! revision, from `--ipsw` or //! `--fetch`, beside the old ones, which its rollback boots again; this //! makes it an update even with the same `stela.efi`. //! Bundles of a generation that no kept version boots are removed. The @@ -26,20 +27,17 @@ //! new system on the container's Update volume and sets `boot-command //! upgrade`, which `stela.efi` boots from that volume as iBEC would //! (`stela_loader::upgrade`), and every later boot builds from the -//! Preboot volume's new objects. `--update-os` brings the setup to a new -//! build offline: its System Recovery bundles and, for a setup with -//! installs, the build's install medium and each machine's erase and -//! update restore bundles. The Update macOS choice then restores -//! the build's Update identity over the installed system, keeping its -//! data, as Apple Configurator's update restore does. The previous -//! build's medium is kept for rollback ([`MEDIA_KEPT`] media in all), so -//! the USB needs room for both. +//! Preboot volume's new objects. `--update-os` brings the setup's Install +//! macOS to a new build offline: the build's install medium and each +//! machine's restore bundles. The previous build's medium is kept for +//! rollback ([`MEDIA_KEPT`] media in all), so the USB needs room for +//! both. //! //! Neither touches the installed disks' partitions. use super::{ Environment, LOADER_PATH, MEDIA_KEPT, Prepared, Record, apply_install, bundle, check_bundle_revision, check_space, copy_bundles, describe_install, first_schema, plan_install, - prepare_bundles, prepare_kind, publish, read_efi, restore_bundles, write_record, + prepare_kind, publish, read_efi, restore_bundles, write_record, }; use crate::efi; use anyhow::{Context, Result, bail, ensure}; @@ -54,7 +52,7 @@ use std::{ pub(super) const VERSIONS: &str = "EFI/stela/versions"; const VERSION_FILE: &str = "stela.efi"; const VERSION_ID_DIGITS: usize = 16; -/// Stela versions and recoveryOS builds kept for rollback, the active one +/// Stela versions and macOS builds kept for rollback, the active one /// included. pub(super) const KEEP: usize = 3; @@ -77,7 +75,7 @@ pub(super) enum Change { #[serde(default)] to_revision: u32, }, - /// recoveryOS builds. + /// macOS builds of the install media and restore bundles. Os { from: String, to: String }, } @@ -153,21 +151,9 @@ fn activate_stela(esp: &Path, id: &str) -> Result<()> { Ok(()) } -/// Point `stela.cfg` at `build`'s recoveryOS, which must have a bundle for -/// every machine of the active generation. +/// Make `build` the active build, which Install macOS restores; its +/// restore bundles and medium are the startup choices' from now on. fn activate_build(record: &mut Record, build: &str) -> Result<()> { - let missing = record.missing_bundles(build); - ensure!( - missing.is_empty(), - "recoveryOS {build} has no {} bundle for {}; prepare them with `stela setup \ - --repair --ipsw` of that build after activating it, or keep the current build", - record.generation(), - missing - .iter() - .map(|ecid| ecid.map_or_else(|| "the setup".into(), |e| format!("ECID {e}"))) - .collect::>() - .join(", ") - ); record.build = build.into(); record.bundle_directory = bundle::build_directory(&record.volume, build); publish(record) @@ -183,8 +169,8 @@ fn prune(record: &mut Record) -> Result<()> { } } } - while record.recovery_builds.len() > KEEP { - let build = record.recovery_builds.remove(0); + while record.builds.len() > KEEP { + let build = record.builds.remove(0); if build != record.build { let directory = bundle::build_directory(&record.volume, &build); if directory.is_dir() { @@ -195,14 +181,14 @@ fn prune(record: &mut Record) -> Result<()> { } let kept = |change: &Change| match change { Change::Stela { from, .. } => record.stela_versions.contains(from), - Change::Os { from, .. } => record.recovery_builds.contains(from), + Change::Os { from, .. } => record.builds.contains(from), }; let history: Vec = record.history.iter().filter(|c| kept(c)).cloned().collect(); record.history = history; remove_unbooted_bundles(record)?; // The media of the newest kept builds, the active one's first. let newest: Vec = record - .recovery_builds + .builds .iter() .rev() .filter(|build| **build != record.build) @@ -327,17 +313,16 @@ pub(super) fn update_stela( version_path(&esp, &to).display() )?; } - // Bundles of the new generation for every machine of the active build, - // restore ones too while it has an install medium. + // Restore bundles of the new generation for every machine of the active + // build while it has an install medium. let mut next = record.clone(); next.bundle_schema = to_generation.schema; next.bundle_revision = to_generation.revision; - let missing = next.missing_bundles(&record.build); let missing_restore = match from_generation == to_generation { true => Vec::new(), false => next.missing_restore_bundles(), }; - let prepared = if missing.is_empty() && missing_restore.is_empty() { + let prepared = if missing_restore.is_empty() { Vec::new() } else { let Some(ipsw) = ipsw else { @@ -349,18 +334,6 @@ pub(super) fn update_stela( ); }; let mut prepared: Vec = Vec::new(); - if !missing.is_empty() { - prepared.extend( - prepare_bundles( - environment, - ipsw, - &record.model, - Some(&record.build), - &missing, - )? - .2, - ); - } for kind in bundle::RESTORE_KINDS { let ecids: Vec<_> = missing_restore .iter() @@ -476,8 +449,8 @@ fn stela_change( } } -/// Add `ipsw`'s recoveryOS for every machine and boot it for System -/// Recovery. +/// Add `ipsw`'s install medium and every machine's restore bundles, and +/// make its build the one Install macOS restores. pub(super) fn update_os( environment: &Environment<'_>, mut record: Record, @@ -496,66 +469,34 @@ pub(super) fn update_os( }; ensure!( build != from, - "recoveryOS {build} is already the System Recovery of this setup" + "macOS {build} is already the build this setup installs" ); - let machines = record.machines(); - let (_, _, prepared) = - prepare_bundles(environment, ipsw, &record.model, Some(&build), &machines)?; - let recovery_bytes: u64 = prepared.iter().map(|p| p.bytes).sum(); - // With installs, the build's install medium and restore bundles, so - // Install and Update macOS restore the new build offline. - let install = match record.installs.is_empty() { - true => { - check_space(environment.host, &record.volume, &prepared)?; - None - } - false => Some(plan_install( - environment, - &record, - &build, - record.pieces_volume(), - ipsw, - &restore_bundles(&record.install_machines()), - recovery_bytes, - )?), - }; + // The build's install medium and restore bundles, so Install macOS + // restores the new build offline. + let install = plan_install( + environment, + &record, + &build, + record.pieces_volume(), + ipsw, + &restore_bundles(&record.install_machines()), + 0, + )?; let mut text = String::new(); writeln!(text, "macOS update to {product_version} ({build}):")?; - for bundle in &prepared { + describe_install(&record, &install, &mut text)?; + if let Some(medium) = record.active_medium() { writeln!( text, - " recoveryOS {} ({:.1} GB); {from}'s stays for rollback", - bundle::directory(&record.volume, &build, bundle.ecid, record.generation()).display(), - bundle.bytes as f64 / 1e9 + " keeps {} and {from}'s restore bundles for rollback", + medium.directory().display() )?; } - if let Some(plan) = &install { - describe_install(&record, plan, &mut text)?; - if let Some(medium) = record.active_medium() { - writeln!( - text, - " keeps {} for rollback", - medium.directory().display() - )?; - } - } writeln!( text, - " stela.cfg boots recoveryOS {build} for System Recovery" + " next choose Install macOS in the startup choices: it erases the disk and \ + restores {product_version}" )?; - match &install { - Some(_) => writeln!( - text, - " next choose Update macOS in the startup choices: it restores \ - {product_version} over the installed system offline and keeps its data (Install \ - macOS erases the disk instead)" - )?, - None => writeln!( - text, - " next boot System Recovery and choose Reinstall macOS, which downloads \ - {product_version} from Apple; an install added with --target restores it offline" - )?, - } writeln!( text, " note macOS's own Software Update stages the update on the Update volume; \ @@ -573,17 +514,13 @@ pub(super) fn update_os( }); write_record(&record.esp.clone(), &record)?; } - copy_bundles(&mut record, &prepared)?; - write_record(&record.esp.clone(), &record)?; - if let Some(plan) = install { - apply_install(environment, &mut record, ipsw, plan)?; - } + apply_install(environment, &mut record, ipsw, install)?; activate_build(&mut record, &build)?; - if !record.recovery_builds.contains(&from) { - record.recovery_builds.insert(0, from.clone()); + if !record.builds.contains(&from) { + record.builds.insert(0, from.clone()); } - record.recovery_builds.retain(|b| *b != build); - record.recovery_builds.push(build.clone()); + record.builds.retain(|b| *b != build); + record.builds.push(build.clone()); record.history.push(Change::Os { from, to: build }); record.pending = None; prune(&mut record)?; @@ -618,7 +555,7 @@ pub(super) fn rollback(mut record: Record, dry_run: bool) -> Result { )?, Change::Os { from, to } => writeln!( text, - "Roll back the {what} macOS update: System Recovery {to} -> {from}" + "Roll back the {what} macOS update: macOS {to} -> {from}" )?, } if dry_run { @@ -650,11 +587,11 @@ pub(super) fn rollback(mut record: Record, dry_run: bool) -> Result { Change::Os { from, to } => { ensure!( bundle::build_directory(&record.volume, from).is_dir(), - "recoveryOS {from} is no longer kept at {}", + "the macOS {from} bundles are no longer kept at {}", bundle::build_directory(&record.volume, from).display() ); activate_build(&mut record, from)?; - record.recovery_builds.retain(|b| b != to); + record.builds.retain(|b| b != to); let directory = bundle::build_directory(&record.volume, to); if *to != *from && directory.is_dir() { fs::remove_dir_all(directory)?; diff --git a/crates/stela-cli/src/setup/wizard.rs b/crates/stela-cli/src/setup/wizard.rs index 17bb3dad77..4af36a6595 100644 --- a/crates/stela-cli/src/setup/wizard.rs +++ b/crates/stela-cli/src/setup/wizard.rs @@ -283,8 +283,9 @@ fn configure_inner(command: &mut Setup, host: &dyn Host) -> Result { models.sort(); models.dedup(); command.model = Some(choices::model(&models, &names, command.model.as_deref())?); - // Full installation always needs fresh TSS personalization, so the - // wizard does not offer it as a choice; scripts keep `--no-tss`. + // Every setup installs macOS, which needs TSS personalization, so the + // wizard does not offer it as a choice; `--no-tss` withdraws the + // opt-in from an existing setup. cliclack::set_theme(theme::Stela { extras: true }); let extras = cliclack::multiselect("5 / 6 Choose extras") .item(0, "Profiling", "Save translation timing in the boot log") diff --git a/crates/stela-cli/tests/fixtures/recovery-volume/make-recovery-volume.sh b/crates/stela-cli/tests/fixtures/recovery-volume/make-recovery-volume.sh deleted file mode 100644 index e2bc81e5e8..0000000000 --- a/crates/stela-cli/tests/fixtures/recovery-volume/make-recovery-volume.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# Make recovery-volume.img.gz: Apple's own form of the recoveryOS volume -# `stela boot prepare --recovery` writes (boot/recovery_volume.rs), from -# hdiutil, holding a 4096-byte synthetic file in place of the BaseSystem -# image. It is the reference the written volume's key hashes are checked on. -# Needs macOS (hdiutil); no root. -set -eu -here="$(cd "$(dirname "$0")" && pwd)" -work="$(mktemp -d)" -trap 'rm -rf "$work"' EXIT -mkdir -p "$work/stage/usr/standalone/firmware" -head -c 4096 /dev/zero | tr '\0' 'S' > "$work/stage/usr/standalone/firmware/arm64eBaseSystem.dmg" -hdiutil create -quiet -fs APFS -layout NONE -format UDRW -volname "Stela recoveryOS" \ - -srcfolder "$work/stage" "$work/volume.dmg" -gzip -9 -n -c "$work/volume.dmg" > "$here/recovery-volume.img.gz" diff --git a/crates/stela-cli/tests/fixtures/recovery-volume/recovery-volume.img.gz b/crates/stela-cli/tests/fixtures/recovery-volume/recovery-volume.img.gz deleted file mode 100644 index 5a0bb8249d863109c5981ee95fc8d2cfc52df7a8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13301 zcmeI2X;c$w*2mM@$S5k>N`s2TopES(0X0CTK^qZ-Rz#FVkX1m40ojSc7lEc}i6Ri( zpluKtwy-1w0wF8{$`%cq5JCnJ0tAR5ge)X^rkFYJ`~CegXU?45FIDH%zv@2s_uPBy zo;n53_!DfyHf>&HVIR8=VPIctdDIkEN{Y<;|rvgnX_JWeIAQQiefy}3a@0>z>ZC;)X zW_V{cPlzV08d0dV>c;x5jXj*rxY{5#MwA~j;U~J!6TK9eFS!Hpgvd)A;#KnJqJS$r zy&SiSc~2d8n>@ze)NF?yRAqh0`U7VwpcRY>UlWj5Vgv+d`^o}_$F-I%*3xf(fjuIRC6z*6AM}Jb5VX(1;JKWikOgTzVI^)=2YTr zH9)%a2_X^=xpoX6AF!R9!;$pRiIVug&bzl9N@?ZG%J(xn#8i9yW*Dr6&RRSQ8p|Y2 z+}yxvKz;#m5=kt!LWZpjdGTX_RNUVyOkObGWE=WX#m~2V1;AiNI!$%*lnjxf2Sv9a zy|qjL-h51`mjNR2tfvAiZ9z--r+qdk2p_TRjTX*Fn>Ia!w!^3#!ET)72k|_|kO0{U z{LBFIrdvr4Fbw;iqv-Mw%D@5B5%npvtpf16u7Tp?mnT9uhoO}oF!`qs3AQBcfq~YZjc^=Kut6u=vuS$fO+s;MD_?qB0Nxf2O|F2*EtLnf zO#w0{Z^>5yt{NVO;@Hmh!*JoeGom)d|N7u)40Z#2_VCw?P}sX_SoPr-|L0`M?Oto% zW1tH2F_FZwbFpk$7hIOCh3blA{U}j7r83MN^7?#N-*&<=x}5Z7?I*tgB;jbXY2FSA7NV19*(@Gs8OlHXadf>VPEfzB7*uG{j*fg+dE4N7hmkA? z;g(lj=nS5zVCOe5*u+gwS9cfMsk_a`9}W6FJ4mJps~f%J<2s&Tgi~0jmUW_w8}v|_ z=M=!1^_~@^rV`521wb$_vO@q+y~h$D?`!}4t^iCA%Br7(0%x6I1rkcnFScv4V&bO1 zE=hnJ*Cgp_cQDGTc0KFpW=P4~ApnqTpOt#w$=stN5H_%!ctSzY0p1O%<4;0&EG2gW za<-|!D1KA|_?V!BzA#wQlMa{mM}VFg13o=Sz!SWrBN+?0-GDP7rX77ayXNmK=uQav zQ^kxPtm3tmWT!TLon*QP5c&oQmwJ4wBP!;9@=}GtUixp7qc7WHy+p=o)q&69z& z3^g@md?7kiZaf8S_5;E;lp{Pufweo`vmd5CvK~bg01N+0c=<>Ubjz_E`a5LdE8zY9 z9aJj+iPrM@0~e}&Sl(*j!oQBW^Bc!q07~!wueE4hUu8T9fS0 zw}B*DqS6{bE3$x2eIle(B%*3j)9~g{Oq4tQZGbr_pj%dE18lkR!_a#h{pGiW^Z#78 z52F#?>ilb(cVE=KVj+e2GItjES>XpA$U~IvknY4wx)u0nrm88I_m!FQu_uQMzV8;m zuB2r(-V8OsTu4&i2C0(xx1#3@a#z?Z`g)xbW{|u{yz-(UGgNg-Q4{P6m4h&ev2@l; z4U+EZSFh{Ed=)Z>U!uLBis%P!l^WWmpXTWAxI(D9J{g=TZP3G}8Q z=ZSDLKs&Ei`fGq*IOYB?Vr*c^O%d&A1IuJUywMP}kd^k+z};5{w?+mDYkJ(qiGja} zY3F6?(8Z@m6iD&MCn#2AAGWtQQ`IoXlp&@)?gS3)ZTpNB1@PGv>dfUWwOQC8U10t& zp?$dO^hvcSYI~ibm107QU0(`Hs6+7{sfOcX9D$r}O)3l$9Q2~HGR(u5(>0HbQHhWj ze_v)^qauZi6g;wXiVM40VY0eIE}lzwDCLE2O&MSP`QY=NQROzmi_!p*=e35n*KU+) zAf1}?o@S$VhMfN{fU{tGCPHUQE2YYE51>1QQ{~mNmI-f5A%Yh#2vvO%@k~rRqi=X) zsG&)^PLlq)%-Y4tKHRQtM!;oYI)vX&QP~*9)>TTsd zPCCR!`^_d=RRV8(x>`6R0D@yQsoi{QIT=tA`u14_OkugeIs6QFqjVfS?JwN7mCjrk z0laS^QNyA>!80FDEG)esW^NL*kxG>cd^?CPf>Of>|JH}rA)Lx!a zb!gFfq2SU&jHWeQVR@1>qc%C}k6n_)k@5v|NaP__IO^61(AS6wa$YQ4BaS1M6vJvU zYtgK_>QL?)lk$|~+JMj(ncokT{_Tai=niveXuxZq|C8|>KlB^2N5?5&9Kw3o?7DbX z90Ko&8PPb5IX^bAl1p67pdVqiPBg^8^T&p2mzs{VdK#mnVv|vzhr}F>BX%7+;yg4#jv~ng84Mo2z)ZK1w3w!4vP5T>D~L5i59m z?GhoaGN%fndzYKmQQrdbfv zD_Ae$nI`&%?aUlh3n*82{vt}-S?^*fThr!bY?*Z@r++Le_G|b0bfg>z@K?tqIRhgF z5?$MJfLyWG>XQPsET+pw9bHxkdh9Z2bw}7}hhloMYsEMDIv)_h>EXFv^ zirYKNMx*<=6Km2!ftz-G&DWung76A<4SFWE)}hd7Dw-U{8zV+~jbvUzc+lhNDjAw& zeQN@BNmeIdYLZ_iL`Q(lwQvJmRaLk`{Be{?C6$rhCbX|1C<)8%qj5D>AaM!4qwBbW z*1JqQ{@Y^hkqEOf3zmllG`-iW;I#E;8wCdsm~gmg8P@BB!RL}5C_bOIxNxTdMWtZ@ zqsDj-H~^3h0bPLe8#I@}v}jqo!ZA^ncp3FD6uS(xq3&}Sy3tq>Lkqm=_yy7_W>z9E zPIGE6A#QX6e4Qux&3gaDYYTOFY&8R^!W%BwIt@Y5cJAX-Wc00!ji(0!ji(0!ji(0!ji(0!jk^c?6O` zkowMz?;o%vnfHMoU6rOJpd_Fqpd_Fqpd_Fqpd_Fqpd_Fqpd_Fqpd|3$PT-Bz>0=w; t0(PwelEubvI7(9zP!doQP!doQP!doQP!jkz5@@-+^Wbn9?Dp@le*pC-lEwf4 diff --git a/crates/stela-loader/src/boot_bundle.rs b/crates/stela-loader/src/boot_bundle.rs index f34f9672e6..6ceab0d98a 100644 --- a/crates/stela-loader/src/boot_bundle.rs +++ b/crates/stela-loader/src/boot_bundle.rs @@ -184,8 +184,7 @@ pub struct Inputs<'a> { /// Trust cache modules placed after the static one in `TrustCache`. pub extra_trust_caches: Vec>, /// A ramdisk, placed as the `RAMDisk` region: a restore ramdisk the - /// kernel roots from as `md0`, or the disk image of a - /// [`root_selection::Root::RamImage`] root. + /// kernel roots from as `md0`. pub ramdisk: Option>, /// The sealed volume the boot roots from, and its root-hash `IM4P` when /// one is available; `None` when it roots from no sealed volume. @@ -1043,23 +1042,6 @@ fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> ), } boot_policy::refuse_ramdisk_image_root(&options.boot_args)?; - let ram_image = matches!(options.root, Some(root_selection::Root::RamImage { .. })); - if ram_image { - let bytes = - ramdisk_bytes.context("a RAM disk image root needs the image as the ramdisk")?; - // A memory-device root wins over `boot-uuid` in `IOFindBSDRoot`, and - // iBoot names the root in /chosen only without `rd=`. - ensure!( - !options - .boot_args - .split_whitespace() - .any(|argument| argument.starts_with("rd=") || argument.starts_with("rootdev=")), - "a RAM disk image root is named by /chosen boot-uuid; boot-args must not name rd= \ - or rootdev=" - ); - // The physical address follows placement; the length is fixed. - root_selection::ram_image(&mut tree, 0, bytes as u64)?; - } carveouts::publish(&mut tree, &carveouts)?; if let Some(chip_id) = inputs.target.chip_id { aic::publish(&mut tree, chip_id)?; @@ -1391,17 +1373,6 @@ fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> ) }) .transpose()?; - if ram_image { - // The image keeps the `RAMDisk` region, a name SPTM types (its - // region table, `sptm.t8112` file offset 0x28a3); XNU also makes - // `md0` of it, which nothing roots from without `rd=`. - let image = region("RAMDisk")?; - security.extend(root_selection::ram_image( - &mut tree, - image.guest_pa, - image.bytes, - )?); - } if let Some(object) = &boot_manifest_object { let manifest = region("BootManifest")?; let protected = read_only_region @@ -3369,59 +3340,14 @@ mod tests { tag_storage::LOCK | (dram_end - tag_storage::bytes(m4_options.dram_size)) ); - // A RAM disk image root: DiskImages gets the placed region from - // /chosen, and boot-uuid names the volume. - const VOLUME: &str = "11111111-2222-3333-4444-555555555555"; - let image_root = Options { - boot_args: "-v rp0=file:///a.dmg".into(), - root: Some(root_selection::Root::RamImage { - volume: VOLUME.into(), - }), - ..options.clone() - }; - let imaged = prepare(&inputs, &image_root)?; - let file = |name: &str| &imaged.files.iter().find(|(n, _)| n == name).unwrap().1; - let tree = DeviceTree::parse(file(DEVICE_TREE_FILE))?; - let ramdisk = imaged - .manifest - .regions - .iter() - .find(|r| r.name == "RAMDisk") - .unwrap(); - let chosen = |name: &str| tree.property("/chosen", name).map(|p| p.value.clone()); - assert_eq!( - chosen(root_selection::BOOT_RAMDMG_SIZE), - Some(100u64.to_le_bytes().to_vec()) - ); - let mut extent = ramdisk.guest_pa.to_le_bytes().to_vec(); - extent.extend(100u64.to_le_bytes()); - assert_eq!(chosen(root_selection::BOOT_RAMDMG_EXTENTS), Some(extent)); - assert_eq!( - chosen(root_selection::BOOT_UUID), - Some(format!("{VOLUME}\0").into_bytes()) - ); - // A memory-device root argument contradicts it, and rd=md0 with an - // image root is refused on any root. - let with_rd = Options { - boot_args: "-v rd=md0 rp0=file:///a.dmg".into(), - ..image_root.clone() - }; - let refusal = prepare(&inputs, &with_rd).err().unwrap().to_string(); - assert!(refusal.contains("memory device md0"), "{refusal}"); - let rootdev = Options { - boot_args: "-v rootdev=disk1s1".into(), - ..image_root.clone() - }; - assert!(prepare(&inputs, &rootdev).is_err()); + // A memory-device root cannot pivot to a disk image. let ramdisk_pivot = Options { boot_args: "-v rd=md0 rp0=file:///a.dmg".into(), root: Some(root_selection::Root::Ramdisk), ..options.clone() }; - assert!(prepare(&inputs, &ramdisk_pivot).is_err()); - let ramdisk = inputs.ramdisk.take(); - assert!(prepare(&inputs, &image_root).is_err()); - inputs.ramdisk = ramdisk; + let refusal = prepare(&inputs, &ramdisk_pivot).err().unwrap().to_string(); + assert!(refusal.contains("memory device md0"), "{refusal}"); // With SEP firmware, SEPFW is a reserved, zero-filled staging region // between RAMDisk and BootArgs that holds the image's IMG4 container; diff --git a/crates/stela-loader/src/boot_policy.rs b/crates/stela-loader/src/boot_policy.rs index 4e335ef95a..4de1fbf9dc 100644 --- a/crates/stela-loader/src/boot_policy.rs +++ b/crates/stela-loader/src/boot_policy.rs @@ -439,8 +439,7 @@ pub fn ramdisk_root_device(boot_args: &str) -> Option<&str> { /// ramdisk"); the first root already holds that device, so the image's /// mount fails with EBUSY and imageboot panics (`vfs_mountroot() failed`, /// `imageboot.c:468`). A Mac never passes `rd=` for recoveryOS; a root that -/// pivots to an image is named by `/chosen` instead -/// ([`crate::root_selection::Root::RamImage`]). +/// pivots to an image is named by `/chosen` instead. pub fn refuse_ramdisk_image_root(boot_args: &str) -> Result<()> { if let Some(device) = ramdisk_root_device(boot_args).filter(|_| image_boot_named(boot_args)) { anyhow::bail!( diff --git a/crates/stela-loader/src/boot_selection.rs b/crates/stela-loader/src/boot_selection.rs index 380e9bdf74..4094c33dbe 100644 --- a/crates/stela-loader/src/boot_selection.rs +++ b/crates/stela-loader/src/boot_selection.rs @@ -67,10 +67,11 @@ //! holds such a machine at its startup choices instead of booting the //! half-restored disk. //! -//! A recoveryOS boot prefers the copy on the boot disk, as LLB does: the +//! A recoveryOS boot reads the copy on the boot disk, as LLB does: the //! paired recoveryOS from the boot container's Recovery volume, then System -//! Recovery from the RecoveryOSContainer, then Stela's own System Recovery -//! bundle ([`route`], `stela_loader::recovery`). +//! Recovery from the RecoveryOSContainer ([`route`], +//! `stela_loader::recovery`). A disk that holds neither is refused: Stela has +//! no recoveryOS of its own to fall back to. //! //! Refused explicitly: `field-diags-paired` (a diagnostics image Stela does //! not read). @@ -296,8 +297,7 @@ pub enum Target { /// The recoveryOS paired with the installed system (its container's /// Recovery volume). PairedRecovery, - /// System Recovery: the recoveryOS container's, or Stela's recovery - /// bundle when the disk has none. + /// System Recovery: the recoveryOS container's. SystemRecovery, /// The update ramdisk macOS staged on its container's Update volume. Upgrade, @@ -329,8 +329,7 @@ pub struct Selection { /// otherwise a paired recovery boot falls back to System Recovery. pub paired_on_disk: bool, /// The boot disk holds System Recovery in its RecoveryOSContainer - /// (`--system-recovery`); otherwise System Recovery is Stela's own - /// bundle (`--recovery-bundle`). + /// (`--system-recovery`); otherwise a recoveryOS boot is refused. pub system_on_disk: bool, } @@ -552,9 +551,6 @@ pub fn choose(variables: &mut Variables, volume: &BootVolume, once: bool) -> Res /// `stela.cfg`'s installed-system option: the disk the bundle is built from. pub const PREBOOT_OPTION: &str = "--preboot"; -/// `stela.cfg`'s recoveryOS option: the ESP directory of Stela's recovery -/// bundle (`stela boot prepare --recovery`), booted for System Recovery. -pub const RECOVERY_BUNDLE_OPTION: &str = "--recovery-bundle"; pub const BUNDLE_OPTION: &str = "--bundle"; /// Options `stela.efi` passes its engine: the boot volume to build from and /// a safe-mode boot. @@ -575,6 +571,9 @@ pub const SYSTEM_RECOVERY_OPTION: &str = "--system-recovery"; /// mount can tell it from other refusals and hold the machine at its /// startup choices. pub const RECOVERY_MODE_REFUSAL: &str = "NVRAM holds the machine in iBoot's recovery mode"; +/// How [`route`]'s refusal of a recoveryOS boot of a disk without one +/// starts. +pub const NO_RECOVERY_REFUSAL: &str = "NVRAM boots recoveryOS"; /// What the engine is told only by NVRAM. const NVRAM_OPTIONS: [&str; 6] = [ BOOT_VOLUME_OPTION, @@ -589,34 +588,18 @@ const NVRAM_OPTIONS: [&str; 6] = [ /// macOS boot keeps `--preboot` and adds the boot volume and safe mode; an /// update adds `--upgrade`, a paired recoveryOS the disk holds /// `--paired-recovery`, and System Recovery the disk holds (also in place -/// of a paired recoveryOS it lacks) `--system-recovery`; any other -/// recoveryOS boot replaces `--preboot` with `--bundle` of the -/// `--recovery-bundle` directory, and is refused without one. Recovery mode -/// boots nothing and is refused ([`Target::RecoveryMode`]). -/// `--recovery-bundle` never reaches the engine. Returns the options and -/// what the boot log should say. +/// of a paired recoveryOS it lacks) `--system-recovery`; a recoveryOS boot +/// of a disk that holds neither is refused. Recovery mode boots nothing and +/// is refused ([`Target::RecoveryMode`]). Returns the options and what the +/// boot log should say. pub fn route(options: &str, selection: Option<&Selection>) -> Result<(String, String)> { - let mut words: Vec<&str> = options.split_ascii_whitespace().collect(); - let take = |words: &mut Vec<&str>, name: &str| -> Result> { - let Some(at) = words.iter().position(|w| *w == name) else { - return Ok(None); - }; - ensure!(at + 1 < words.len(), "{name} has no value"); - let value = words[at + 1].into(); - words.drain(at..at + 2); - ensure!( - !words.contains(&name), - "{name} appears more than once in stela.cfg" - ); - Ok(Some(value)) - }; + let words: Vec<&str> = options.split_ascii_whitespace().collect(); for option in NVRAM_OPTIONS { ensure!( !words.contains(&option), "{option} is chosen from NVRAM, not stela.cfg" ); } - let recovery = take(&mut words, RECOVERY_BUNDLE_OPTION)?; let Some(selection) = selection else { return Ok((words.join(" "), "NVRAM not read".into())); }; @@ -695,28 +678,10 @@ pub fn route(options: &str, selection: Option<&Selection>) -> Result<(String, St _ => format!("System Recovery from the RecoveryOSContainer ({reasons})"), } } - target @ (Target::PairedRecovery | Target::SystemRecovery) => { - let Some(directory) = recovery else { - bail!( - "NVRAM boots recoveryOS ({reasons}), but stela.cfg names no \ - {RECOVERY_BUNDLE_OPTION}" - ); - }; - take(&mut words, PREBOOT_OPTION)?; - ensure!( - !words.contains(&BUNDLE_OPTION), - "stela.cfg names both {BUNDLE_OPTION} and {RECOVERY_BUNDLE_OPTION}" - ); - extra.push(BUNDLE_OPTION.into()); - extra.push(directory); - match target { - Target::PairedRecovery => format!( - "recoveryOS ({reasons}): the boot disk holds neither a paired recoveryOS \ - nor System Recovery, so Stela's System Recovery bundle boots" - ), - _ => format!("System Recovery ({reasons})"), - } - } + Target::PairedRecovery | Target::SystemRecovery => bail!( + "{NO_RECOVERY_REFUSAL} ({reasons}): the boot disk holds neither a paired \ + recoveryOS nor System Recovery; choose Install macOS to restore it" + ), }; let mut text: Vec = words.into_iter().map(String::from).collect(); text.extend(extra); @@ -988,11 +953,11 @@ mod tests { // recover-system never boots the paired copy. let (options, _) = routed(&system, true, true); assert!(options.ends_with(SYSTEM_RECOVERY_OPTION), "{options}"); - // Neither on the disk: Stela's bundle, without the Preboot disk. - let (options, _) = routed(&system, true, false); - assert!( - options.ends_with("--bundle \\EFI\\stela\\recovery") && !options.contains("--preboot") - ); + // Neither on the disk: refused, with no recoveryOS to fall back to. + let mut neither = system.clone(); + neither.paired_on_disk = true; + let error = route(CONFIG, Some(&neither)).unwrap_err().to_string(); + assert!(error.starts_with(NO_RECOVERY_REFUSAL), "{error}"); // A missing-boot-media boot is System Recovery too. let mut blank = select(&variables(&[])).unwrap(); blank.missing_boot_media(); @@ -1021,8 +986,7 @@ mod tests { ))); } - const CONFIG: &str = "--system --storage S:G --nor S:N --preboot S:G \ - --recovery-bundle \\EFI\\stela\\recovery"; + const CONFIG: &str = "--system --storage S:G --nor S:N --preboot S:G"; #[test] fn macos_boots_keep_the_preboot_disk_and_name_the_volume() { @@ -1038,9 +1002,9 @@ mod tests { ); assert_eq!(options, expected); assert!(log.starts_with("macOS in safe mode")); - // Without NVRAM only the recovery bundle option is removed. + // Without NVRAM the options pass unchanged. let (plain, _) = route(CONFIG, None).unwrap(); - assert!(!plain.contains(RECOVERY_BUNDLE_OPTION) && plain.contains("--preboot S:G")); + assert_eq!(plain, CONFIG); } #[test] @@ -1087,32 +1051,24 @@ mod tests { } #[test] - fn recovery_boots_read_the_recovery_bundle_instead() { + fn recovery_boots_of_a_disk_without_recoveryos_are_refused() { let vars = variables(&[(Partition::Common, BOOT_COMMAND, b"recover-system")]); let selection = select(&vars).unwrap(); - let (options, log) = route(CONFIG, Some(&selection)).unwrap(); - assert_eq!( - options, - "--system --storage S:G --nor S:N \ - --bundle \\EFI\\stela\\recovery" - ); - assert!(log.starts_with("System Recovery")); + let error = route(CONFIG, Some(&selection)).unwrap_err().to_string(); + assert!(error.starts_with(NO_RECOVERY_REFUSAL), "{error}"); + assert!(error.contains("recover-system"), "{error}"); let paired = select(&variables(&[(Partition::System, RECOVERY_BOOT_MODE, b"x")])).unwrap(); - assert!( - route(CONFIG, Some(&paired)) - .unwrap() - .1 - .contains("paired recoveryOS") - ); - // A disk without an installed system boots System Recovery too. + assert!(route(CONFIG, Some(&paired)).is_err()); + // A disk without an installed system or System Recovery is refused + // too. let mut empty = select(&variables(&[])).unwrap(); empty.missing_boot_media(); + let error = route(CONFIG, Some(&empty)).unwrap_err().to_string(); + assert!(error.contains("missing-boot-media"), "{error}"); + empty.system_on_disk = true; let (options, log) = route(CONFIG, Some(&empty)).unwrap(); - assert!(options.ends_with("--bundle \\EFI\\stela\\recovery")); - assert!(log.contains("missing-boot-media")); - let without = "--system --preboot S:G"; - assert!(route(without, Some(&selection)).is_err()); + assert!(options.ends_with(SYSTEM_RECOVERY_OPTION), "{options}"); + assert!(log.contains("missing-boot-media"), "{log}"); assert!(route("--system --safe-boot", None).is_err()); - assert!(route("--system --recovery-bundle", None).is_err()); } } diff --git a/crates/stela-loader/src/mount_interface.rs b/crates/stela-loader/src/mount_interface.rs index df5a208395..250bbf8194 100644 --- a/crates/stela-loader/src/mount_interface.rs +++ b/crates/stela-loader/src/mount_interface.rs @@ -8,7 +8,7 @@ //! reads it from an image ([`find`]) and refuses an image whose interface //! differs from its own, or that has none, instead of installing a //! `stela.efi` that would misread what setup wrote. -//! - **Startup choices.** With several systems, or to reach System Recovery +//! - **Startup choices.** With several systems, or to reach Install macOS //! without a host computer, setup also writes [`CHOICES_FILE`]: a timeout //! line and one entry per line, each a name, a tab and a complete //! `stela.cfg` option line. The first entry is the default, the one @@ -33,7 +33,9 @@ pub const MARKER_BYTES: usize = MAGIC.len() + 4 * FIELDS; /// Revision 6: [`CHOSEN_DISK`] stands for the partition Install macOS chose. /// Revision 7: erase installs select `--development-restore` with `--tss`, /// retaining the original DEV-board FDR failure policy without an FDR proxy. -pub const OPTIONS_REVISION: u32 = 7; +/// Revision 8: `--recovery-bundle` is gone; a recoveryOS boot reads the +/// disk's own recoveryOS or is refused. +pub const OPTIONS_REVISION: u32 = 8; /// The startup choices, beside `stela.cfg` on the ESP. pub const CHOICES_FILE: &str = "\\EFI\\stela\\choices.cfg"; @@ -202,8 +204,6 @@ pub enum ChoiceKind { /// The Mac, from the startup disk NVRAM names, as a Mac starts /// (`--system` with `--preboot`). Mac, - /// recoveryOS from a bundle (`--system` without `--preboot`). - Recovery, /// The restore that lays out the Mac's SSD ([`INSTALL_OPTION`]). Setup, /// The restore that updates the installed system in place @@ -228,7 +228,7 @@ impl Choice { (true, true, _) => ChoiceKind::Update, (true, false, _) => ChoiceKind::Setup, (false, _, true) => ChoiceKind::Mac, - (false, _, false) => ChoiceKind::Recovery, + (false, _, false) => ChoiceKind::Other, } } } @@ -394,10 +394,10 @@ mod tests { }; let disk = "--system --storage A:B --nor A:B"; assert_eq!( - kind(&format!("{disk} --preboot A:B --recovery-bundle r")), + kind(&format!("{disk} --preboot A:B --ecid 1")), ChoiceKind::Mac ); - assert_eq!(kind(&format!("{disk} --bundle r")), ChoiceKind::Recovery); + assert_eq!(kind(&format!("{disk} --bundle r")), ChoiceKind::Other); assert_eq!( kind(&format!("{disk} --bundle s --install p.json")), ChoiceKind::Setup @@ -421,8 +421,8 @@ mod tests { options: "--system --preboot A:B".into(), }, Choice { - name: "macOS - System Recovery".into(), - options: "--system --bundle \\EFI\\x".into(), + name: "macOS - Install macOS".into(), + options: "--system --bundle \\EFI\\x --install p.json".into(), }, ], }; diff --git a/crates/stela-loader/src/recovery.rs b/crates/stela-loader/src/recovery.rs index 79f5635d5f..5d7e70df5a 100644 --- a/crates/stela-loader/src/recovery.rs +++ b/crates/stela-loader/src/recovery.rs @@ -1,6 +1,6 @@ //! The kernel boot bundle of a recoveryOS on the installed disk, built in //! `no_std` so `stela.efi` boots it as iBoot does and `stela boot prepare -//! --disk --recovery` writes the same one. +//! --disk --disk-recovery` writes the same one. //! //! A Mac's internal disk holds two recoveryOS copies (Asahi Linux docs //! `platform/stock-partition-layout.md`, commit `0d1f891`): diff --git a/crates/stela-loader/src/root_selection.rs b/crates/stela-loader/src/root_selection.rs index 4b3de12c9b..f503e1a4c0 100644 --- a/crates/stela-loader/src/root_selection.rs +++ b/crates/stela-loader/src/root_selection.rs @@ -30,19 +30,6 @@ //! 0x24530), so a ramdisk boot keeps the template's 38 zero bytes. Stela //! removes them instead, which TXM's darwin expert reads as the null volume //! UUID rather than an invalid length (docs/research/iboot-handoff.md). -//! -//! Known, from xnu-12377.121.6 and 26A434: a root can also be a volume of a -//! disk image the booter leaves in memory. `IOFindBSDRoot` first calls -//! `di_root_ramfile` (`iokit/bsddev/DINetBootHook.cpp`; KC strings 0xdcea3, -//! 0xdceb4), which reads `/chosen boot-ramdmg-size` (8 bytes, the image's -//! length) and `boot-ramdmg-extents` (`IOAddressRange`s: 8-byte physical -//! address and 8-byte length) and sets the controller's -//! `di-root-ram-file` to that physical memory. DiskImages attaches it -//! through its RAM backing store (`KDIRAMBackingStore`, URL -//! `ramfile://%u`), so the image is an `IOMedia` disk, and a -//! `boot-uuid` then names its volume. Unlike a memory device (`md0`, which -//! is BSD-only), its container is virtual: DiskImages publishes the -//! `Virtual Interface` interconnect APFS tests (`nx_is_virtual`). use crate::{apple_device_tree::DeviceTree, boot_policy::Decision}; use alloc::{format, string::String, vec::Vec}; use anyhow::{Result, ensure}; @@ -53,12 +40,6 @@ pub const APFS_PREBOOT_UUID: &str = "apfs-preboot-uuid"; pub const ASSOCIATED_VOLUME_GROUP: &str = "associated-volume-group"; pub const BOOT_UUID: &str = "boot-uuid"; pub const BOOT_OBJECTS_PATH: &str = "boot-objects-path"; -/// The RAM image's length; `di_root_ramfile` takes exactly 8 bytes. -pub const BOOT_RAMDMG_SIZE: &str = "boot-ramdmg-size"; -/// The RAM image's physical ranges, each an `IOAddressRange` (16 bytes on -/// arm64, `IOVirtualRange`); `IOMemoryDescriptor::withAddressRanges` with -/// no task reads them as physical. -pub const BOOT_RAMDMG_EXTENTS: &str = "boot-ramdmg-extents"; /// The kernel's bound on a UUID property: 36 characters and a NUL. const UUID_PROPERTY_BYTES: usize = 37; /// The kernel's bound on `boot-objects-path`. @@ -93,11 +74,6 @@ pub enum Root { }, /// A ramdisk; no installed volume. Ramdisk, - /// The volume `volume` of the disk image placed as the `RAMDisk` - /// region, which DiskImages attaches from `/chosen boot-ramdmg-*` - /// ([`ram_image`]); `boot-uuid` names the volume. No `rd=` boot-arg: - /// iBoot writes `boot-uuid` only without one. - RamImage { volume: String }, } fn uuid_property(text: &str) -> Result> { @@ -196,12 +172,6 @@ pub fn apply(tree: &mut DeviceTree, root: &Root) -> Result> { (&[BOOT_UUID, BOOT_OBJECTS_PATH], source) } Root::Ramdisk => (&[], "a ramdisk root".into()), - Root::RamImage { volume } => { - let source = format!("volume {volume} of the RAM disk image"); - set(tree, BOOT_UUID, uuid_property(volume)?, source.clone())?; - // The image's ranges follow placement (`ram_image`). - (&[BOOT_UUID, BOOT_RAMDMG_SIZE, BOOT_RAMDMG_EXTENTS], source) - } }; let chosen = tree.node_mut(CHOSEN).expect("checked"); for property in [ @@ -209,8 +179,6 @@ pub fn apply(tree: &mut DeviceTree, root: &Root) -> Result> { ASSOCIATED_VOLUME_GROUP, BOOT_UUID, BOOT_OBJECTS_PATH, - BOOT_RAMDMG_SIZE, - BOOT_RAMDMG_EXTENTS, ] { if !keep.contains(&property) && chosen.property(property).is_some() { chosen.remove_property(property); @@ -225,33 +193,6 @@ pub fn apply(tree: &mut DeviceTree, root: &Root) -> Result> { Ok(decisions) } -/// Hand DiskImages the `bytes`-byte disk image at physical `address` as -/// `di_root_ramfile` reads it: `/chosen boot-ramdmg-size` and one extent in -/// `boot-ramdmg-extents`. Both values have a fixed length, so a caller can -/// write them before placement and again once the address is known. -pub fn ram_image(tree: &mut DeviceTree, address: u64, bytes: u64) -> Result> { - ensure!(tree.node(CHOSEN).is_some(), "DeviceTree has no {CHOSEN}"); - // `di_root_ramfile` ignores a zero size. - ensure!(bytes != 0, "a RAM disk image has bytes"); - let mut extent = address.to_le_bytes().to_vec(); - extent.extend(bytes.to_le_bytes()); - let source = String::from("the RAM disk image DiskImages attaches (di_root_ramfile)"); - let mut decisions = Vec::new(); - for (property, value) in [ - (BOOT_RAMDMG_SIZE, bytes.to_le_bytes().to_vec()), - (BOOT_RAMDMG_EXTENTS, extent), - ] { - decisions.push(Decision { - path: CHOSEN.into(), - property: property.into(), - value_hex: hex::encode(&value), - source: source.clone(), - }); - tree.set_property(CHOSEN, property, value)?; - } - Ok(decisions) -} - #[cfg(test)] mod tests { use super::*; @@ -337,43 +278,6 @@ mod tests { ); } - #[test] - fn a_ram_image_root_names_its_volume_and_physical_extent() { - let mut tree = tree(); - let root = Root::RamImage { - volume: RECOVERY.into(), - }; - apply(&mut tree, &root).unwrap(); - assert_eq!(value(&tree, APFS_PREBOOT_UUID), None); - assert_eq!(value(&tree, ASSOCIATED_VOLUME_GROUP), None); - assert_eq!(value(&tree, BOOT_OBJECTS_PATH), None); - assert_eq!( - value(&tree, BOOT_UUID), - Some(format!("{RECOVERY}\0").as_bytes()) - ); - let decisions = ram_image(&mut tree, 0x8_1234_5000, 0x8d4c_3000).unwrap(); - assert_eq!(decisions.len(), 2); - // `di_root_ramfile`: an 8-byte size and 16-byte IOAddressRanges. - assert_eq!( - value(&tree, BOOT_RAMDMG_SIZE), - Some(0x8d4c_3000u64.to_le_bytes().as_slice()) - ); - let extents = value(&tree, BOOT_RAMDMG_EXTENTS).unwrap(); - assert_eq!(extents.len(), 16); - assert_eq!(&extents[..8], 0x8_1234_5000u64.to_le_bytes()); - assert_eq!(&extents[8..], 0x8d4c_3000u64.to_le_bytes()); - assert!(ram_image(&mut tree, 0x8_0000_0000, 0).is_err()); - // Another root drops the image's values. - apply(&mut tree, &Root::Ramdisk).unwrap(); - assert_eq!(value(&tree, BOOT_RAMDMG_SIZE), None); - assert_eq!(value(&tree, BOOT_RAMDMG_EXTENTS), None); - assert_eq!(value(&tree, BOOT_UUID), None); - let bad = Root::RamImage { - volume: "md0".into(), - }; - assert!(apply(&mut tree, &bad).is_err()); - } - #[test] fn a_ramdisk_boot_removes_the_template_slot_and_bad_uuids_are_refused() { let mut tree = tree(); diff --git a/xtask/src/boot.rs b/xtask/src/boot.rs index a62a7a8de8..0dc20f4325 100644 --- a/xtask/src/boot.rs +++ b/xtask/src/boot.rs @@ -849,7 +849,7 @@ fn launch(arguments: Run) -> Result { } // QEMU's directory volume is FAT16 and holds 516 MB; larger volumes, - // such as a recovery bundle with its ramdisk, go into a FAT32 image. + // such as a restore bundle with its ramdisk, go into a FAT32 image. let fat = match &arguments.usb_image { None if !arguments.directory_volume && directory_bytes(&volume)? > VVFAT_BYTES => { Some(fat_image(&volume, &output)?)