refactor(setup): remove the USB recoveryOS bundle

This commit is contained in:
Tyler Smith committed 2026-10-27 08:01:33 +00:00
1 parent 3adb7be326
commit ee490a23c7
28 files changed
+786 -2976

No files matched your search

+5 -11
View File
@@ -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<Option<&str>> = 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,
-23
View File
@@ -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 {}",
-8
View File
@@ -539,14 +539,6 @@ pub fn dram_base(files: &[File], built: Option<&[(String, Vec<u8>)]>) -> 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<u8>)]>,
) -> Result<bool, String> {
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)]
+39 -47
View File
@@ -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::<Target>().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::<Target>().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<u8>, consume: bool) -> Result<(Vec<u8>, 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<u8>, consume: bool) -> Result<(Vec<u8>, 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,
+8
View File
@@ -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);
+40 -230
View File
@@ -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<Ramdisk>,
/// 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<String>,
/// 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<PathBuf>,
/// The `boot/<hash>` 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<PathBuf>,
/// 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<String>,
/// 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<OsEnvironment>,
/// 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<String>,
/// 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<String>,
) -> 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<Option<u32>> {
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<u64>,
recovery_uuid: Option<&str>,
) -> Result<Options> {
/// environment and root of the selected boot mode.
fn options(&self, board_dram_base: Option<u64>) -> Result<Options> {
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)
);
}
+1 -1
View File
@@ -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()
@@ -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<u8>, 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<String> {
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>(B);
impl<B: AsRef<[u8]>> ReadAt for Memory<B> {
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<u8>) -> Result<Seal> {
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<u8> {
// 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<u8> = (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<u8> {
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<u8> {
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());
}
}
@@ -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<Vec<u8>> {
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<Self> {
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<u8>, Vec<u8>)], 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<u8>, Vec<u8>)) -> 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<u8>, Vec<u8>)>,
file_ino: u64,
next_ino: u64,
directories: u64,
}
impl FileTree {
fn new(path: &str, file_start: u64, bytes: u64, time: u64) -> Result<Self> {
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<u8>);
let mut records: Vec<(Order, Vec<u8>, Vec<u8>)> = 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<u8>, u32) {
let folded = name.to_ascii_lowercase();
let code_points: Vec<u8> = 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<u64>,
) -> Vec<u8> {
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());
}
}
-1
View File
@@ -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};
-263
View File
@@ -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<Partition>)> {
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<Vec<u8>> {
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<u8> {
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(&sectors.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(&sector.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<u8>)]) -> tempfile::NamedTempFile {
let entries: Vec<Value> = 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<u8> = (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());
}
}
File diff suppressed because it is too large. Load diff
+18 -59
View File
@@ -4,9 +4,6 @@
//! the loader that prepared it) and [`Kind`], in
//! `EFI/stela/boot/<build>/<leaf>` of the bundle volume:
//!
//! - `recovery`: a recoveryOS bundle from before machines had ECIDs, schema
//! 1, revision 0;
//! - `recovery-<ECID>`: a machine's recoveryOS bundle, schema 1, revision 0;
//! - `restore-<ECID>`: a machine's restore bundle (`stela boot prepare
//! --restore`), which the Install macOS choice boots;
//! - `update-<ECID>`: 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<Ecid>, 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<Ecid>, generation: Generation) -> String {
leaf_of(Kind::Recovery, ecid, generation)
}
pub(super) fn leaf_of(kind: Kind, ecid: Option<Ecid>, 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<Ecid>,
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<Ecid>, 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();
+25 -86
View File
@@ -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<String> {
)),
}
}
// 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(&region).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<String
));
}
report.line("model", &record.model);
report.line("macOS build", format!("{} (System Recovery)", record.build));
report.line("kept builds", record.recovery_builds.join(", "));
if record.installs.is_empty() {
match record.ecid {
Some(ecid) => 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<S
record.installs[index].ecid = Some(ecid);
assigned.push((install.name.clone(), ecid));
}
if record.ecid.is_none() {
record.ecid = match record.installs.first() {
Some(install) => 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<S
}
}
let stale = record.drop_stale_bundles();
// The active build's bundles: all again with an image, else the damaged.
let mut needed: Vec<Option<Ecid>> = 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<S
record.pieces_volume(),
ipsw,
&restore,
prepared.iter().map(|p| p.bytes).sum(),
0,
)?;
describe_install(&record, &plan, &mut text)?;
Some(plan)
@@ -753,8 +694,6 @@ pub(super) fn repair(environment: &Environment<'_>, command: &Setup) -> Result<S
for region in &foreign {
installed::erase_foreign(environment.host, region)?;
}
copy_bundles(&mut record, &prepared)?;
write_record(&esp, &record)?;
if let (Some(plan), Some(ipsw)) = (install, &ipsw) {
apply_install(environment, &mut record, ipsw, plan)?;
}
+18 -14
View File
@@ -12,8 +12,9 @@
//!
//! Setup checks them and writes neither, except that `--initialize-nor`
//! writes a fresh NOR image over a NOR area that is neither blank nor a NOR
//! image, and blanks a SEP area that is neither blank nor a SEP roots record. recoveryOS's Disk Utility and Reinstall macOS write the
//! Apple region, as on a Mac; a region that holds anything but a guest disk
//! image, and blanks a SEP area that is neither blank nor a SEP roots
//! record. Install macOS's restore writes the Apple region, as on a Mac; a
//! region that holds anything but a guest disk
//! or zeros is used only with `--erase-target`, so no host data is lost by
//! accident. Every later Stela or macOS update keeps both partitions.
use super::ecid::Ecid;
@@ -117,30 +118,29 @@ impl InstalledDisk {
}
/// The engine options that boot it: macOS from its Preboot volume, or
/// recoveryOS from `recovery` as NVRAM chooses. The bundle `stela.efi`
/// builds from Preboot carries the machine's `ecid`.
pub(super) fn options(&self, recovery: &str, ecid: Option<Ecid>) -> 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<Ecid>) -> 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<Ecid>) -> 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<Ecid>) -> 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<Checked> {
/// 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<Option<PartitionInfo>> {
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,
+28 -67
View File
@@ -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<Stri
"this setup already has an install named {name:?}"
);
let mut notes = checked.notes.clone();
// The first install takes over the setup's own machine, which kept no
// state, unless the partition holds an earlier machine's.
let takes_over = record
.installs
.is_empty()
.then_some(record.ecid)
.flatten()
.filter(|_| command.ecid.is_none() && !checked.sep_provisioned);
let ecid = machine_ecid(
command.ecid,
takes_over,
None,
checked.sep_provisioned,
command.new_ecid,
&mut notes,
@@ -195,14 +185,10 @@ pub(super) fn add(environment: &Environment<'_>, command: &Setup) -> Result<Stri
};
let mut next = record.clone();
next.installs.push(install.clone());
if next.installs.len() == 1 {
next.ecid = Some(ecid);
}
next.tss |= command.tss;
next.verify_on_read = command.verify_on_read;
next.install_image = command.install_image.or(next.install_image);
let stale = next.drop_stale_bundles();
let missing = next.missing_bundles(&record.build);
// Every install restores from the medium with its own restore bundle.
let Some(ipsw) = command.optional_image()? else {
bail!(
@@ -211,19 +197,6 @@ pub(super) fn add(environment: &Environment<'_>, command: &Setup) -> Result<Stri
record.build
);
};
let prepared: Vec<Prepared> = 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<Ecid>)> =
super::restore_bundles(&next.install_machines())
.into_iter()
@@ -236,7 +209,7 @@ pub(super) fn add(environment: &Environment<'_>, command: &Setup) -> Result<Stri
command.install_volume.as_deref(),
&ipsw,
&restore,
prepared.iter().map(|p| p.bytes).sum(),
0,
)?;
let mut text = String::new();
writeln!(text, "Add install \"{name}\" to {}:", record.esp.display())?;
@@ -248,25 +221,11 @@ pub(super) fn add(environment: &Environment<'_>, command: &Setup) -> Result<Stri
disk.apple_region, disk.apple_region_serial, disk.apple_region_guid
)?;
writeln!(text, " {}", super::state_line(disk))?;
for bundle in &prepared {
writeln!(
text,
" recoveryOS {} ({:.1} GB)",
bundle::directory(
&record.volume,
&bundle.build,
bundle.ecid,
record.generation()
)
.display(),
bundle.bytes as f64 / 1e9
)?;
}
describe_install(&next, &install_plan, &mut text)?;
writeln!(
text,
" choices.cfg lists \"{name}\", its System Recovery, its Install macOS and \
its Update macOS; the startup choices open at every boot"
" choices.cfg lists \"{name}\" and its Install macOS; the startup choices open \
at every boot"
)?;
if checked.nor_image.is_some() {
writeln!(
@@ -289,7 +248,6 @@ pub(super) fn add(environment: &Environment<'_>, command: &Setup) -> Result<Stri
text.push_str("Dry run: nothing was changed.\n");
return Ok(text);
}
copy_bundles(&mut next, &prepared)?;
write_record(&next.esp.clone(), &next)?;
apply_install(environment, &mut next, &ipsw, install_plan)?;
if let Some(region) = &checked.foreign {
@@ -315,13 +273,15 @@ pub(super) fn configure(environment: &Environment<'_>, 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:?}");
}
}
+3 -3
View File
@@ -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()
}
+50 -113
View File
@@ -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::<Vec<_>>()
.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<Change> = 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<String> = 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<Prepared> = 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<String> {
)?,
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<String> {
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)?;
+3 -2
View File
@@ -283,8 +283,9 @@ fn configure_inner(command: &mut Setup, host: &dyn Host) -> Result<bool> {
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")
@@ -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"
+4 -78
View File
@@ -184,8 +184,7 @@ pub struct Inputs<'a> {
/// Trust cache modules placed after the static one in `TrustCache`.
pub extra_trust_caches: Vec<Input<'a>>,
/// 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<Input<'a>>,
/// 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<OwnedRamdisk>) ->
),
}
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<OwnedRamdisk>) ->
)
})
.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;
+1 -2
View File
@@ -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!(
+38 -82
View File
@@ -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<Option<String>> {
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<String> = 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());
}
}
+9 -9
View File
@@ -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(),
},
],
};
+1 -1
View File
@@ -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`):
-96
View File
@@ -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<Vec<u8>> {
@@ -196,12 +172,6 @@ pub fn apply(tree: &mut DeviceTree, root: &Root) -> Result<Vec<Decision>> {
(&[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<Vec<Decision>> {
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<Vec<Decision>> {
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<Vec<Decision>> {
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();
+1 -1
View File
@@ -849,7 +849,7 @@ fn launch(arguments: Run) -> Result<ExitCode> {
}
// 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)?)