feat(boot): place a linked auxiliary kernel collection in SPTM's AuxKC regions

This commit is contained in:
Tyler Smith committed 2026-10-30 16:57:19 +00:00
1 parent b55cfa08e3
commit ae75e2ffbb
6 files changed
+244 -23

No files matched your search

+78
View File
@@ -448,6 +448,17 @@ pub struct Prepare {
/// the others are taken from the IPSW's restore ramdisk.
#[arg(long, conflicts_with = "disk")]
board_firmware: Vec<PathBuf>,
/// A kext to link into an auxiliary kernel collection against the boot
/// collection: the directory `cargo xtask guest` builds, holding its
/// `Info.plist` and arm64e objects (such as `target/guest/StelaGPU.kext`),
/// which the installed system keeps in `/Library/Extensions`; repeat for
/// each kext.
#[arg(long = "kext", requires = "kext_receipt", conflicts_with = "disk")]
kexts: Vec<PathBuf>,
/// The receipt the auxiliary collection carries, which XNU requires
/// before it loads the collection's kexts.
#[arg(long, requires = "kexts")]
kext_receipt: Option<PathBuf>,
}
/// The recoveryOS copy `--disk-recovery` boots.
@@ -634,6 +645,71 @@ pub(super) fn boot_args(console: &str, mode: &[&str]) -> String {
}
impl Prepare {
/// The `--kext` bundles linked against `kernel` (`stela_loader::aux_kc`).
fn auxiliary_collection(&self, kernel: &[u8]) -> Result<Option<Decoded>> {
let Some(receipt) = &self.kext_receipt else {
return Ok(None);
};
let receipt =
std::fs::read(receipt).with_context(|| format!("cannot read {}", receipt.display()))?;
let mut bundles = Vec::with_capacity(self.kexts.len());
for directory in &self.kexts {
let read = |path: &std::path::Path| {
std::fs::read(path).with_context(|| format!("cannot read {}", path.display()))
};
let name = directory
.file_name()
.and_then(|name| name.to_str())
.with_context(|| format!("{} has no UTF-8 name", directory.display()))?;
let mut objects = Vec::new();
for entry in std::fs::read_dir(directory)
.with_context(|| format!("cannot list {}", directory.display()))?
{
let path = entry?.path();
if path.extension().is_some_and(|extension| extension == "o") {
objects.push(path);
}
}
objects.sort();
let objects = objects
.iter()
.map(|path| read(path))
.collect::<Result<Vec<_>>>()?;
bundles.push((
read(&directory.join("Info.plist"))?,
objects,
name.to_owned(),
));
}
let kexts: Vec<_> = bundles
.iter()
.map(|(info, objects, name)| stela_loader::aux_kc::Kext {
info,
objects: objects.iter().map(Vec::as_slice).collect(),
bundle_path: format!("/Library/Extensions/{name}"),
})
.collect();
let bytes = stela_loader::aux_kc::link(kernel, &kexts, &receipt)?;
let digest = stela_formats::sha256(&bytes);
let names: Vec<_> = bundles.iter().map(|(_, _, name)| name.as_str()).collect();
Ok(Some(Decoded {
source: Source {
component: "AuxiliaryKernelCollection".into(),
member: names.join(", "),
container_sha256: digest.clone(),
payload_type: "raw".into(),
description: format!(
"{} linked against the boot kernel collection",
names.join(", ")
),
decoded_bytes: bytes.len() as u64,
decoded_sha256: digest,
},
bytes,
declared_digest: None,
}))
}
fn run(self) -> Result<()> {
ensure!(
!self.output.exists(),
@@ -855,6 +931,7 @@ impl Prepare {
))
})
.collect::<Result<Vec<_>>>()?;
let auxiliary = self.auxiliary_collection(&kernel.bytes)?;
// Set below when the images come from the restore ramdisk.
let sourced: Vec<(String, Decoded)>;
let ramdisk_component: Decoded;
@@ -869,6 +946,7 @@ impl Prepare {
board_id: parse_id(identity.ap_board_id.as_deref())?,
},
kernel_collection: input(&kernel),
auxiliary_collection: auxiliary.as_ref().map(input),
sptm: input(&sptm),
txm: input(&txm),
device_tree: input(&device_tree),
+126 -10
View File
@@ -95,6 +95,9 @@ pub struct Input<'a> {
pub struct Inputs<'a> {
pub target: Target,
pub kernel_collection: Input<'a>,
/// Kexts linked against `kernel_collection` (`stela_loader::aux_kc`),
/// which SPTM maps beside it.
pub auxiliary_collection: Option<Input<'a>>,
pub sptm: Input<'a>,
pub txm: Input<'a>,
pub device_tree: Input<'a>,
@@ -180,6 +183,14 @@ const KERNEL_SPLITS: &[Split] = &[
split("rw", SegmentStart("__PRELINK_INFO"), SegmentEnd("__DATA")),
split("le", SegmentStart("__LINKEDIT"), ImageEnd),
];
/// An auxiliary collection's writable segments come first, then its
/// read-only ones with the executable `__TEXT_EXEC` last (`aux_kc`).
const AUXILIARY_SPLITS: &[Split] = &[
split("rw", ImageStart, SegmentStart("__TEXT")),
split("ro", SegmentStart("__TEXT"), SegmentStart("__TEXT_EXEC")),
split("rx", SegmentStart("__TEXT_EXEC"), SegmentEnd("__TEXT_EXEC")),
split("le", SegmentStart("__LINKEDIT"), ImageEnd),
];
const SPTM_SPLITS: &[Split] = &[
split("ro", ImageStart, SegmentStart("__TEXT_EXEC")),
split("rx", SegmentStart("__TEXT_EXEC"), SegmentEnd("__TEXT_EXEC")),
@@ -211,6 +222,8 @@ const REGION_ORDER: &[&str] = &[
"TXM-rx",
"TXM-bx",
"TrustCache",
"AuxKC-ro",
"AuxKC-rx",
"BootKC-rx",
"BootKC-bx",
"BootKC-ro",
@@ -224,6 +237,8 @@ const REGION_ORDER: &[&str] = &[
"TXM-le",
"BootKC-rw",
"BootKC-le",
"AuxKC-rw",
"AuxKC-le",
// M4 and later, without a CL4 image (`lock_regs::CL4_DUMMY_PAGE`).
lock_regs::CL4_DUMMY_PAGE,
"RAMDisk",
@@ -323,6 +338,7 @@ fn sptm_image_span(regions: &[Region]) -> Result<core::ops::Range<u64>> {
const ABSENT_SECURE_KERNEL: [&str; 3] = ["CL4-entry", "CL4-rx", "CL4-virt"];
const KERNEL_FILE: &str = "kernelcache.img";
const AUXILIARY_FILE: &str = "auxkc.img";
const SPTM_FILE: &str = "sptm.img";
const TXM_FILE: &str = "txm.img";
/// The bundle file holding the prepared DeviceTree.
@@ -788,9 +804,10 @@ impl Placement {
}
}
/// The three boot images, split into their regions.
/// The boot images, split into their regions.
struct Images {
kernel: LoadedImage,
auxiliary: Option<LoadedImage>,
sptm: LoadedImage,
txm: LoadedImage,
}
@@ -805,6 +822,19 @@ impl Images {
inputs.kernel_collection.bytes,
KERNEL_SPLITS,
)?,
auxiliary: inputs
.auxiliary_collection
.as_ref()
.map(|input| {
LoadedImage::new(
"AuxKC",
AUXILIARY_FILE,
KernelCollection::parse_auxiliary(input.bytes)?,
input.bytes,
AUXILIARY_SPLITS,
)
})
.transpose()?,
sptm: LoadedImage::new(
"SPTM",
SPTM_FILE,
@@ -827,7 +857,7 @@ impl Images {
[&self.sptm, &self.txm, &self.kernel]
.into_iter()
.map(|image| {
let offset = image.collection.entry_offset();
let offset = image.collection.entry_offset()?;
let (name, range) = image
.pieces
.iter()
@@ -845,7 +875,7 @@ impl Images {
vm_bytes: image.collection.image_bytes(),
entry: Entry {
image: image.name.into(),
virtual_address: image.collection.thread.pc,
virtual_address: image.collection.entry()?.pc,
physical_address: region.guest_pa + (offset - range.start),
},
fileset_entries: image.collection.fileset_entries.len(),
@@ -1178,9 +1208,11 @@ fn contents(
boot_args::BYTES as u64,
BOOT_ARGS_REGION_BYTES,
),
piece if piece.starts_with("AuxKC") && images.auxiliary.is_none() => continue,
piece => {
let image = [&images.kernel, &images.sptm, &images.txm]
.into_iter()
.chain(&images.auxiliary)
.find(|image| piece.starts_with(image.name))
.with_context(|| format!("no image provides {piece}"))?;
let range = image
@@ -1291,12 +1323,12 @@ fn fill_memory_map(
),
(
"TXM-entry",
range_value(images.txm.collection.entry_offset(), 0),
range_value(images.txm.collection.entry_offset()?, 0),
),
("TXM-virt", range_value(0, 0)),
(
"BootKC-entry",
range_value(images.kernel.collection.entry_offset(), 0),
range_value(images.kernel.collection.entry_offset()?, 0),
),
("BootKC-virt", range_value(0, 0)),
(
@@ -1362,6 +1394,9 @@ fn files(
(TRUST_CACHE_FILE.to_owned(), trust_cache),
(BOOT_ARGS_FILE.to_owned(), boot_args_bytes),
];
if let Some(auxiliary) = images.auxiliary {
files.push((AUXILIARY_FILE.to_owned(), auxiliary.memory));
}
if let Some(manifest) = &inputs.boot_manifest {
files.push((BOOT_MANIFEST_FILE.to_owned(), manifest.bytes.to_vec()));
}
@@ -1414,13 +1449,14 @@ fn hash_regions(regions: &mut [Region], files: &[(String, Vec<u8>)]) -> Result<(
/// Every input's source, in manifest order.
fn sources(inputs: &Inputs, ramdisk_source: Option<Source>) -> Vec<Source> {
let mut sources = vec![
source_of(&inputs.kernel_collection),
let mut sources = vec![source_of(&inputs.kernel_collection)];
sources.extend(inputs.auxiliary_collection.iter().map(source_of));
sources.extend([
source_of(&inputs.sptm),
source_of(&inputs.txm),
source_of(&inputs.device_tree),
source_of(&inputs.static_trust_cache),
];
]);
sources.extend(
inputs
.sep_firmware
@@ -2772,6 +2808,7 @@ mod tests {
board_id: Some(0x2e),
},
kernel_collection: input(),
auxiliary_collection: None,
sptm: input(),
txm: input(),
device_tree: input(),
@@ -2828,6 +2865,7 @@ mod tests {
board_id: Some(0x2e),
},
kernel_collection: input(leak(kernel), "KernelCache"),
auxiliary_collection: None,
sptm: input(leak(sptm), "Ap,SecurePageTableMonitor"),
txm: input(leak(txm), "Ap,TrustedExecutionMonitor"),
device_tree: input(leak(tree), "DeviceTree"),
@@ -2965,7 +3003,9 @@ mod tests {
let expected: Vec<_> = REGION_ORDER
.iter()
.copied()
.filter(|n| !["SEPFW", lock_regs::CL4_DUMMY_PAGE].contains(n))
.filter(|n| {
!["SEPFW", lock_regs::CL4_DUMMY_PAGE].contains(n) && !n.starts_with("AuxKC")
})
.collect();
assert_eq!(names, expected);
// The M1 to M3 hand off no core lock registers.
@@ -3319,7 +3359,7 @@ mod tests {
let expected: Vec<_> = REGION_ORDER
.iter()
.copied()
.filter(|n| *n != lock_regs::CL4_DUMMY_PAGE)
.filter(|n| *n != lock_regs::CL4_DUMMY_PAGE && !n.starts_with("AuxKC"))
.collect();
assert_eq!(names, expected);
let sepfw = staged
@@ -3346,12 +3386,88 @@ mod tests {
.any(|u| u.starts_with("SEPFW"))
);
// An auxiliary collection's read-only and executable regions join
// SPTM's run before the boot collection's; its writable ones follow
// the boot collection's.
inputs.auxiliary_collection = Some(input(leak(auxiliary_collection()), "AuxKC"));
let linked = prepare(&inputs, &options)?;
let names: Vec<_> = linked
.manifest
.regions
.iter()
.map(|r| r.name.as_str())
.collect();
let at = |name: &str| names.iter().position(|n| *n == name).unwrap();
assert_eq!(
names[at("TrustCache")..=at("BootKC-rx")],
["TrustCache", "AuxKC-ro", "AuxKC-rx", "BootKC-rx"]
);
assert_eq!(
names[at("BootKC-rw")..=at("AuxKC-le")],
["BootKC-rw", "BootKC-le", "AuxKC-rw", "AuxKC-le"]
);
let region = |name: &str| {
linked
.manifest
.regions
.iter()
.find(|r| r.name == name)
.unwrap()
};
assert_eq!(
region("AuxKC-ro").guest_pa + 4 * PAGE,
region("AuxKC-rx").guest_pa
);
for (name, offset, bytes) in [
("AuxKC-rw", 0, 2 * PAGE),
("AuxKC-ro", 2 * PAGE, 4 * PAGE),
("AuxKC-rx", 6 * PAGE, PAGE),
("AuxKC-le", 7 * PAGE, PAGE),
] {
let piece = region(name);
assert_eq!(
(piece.file.as_str(), piece.file_offset, piece.memory_bytes),
(AUXILIARY_FILE, offset, bytes)
);
assert_eq!(piece.virtual_address, Some(BASE + offset));
}
let file = |name: &str| &linked.files.iter().find(|(n, _)| n == name).unwrap().1;
assert_eq!(file(AUXILIARY_FILE).len() as u64, 8 * PAGE);
let tree = DeviceTree::parse(file(DEVICE_TREE_FILE))?;
assert_eq!(
tree.property(MEMORY_MAP, "AuxKC-rx").unwrap().value,
range_value(region("AuxKC-rx").guest_pa, PAGE)
);
assert!(
linked
.manifest
.sources
.iter()
.any(|source| source.component == "AuxKC")
);
inputs.auxiliary_collection = None;
// A manifest for another board is refused.
let mut other = Inputs { ..inputs };
other.target.board_id = Some(0x24);
assert!(prepare(&other, &options).is_err());
Ok(())
}
/// An auxiliary collection as `aux_kc` lays one out, a page a segment.
fn auxiliary_collection() -> Vec<u8> {
Builder::new(macho::MH_FILESET)
.segment("__PRELINK_INFO", PAGE, &page(0))
.segment("__DATA", PAGE, &page(1))
.segment("__TEXT", PAGE, &page(2))
.segment("__PRELINK_TEXT", PAGE, &page(3))
.segment("__DATA_CONST", PAGE, &page(4))
.segment("__RECEIPT_INFO", PAGE, &page(5))
.segment("__TEXT_EXEC", PAGE, &page(6))
.segment("__LINKEDIT", PAGE, &page(7))
.fileset("com.stela.StelaGPU", BASE + 3 * PAGE)
.build()
}
}
#[cfg(test)]
+1
View File
@@ -613,6 +613,7 @@ pub fn prepare<R: ReadAt>(
board_id: manifest_id(manifest.as_ref(), "BORD")?,
},
kernel_collection: kernel.input(),
auxiliary_collection: None,
sptm: sptm.input(),
txm: txm.input(),
device_tree: device_tree.input(),
+37 -13
View File
@@ -54,7 +54,8 @@ pub struct KernelCollection {
pub uuid: Option<String>,
pub segments: Vec<Segment>,
pub fileset_entries: Vec<FilesetEntry>,
pub thread: Arm64UnixThread,
/// The entry thread; an auxiliary collection has none.
pub thread: Option<Arm64UnixThread>,
/// Lowest segment `vmaddr`; the image's load base maps here.
pub vm_base: u64,
/// End of the highest segment.
@@ -85,17 +86,23 @@ fn fixed_name(bytes: &[u8]) -> Result<String> {
}
impl KernelCollection {
/// Parse an `MH_FILESET` kernel collection.
/// Parse the boot `MH_FILESET` kernel collection, which has an entry.
pub fn parse(bytes: &[u8]) -> Result<Self> {
Self::parse_kind(bytes, macho::MH_FILESET)
Self::parse_kind(bytes, macho::MH_FILESET, true)
}
/// Parse an auxiliary `MH_FILESET` kernel collection, which XNU enters
/// through no entry of its own.
pub fn parse_auxiliary(bytes: &[u8]) -> Result<Self> {
Self::parse_kind(bytes, macho::MH_FILESET, false)
}
/// Parse an `MH_EXECUTE` boot image such as SPTM or TXM.
pub fn parse_executable(bytes: &[u8]) -> Result<Self> {
Self::parse_kind(bytes, macho::MH_EXECUTE)
Self::parse_kind(bytes, macho::MH_EXECUTE, true)
}
fn parse_kind(bytes: &[u8], expected_type: u32) -> Result<Self> {
fn parse_kind(bytes: &[u8], expected_type: u32, entered: bool) -> Result<Self> {
ensure!(
word(bytes, 0)? == macho::MH_MAGIC_64,
"not a little-endian 64-bit Mach-O"
@@ -152,7 +159,15 @@ impl KernelCollection {
offset == commands_bytes,
"load commands do not fill sizeofcmds"
);
let thread = thread.context("image has no LC_UNIXTHREAD entry point")?;
ensure!(
thread.is_some() == entered,
"image {} an LC_UNIXTHREAD entry point",
if entered {
"has no"
} else {
"unexpectedly has"
}
);
ensure!(!segments.is_empty(), "image has no segments");
let mut ordered: Vec<&Segment> = segments.iter().filter(|s| s.vm_size > 0).collect();
ordered.sort_by_key(|s| s.vm_address);
@@ -195,9 +210,11 @@ impl KernelCollection {
vm_base,
vm_end,
};
collection
.segment_containing(collection.thread.pc)
.context("entry point lies outside every segment")?;
if let Some(thread) = &collection.thread {
collection
.segment_containing(thread.pc)
.context("entry point lies outside every segment")?;
}
Ok(collection)
}
@@ -220,9 +237,13 @@ impl KernelCollection {
self.vm_end - self.vm_base
}
pub fn entry(&self) -> Result<&Arm64UnixThread> {
self.thread.as_ref().context("image has no entry point")
}
/// Entry PC relative to the load base.
pub fn entry_offset(&self) -> u64 {
self.thread.pc - self.vm_base
pub fn entry_offset(&self) -> Result<u64> {
Ok(self.entry()?.pc - self.vm_base)
}
/// Physical address of a linked virtual address for an image whose load
@@ -413,9 +434,9 @@ pub(crate) mod tests {
assert_eq!(kc.segments.len(), 3);
assert_eq!(kc.vm_base, BASE);
assert_eq!(kc.image_bytes(), 0xc000);
assert_eq!(kc.entry_offset(), 0x4008);
assert_eq!(kc.entry_offset()?, 0x4008);
assert_eq!(
kc.segment_containing(kc.thread.pc).unwrap().name,
kc.segment_containing(kc.entry()?.pc).unwrap().name,
"__TEXT_EXEC"
);
assert_eq!(
@@ -433,6 +454,7 @@ pub(crate) mod tests {
assert_eq!(&image[0x4000..0x4010], &[0xaa; 0x10]);
assert_eq!(image[0x4010], 0);
assert!(KernelCollection::parse_executable(&bytes).is_err());
assert!(KernelCollection::parse_auxiliary(&bytes).is_err());
Ok(())
}
@@ -442,6 +464,8 @@ pub(crate) mod tests {
.segment("__TEXT", 0x4000, &[0; 0x4000])
.build();
assert!(KernelCollection::parse(&no_thread).is_err());
let auxiliary = KernelCollection::parse_auxiliary(&no_thread).unwrap();
assert!(auxiliary.thread.is_none() && auxiliary.entry_offset().is_err());
let outside = Builder::new(macho::MH_EXECUTE)
.segment("__TEXT", 0x4000, &[0; 0x4000])
.thread(BASE + 0x8000)
+1
View File
@@ -604,6 +604,7 @@ pub fn prepare<R: ReadAt>(
board_id: manifest_id(manifest.as_ref(), "BORD")?,
},
kernel_collection: kernel.input(),
auxiliary_collection: None,
sptm: sptm.input(),
txm: txm.input(),
device_tree: device_tree.input(),
+1
View File
@@ -509,6 +509,7 @@ pub fn prepare<R: ReadAt>(
board_id: id("BORD"),
},
kernel_collection: kernel.input(),
auxiliary_collection: None,
sptm: sptm.input(),
txm: txm.input(),
device_tree: device_tree.input(),