refactor(runtime): extract shared formats and machine contracts

This commit is contained in:
Tyler Smith committed 2026-10-28 18:56:16 +00:00
1 parent b93be1a998
commit ab7f201609
480 files changed
+4852 -3492

No files matched your search

Generated
+32
View File
@@ -1917,7 +1917,9 @@ dependencies = [
"sha1",
"sha2",
"stela-boot-core",
"stela-contracts",
"stela-drivers",
"stela-formats",
"stela-loader",
"stela-runtime",
"tempfile",
@@ -1935,6 +1937,13 @@ dependencies = [
"stela-fingerprint",
]
[[package]]
name = "stela-contracts"
version = "0.1.0"
dependencies = [
"serde",
]
[[package]]
name = "stela-dev"
version = "0.1.0"
@@ -1946,6 +1955,8 @@ dependencies = [
"serde_json",
"stela-cli",
"stela-compiler",
"stela-contracts",
"stela-formats",
"stela-loader",
"stela-runtime",
"tempfile",
@@ -1976,6 +1987,21 @@ dependencies = [
"sha2",
]
[[package]]
name = "stela-formats"
version = "0.1.0"
dependencies = [
"crypto-bigint",
"hex",
"lzfse_rust",
"miniz_oxide",
"serde",
"serde_json",
"sha1",
"sha2",
"stela-contracts",
]
[[package]]
name = "stela-loader"
version = "0.1.0"
@@ -1988,7 +2014,9 @@ dependencies = [
"serde_json",
"sha2",
"stela-compiler",
"stela-contracts",
"stela-drivers",
"stela-formats",
"stela-runtime",
"tempfile",
]
@@ -2020,8 +2048,10 @@ dependencies = [
"sha2",
"smoltcp",
"stela-compiler",
"stela-contracts",
"stela-drivers",
"stela-fingerprint",
"stela-formats",
"tempfile",
"zeroize",
]
@@ -2575,7 +2605,9 @@ dependencies = [
"stela-boot-core",
"stela-cli",
"stela-compiler",
"stela-contracts",
"stela-drivers",
"stela-formats",
"stela-loader",
"stela-runtime",
"tempfile",
+6
View File
@@ -8,6 +8,8 @@ members = [
"crates/stela-drivers",
"crates/stela-drivers/src/gpu/metal/input",
"crates/stela-fingerprint",
"crates/stela-contracts",
"crates/stela-formats",
"crates/stela-runtime",
"xtask",
]
@@ -23,6 +25,8 @@ default-members = [
"crates/stela-compiler",
"crates/stela-drivers",
"crates/stela-drivers/src/gpu/metal/input",
"crates/stela-contracts",
"crates/stela-formats",
"crates/stela-runtime",
]
# The UEFI application builds for its own target with aborting panics.
@@ -48,6 +52,8 @@ stela-boot-core = { path = "crates/stela-boot-core" }
stela-compiler = { path = "crates/stela-compiler" }
stela-fingerprint = { path = "crates/stela-fingerprint" }
stela-drivers = { path = "crates/stela-drivers" }
stela-contracts = { path = "crates/stela-contracts" }
stela-formats = { path = "crates/stela-formats" }
stela-runtime = { path = "crates/stela-runtime" }
stela-loader = { path = "crates/stela-loader" }
stela-cli = { path = "crates/stela-cli" }
+2
View File
@@ -28,6 +28,8 @@ test = false
native-profile = ["stela-runtime/native-profile"]
[dependencies]
stela-contracts = { path = "../stela-contracts", default-features = false }
stela-formats = { path = "../stela-formats", default-features = false }
uefi = { version = "0.41", default-features = false, features = ["alloc"] }
stela-boot-core = { path = "../stela-boot-core" }
stela-drivers = { path = "../stela-drivers", features = ["linux-kernel", "native-acpi"] }
+2 -2
View File
@@ -308,7 +308,7 @@ pub unsafe fn run(handoff: &Handoff, mode: AudioCheck) -> Result<(), String> {
FORMAT.bits,
FORMAT.channels,
RING_BYTES,
stela_runtime::sha256(&pcm)
stela_formats::sha256(&pcm)
));
if let Some(capture) = capture {
controller
@@ -387,7 +387,7 @@ pub unsafe fn run(handoff: &Handoff, mode: AudioCheck) -> Result<(), String> {
"AUDIO CHECK capture bytes={} changed={} sha256={}\n",
capture_pcm.len(),
changed,
stela_runtime::sha256(&capture_pcm)
stela_formats::sha256(&capture_pcm)
));
if changed != RING_BYTES {
return Err("capture DMA did not replace the complete prefilled ring".into());
+6 -15
View File
@@ -53,16 +53,7 @@ use stela_compiler::TargetCpu;
use stela_loader::{apple_device_tree::DeviceTree, boot_bundle, installed};
use stela_runtime::machine::apple::WallClock;
use stela_runtime::machine::engine::{Call, step_timing};
use stela_runtime::machine::{
Chip, Cpu, CpuProfile, Event, Host, Machine, PeerState, Stop, Transition,
apple::{AicInput, AicLayout, AppleDevices, ConsoleBusy, ConsoleSink, Range},
exception::Pstate,
identification::Speculation,
mount,
registers::encodings::DCZID_EL0,
soc,
system::Register,
};
use {stela_contracts::Chip, stela_runtime::machine::Cpu, stela_runtime::machine::CpuProfile, stela_runtime::machine::Event, stela_runtime::machine::Host, stela_runtime::machine::Machine, stela_runtime::machine::PeerState, stela_runtime::machine::Stop, stela_runtime::machine::Transition, stela_runtime::machine::apple::AicInput, stela_runtime::machine::apple::AicLayout, stela_runtime::machine::apple::AppleDevices, stela_runtime::machine::apple::ConsoleBusy, stela_runtime::machine::apple::ConsoleSink, stela_runtime::machine::apple::Range, stela_runtime::machine::exception::Pstate, stela_runtime::machine::identification::Speculation, stela_runtime::machine::mount, stela_runtime::machine::registers::encodings::DCZID_EL0, stela_runtime::machine::soc, stela_runtime::machine::system::Register};
use stela_runtime::pc::{gpt::Guid, storage::Target};
use stela_runtime::restore::store::Verify;
@@ -861,7 +852,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
output::arguments(format_args!(
"NETWORK CHECK body bytes={} sha256={}\n",
body.len(),
stela_runtime::sha256(&body)
stela_formats::sha256(&body)
));
output::arguments(format_args!("NETWORK CHECK passed\n"))
}
@@ -1111,7 +1102,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
"GUEST IMAGE pa={:#x} bytes={} sha256={}\n",
options.load,
source.len(),
stela_runtime::sha256(source),
stela_formats::sha256(source),
));
(options.entry, options.x0)
};
@@ -1387,7 +1378,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
scanout,
firmware: &firmware,
build: loaded_source.as_ref().map(|source| {
stela_runtime::builds::find(&source.selected().product_build)
stela_formats::builds::find(&source.selected().product_build)
.unwrap_or_else(|error| output::fatal(&alloc::format!("{error}")))
}),
},
@@ -1450,7 +1441,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
}
let processor_power = match (&topology_source, &assigned, &loaded_source) {
(Some(source), Some(assigned), Some(intake)) => {
let original = stela_runtime::machine::adt::Node::root(intake.original())
let original = stela_contracts::adt::Node::root(intake.original())
.unwrap_or_else(|| output::fatal("retained original source ADT is malformed"));
devices
.connect_processor_power(
@@ -1479,7 +1470,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
}
let restore = source.map(|source| {
let boot_ecid = tree
.and_then(stela_runtime::machine::adt::Node::root)
.and_then(stela_contracts::adt::Node::root)
.and_then(|root| root.child("chosen"))
.and_then(|chosen| chosen.property("unique-chip-id"))
.and_then(|bytes| <[u8; 8]>::try_from(bytes).ok())
+2 -6
View File
@@ -1,6 +1,6 @@
//! The kernel boot bundle: `bundle.json` and the files it lists, as prepared
//! on the host by `stela-dev boot prepare` (the iBoot side of the hand-off).
//! `stela_runtime::boot_bundle` checks every region's SHA-256, writes the
//! `stela_formats::boot_bundle` checks every region's SHA-256, writes the
//! regions and their zero tails into guest DRAM, and fills the patch slots
//! only the running machine knows; this supplies the machine's side: guest
//! RAM through the engine's host, RDSEED or RDRAND entropy and the timebase.
@@ -32,11 +32,7 @@ use stela_loader::{
apple_device_tree::DeviceTree, boot_bundle::Options, boot_selection::BootVolume, boot_trace,
installed, recovery, upgrade,
};
use stela_runtime::{
boot_bundle::{Framebuffer, MANIFEST_FILE, Machine, Manifest, Nvram},
machine::Host,
payload::{self, PayloadManifest, ReadAt},
};
use {stela_formats::boot_bundle::Framebuffer, stela_formats::boot_bundle::MANIFEST_FILE, stela_formats::boot_bundle::Machine, stela_formats::boot_bundle::Manifest, stela_formats::boot_bundle::Nvram, stela_runtime::machine::Host, stela_formats::payload, stela_formats::payload::PayloadManifest, stela_formats::payload::ReadAt};
use uefi::{
CString16, boot,
proto::media::{
@@ -9,7 +9,7 @@ pub(crate) mod registered;
use alloc::{format, string::String, vec::Vec};
use stela_loader::{apple_device_tree::DeviceTree, boot_args};
use stela_runtime::{boot_bundle::LoadedRegion, machine::Host};
use {stela_formats::boot_bundle::LoadedRegion, stela_runtime::machine::Host};
pub(crate) trait Ram {
fn read(&mut self, physical: u64, bytes: &mut [u8]) -> bool;
+12 -13
View File
@@ -8,12 +8,11 @@ mod cpus;
use alloc::{collections::BTreeSet, format, string::String, vec::Vec};
use sha2::{Digest, Sha256};
use stela_loader::{apple_device_tree::DeviceTree, boot_bundle::ORIGINAL_DEVICE_TREE_FILE};
use stela_runtime::{
boot_bundle::{Manifest, Source, Target, Verified},
machine::{
Chip,
soc::assigned::{ResourceProfile, SourceIdentity},
},
use {
stela_contracts::Chip, stela_formats::boot_bundle::Manifest,
stela_formats::boot_bundle::Source, stela_formats::boot_bundle::Target,
stela_formats::boot_bundle::Verified, stela_runtime::machine::soc::assigned::ResourceProfile,
stela_runtime::machine::soc::assigned::SourceIdentity,
};
/// Retains the verified original and exact selected metadata. Original bytes
@@ -332,19 +331,19 @@ mod tests {
},
"sources": [{
"component": "RestoreDeviceTree", "member": "Firmware/test.im4p",
"container_sha256": stela_runtime::sha256(b"synthetic container"),
"container_sha256": stela_formats::sha256(b"synthetic container"),
"payload_type": "dtre", "description": "",
"decoded_bytes": original.len(), "decoded_sha256": stela_runtime::sha256(original)
"decoded_bytes": original.len(), "decoded_sha256": stela_formats::sha256(original)
}],
"options": {"dram_base": 0x800000000u64, "dram_size": 0x40000000, "phys_base": 0x800000000u64},
"files": [
{"name": ORIGINAL_DEVICE_TREE_FILE, "bytes": original.len(), "sha256": stela_runtime::sha256(original)},
{"name": "devicetree.adt", "bytes": prepared.len(), "sha256": stela_runtime::sha256(prepared)}
{"name": ORIGINAL_DEVICE_TREE_FILE, "bytes": original.len(), "sha256": stela_formats::sha256(original)},
{"name": "devicetree.adt", "bytes": prepared.len(), "sha256": stela_formats::sha256(prepared)}
],
"regions": [{
"name": "DeviceTree", "file": "devicetree.adt", "file_offset": 0,
"bytes": prepared.len(), "guest_pa": 0x800000000u64, "memory_bytes": 0x4000,
"sha256": stela_runtime::sha256(prepared)
"sha256": stela_formats::sha256(prepared)
}],
"entry": {"image": "synthetic", "virtual_address": 0, "physical_address": 0x800000000u64},
"entry_x0": 0x800004000u64, "boot_args": {"command_line": "-v"},
@@ -519,7 +518,7 @@ mod tests {
for (key, value) in [
(
"decoded_sha256",
json!(stela_runtime::sha256(b"different source")),
json!(stela_formats::sha256(b"different source")),
),
("decoded_bytes", json!(original.len() + 1)),
("container_sha256", json!("0".repeat(64))),
@@ -532,7 +531,7 @@ mod tests {
let mut loaded = base.clone();
loaded["regions"][0]["file"] = json!(ORIGINAL_DEVICE_TREE_FILE);
loaded["regions"][0]["bytes"] = json!(original.len());
loaded["regions"][0]["sha256"] = json!(stela_runtime::sha256(&original));
loaded["regions"][0]["sha256"] = json!(stela_formats::sha256(&original));
assert!(intake(&loaded, &original, &prepared).is_err());
let mut patched = base.clone();
patched["patches"] = json!([{
@@ -1,7 +1,7 @@
//! Selected PE provenance and the prepared CPU sequence retained across loading.
use alloc::{format, string::String, vec::Vec};
use stela_loader::apple_device_tree::{DeviceTree, Node, Property};
use stela_runtime::boot_bundle::{BootCpu, BootCpuSelection};
use {stela_formats::boot_bundle::BootCpu, stela_formats::boot_bundle::BootCpuSelection};
#[derive(Debug, PartialEq, Eq)]
struct Cpu {
+2 -2
View File
@@ -5,14 +5,14 @@
//! The mount gives the guest one of the screen mode's size (the mode
//! `console::mode` chose, which the DCP model can advertise), 32 bits per
//! pixel, at the top of guest DRAM, outside the range the kernel manages
//! (`stela_runtime::boot_bundle::Machine`), and shows only the frames the
//! (`stela_formats::boot_bundle::Machine`), and shows only the frames the
//! modeled DCP presents. XNU's 32-bit pixels are x8r8g8b8 with blue in the
//! low byte (public XNU `osfmk/console/video_console.c`), GOP's BGR order;
//! an RGB or channel-mask mode re-encodes each pixel.
use crate::console::{self, Framebuffer};
use crate::output;
use core::sync::atomic::{AtomicBool, Ordering};
use stela_runtime::boot_bundle;
use stela_formats::boot_bundle;
use stela_runtime::machine::apple::{DisplayLog, Scanout, ScanoutFormat, ScanoutMode};
/// Whether the DCP model has presented a swap: the first one takes the
+2 -2
View File
@@ -42,7 +42,7 @@ impl<'a> Placement<'a> {
}
let path = core::str::from_utf8(bytes.get(HEADER..path_end).ok_or("FDR path bounds")?)
.map_err(|_| "FDR path is not UTF-8")?;
if !stela_runtime::payload::safe_path(path) {
if !stela_formats::payload::safe_path(path) {
return Err(String::from("invalid FDR state file path"));
}
Ok(Self {
@@ -133,7 +133,7 @@ pub fn writer(
output::arguments(format_args!(
"FDR COMMIT durable bytes={} sha256={} flushed/readback verified\n",
bytes.len(),
stela_runtime::sha256(bytes)
stela_formats::sha256(bytes)
));
Ok(())
}))
+1 -4
View File
@@ -12,10 +12,7 @@ use super::bundle::{self, Bytes};
use crate::output;
use alloc::{boxed::Box, format, string::String, vec::Vec};
use stela_drivers::block::BlockDevice;
use stela_runtime::{
payload::{Layout, PayloadManifest, piece_name, pieces::Joined},
pc::fat32::Fat32,
};
use {stela_formats::payload::Layout, stela_formats::payload::PayloadManifest, stela_formats::payload::piece_name, stela_formats::payload::pieces::Joined, stela_runtime::pc::fat32::Fat32};
use uefi::proto::media::file::Directory;
/// The joined install medium the restore host reads.
+1 -9
View File
@@ -13,15 +13,7 @@
use crate::output;
use alloc::{boxed::Box, collections::BTreeMap, format, vec::Vec};
use stela_drivers::block::{BlockDevice, BlockError, Shared, Submission};
use stela_runtime::{
boot_bundle::Nvram,
machine::apple::{
AppleDevices,
nor::{CAPACITY, Image, persist},
sep_state,
},
pc::{boot_log, machine_state},
};
use {stela_formats::boot_bundle::Nvram, stela_runtime::machine::apple::AppleDevices, stela_runtime::machine::apple::nor::CAPACITY, stela_runtime::machine::apple::nor::Image, stela_runtime::machine::apple::nor::persist, stela_runtime::machine::apple::sep_state, stela_runtime::pc::boot_log, stela_runtime::pc::machine_state};
/// Split the Apple region `partition` into the guest's ANS2 namespace and
/// the machine state in its tail. A partition too small for both, or with
+1 -7
View File
@@ -14,13 +14,7 @@
use super::network::Shared;
use crate::output;
use alloc::{collections::VecDeque, string::String};
use stela_runtime::{
net::{
NetError, Transfer,
http::{self, Ranged},
},
payload::{Layout, PayloadManifest, ReadAt},
};
use {stela_runtime::net::NetError, stela_runtime::net::Transfer, stela_runtime::net::http, stela_runtime::net::http::Ranged, stela_formats::payload::Layout, stela_formats::payload::PayloadManifest, stela_formats::payload::ReadAt};
/// How far [`Remote::pump`] fills ahead of the restore.
const AHEAD: usize = 32 << 20;
+2 -15
View File
@@ -24,20 +24,7 @@ use crate::{
use alloc::{boxed::Box, collections::VecDeque, format, rc::Rc, string::String, vec::Vec};
use core::{cell::RefCell, task::Poll};
use stela_drivers::block::{Ahead, BlockDevice, ReadAhead};
use stela_runtime::{
machine::apple::{AppleDevices, MuxStream, UsbClient, UsbId},
net::Transfer,
payload::{PayloadManifest, Purpose, ReadAt},
restore::{
answers::Answers,
driver::{Driver, Ports},
proxy::{Control, Destination, Event as ProxyEvent, Peer, Version},
route::Route,
source::Extent,
store::{Store, Verify},
stream::ByteStream,
},
};
use {stela_runtime::machine::apple::AppleDevices, stela_runtime::machine::apple::MuxStream, stela_runtime::machine::apple::UsbClient, stela_runtime::machine::apple::UsbId, stela_runtime::net::Transfer, stela_formats::payload::PayloadManifest, stela_formats::payload::Purpose, stela_formats::payload::ReadAt, stela_runtime::restore::answers::Answers, stela_runtime::restore::driver::Driver, stela_runtime::restore::driver::Ports, stela_runtime::restore::proxy::Control, stela_runtime::restore::proxy::Destination, stela_runtime::restore::proxy::Event as ProxyEvent, stela_runtime::restore::proxy::Peer, stela_runtime::restore::proxy::Version, stela_runtime::restore::route::Route, stela_runtime::restore::source::Extent, stela_runtime::restore::store::Store, stela_runtime::restore::store::Verify, stela_runtime::restore::stream::ByteStream};
/// The bundle's boot manifest (`stela_loader::boot_bundle`).
const BOOT_MANIFEST_FILE: &str = "boot-manifest.im4m";
@@ -688,7 +675,7 @@ impl Experiment {
output::arguments(format_args!(
"FDR DIAGNOSTIC bytes={} sha256={} original Memory-store import; durable host commit enabled; factory trust unqualified\n",
placement.diagnostic.len(),
stela_runtime::sha256(placement.diagnostic),
stela_formats::sha256(placement.diagnostic),
));
}
if signer.is_some() {
+22 -12
View File
@@ -666,15 +666,25 @@ mod tests {
use core::cell::Cell;
use sha2::{Digest, Sha256};
use stela_loader::apple_device_tree::Node;
use stela_runtime::machine::{
Chip,
caches::{Cache, Caches},
registers::Identity,
soc::assigned::{
CacheId, Capacity, CapacityKind, ClusterId, ClusterSlot, CoreKind, DomainId,
InterruptId, InterruptTarget, KindId, PeSlot, PowerResource, ResourceProfile,
Resources, SharedCache, StartId, StartResource,
},
use {
stela_contracts::Chip, stela_contracts::caches::Cache, stela_contracts::caches::Caches,
stela_contracts::identity::Identity, stela_runtime::machine::soc::assigned::CacheId,
stela_runtime::machine::soc::assigned::Capacity,
stela_runtime::machine::soc::assigned::CapacityKind,
stela_runtime::machine::soc::assigned::ClusterId,
stela_runtime::machine::soc::assigned::ClusterSlot,
stela_runtime::machine::soc::assigned::CoreKind,
stela_runtime::machine::soc::assigned::DomainId,
stela_runtime::machine::soc::assigned::InterruptId,
stela_runtime::machine::soc::assigned::InterruptTarget,
stela_runtime::machine::soc::assigned::KindId,
stela_runtime::machine::soc::assigned::PeSlot,
stela_runtime::machine::soc::assigned::PowerResource,
stela_runtime::machine::soc::assigned::ResourceProfile,
stela_runtime::machine::soc::assigned::Resources,
stela_runtime::machine::soc::assigned::SharedCache,
stela_runtime::machine::soc::assigned::StartId,
stela_runtime::machine::soc::assigned::StartResource,
};
fn cpuid_identity(maximum: u32, vendor: [u32; 3]) -> native::Cpuid {
@@ -1093,8 +1103,8 @@ mod tests {
}
fn captured_live_tree(mut tree: DeviceTree, command: &str) -> LiveTree {
use crate::boot_live_tree::Ram;
use stela_formats::boot_bundle::LoadedRegion;
use stela_loader::boot_args::{self, BootArgs, Video};
use stela_runtime::boot_bundle::LoadedRegion;
const ARGS: u64 = 0x1000;
const TREE: u64 = 0x10000;
const BYTES: usize = 1 << 20;
@@ -1168,7 +1178,7 @@ mod tests {
.join("DeviceTree.j473ap.adt");
let original = std::fs::read(file).unwrap();
assert_eq!(
stela_runtime::sha256(&original),
stela_formats::sha256(&original),
"a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c"
);
let mut tree = DeviceTree::parse(&original).unwrap();
@@ -1295,7 +1305,7 @@ mod tests {
#[test]
#[ignore = "requires retained original26A434J314s and prepared bundle DT"]
fn original_mode1_factory_projects_actual_live_tree_without_public_pmgr_admission() {
use stela_runtime::machine::{adt, soc};
use {stela_contracts::adt, stela_runtime::machine::soc};
let original = std::fs::read(std::env::var("STELA_TEST_ASSIGNED_DT").unwrap()).unwrap();
let raw = std::fs::read(std::env::var("STELA_TEST_ASSIGNED_PREPARED_DT").unwrap()).unwrap();
assert_eq!(
+2 -2
View File
@@ -344,7 +344,7 @@ fn record(
let bytes: usize = manifest.images.iter().map(|image| image.length).sum();
let record = serde_json::json!({
"kind": "manifest", "phase": phase, "images": images, "bytes": bytes,
"sha256": stela_runtime::sha256(manifest_bytes),
"sha256": stela_formats::sha256(manifest_bytes),
});
output::arguments(format_args!("HOST FIRMWARE RECORD {record}\n"));
for (index, expected) in manifest.images.iter().enumerate() {
@@ -553,7 +553,7 @@ mod tests {
.flat_map(|requirement| [true, false].map(|collide| (requirement, collide)))
{
let target = requirement.target;
let digest = stela_runtime::sha256(&RAW);
let digest = stela_formats::sha256(&RAW);
let manifest = serde_json::json!({"schema":1,"images":[{
"name":if collide_name {requirement.name} else {"synthetic/raw.bin"},
"path":"raw.bin","length":RAW.len(),"sha256":digest,
+2 -5
View File
@@ -25,10 +25,7 @@ use crate::{
};
use alloc::{format, string::String, vec, vec::Vec};
use sha2::{Digest, Sha256};
use stela_runtime::{
payload::gpt::{self, Found, Guid, Role, Table},
pc::{machine_state, storage::Target},
};
use {stela_formats::payload::gpt, stela_formats::payload::gpt::Found, stela_formats::payload::gpt::Guid, stela_formats::payload::gpt::Role, stela_formats::payload::gpt::Table, stela_runtime::pc::machine_state, stela_runtime::pc::storage::Target};
use uefi::{
Handle,
boot::{self, OpenProtocolAttributes, OpenProtocolParams, ScopedProtocol},
@@ -574,7 +571,7 @@ fn disks() -> Vec<Disk> {
};
let found = gpt::read(geometry, |lba, blocks| {
disk.read(lba, blocks)
.map_err(stela_runtime::payload::PayloadError::Disk)
.map_err(stela_formats::payload::PayloadError::Disk)
});
match found {
Ok(Found::Table { table, .. }) => disk.table = Some(table),
@@ -6,18 +6,7 @@ use crate::{apic::Apic, engine::host, handoff::Handoff};
use alloc::{sync::Arc, vec::Vec};
use stela_compiler::{GuestState, TargetCpu};
use stela_drivers::bus::dma::memory::{CacheAttribute, CpuMapping, PageSource, PinnedPages};
use stela_runtime::{
machine::{
self, Chip, Cpu, CpuProfile, DeviceError, Devices, Host, Identity, Lines, Machine,
PeerState, Stop,
engine::{
self,
publication::{WorkerBinding, WorkerId},
},
exception::Pstate,
},
memory::{RegisteredSystemRam, ReservedSystemRamRange},
};
use {stela_runtime::machine, stela_contracts::Chip, stela_runtime::machine::Cpu, stela_runtime::machine::CpuProfile, stela_runtime::machine::DeviceError, stela_runtime::machine::Devices, stela_runtime::machine::Host, stela_contracts::identity::Identity, stela_runtime::machine::Lines, stela_runtime::machine::Machine, stela_runtime::machine::PeerState, stela_runtime::machine::Stop, stela_runtime::machine::engine, stela_runtime::machine::engine::publication::WorkerBinding, stela_runtime::machine::engine::publication::WorkerId, stela_runtime::machine::exception::Pstate, stela_runtime::memory::RegisteredSystemRam, stela_runtime::memory::ReservedSystemRamRange};
struct Reservation {
pages: PinnedPages,
@@ -6,7 +6,7 @@ use stela_loader::{
apple_device_tree::{DeviceTree, Node},
boot_args::{self, BootArgs, Video},
};
use stela_runtime::boot_bundle::LoadedRegion;
use stela_formats::boot_bundle::LoadedRegion;
/// # Safety
/// Cold fixture owns this exact registered RAM; no frames or producers exist.
+2 -9
View File
@@ -23,14 +23,7 @@ use alloc::{
vec::Vec,
};
use sha2::{Digest, Sha256};
use stela_runtime::payload::{
CopyError, Layout, MANIFEST_FILE, MemberRead, PayloadError, PayloadManifest, PayloadSource,
ReadAt, copy_verified,
gpt::{self, Disk, Guid, Request, Role},
images_directory, slice_count, slice_path,
staging::{self, Header},
zip::{Archive, MemberStream},
};
use {stela_formats::payload::CopyError, stela_formats::payload::Layout, stela_formats::payload::MANIFEST_FILE, stela_formats::payload::MemberRead, stela_formats::payload::PayloadError, stela_formats::payload::PayloadManifest, stela_formats::payload::PayloadSource, stela_formats::payload::ReadAt, stela_formats::payload::copy_verified, stela_formats::payload::gpt, stela_formats::payload::gpt::Disk, stela_formats::payload::gpt::Guid, stela_formats::payload::gpt::Request, stela_formats::payload::gpt::Role, stela_formats::payload::images_directory, stela_formats::payload::slice_count, stela_formats::payload::slice_path, stela_formats::payload::staging, stela_formats::payload::staging::Header, stela_formats::payload::zip::Archive, stela_formats::payload::zip::MemberStream};
use uefi::{
CString16, Handle,
boot::{self, OpenProtocolAttributes, OpenProtocolParams, ScopedProtocol},
@@ -828,7 +821,7 @@ fn stage(
payload_path: &str,
) -> Result<(), &'static str> {
let source_json = source.manifest.to_json();
let header = Header::plan(subset, stela_runtime::sha256(source_json.as_bytes()));
let header = Header::plan(subset, stela_formats::sha256(source_json.as_bytes()));
let mut target = find_target(install, payload_path)?;
output::arguments(format_args!(
"TARGET path={} block={} blocks={}\n",
+1 -13
View File
@@ -31,19 +31,7 @@ use stela_loader::{
mount_interface::ChoiceKind,
recovery,
};
use stela_runtime::{
apfs::{self, ApfsError, Container},
machine::apple::nor::{
CAPACITY, Image, SECTOR_SIZE,
nvram::{Variables, empty_bank},
},
payload::{
PayloadError, ReadAt,
gpt::{self, Disk, Role},
},
pc::{machine_state, storage::Target},
preboot::{self, PrebootError},
};
use {stela_formats::apfs, stela_formats::apfs::ApfsError, stela_formats::apfs::Container, stela_runtime::machine::apple::nor::CAPACITY, stela_runtime::machine::apple::nor::Image, stela_runtime::machine::apple::nor::SECTOR_SIZE, stela_runtime::machine::apple::nor::nvram::Variables, stela_runtime::machine::apple::nor::nvram::empty_bank, stela_formats::payload::PayloadError, stela_formats::payload::ReadAt, stela_formats::payload::gpt, stela_formats::payload::gpt::Disk, stela_formats::payload::gpt::Role, stela_runtime::pc::machine_state, stela_runtime::pc::storage::Target, stela_formats::preboot, stela_formats::preboot::PrebootError};
use uefi::{
Handle,
boot::{self, OpenProtocolAttributes, OpenProtocolParams, ScopedProtocol},
+1 -1
View File
@@ -337,7 +337,7 @@ impl Prepared {
let mut first = alloc::vec![0; disk.block_size as usize];
partition
.read(0, &mut first)
.map(|()| stela_runtime::sha256(&first))
.map(|()| stela_formats::sha256(&first))
.map_err(storage::StorageError::Device)
};
match result {
+2
View File
@@ -14,6 +14,8 @@ name = "stela-launcher"
path = "src/bin/stela-launcher/main.rs"
[dependencies]
stela-contracts = { path = "../stela-contracts" }
stela-formats = { path = "../stela-formats", default-features = false }
anyhow.workspace = true
clap.workspace = true
serde = { workspace = true, features = ["std"] }
+7 -6
View File
@@ -1,4 +1,4 @@
//! Inspect APFS images with Stela's own reader (`stela_runtime::apfs`), the
//! Inspect APFS images with Stela's own reader (`stela_formats::apfs`), the
//! one `stela.efi` uses: list containers and volumes, directories, and copy
//! files out with their SHA-256.
use anyhow::{Context, Result, bail, ensure};
@@ -9,9 +9,10 @@ use std::{
io::{Read, Seek, SeekFrom, Write},
path::{Path, PathBuf},
};
use stela_runtime::{
apfs::{self, Container, Volume, uuid_text, volume::Snapshot},
payload::ReadAt,
use {
stela_formats::apfs, stela_formats::apfs::Container, stela_formats::apfs::Volume,
stela_formats::apfs::uuid_text, stela_formats::apfs::volume::Snapshot,
stela_formats::payload::ReadAt,
};
/// An image file as a reader source.
@@ -199,7 +200,7 @@ impl ApfsCommand {
match volume.read(&mut container.device, &inode) {
Ok(bytes) => {
json!({"path": child, "kind": "file", "bytes": inode.logical_size(),
"sha256": stela_runtime::sha256(&bytes)})
"sha256": stela_formats::sha256(&bytes)})
}
Err(error) => {
json!({"path": child, "kind": "file", "bytes": inode.logical_size(),
@@ -226,7 +227,7 @@ impl ApfsCommand {
File::create_new(&output)?.write_all(&bytes)?;
println!(
"{}",
json!({"path": target.path, "bytes": bytes.len(), "sha256": stela_runtime::sha256(&bytes)})
json!({"path": target.path, "bytes": bytes.len(), "sha256": stela_formats::sha256(&bytes)})
);
}
}
+10 -10
View File
@@ -6,6 +6,7 @@ use crate::{
use anyhow::{Context, Result, bail, ensure};
use clap::{Args, Subcommand};
use std::{fs::OpenOptions, io::Write, path::PathBuf};
use stela_formats::payload::Purpose;
use stela_loader::boot_bundle::{
self, Input, Inputs, Options, OverlayProperty, RootHash, Source, Target,
};
@@ -13,7 +14,6 @@ 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::payload::Purpose;
mod board_firmware;
mod disk;
@@ -221,7 +221,7 @@ fn mount(
}
let manifest = std::fs::read(bundle.join("bundle.json"))
.map_err(|error| format!("{} has no manifest: {error}", bundle.display()))?;
let manifest = stela_runtime::boot_bundle::Manifest::parse(&manifest)
let manifest = stela_formats::boot_bundle::Manifest::parse(&manifest)
.map_err(|error| format!("bundle manifest: {error:?}"))?;
// A bundle prepared for no particular machine has no ECID; the SEP
// takes a stand-in one, as the SSD takes a stand-in disk.
@@ -290,7 +290,7 @@ fn mount(
build: manifest
.target
.as_ref()
.map(|target| stela_runtime::builds::find(&target.product_build))
.map(|target| stela_formats::builds::find(&target.product_build))
.transpose()
.map_err(|error| error.to_string())?,
},
@@ -684,13 +684,13 @@ impl Prepare {
let source = Source {
component: label,
member: entry.path.clone(),
container_sha256: stela_runtime::sha256(&container),
container_sha256: stela_formats::sha256(&container),
payload_type: receipt
.as_ref()
.map_or_else(|| "opaque".into(), |r| r.payload_type.clone()),
description: receipt.map(|r| r.description).unwrap_or_default(),
decoded_bytes: bytes.len() as u64,
decoded_sha256: stela_runtime::sha256(&bytes),
decoded_sha256: stela_formats::sha256(&bytes),
};
Ok(Decoded {
bytes,
@@ -740,11 +740,11 @@ impl Prepare {
}
.into(),
member,
container_sha256: stela_runtime::sha256(&bytes),
container_sha256: stela_formats::sha256(&bytes),
payload_type: "im4m".into(),
description: String::new(),
decoded_bytes: bytes.len() as u64,
decoded_sha256: stela_runtime::sha256(&bytes),
decoded_sha256: stela_formats::sha256(&bytes),
};
Ok(Some(Decoded {
bytes,
@@ -764,7 +764,7 @@ impl Prepare {
BUILD_MANIFEST_LIMIT,
)?;
let bytes = ticket::personalized(&manifest, identity.index, ecid)?;
let digest = stela_runtime::sha256(&bytes);
let digest = stela_formats::sha256(&bytes);
Some(Decoded {
source: Source {
component: "Boot manifest".into(),
@@ -795,7 +795,7 @@ impl Prepare {
payload_type: receipt.payload_type,
description: receipt.description,
decoded_bytes: bytes.len() as u64,
decoded_sha256: stela_runtime::sha256(&bytes),
decoded_sha256: stela_formats::sha256(&bytes),
..raw.source
},
bytes,
@@ -835,7 +835,7 @@ impl Prepare {
.and_then(|name| name.to_str())
.with_context(|| format!("{} has no UTF-8 file name", path.display()))?
.to_owned();
let digest = stela_runtime::sha256(&bytes);
let digest = stela_formats::sha256(&bytes);
let source = Source {
component: "BoardFirmware".into(),
member: path.canonicalize()?.display().to_string(),
+6 -7
View File
@@ -13,10 +13,9 @@
use super::Decoded;
use anyhow::{Context, Result, bail};
use stela_loader::boot_bundle::{Bundle, DEVICE_TREE_FILE, Source};
use stela_runtime::{
apfs::{self, Container},
machine::soc,
payload::ReadAt,
use {
stela_formats::apfs, stela_formats::apfs::Container, stela_formats::payload::ReadAt,
stela_runtime::machine::soc,
};
/// Where the restore ramdisk keeps the board's firmware images.
@@ -90,7 +89,7 @@ pub(super) fn from_ramdisk(
)
})?;
let bytes = volume.read(&mut container.device, &inode)?;
let digest = stela_runtime::sha256(&bytes);
let digest = stela_formats::sha256(&bytes);
let source = Source {
component: "BoardFirmware".into(),
member: member.clone(),
@@ -127,7 +126,7 @@ mod tests {
assert_eq!(compressed[3], 0, "gzip -n: no optional header fields");
let bytes = miniz_oxide::inflate::decompress_to_vec(&compressed[10..compressed.len() - 8])
.expect("gzip -n deflate stream");
let digest = stela_runtime::sha256(&bytes);
let digest = stela_formats::sha256(&bytes);
Decoded {
source: Source {
component: "RestoreRamDisk".into(),
@@ -156,7 +155,7 @@ mod tests {
assert_eq!((name.as_str(), &image.bytes), ("pattern.bin", &pattern));
assert_eq!(image.source.member, "ramdisk.dmg");
assert_eq!(image.source.container_sha256, "c".repeat(64));
assert_eq!(image.source.decoded_sha256, stela_runtime::sha256(&pattern));
assert_eq!(image.source.decoded_sha256, stela_formats::sha256(&pattern));
assert!(
image
.source
+1 -1
View File
@@ -7,8 +7,8 @@ use super::{DiskRecovery, Prepare};
use crate::apfs::open_image;
use anyhow::{Result, ensure};
use std::path::Path;
use stela_formats::apfs;
use stela_loader::{boot_selection::BootVolume, installed, recovery, upgrade};
use stela_runtime::apfs;
impl Prepare {
pub(super) fn run_disk(&self, path: &Path) -> Result<()> {
+1 -1
View File
@@ -30,7 +30,7 @@ use std::{
use stela_loader::mount_interface;
use stela_runtime::pc::boot_log;
use stela_runtime::payload::MAX_SLICE_BYTES;
use stela_formats::payload::MAX_SLICE_BYTES;
/// The removable-media boot loader path for x64 (UEFI 2.10, Removable Media
/// Boot Behavior).
+1 -1
View File
@@ -14,7 +14,7 @@ use std::collections::BTreeMap;
#[cfg(any(test, all(target_os = "macos", target_arch = "x86_64")))]
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use stela_runtime::builds::{self, Build};
use {stela_formats::builds, stela_formats::builds::Build};
/// Development override: a colon-separated list of guest roots.
#[cfg(any(test, all(target_os = "macos", target_arch = "x86_64")))]
+6 -6
View File
@@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{IsTerminal, Read};
use std::path::{Path, PathBuf};
use stela_runtime::payload::Purpose;
use stela_formats::payload::Purpose;
/// The receipt's `kind`.
pub(super) const KIND: &str = "stela_guest_system";
@@ -567,7 +567,7 @@ mod tests {
listed.push(disk::Copied {
path: path.to_string(),
bytes: bytes.len() as u64,
sha256: stela_runtime::sha256(bytes),
sha256: stela_formats::sha256(bytes),
});
}
stela_runtime::write_json(
@@ -589,7 +589,7 @@ mod tests {
&cache,
&[("/System/Library/dyld/dyld_shared_cache_arm64e", b"cache")],
)?;
let layout = Layout::new(work.path().join("Stela"), stela_runtime::builds::DEFAULT);
let layout = Layout::new(work.path().join("Stela"), stela_formats::builds::DEFAULT);
from_roots(&layout, &[files.clone(), cache.clone()], true)?;
assert!(!layout.directory().exists(), "a dry run changes nothing");
from_roots(&layout, &[files.clone(), cache.clone()], false)?;
@@ -618,7 +618,7 @@ mod tests {
],
)?;
fs::write(files.join("usr/lib/dyld"), b"changed")?;
let layout = Layout::new(work.path().join("Stela"), stela_runtime::builds::DEFAULT);
let layout = Layout::new(work.path().join("Stela"), stela_formats::builds::DEFAULT);
let error = from_roots(&layout, &[files], false)
.unwrap_err()
.to_string();
@@ -632,7 +632,7 @@ mod tests {
let work = tempfile::tempdir()?;
let files = work.path().join("guest-files");
extraction(&files, &[("/usr/lib/dyld", b"dyld")])?;
let layout = Layout::new(work.path().join("Stela"), stela_runtime::builds::DEFAULT);
let layout = Layout::new(work.path().join("Stela"), stela_formats::builds::DEFAULT);
assert!(from_roots(&layout, &[files], false).is_err());
Ok(())
}
@@ -642,7 +642,7 @@ mod tests {
let work = tempfile::tempdir()?;
let ipsw = work.path().join("other.ipsw");
restore::payload::synthetic_ipsw_of(&ipsw, "99Z999")?;
let layout = Layout::new(work.path().join("Stela"), stela_runtime::builds::DEFAULT);
let layout = Layout::new(work.path().join("Stela"), stela_formats::builds::DEFAULT);
let error = from_ipsw(&layout, &ipsw, None, false)
.unwrap_err()
.to_string();
@@ -37,7 +37,7 @@ pub(in crate::guest_system) fn read(
record.kind == KIND
&& record.schema_version == SCHEMA
&& record.product_build == original.product_build
&& record.receipt_sha256 == stela_runtime::sha256(receipt)
&& record.receipt_sha256 == stela_formats::sha256(receipt)
&& !record.kernels.is_empty()
&& [record.source_sha256, record.manifest_sha256]
.iter()
@@ -183,9 +183,9 @@ pub(in crate::guest_system) fn refresh(
kind: KIND.into(),
schema_version: SCHEMA,
product_build: layout.build.build.into(),
receipt_sha256: stela_runtime::sha256(&original),
receipt_sha256: stela_formats::sha256(&original),
source_sha256,
manifest_sha256: stela_runtime::sha256(&manifest_bytes),
manifest_sha256: stela_formats::sha256(&manifest_bytes),
kernels,
};
if dry_run {
@@ -234,7 +234,7 @@ mod tests {
let work = tempfile::tempdir()?;
let layout = Layout::new(
work.path().join("installed"),
stela_runtime::builds::DEFAULT,
stela_formats::builds::DEFAULT,
);
fs::create_dir_all(layout.root().join("usr/lib"))?;
fs::write(layout.root().join("usr/lib/dyld"), b"original dyld")?;
@@ -301,14 +301,14 @@ mod tests {
component: component.into(),
member: member.into(),
member_bytes: aea.len() as u64,
aea_header_sha256: stela_runtime::sha256(&header),
aea_header_sha256: stela_formats::sha256(&header),
volume: None,
})
.into(),
files: vec![disk::Copied {
path: "/usr/lib/dyld".into(),
bytes: 13,
sha256: stela_runtime::sha256(b"original dyld"),
sha256: stela_formats::sha256(b"original dyld"),
}],
kernels: vec![],
};
+1 -1
View File
@@ -303,7 +303,7 @@ pub fn remote_inventory(
"{http} serves another object than {}",
image.url
);
let layout = stela_runtime::payload::Layout::Remote {
let layout = stela_formats::payload::Layout::Remote {
url: http,
etag: source.etag().into(),
};
+1 -1
View File
@@ -10,7 +10,7 @@ use std::{
path::{Path, PathBuf},
time::Duration,
};
use stela_runtime::sha256;
use stela_formats::sha256;
const MAX_METADATA: usize = 64 * 1024;
const MAX_KEY: usize = 64 * 1024;
@@ -141,11 +141,11 @@ impl Root {
return Ok(data);
}
let decoded = match self.compression {
LZFSE => stela_runtime::lzfse::decode(&data, raw),
LZVN if stela_runtime::lzfse::is_lzfse(&data) => {
stela_runtime::lzfse::decode(&data, raw)
LZFSE => stela_formats::lzfse::decode(&data, raw),
LZVN if stela_formats::lzfse::is_lzfse(&data) => {
stela_formats::lzfse::decode(&data, raw)
}
LZVN => stela_runtime::lzfse::decode_lzvn(&data, raw),
LZVN => stela_formats::lzfse::decode_lzvn(&data, raw),
_ => bail!(
"an AEA1 segment of stored data is {} bytes, not {raw}",
data.len()
@@ -181,7 +181,7 @@ pub(super) fn decrypt(
);
let auth = read_vec(input, auth_bytes, "metadata")?;
ensure!(
stela_runtime::sha256(&[&fixed[..], &auth].concat()) == header_sha256,
stela_formats::sha256(&[&fixed[..], &auth].concat()) == header_sha256,
"the AEA1 header differs from the one inspected"
);
let salt: [u8; SALT_BYTES] = read(input, "salt")?;
+1 -1
View File
@@ -14,7 +14,7 @@
use super::manifest::{Component, Identity, RestoreManifest};
use anyhow::{Context, Result, bail};
use std::fmt;
use stela_runtime::payload::Purpose;
use stela_formats::payload::Purpose;
/// The profile registry: each board's `Ap,ProductType`, `ApChipID`,
/// `ApBoardID` and `DeviceClass`.
+1 -1
View File
@@ -152,7 +152,7 @@ pub fn inspect(bytes: &[u8], model: Option<&str>) -> Result<RestoreManifest> {
.collect::<Result<_>>()?;
Ok(RestoreManifest {
schema_version: 1,
manifest_sha256: stela_runtime::sha256(bytes),
manifest_sha256: stela_formats::sha256(bytes),
product_version: required(root, "ProductVersion")?,
product_build: required(root, "ProductBuildVersion")?,
supported_models,
+17 -12
View File
@@ -17,12 +17,17 @@ use std::{
io::{Read, Seek, Write},
path::{Path, PathBuf},
};
use stela_runtime::payload::{
AeaKey, BLOCK_HASHES_FILE, BlockHashes, HASH_BLOCK_BYTES, IdentitySet, KIND, Layout,
MANIFEST_FILE, Member, PayloadManifest, Purpose, SourceImage, images_directory, slice_count,
slice_path,
};
use zip::ZipArchive;
use {
stela_formats::payload::AeaKey, stela_formats::payload::BLOCK_HASHES_FILE,
stela_formats::payload::BlockHashes, stela_formats::payload::HASH_BLOCK_BYTES,
stela_formats::payload::IdentitySet, stela_formats::payload::KIND,
stela_formats::payload::Layout, stela_formats::payload::MANIFEST_FILE,
stela_formats::payload::Member, stela_formats::payload::PayloadManifest,
stela_formats::payload::Purpose, stela_formats::payload::SourceImage,
stela_formats::payload::images_directory, stela_formats::payload::slice_count,
stela_formats::payload::slice_path,
};
const BUILD_MANIFEST: &str = "BuildManifest.plist";
const RESTORE_PLIST: &str = "Restore.plist";
@@ -146,7 +151,7 @@ fn select_scope<R: Read + Seek>(
.collect();
for name in &names {
ensure!(
stela_runtime::payload::safe_path(name),
stela_formats::payload::safe_path(name),
"unsafe member {name}"
);
archive
@@ -233,7 +238,7 @@ fn block_hashes(hashed: &[Hashed]) -> (Vec<u8>, BlockHashes) {
let entry = BlockHashes {
file: BLOCK_HASHES_FILE.into(),
block_bytes: HASH_BLOCK_BYTES,
sha256: stela_runtime::sha256(&file),
sha256: stela_formats::sha256(&file),
};
(file, entry)
}
@@ -307,7 +312,7 @@ fn make_key(
member: member.into(),
header_sha256: metadata.header_sha256.clone(),
url,
key_sha256: stela_runtime::sha256(key_pem.as_bytes()),
key_sha256: stela_formats::sha256(key_pem.as_bytes()),
url_asset_sha256: Some(url_asset_sha256),
key_pem,
})
@@ -759,7 +764,7 @@ pub fn write(options: &WriteOptions<'_>) -> Result<serde_json::Value> {
let (layout, members, whole) = match options.layout {
PayloadLayout::Split => {
ensure!(
(1..=stela_runtime::payload::MAX_SLICE_BYTES).contains(&options.slice_bytes),
(1..=stela_formats::payload::MAX_SLICE_BYTES).contains(&options.slice_bytes),
"slice size must be 1..=4 GiB-1"
);
let whole = std::thread::scope(|scope| {
@@ -1005,7 +1010,7 @@ pub fn synthetic_ipsw_of(path: &Path, build: &str) -> Result<()> {
#[cfg(test)]
mod tests {
use super::*;
use stela_runtime::payload::Purpose;
use stela_formats::payload::Purpose;
fn options<'a>(image: &'a Path, root: &'a Path, layout: PayloadLayout) -> WriteOptions<'a> {
WriteOptions {
@@ -1058,7 +1063,7 @@ mod tests {
let mut original = Vec::new();
archive.by_name(&member.name)?.read_to_end(&mut original)?;
assert_eq!(joined, original);
assert_eq!(Some(stela_runtime::sha256(&joined)), member.sha256);
assert_eq!(Some(stela_formats::sha256(&joined)), member.sha256);
}
assert!(directory.join("Firmware/stelatest-os.dmg.003").exists());
assert!(!directory.join("Firmware/unrelated.bin.000").exists());
@@ -1172,7 +1177,7 @@ mod tests {
assert_eq!(in_place.source, manifest.source);
// Its block hashes cover every member's blocks, in order.
let entry = in_place.block_hashes.as_ref().unwrap();
assert_eq!(entry.sha256, stela_runtime::sha256(&blocks));
assert_eq!(entry.sha256, stela_formats::sha256(&blocks));
assert_eq!(blocks.len() as u64, in_place.hash_blocks() * 32);
let mut archive = ZipArchive::new(File::open(&image)?)?;
let mut at = 0;
+6 -6
View File
@@ -101,8 +101,8 @@ use std::{
fs,
path::{Path, PathBuf},
};
use stela_formats::builds;
use stela_loader::mount_interface::{self, Interface};
use stela_runtime::builds;
use uninstall::uninstall;
/// The Mac model Stela presents by default.
@@ -255,7 +255,7 @@ impl InstallMedium {
);
let (_, build) = restore::payload::identity(&self.ipsw, &self.model)?;
let bytes = fs::metadata(&self.ipsw)?.len();
let piece_bytes = stela_runtime::payload::PIECE_BYTES;
let piece_bytes = stela_formats::payload::PIECE_BYTES;
medium::check_space(&host, &self.volume, &build, bytes, piece_bytes)?;
let expected = medium::Expected::of(restore::receipt(&self.ipsw)?.as_ref());
let inventory = restore::payload::inventory(&self.ipsw, &self.model, true, None, None)?;
@@ -271,8 +271,8 @@ impl InstallMedium {
println!(
"Engine options: --install \\{}\\{} --install-source <the partition's GPT unique \
GUID>",
stela_runtime::payload::install_directory(&build).replace('/', "\\"),
stela_runtime::payload::MANIFEST_FILE
stela_formats::payload::install_directory(&build).replace('/', "\\"),
stela_formats::payload::MANIFEST_FILE
);
if expected.sha1.is_none() {
println!(
@@ -313,7 +313,7 @@ struct Environment<'a> {
/// The revision of the bundles this `stela` prepares
/// (`stela_loader::boot_bundle::REVISION`).
bundle_revision: u32,
/// The macOS builds setup prepares (`stela_runtime::builds::SUPPORTED`);
/// The macOS builds setup prepares (`stela_formats::builds::SUPPORTED`);
/// tests add their synthetic images' builds.
builds: &'a [builds::Build],
}
@@ -419,7 +419,7 @@ impl Request {
let image = restore::select(&restore::catalog()?, Some(&build), Some(model))?;
restore::remote_inventory(&image, model, None)
},
piece_bytes: stela_runtime::payload::PIECE_BYTES,
piece_bytes: stela_formats::payload::PIECE_BYTES,
interface: mount_interface::CURRENT,
bundle_revision: stela_loader::boot_bundle::REVISION,
builds: builds::SUPPORTED,
+1 -1
View File
@@ -38,7 +38,7 @@ const FIRST_SCHEMA: u32 = 1;
const FIRST_REVISION: u32 = 0;
/// What a bundle's content is: its boot-bundle schema, the format
/// `stela.efi` reads (`stela_runtime::boot_bundle::SCHEMA_VERSION`), and its
/// `stela.efi` reads (`stela_formats::boot_bundle::SCHEMA_VERSION`), and its
/// revision, that of the loader that prepared it
/// (`stela_loader::boot_bundle::REVISION`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+1 -1
View File
@@ -22,7 +22,7 @@ use std::{
fs,
path::{Path, PathBuf},
};
use stela_runtime::builds;
use stela_formats::builds;
/// The setup USB's one unmounted partition besides its EFI partition: a
/// raw partition, which becomes the Mac's internal SSD. `None` when the USB
+5 -5
View File
@@ -28,11 +28,11 @@ use crate::efi;
use anyhow::{Result, bail};
use std::{fmt::Write as _, fs, path::Path};
use stela_loader::{boot_selection, mount_interface, recovery};
use stela_runtime::{
apfs::{self, Container, volume::APFS_VOL_ROLE_UPDATE},
machine::apple::{nor::CAPACITY, sep_state},
payload::ReadAt,
preboot,
use {
stela_formats::apfs, stela_formats::apfs::Container,
stela_formats::apfs::volume::APFS_VOL_ROLE_UPDATE, stela_formats::payload::ReadAt,
stela_formats::preboot, stela_runtime::machine::apple::nor::CAPACITY,
stela_runtime::machine::apple::sep_state,
};
/// A host partition as an APFS source.
+1 -1
View File
@@ -240,7 +240,7 @@ fn volume_label(label: &str) -> Result<[u8; 11]> {
mod tests {
use super::*;
use stela_drivers::block::RamDisk;
use stela_runtime::{payload::ReadAt, pc::fat32::Fat32};
use {stela_formats::payload::ReadAt, stela_runtime::pc::fat32::Fat32};
/// A disk holding the layout's writes over bytes that are not zero.
fn image(bytes: u64, block_size: u32, layout: &Layout) -> RamDisk {
+8 -5
View File
@@ -26,11 +26,14 @@ use stela_loader::{
boot_selection::{BOOT_COMMAND, Command, ONE_TIME_BOOT_COMMAND, RECOVERY_BOOT_MODE, lookup},
mount_interface::CHOSEN_DISK,
};
use stela_runtime::{
machine::apple::nor::{CAPACITY, Image, SECTOR_SIZE, nvram::Partition, nvram::Variables},
machine::apple::sep_state,
payload::gpt::DEFAULT_MIN_APPLE_BYTES,
pc::{boot_log, machine_state, storage::Target},
use {
stela_formats::payload::gpt::DEFAULT_MIN_APPLE_BYTES,
stela_runtime::machine::apple::nor::CAPACITY, stela_runtime::machine::apple::nor::Image,
stela_runtime::machine::apple::nor::SECTOR_SIZE,
stela_runtime::machine::apple::nor::nvram::Partition,
stela_runtime::machine::apple::nor::nvram::Variables, stela_runtime::machine::apple::sep_state,
stela_runtime::pc::boot_log, stela_runtime::pc::machine_state,
stela_runtime::pc::storage::Target,
};
const GPT_SIGNATURE: &[u8; 8] = b"EFI PART";
+17 -13
View File
@@ -33,9 +33,13 @@ use std::{
path::{Path, PathBuf},
};
use stela_boot_core::options::System;
use stela_runtime::payload::{
BLOCK_HASHES_FILE, BlockHashes, HASH_BLOCK_BYTES, Layout, MANIFEST_FILE, MAX_PIECES,
PIECE_HASHES_FILE, Piece, install_directory, piece_name, piece_sizes,
use {
stela_formats::payload::BLOCK_HASHES_FILE, stela_formats::payload::BlockHashes,
stela_formats::payload::HASH_BLOCK_BYTES, stela_formats::payload::Layout,
stela_formats::payload::MANIFEST_FILE, stela_formats::payload::MAX_PIECES,
stela_formats::payload::PIECE_HASHES_FILE, stela_formats::payload::Piece,
stela_formats::payload::install_directory, stela_formats::payload::piece_name,
stela_formats::payload::piece_sizes,
};
pub(super) mod download;
@@ -111,13 +115,13 @@ impl Medium {
Ok(bytes) => bytes,
Err(_) => return vec![format!("{} is missing", manifest.display())],
};
if stela_runtime::sha256(&bytes) != self.manifest_sha256 {
if stela_formats::sha256(&bytes) != self.manifest_sha256 {
return vec![format!(
"{} differs from the one setup wrote",
manifest.display()
)];
}
let Ok(parsed) = stela_runtime::payload::PayloadManifest::parse(&bytes) else {
let Ok(parsed) = stela_formats::payload::PayloadManifest::parse(&bytes) else {
return vec![format!("{} is not a restore inventory", manifest.display())];
};
if self.remote {
@@ -512,7 +516,7 @@ pub(super) fn write(
block_hashes: BlockHashes {
file: PIECE_HASHES_FILE.into(),
block_bytes: HASH_BLOCK_BYTES,
sha256: stela_runtime::sha256(&piece_blocks),
sha256: stela_formats::sha256(&piece_blocks),
},
};
manifest
@@ -522,7 +526,7 @@ pub(super) fn write(
efi::write_atomic(&directory.join(BLOCK_HASHES_FILE), &inventory.blocks, false)?;
let json = manifest.to_json();
efi::write_atomic(&manifest_path, json.as_bytes(), false)?;
written.manifest_sha256 = stela_runtime::sha256(json.as_bytes());
written.manifest_sha256 = stela_formats::sha256(json.as_bytes());
progress.finish();
Ok(written)
}
@@ -543,7 +547,7 @@ pub(super) fn write_remote(
efi::write_atomic(&directory.join(BLOCK_HASHES_FILE), &inventory.blocks, false)?;
let json = inventory.manifest.to_json();
efi::write_atomic(&directory.join(MANIFEST_FILE), json.as_bytes(), false)?;
Ok(stela_runtime::sha256(json.as_bytes()))
Ok(stela_formats::sha256(json.as_bytes()))
}
/// Remove what `previous`, the medium of the same build that `current`
@@ -577,7 +581,7 @@ pub(super) fn remove_replaced(previous: &Medium, current: &Medium) -> Result<()>
#[cfg(test)]
pub(super) mod tests {
use super::*;
use stela_runtime::payload::{PayloadManifest, pieces::Extent};
use {stela_formats::payload::PayloadManifest, stela_formats::payload::pieces::Extent};
/// Small pieces, so the synthetic IPSW takes several.
pub(in crate::setup) const PIECE_BYTES: u64 = HASH_BLOCK_BYTES;
@@ -596,7 +600,7 @@ pub(super) mod tests {
fn expected(ipsw: &Path) -> Expected {
let bytes = fs::read(ipsw).unwrap();
Expected {
sha256: Some(stela_runtime::sha256(&bytes)),
sha256: Some(stela_formats::sha256(&bytes)),
sha1: Some(hex::encode(Sha1::digest(&bytes))),
}
}
@@ -604,7 +608,7 @@ pub(super) mod tests {
/// An in-memory disk image holding the pieces back to back.
struct Joined(Vec<u8>);
impl stela_runtime::payload::ReadAt for Joined {
impl stela_formats::payload::ReadAt for Joined {
type Error = &'static str;
fn len(&self) -> u64 {
self.0.len() as u64
@@ -655,10 +659,10 @@ pub(super) mod tests {
}
let hashes = fs::read(directory.join(PIECE_HASHES_FILE)).unwrap();
let mut joined =
stela_runtime::payload::pieces::Joined::new(Joined(disk), &manifest, extents, &hashes)
stela_formats::payload::pieces::Joined::new(Joined(disk), &manifest, extents, &hashes)
.unwrap();
let mut read = vec![0; bytes.len()];
stela_runtime::payload::ReadAt::read_at(&mut joined, 0, &mut read).unwrap();
stela_formats::payload::ReadAt::read_at(&mut joined, 0, &mut read).unwrap();
assert_eq!(read, bytes);
assert!(
Medium {
@@ -57,7 +57,7 @@ fn write_from(
) -> Result<Written> {
ensure!(
piece_bytes > 0
&& piece_bytes <= stela_runtime::payload::MAX_SLICE_BYTES
&& piece_bytes <= stela_formats::payload::MAX_SLICE_BYTES
&& piece_bytes.is_multiple_of(HASH_BLOCK_BYTES),
"invalid FAT32 piece size"
);
@@ -150,7 +150,7 @@ fn write_from(
block_hashes: BlockHashes {
file: PIECE_HASHES_FILE.into(),
block_bytes: HASH_BLOCK_BYTES,
sha256: stela_runtime::sha256(&piece_blocks),
sha256: stela_formats::sha256(&piece_blocks),
},
};
inventory.manifest.validate().map_err(anyhow::Error::msg)?;
@@ -161,7 +161,7 @@ fn write_from(
Ok(Written {
wrote: sizes.len(),
kept: 0,
manifest_sha256: stela_runtime::sha256(json.as_bytes()),
manifest_sha256: stela_formats::sha256(json.as_bytes()),
})
}
@@ -255,10 +255,10 @@ mod tests {
"the fixture must exercise joined-piece reads"
);
let manifest = fs::read(directory(&volume, &image.build).join(MANIFEST_FILE))?;
let manifest = stela_runtime::payload::PayloadManifest::parse(&manifest)
let manifest = stela_formats::payload::PayloadManifest::parse(&manifest)
.map_err(anyhow::Error::msg)?;
assert!(matches!(manifest.layout, Layout::Pieces { .. }));
assert_eq!(manifest.source.sha256, Some(stela_runtime::sha256(&bytes)));
assert_eq!(manifest.source.sha256, Some(stela_formats::sha256(&bytes)));
let mut damaged = bytes.clone();
damaged[0] ^= 1;
let mut oversized = bytes.clone();
+1 -1
View File
@@ -13,7 +13,7 @@ use std::{
fs,
path::{Path, PathBuf},
};
use stela_runtime::builds;
use stela_formats::builds;
/// A boot bundle prepared on this computer, not yet copied.
pub(super) struct Prepared {
+5 -5
View File
@@ -317,7 +317,7 @@ fn fake_inventory(ipsw: &Path, model: &str) -> Result<restore::payload::Inventor
/// The synthetic IPSW's inventory as if it were on Apple's servers.
fn fake_remote_inventory(ipsw: &Path, model: &str) -> Result<restore::payload::Inventory> {
let layout = stela_runtime::payload::Layout::Remote {
let layout = stela_formats::payload::Layout::Remote {
url: "http://updates-http.example.test/Synthetic.ipsw".into(),
etag: "\"synthetic\"".into(),
};
@@ -1109,7 +1109,7 @@ fn a_signing_setup_without_a_target_installs_on_the_disk_chosen_in_stela_efi() {
for index in 0.. {
let piece = medium
.directory()
.join(stela_runtime::payload::piece_name(index));
.join(stela_formats::payload::piece_name(index));
let Ok(bytes) = fs::read(piece) else { break };
joined.extend(bytes);
}
@@ -1229,7 +1229,7 @@ fn an_install_reads_the_image_from_the_usb_offline_or_streams_it_online() {
);
let first_piece = offline
.directory()
.join(stela_runtime::payload::piece_name(0));
.join(stela_formats::payload::piece_name(0));
assert!(first_piece.is_file());
// Back online, the pieces go.
let online = switch(InstallImage::Online);
@@ -1373,7 +1373,7 @@ fn an_installed_disk_boots_macos_or_recoveryos_and_keeps_its_partitions() {
for index in 0.. {
let piece = medium
.directory()
.join(stela_runtime::payload::piece_name(index));
.join(stela_formats::payload::piece_name(index));
let Ok(bytes) = fs::read(piece) else { break };
joined.extend(bytes);
}
@@ -1381,7 +1381,7 @@ fn an_installed_disk_boots_macos_or_recoveryos_and_keeps_its_partitions() {
// Status finds a damaged piece by name.
let first = medium
.directory()
.join(stela_runtime::payload::piece_name(0));
.join(stela_formats::payload::piece_name(0));
let piece = fs::read(&first).unwrap();
fs::write(&first, &piece[1..]).unwrap();
let status = format!(
+1 -1
View File
@@ -242,7 +242,7 @@ fn configure_inner(command: &mut Request, host: &dyn Host) -> Result<bool> {
let manifest =
local_image(&path).with_context(|| format!("reading {}", path.display()))?;
progress.finish();
stela_runtime::builds::find(&manifest.product_build)
stela_formats::builds::find(&manifest.product_build)
.with_context(|| path.display().to_string())?;
command.ipsw = Some(path);
command.fetch = false;
+3 -3
View File
@@ -15,9 +15,9 @@ fn majors(images: &[Image]) -> Vec<(String, Vec<usize>)> {
groups
}
/// Whether Stela supports `image`'s build (`stela_runtime::builds`).
/// Whether Stela supports `image`'s build (`stela_formats::builds`).
fn supported(image: &Image) -> bool {
stela_runtime::builds::find(&image.build).is_ok()
stela_formats::builds::find(&image.build).is_ok()
}
/// The major-version group the release picker opens on: `preferred`'s, else
@@ -251,7 +251,7 @@ mod tests {
url: String::new(),
sha1: None,
};
let supported = stela_runtime::builds::DEFAULT;
let supported = stela_formats::builds::DEFAULT;
let images = [
image("28.1", "28B70"),
image("27.1", "27B74"),
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "stela-contracts"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[features]
default = ["std"]
std = ["serde/std"]
test-support = []
native-profile = []
[dependencies]
serde.workspace = true
@@ -345,8 +345,8 @@ impl<'a> Node<'a> {
/// An ADT image of one node: `properties` as (name, value) and its encoded
/// children, for tests.
#[cfg(test)]
pub(crate) fn encode(properties: &[(&str, &[u8])], children: &[Vec<u8>]) -> Vec<u8> {
#[cfg(any(test, feature = "test-support"))]
pub fn encode(properties: &[(&str, &[u8])], children: &[Vec<u8>]) -> Vec<u8> {
let mut out = Vec::new();
out.extend((properties.len() as u32).to_le_bytes());
out.extend((children.len() as u32).to_le_bytes());
@@ -13,7 +13,7 @@ use core::any::Any;
#[cfg(test)]
mod advance_tests;
mod container;
pub(crate) use container::SharedView;
pub use container::SharedView;
/// Access width in bytes. Apple MMIO is little-endian.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -205,7 +205,7 @@ pub enum AdvancePolicy {
}
/// Builds the refusal for one device register.
pub(crate) fn refuse(
pub fn refuse(
device: &'static str,
offset: u64,
width: Width,
@@ -470,7 +470,7 @@ impl Bus {
}
/// The device and device offset for a complete guest PA access. Mounts
/// may inspect ownership without reading or changing a register.
pub(crate) fn route(&self, address: u64, width: Width) -> Result<(DeviceId, u64), MmioError> {
pub fn route(&self, address: u64, width: Width) -> Result<(DeviceId, u64), MmioError> {
if !address.is_multiple_of(width.bytes()) {
return Err(MmioError::Misaligned { address, width });
}
@@ -578,7 +578,7 @@ impl Bus {
#[cfg(test)]
mod tests {
use super::*;
use crate::platform::apple::interrupt::InterruptLatch;
use crate::interrupt::InterruptLatch;
/// A 16-byte scratch register file, for routing tests only.
struct Scratch([u8; 16]);
@@ -1,6 +1,6 @@
//! Registration, failure-order and mutation controls for passive advancement.
use super::*;
use crate::platform::apple::interrupt::InterruptLatch;
use crate::interrupt::InterruptLatch;
use alloc::{boxed::Box, rc::Rc, vec, vec::Vec};
use core::cell::RefCell;
@@ -5,7 +5,7 @@ use alloc::vec::Vec;
/// An explicit existing subview. It retains no storage and authorizes no MMIO
/// effects. The planner rechecks its actual owner and affine offsets each time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SharedView {
pub struct SharedView {
device: DeviceId,
start: u64,
end: u64,
@@ -16,7 +16,7 @@ impl Bus {
/// Validate a complete already-owned view, including every byte and its
/// device offset. Neither endpoint probes nor a matching device ID alone
/// qualify a subview. Adjacent bindings must preserve one affine mapping.
pub(crate) fn shared_view(
pub fn shared_view(
&self,
device: DeviceId,
start: u64,
@@ -64,7 +64,7 @@ impl Bus {
/// Coalesce physical aliases and leave complete actual child routes intact.
/// Offsets in the returned bindings are physical addresses. Planning is
/// read-only; callers install the complete result in one transaction.
pub(crate) fn container_bindings(
pub fn container_bindings(
&self,
views: &[(u64, u64)],
children: &[DeviceId],
@@ -75,7 +75,7 @@ impl Bus {
/// Partial intersections additionally require explicit, completely validated
/// shared views. These describe physical aliases of actual owners, never a
/// second model, storage allocation or relaxed gap/overlap admission.
pub(crate) fn container_bindings_with_shared(
pub fn container_bindings_with_shared(
&self,
views: &[(u64, u64)],
children: &[DeviceId],
@@ -170,7 +170,7 @@ impl Bus {
/// The placed window holding `address`: its bounds, owner and the
/// owner's offset at its start.
pub(crate) fn window_at(&self, address: u64) -> Option<(u64, u64, DeviceId, u64)> {
pub fn window_at(&self, address: u64) -> Option<(u64, u64, DeviceId, u64)> {
self.regions
.iter()
.find(|region| region.start <= address && address < region.end)
@@ -185,7 +185,7 @@ impl Bus {
}
/// A diagnostic names the actual retained owner without accessing it.
pub(crate) fn device_name(&self, id: DeviceId) -> Option<&'static str> {
pub fn device_name(&self, id: DeviceId) -> Option<&'static str> {
self.devices.get(id.0).map(|device| device.name())
}
}
@@ -193,7 +193,7 @@ impl Bus {
#[cfg(test)]
mod tests {
use super::*;
use crate::platform::apple::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse};
use crate::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse};
use alloc::boxed::Box;
struct Refusing;
@@ -20,8 +20,6 @@
//! CCSIDR_EL1 reads 0 for a selection without a cache, one of the UNKNOWN
//! values the architecture permits.
pub mod cram;
/// CLIDR_EL1.Ctype values.
const SEPARATE: u64 = 0b011;
const UNIFIED: u64 = 0b100;
@@ -5,7 +5,7 @@
//! chip lacks UNDEFINED (or a NOP, where Arm decodes it so), as
//! [`Chip::admit_table`] does for a PE whose identification withholds
//! features its chip has.
use super::system::generated::{CAPS, CHIPS, Feature};
use crate::cpu_features::{CAPS, CHIPS, Feature};
use alloc::{vec, vec::Vec};
#[rustfmt::skip]
@@ -335,7 +335,7 @@ impl Chip {
/// The (mask, value) of every form with a variant on this chip, and that
/// variant's checks, for tests covering classes of forms.
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
pub fn check_forms(self) -> Vec<(u32, u32, &'static [Check])> {
let bit = 1u8 << self as u8;
checks::CHECKS
@@ -354,25 +354,12 @@ impl Chip {
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|chip| chip.name() == name)
}
/// Whether the chip has `feature`: `Ok(false)` without it, `Ok(true)`
/// when the engine implements it, and the reason to stop when the chip
/// has a feature the engine does not implement yet.
pub fn implemented(self, feature: Feature) -> Result<bool, &'static str> {
if !feature.on(self) {
Ok(false)
} else if engine_implements(feature) {
Ok(true)
} else {
Err(feature.unimplemented())
}
}
}
/// The chip the runtime's unit tests build their default CPUs and machines
/// for: `STELA_TEST_CHIP`, or [`Chip::DEFAULT`]. A test that fixes its chip
/// does not call it.
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
pub fn test_chip() -> Chip {
extern crate std;
std::env::var("STELA_TEST_CHIP").map_or(Chip::DEFAULT, |name| {
@@ -380,71 +367,6 @@ pub fn test_chip() -> Chip {
})
}
/// Whether the engine implements a feature that only some chips have: every
/// feature the M2 has; the M3's FEAT_HCX, FEAT_NV and FEAT_NV2; the M4's
/// Armv8.7 (FEAT_AFP, FEAT_PAN3, FEAT_WFxT and FEAT_XS), the activity
/// monitors FEAT_AMUv1 and FEAT_AMUv1p1 (`machine::amu`) and FEAT_SME with
/// FEAT_SME2, FEAT_SME_F64F64 and FEAT_SME_I16I64, whose streaming mode, ZA,
/// ZT0 and instructions the engine runs (`engine::scalable`); the M5's
/// FEAT_SME2p1, FEAT_SME_B16B16, FEAT_SME_F16F16 and FEAT_SVE_B16B16 too,
/// FEAT_SPECRES2, FEAT_MTE and FEAT_MTE2 (Allocation Tags and synchronous
/// Tag Checks) and the instruction-only FEAT_CSSC and FEAT_HBC; and the M6's
/// FEAT_SME_LUTv2, FEAT_FPACCOMBINE, FEAT_FP8 with FEAT_FPMR (the AdvSIMD
/// FP8 conversions), FEAT_CPA (whose arithmetic the engine completes),
/// FEAT_PAuth_LR with FEAT_SCTLR2 (PACM and the two-modifier PAC forms),
/// FEAT_RASv2 with FEAT_FGT2 (the error record group status and its trap) and
/// the instruction-only FEAT_FAMINMAX and FEAT_LUT, whose forms the
/// system-mode compiler admits.
const fn engine_implements(feature: Feature) -> bool {
match feature {
Feature::FEAT_AMUv1p1
| Feature::FEAT_BF16
| Feature::FEAT_ECV
| Feature::FEAT_FGT
| Feature::FEAT_FPAC
| Feature::FEAT_I8MM
| Feature::FEAT_PAuth2
| Feature::FEAT_SSBS
| Feature::FEAT_SSBS2
| Feature::v8Ap6
| Feature::v8Ap7
| Feature::FEAT_NV
| Feature::FEAT_NV2
| Feature::FEAT_HCX
| Feature::FEAT_AFP
| Feature::FEAT_CPA
| Feature::FEAT_CSSC
| Feature::FEAT_FAMINMAX
| Feature::FEAT_HBC
| Feature::FEAT_FPACCOMBINE
| Feature::FEAT_LUT
| Feature::FEAT_PAN3
| Feature::FEAT_PAuth_LR
| Feature::FEAT_SCTLR2
| Feature::FEAT_FGT2
| Feature::FEAT_RASv2
| Feature::FEAT_SPECRES2
| Feature::FEAT_WFxT
| Feature::FEAT_XS
| Feature::FEAT_SME
| Feature::FEAT_SME2
| Feature::FEAT_AMUv1
| Feature::FEAT_FP8
| Feature::FEAT_FPMR
| Feature::FEAT_MTE
| Feature::FEAT_MTE2
| Feature::FEAT_SME2p1
| Feature::FEAT_SME_B16B16
| Feature::FEAT_SME_F16F16
| Feature::FEAT_SME_F64F64
| Feature::FEAT_SME_I16I64
| Feature::FEAT_SME_LUTv2
| Feature::FEAT_SVE_B16B16
| Feature::FEAT_SME_F8F16
| Feature::FEAT_SME_F8F32 => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -548,25 +470,11 @@ mod tests {
}
#[test]
fn chips_are_ordered_and_the_m2_implements_all_it_has() {
fn chip_names_round_trip_in_table_order() {
for (index, chip) in Chip::ALL.into_iter().enumerate() {
assert_eq!(chip as usize, index);
assert_eq!(Chip::from_name(chip.name()), Some(chip));
}
// The default chip implements every feature it has, as before any
// other chip was modeled; a later chip's addition stops explicitly.
for feature in Feature::ALL {
assert_ne!(
Chip::DEFAULT.implemented(feature),
Err(feature.unimplemented())
);
}
assert_eq!(Chip::AppleM2.implemented(Feature::FEAT_HCX), Ok(false));
assert_eq!(Chip::AppleM3.implemented(Feature::FEAT_HCX), Ok(true));
assert_eq!(Chip::AppleM4.implemented(Feature::FEAT_SME), Ok(true));
assert_eq!(Chip::AppleM4.implemented(Feature::FEAT_MTE2), Ok(false));
assert_eq!(Chip::AppleM5.implemented(Feature::FEAT_MTE2), Ok(true));
assert_eq!(Chip::AppleM1.implemented(Feature::FEAT_FGT), Ok(false));
}
#[test]
@@ -101,7 +101,7 @@ pub(super) fn groups(word: u32) -> impl Iterator<Item = &'static CheckGroup> {
#[cfg(test)]
mod tests {
use super::*;
use crate::machine::Chip;
use crate::Chip;
#[test]
fn compact_prefix_candidates_are_complete_unique_and_in_original_order() {
+641
View File
@@ -0,0 +1,641 @@
//! Generated Apple CPU feature profiles from Arm AARCHMRS 2026-06.
//! Arm data: BSD-3-Clause, Copyright (c) 2010-2026 Arm Limited
//! or its affiliates.
//! Regenerate with `cargo xtask sysregs --aarchmrs DIR`.
#![allow(non_camel_case_types, reason = "feature names follow Arm AARCHMRS")]
use crate::Chip;
/// The Apple CPUs, in the order of the per-chip tables.
pub const CHIPS: [&str; 6] = [
"apple-m1", "apple-m2", "apple-m3", "apple-m4", "apple-m5", "apple-m6",
];
/// Each chip's Apple clang architectural features, as exported.
pub const CAPS: [&[&str]; 6] = [
&[
"FEAT_AES",
"FEAT_AMUv1",
"FEAT_AdvSIMD",
"FEAT_BTI",
"FEAT_CRC32",
"FEAT_CSV2_2",
"FEAT_DIT",
"FEAT_DPB",
"FEAT_DPB2",
"FEAT_DotProd",
"FEAT_FCMA",
"FEAT_FHM",
"FEAT_FP",
"FEAT_FP16",
"FEAT_FRINTTS",
"FEAT_FlagM",
"FEAT_FlagM2",
"FEAT_JSCVT",
"FEAT_LOR",
"FEAT_LRCPC",
"FEAT_LRCPC2",
"FEAT_LSE",
"FEAT_LSE2",
"FEAT_MPAM",
"FEAT_NV",
"FEAT_NV2",
"FEAT_PAN",
"FEAT_PAN2",
"FEAT_PAuth",
"FEAT_PMULL",
"FEAT_PMUv3",
"FEAT_RAS",
"FEAT_RASv1p1",
"FEAT_RDM",
"FEAT_SB",
"FEAT_SEL2",
"FEAT_SHA1",
"FEAT_SHA256",
"FEAT_SHA3",
"FEAT_SHA512",
"FEAT_SPECRES",
"FEAT_SSBS",
"FEAT_SSBS2",
"FEAT_TLBIOS",
"FEAT_TLBIRANGE",
"FEAT_TRF",
"FEAT_UAO",
"FEAT_VHE",
],
&[
"FEAT_AES",
"FEAT_AMUv1",
"FEAT_AMUv1p1",
"FEAT_AdvSIMD",
"FEAT_BF16",
"FEAT_BTI",
"FEAT_CRC32",
"FEAT_CSV2_2",
"FEAT_DIT",
"FEAT_DPB",
"FEAT_DPB2",
"FEAT_DotProd",
"FEAT_ECV",
"FEAT_FCMA",
"FEAT_FGT",
"FEAT_FHM",
"FEAT_FP",
"FEAT_FP16",
"FEAT_FPAC",
"FEAT_FRINTTS",
"FEAT_FlagM",
"FEAT_FlagM2",
"FEAT_I8MM",
"FEAT_JSCVT",
"FEAT_LOR",
"FEAT_LRCPC",
"FEAT_LRCPC2",
"FEAT_LSE",
"FEAT_LSE2",
"FEAT_MPAM",
"FEAT_NV",
"FEAT_NV2",
"FEAT_PAN",
"FEAT_PAN2",
"FEAT_PAuth",
"FEAT_PMULL",
"FEAT_PMUv3",
"FEAT_RAS",
"FEAT_RASv1p1",
"FEAT_RDM",
"FEAT_SB",
"FEAT_SEL2",
"FEAT_SHA1",
"FEAT_SHA256",
"FEAT_SHA3",
"FEAT_SHA512",
"FEAT_SPECRES",
"FEAT_SSBS",
"FEAT_SSBS2",
"FEAT_TLBIOS",
"FEAT_TLBIRANGE",
"FEAT_TRF",
"FEAT_UAO",
"FEAT_VHE",
],
&[
"FEAT_AES",
"FEAT_AMUv1",
"FEAT_AMUv1p1",
"FEAT_AdvSIMD",
"FEAT_BF16",
"FEAT_BTI",
"FEAT_CRC32",
"FEAT_CSV2_2",
"FEAT_DIT",
"FEAT_DPB",
"FEAT_DPB2",
"FEAT_DotProd",
"FEAT_ECV",
"FEAT_FCMA",
"FEAT_FGT",
"FEAT_FHM",
"FEAT_FP",
"FEAT_FP16",
"FEAT_FPAC",
"FEAT_FRINTTS",
"FEAT_FlagM",
"FEAT_FlagM2",
"FEAT_HCX",
"FEAT_I8MM",
"FEAT_JSCVT",
"FEAT_LOR",
"FEAT_LRCPC",
"FEAT_LRCPC2",
"FEAT_LSE",
"FEAT_LSE2",
"FEAT_MPAM",
"FEAT_NV",
"FEAT_NV2",
"FEAT_PAN",
"FEAT_PAN2",
"FEAT_PAuth",
"FEAT_PMULL",
"FEAT_PMUv3",
"FEAT_RAS",
"FEAT_RASv1p1",
"FEAT_RDM",
"FEAT_SB",
"FEAT_SEL2",
"FEAT_SHA1",
"FEAT_SHA256",
"FEAT_SHA3",
"FEAT_SHA512",
"FEAT_SPECRES",
"FEAT_SSBS",
"FEAT_SSBS2",
"FEAT_TLBIOS",
"FEAT_TLBIRANGE",
"FEAT_TRF",
"FEAT_UAO",
"FEAT_VHE",
],
&[
"FEAT_AES",
"FEAT_AMUv1",
"FEAT_AMUv1p1",
"FEAT_AdvSIMD",
"FEAT_BF16",
"FEAT_BTI",
"FEAT_CRC32",
"FEAT_CSV2_2",
"FEAT_DIT",
"FEAT_DPB",
"FEAT_DPB2",
"FEAT_DotProd",
"FEAT_ECV",
"FEAT_FCMA",
"FEAT_FGT",
"FEAT_FHM",
"FEAT_FP",
"FEAT_FP16",
"FEAT_FPAC",
"FEAT_FRINTTS",
"FEAT_FlagM",
"FEAT_FlagM2",
"FEAT_HCX",
"FEAT_I8MM",
"FEAT_JSCVT",
"FEAT_LOR",
"FEAT_LRCPC",
"FEAT_LRCPC2",
"FEAT_LSE",
"FEAT_LSE2",
"FEAT_MPAM",
"FEAT_NV",
"FEAT_NV2",
"FEAT_PAN",
"FEAT_PAN2",
"FEAT_PAuth",
"FEAT_PMULL",
"FEAT_PMUv3",
"FEAT_RAS",
"FEAT_RASv1p1",
"FEAT_RDM",
"FEAT_SB",
"FEAT_SEL2",
"FEAT_SHA1",
"FEAT_SHA256",
"FEAT_SHA3",
"FEAT_SHA512",
"FEAT_SME",
"FEAT_SME2",
"FEAT_SME_F64F64",
"FEAT_SME_I16I64",
"FEAT_SPECRES",
"FEAT_TLBIOS",
"FEAT_TLBIRANGE",
"FEAT_TRF",
"FEAT_UAO",
"FEAT_VHE",
"FEAT_WFxT",
"FEAT_XS",
],
&[
"FEAT_AES",
"FEAT_AMUv1",
"FEAT_AMUv1p1",
"FEAT_AdvSIMD",
"FEAT_BF16",
"FEAT_BTI",
"FEAT_CRC32",
"FEAT_CSSC",
"FEAT_CSV2_2",
"FEAT_DIT",
"FEAT_DPB",
"FEAT_DPB2",
"FEAT_DotProd",
"FEAT_ECV",
"FEAT_FCMA",
"FEAT_FGT",
"FEAT_FHM",
"FEAT_FP",
"FEAT_FP16",
"FEAT_FPAC",
"FEAT_FRINTTS",
"FEAT_FlagM",
"FEAT_FlagM2",
"FEAT_HBC",
"FEAT_HCX",
"FEAT_I8MM",
"FEAT_JSCVT",
"FEAT_LOR",
"FEAT_LRCPC",
"FEAT_LRCPC2",
"FEAT_LSE",
"FEAT_LSE2",
"FEAT_MPAM",
"FEAT_MTE",
"FEAT_MTE2",
"FEAT_NV",
"FEAT_NV2",
"FEAT_PAN",
"FEAT_PAN2",
"FEAT_PAuth",
"FEAT_PMULL",
"FEAT_PMUv3",
"FEAT_RAS",
"FEAT_RASv1p1",
"FEAT_RDM",
"FEAT_SB",
"FEAT_SEL2",
"FEAT_SHA1",
"FEAT_SHA256",
"FEAT_SHA3",
"FEAT_SHA512",
"FEAT_SME",
"FEAT_SME2",
"FEAT_SME2p1",
"FEAT_SME_B16B16",
"FEAT_SME_F16F16",
"FEAT_SME_F64F64",
"FEAT_SME_I16I64",
"FEAT_SPECRES",
"FEAT_SPECRES2",
"FEAT_SVE_B16B16",
"FEAT_TLBIOS",
"FEAT_TLBIRANGE",
"FEAT_TRF",
"FEAT_UAO",
"FEAT_VHE",
"FEAT_WFxT",
"FEAT_XS",
],
&[
"FEAT_AES",
"FEAT_AMUv1",
"FEAT_AMUv1p1",
"FEAT_AdvSIMD",
"FEAT_BF16",
"FEAT_BTI",
"FEAT_CPA",
"FEAT_CRC32",
"FEAT_CSSC",
"FEAT_CSV2_2",
"FEAT_DIT",
"FEAT_DPB",
"FEAT_DPB2",
"FEAT_DotProd",
"FEAT_ECV",
"FEAT_FAMINMAX",
"FEAT_FCMA",
"FEAT_FGT",
"FEAT_FHM",
"FEAT_FP",
"FEAT_FP16",
"FEAT_FP8",
"FEAT_FPAC",
"FEAT_FRINTTS",
"FEAT_FlagM",
"FEAT_FlagM2",
"FEAT_HBC",
"FEAT_HCX",
"FEAT_I8MM",
"FEAT_JSCVT",
"FEAT_LOR",
"FEAT_LRCPC",
"FEAT_LRCPC2",
"FEAT_LSE",
"FEAT_LSE2",
"FEAT_LUT",
"FEAT_MPAM",
"FEAT_MTE",
"FEAT_MTE2",
"FEAT_NV",
"FEAT_NV2",
"FEAT_PAN",
"FEAT_PAN2",
"FEAT_PAuth",
"FEAT_PAuth_LR",
"FEAT_PMULL",
"FEAT_PMUv3",
"FEAT_RAS",
"FEAT_RASv1p1",
"FEAT_RASv2",
"FEAT_RDM",
"FEAT_SB",
"FEAT_SEL2",
"FEAT_SHA1",
"FEAT_SHA256",
"FEAT_SHA3",
"FEAT_SHA512",
"FEAT_SME",
"FEAT_SME2",
"FEAT_SME2p1",
"FEAT_SME_B16B16",
"FEAT_SME_F16F16",
"FEAT_SME_F64F64",
"FEAT_SME_F8F16",
"FEAT_SME_F8F32",
"FEAT_SME_I16I64",
"FEAT_SME_LUTv2",
"FEAT_SPECRES",
"FEAT_SPECRES2",
"FEAT_SVE_B16B16",
"FEAT_TLBIOS",
"FEAT_TLBIRANGE",
"FEAT_TRF",
"FEAT_UAO",
"FEAT_VHE",
"FEAT_WFxT",
"FEAT_XS",
],
];
/// The features only some chips have.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Feature {
FEAT_AFP,
FEAT_AMUv1,
FEAT_AMUv1p1,
FEAT_BF16,
FEAT_CPA,
FEAT_CSSC,
FEAT_ECV,
FEAT_FAMINMAX,
FEAT_FGT,
FEAT_FGT2,
FEAT_FP8,
FEAT_FPAC,
FEAT_FPACCOMBINE,
FEAT_FPMR,
FEAT_HBC,
FEAT_HCX,
FEAT_I8MM,
FEAT_LUT,
FEAT_MTE,
FEAT_MTE2,
FEAT_NV,
FEAT_NV2,
FEAT_PAN3,
FEAT_PAuth2,
FEAT_PAuth_LR,
FEAT_RASv2,
FEAT_SCTLR2,
FEAT_SME,
FEAT_SME2,
FEAT_SME2p1,
FEAT_SME_B16B16,
FEAT_SME_F16F16,
FEAT_SME_F64F64,
FEAT_SME_F8F16,
FEAT_SME_F8F32,
FEAT_SME_I16I64,
FEAT_SME_LUTv2,
FEAT_SPECRES2,
FEAT_SSBS,
FEAT_SSBS2,
FEAT_SVE_B16B16,
FEAT_WFxT,
FEAT_XS,
v8Ap6,
v8Ap7,
}
impl Feature {
pub const ALL: [Feature; 45] = [
Feature::FEAT_AFP,
Feature::FEAT_AMUv1,
Feature::FEAT_AMUv1p1,
Feature::FEAT_BF16,
Feature::FEAT_CPA,
Feature::FEAT_CSSC,
Feature::FEAT_ECV,
Feature::FEAT_FAMINMAX,
Feature::FEAT_FGT,
Feature::FEAT_FGT2,
Feature::FEAT_FP8,
Feature::FEAT_FPAC,
Feature::FEAT_FPACCOMBINE,
Feature::FEAT_FPMR,
Feature::FEAT_HBC,
Feature::FEAT_HCX,
Feature::FEAT_I8MM,
Feature::FEAT_LUT,
Feature::FEAT_MTE,
Feature::FEAT_MTE2,
Feature::FEAT_NV,
Feature::FEAT_NV2,
Feature::FEAT_PAN3,
Feature::FEAT_PAuth2,
Feature::FEAT_PAuth_LR,
Feature::FEAT_RASv2,
Feature::FEAT_SCTLR2,
Feature::FEAT_SME,
Feature::FEAT_SME2,
Feature::FEAT_SME2p1,
Feature::FEAT_SME_B16B16,
Feature::FEAT_SME_F16F16,
Feature::FEAT_SME_F64F64,
Feature::FEAT_SME_F8F16,
Feature::FEAT_SME_F8F32,
Feature::FEAT_SME_I16I64,
Feature::FEAT_SME_LUTv2,
Feature::FEAT_SPECRES2,
Feature::FEAT_SSBS,
Feature::FEAT_SSBS2,
Feature::FEAT_SVE_B16B16,
Feature::FEAT_WFxT,
Feature::FEAT_XS,
Feature::v8Ap6,
Feature::v8Ap7,
];
pub const fn name(self) -> &'static str {
match self {
Feature::FEAT_AFP => "FEAT_AFP",
Feature::FEAT_AMUv1 => "FEAT_AMUv1",
Feature::FEAT_AMUv1p1 => "FEAT_AMUv1p1",
Feature::FEAT_BF16 => "FEAT_BF16",
Feature::FEAT_CPA => "FEAT_CPA",
Feature::FEAT_CSSC => "FEAT_CSSC",
Feature::FEAT_ECV => "FEAT_ECV",
Feature::FEAT_FAMINMAX => "FEAT_FAMINMAX",
Feature::FEAT_FGT => "FEAT_FGT",
Feature::FEAT_FGT2 => "FEAT_FGT2",
Feature::FEAT_FP8 => "FEAT_FP8",
Feature::FEAT_FPAC => "FEAT_FPAC",
Feature::FEAT_FPACCOMBINE => "FEAT_FPACCOMBINE",
Feature::FEAT_FPMR => "FEAT_FPMR",
Feature::FEAT_HBC => "FEAT_HBC",
Feature::FEAT_HCX => "FEAT_HCX",
Feature::FEAT_I8MM => "FEAT_I8MM",
Feature::FEAT_LUT => "FEAT_LUT",
Feature::FEAT_MTE => "FEAT_MTE",
Feature::FEAT_MTE2 => "FEAT_MTE2",
Feature::FEAT_NV => "FEAT_NV",
Feature::FEAT_NV2 => "FEAT_NV2",
Feature::FEAT_PAN3 => "FEAT_PAN3",
Feature::FEAT_PAuth2 => "FEAT_PAuth2",
Feature::FEAT_PAuth_LR => "FEAT_PAuth_LR",
Feature::FEAT_RASv2 => "FEAT_RASv2",
Feature::FEAT_SCTLR2 => "FEAT_SCTLR2",
Feature::FEAT_SME => "FEAT_SME",
Feature::FEAT_SME2 => "FEAT_SME2",
Feature::FEAT_SME2p1 => "FEAT_SME2p1",
Feature::FEAT_SME_B16B16 => "FEAT_SME_B16B16",
Feature::FEAT_SME_F16F16 => "FEAT_SME_F16F16",
Feature::FEAT_SME_F64F64 => "FEAT_SME_F64F64",
Feature::FEAT_SME_F8F16 => "FEAT_SME_F8F16",
Feature::FEAT_SME_F8F32 => "FEAT_SME_F8F32",
Feature::FEAT_SME_I16I64 => "FEAT_SME_I16I64",
Feature::FEAT_SME_LUTv2 => "FEAT_SME_LUTv2",
Feature::FEAT_SPECRES2 => "FEAT_SPECRES2",
Feature::FEAT_SSBS => "FEAT_SSBS",
Feature::FEAT_SSBS2 => "FEAT_SSBS2",
Feature::FEAT_SVE_B16B16 => "FEAT_SVE_B16B16",
Feature::FEAT_WFxT => "FEAT_WFxT",
Feature::FEAT_XS => "FEAT_XS",
Feature::v8Ap6 => "v8Ap6",
Feature::v8Ap7 => "v8Ap7",
}
}
/// Why an access stops on a chip with the feature when the engine
/// does not implement it.
pub const fn unimplemented(self) -> &'static str {
match self {
Feature::FEAT_AFP => "FEAT_AFP of the chip is not implemented",
Feature::FEAT_AMUv1 => "FEAT_AMUv1 of the chip is not implemented",
Feature::FEAT_AMUv1p1 => "FEAT_AMUv1p1 of the chip is not implemented",
Feature::FEAT_BF16 => "FEAT_BF16 of the chip is not implemented",
Feature::FEAT_CPA => "FEAT_CPA of the chip is not implemented",
Feature::FEAT_CSSC => "FEAT_CSSC of the chip is not implemented",
Feature::FEAT_ECV => "FEAT_ECV of the chip is not implemented",
Feature::FEAT_FAMINMAX => "FEAT_FAMINMAX of the chip is not implemented",
Feature::FEAT_FGT => "FEAT_FGT of the chip is not implemented",
Feature::FEAT_FGT2 => "FEAT_FGT2 of the chip is not implemented",
Feature::FEAT_FP8 => "FEAT_FP8 of the chip is not implemented",
Feature::FEAT_FPAC => "FEAT_FPAC of the chip is not implemented",
Feature::FEAT_FPACCOMBINE => "FEAT_FPACCOMBINE of the chip is not implemented",
Feature::FEAT_FPMR => "FEAT_FPMR of the chip is not implemented",
Feature::FEAT_HBC => "FEAT_HBC of the chip is not implemented",
Feature::FEAT_HCX => "FEAT_HCX of the chip is not implemented",
Feature::FEAT_I8MM => "FEAT_I8MM of the chip is not implemented",
Feature::FEAT_LUT => "FEAT_LUT of the chip is not implemented",
Feature::FEAT_MTE => "FEAT_MTE of the chip is not implemented",
Feature::FEAT_MTE2 => "FEAT_MTE2 of the chip is not implemented",
Feature::FEAT_NV => "FEAT_NV of the chip is not implemented",
Feature::FEAT_NV2 => "FEAT_NV2 of the chip is not implemented",
Feature::FEAT_PAN3 => "FEAT_PAN3 of the chip is not implemented",
Feature::FEAT_PAuth2 => "FEAT_PAuth2 of the chip is not implemented",
Feature::FEAT_PAuth_LR => "FEAT_PAuth_LR of the chip is not implemented",
Feature::FEAT_RASv2 => "FEAT_RASv2 of the chip is not implemented",
Feature::FEAT_SCTLR2 => "FEAT_SCTLR2 of the chip is not implemented",
Feature::FEAT_SME => "FEAT_SME of the chip is not implemented",
Feature::FEAT_SME2 => "FEAT_SME2 of the chip is not implemented",
Feature::FEAT_SME2p1 => "FEAT_SME2p1 of the chip is not implemented",
Feature::FEAT_SME_B16B16 => "FEAT_SME_B16B16 of the chip is not implemented",
Feature::FEAT_SME_F16F16 => "FEAT_SME_F16F16 of the chip is not implemented",
Feature::FEAT_SME_F64F64 => "FEAT_SME_F64F64 of the chip is not implemented",
Feature::FEAT_SME_F8F16 => "FEAT_SME_F8F16 of the chip is not implemented",
Feature::FEAT_SME_F8F32 => "FEAT_SME_F8F32 of the chip is not implemented",
Feature::FEAT_SME_I16I64 => "FEAT_SME_I16I64 of the chip is not implemented",
Feature::FEAT_SME_LUTv2 => "FEAT_SME_LUTv2 of the chip is not implemented",
Feature::FEAT_SPECRES2 => "FEAT_SPECRES2 of the chip is not implemented",
Feature::FEAT_SSBS => "FEAT_SSBS of the chip is not implemented",
Feature::FEAT_SSBS2 => "FEAT_SSBS2 of the chip is not implemented",
Feature::FEAT_SVE_B16B16 => "FEAT_SVE_B16B16 of the chip is not implemented",
Feature::FEAT_WFxT => "FEAT_WFxT of the chip is not implemented",
Feature::FEAT_XS => "FEAT_XS of the chip is not implemented",
Feature::v8Ap6 => "v8Ap6 of the chip is not implemented",
Feature::v8Ap7 => "v8Ap7 of the chip is not implemented",
}
}
/// Whether `chip`'s profile has the feature.
pub const fn on(self, chip: Chip) -> bool {
match self {
Feature::FEAT_AFP => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_AMUv1 => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_AMUv1p1 => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_BF16 => [false, true, true, true, true, true][chip as usize],
Feature::FEAT_CPA => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_CSSC => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_ECV => [false, true, true, true, true, true][chip as usize],
Feature::FEAT_FAMINMAX => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_FGT => [false, true, true, true, true, true][chip as usize],
Feature::FEAT_FGT2 => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_FP8 => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_FPAC => [false, true, true, true, true, true][chip as usize],
Feature::FEAT_FPACCOMBINE => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_FPMR => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_HBC => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_HCX => [false, false, true, true, true, true][chip as usize],
Feature::FEAT_I8MM => [false, true, true, true, true, true][chip as usize],
Feature::FEAT_LUT => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_MTE => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_MTE2 => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_NV => [false, false, true, true, true, true][chip as usize],
Feature::FEAT_NV2 => [false, false, true, true, true, true][chip as usize],
Feature::FEAT_PAN3 => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_PAuth2 => [false, true, true, true, true, true][chip as usize],
Feature::FEAT_PAuth_LR => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_RASv2 => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_SCTLR2 => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_SME => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_SME2 => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_SME2p1 => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_SME_B16B16 => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_SME_F16F16 => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_SME_F64F64 => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_SME_F8F16 => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_SME_F8F32 => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_SME_I16I64 => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_SME_LUTv2 => [false, false, false, false, false, true][chip as usize],
Feature::FEAT_SPECRES2 => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_SSBS => [true, true, true, false, false, false][chip as usize],
Feature::FEAT_SSBS2 => [true, true, true, false, false, false][chip as usize],
Feature::FEAT_SVE_B16B16 => [false, false, false, false, true, true][chip as usize],
Feature::FEAT_WFxT => [false, false, false, true, true, true][chip as usize],
Feature::FEAT_XS => [false, false, false, true, true, true][chip as usize],
Feature::v8Ap6 => [false, true, true, true, true, true][chip as usize],
Feature::v8Ap7 => [false, false, false, true, true, true][chip as usize],
}
}
}
@@ -1,7 +1,7 @@
//! Device DMA: guest RAM as bus masters and IOMMU table walks reach it (RAM
//! only, never device registers), and one stream's view of it through its
//! IOMMU.
use super::apple::bus::Access;
use crate::bus::Access;
/// Guest RAM by physical address. The boolean methods serve callers that do
/// not resume a transfer. Stateful DMA owners use the progress methods to
@@ -192,15 +192,16 @@ impl Port<'_, '_> {
}
}
#[cfg(test)]
pub(crate) mod tests {
#[cfg(any(test, feature = "test-support"))]
pub mod test_support {
use super::*;
use crate::platform::apple::interrupt::InterruptLatch;
#[cfg(test)]
use crate::interrupt::InterruptLatch;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
/// RAM of `bytes.len()` bytes at `base`.
pub(crate) struct Ram {
pub struct Ram {
pub base: u64,
pub bytes: Vec<u8>,
}
@@ -246,11 +247,13 @@ pub(crate) mod tests {
/// Pages of 16 bytes, each mapped to the physical page `offset` bytes
/// above it, except page `hole`.
#[cfg(test)]
struct Shift {
offset: u64,
hole: u64,
}
#[cfg(test)]
impl Iommu for Shift {
fn page(&self) -> u64 {
16
+14
View File
@@ -0,0 +1,14 @@
//! Identification data for a processor in a declared topology.
/// The identification values one PE does not share with the others; they
/// replace `fixed` entries of the same registers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Identity {
pub midr: u64,
pub mpidr: u64,
/// The core clock in Hz, where the SoC row has evidence of it; it paces
/// the cycle counter of Apple's performance monitor (`machine::pmu`).
pub clock: Option<u64>,
/// The PE's caches, where the SoC row and DeviceTree describe them;
/// without them CLIDR_EL1 and CCSIDR_EL1 take the profile's values.
pub caches: Option<crate::caches::Caches>,
}
@@ -76,7 +76,7 @@ impl InterruptLatch {
pub fn take_aic_inputs(&mut self) -> Vec<(AicInput, bool)> {
core::mem::take(&mut self.aic_inputs)
}
#[cfg(test)]
#[cfg(any(test, feature = "test-support"))]
pub fn is_asserted(&self, wire: Wire) -> bool {
self.asserted.contains(&wire)
}
+18
View File
@@ -0,0 +1,18 @@
//! Shared CPU descriptions and device boundaries used by loaders and engines.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg_attr(all(test, not(feature = "std")), macro_use)]
extern crate alloc;
pub mod adt;
pub mod bus;
pub mod caches;
pub mod chip;
pub mod cpu_features;
pub mod dma;
pub mod identity;
pub mod interrupt;
pub mod pauth;
pub mod tag_storage;
pub use chip::Chip;
pub use cpu_features::Feature;
+36
View File
@@ -0,0 +1,36 @@
//! Pointer-signing metadata shared by image fixups and execution providers.
use serde::Serialize;
/// The architectural key slot and pointer address domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Key {
Ia,
Ib,
Da,
Db,
}
impl Key {
pub const fn index(self) -> usize {
match self {
Self::Ia => 0,
Self::Ib => 1,
Self::Da => 2,
Self::Db => 3,
}
}
pub const fn is_data(self) -> bool {
matches!(self, Self::Da | Self::Db)
}
pub const fn is_b(self) -> bool {
matches!(self, Self::Ib | Self::Db)
}
}
/// A process-owned pointer-signing provider. Format readers own no keys.
pub trait Signer {
type Error;
fn address_space(&self) -> u64;
fn profile_id(&self) -> &'static str;
fn sign(&self, key: Key, pointer: u64, modifier: u64) -> Result<u64, Self::Error>;
}
+80
View File
@@ -0,0 +1,80 @@
//! TAG_OFFSET_EL2: where the M5 and later keep memory tags in DRAM.
//!
//! Public XNU `xnu-12377.121.6` names it (`osfmk/arm64/proc_reg.h:3407-3421`):
//! `MTE_TAG_OFFSET_EL2` `S3_0_C11_C9_0`, "the start of the stolen DRAM memory
//! that contains MTE tags metadata", a physically contiguous array aligned to
//! 1 MiB, its address in bits 41:20; one tag page covers 32 pages
//! (`MTE_PAGES_PER_TAG_PAGE`). iBoot programs and locks it: M5 iBoot
//! (`iBoot.j813` `0x31854..0x318dc`) requires it to read 0, sizes its tag
//! carveout (region 0xda) at DRAM size / 32 with 1 MiB alignment
//! (`0x38194`), and writes the carveout's base with bit 63 set, reading it
//! back. SPTM 26A434 only reads it (T8142 `0xfffffff0270bed98..0x...bedcc`;
//! T6050 and T8152 alike, the T8132 and T8140 never): it takes `/chosen
//! dram-size` >> 19 as the 16 KiB tag pages, requires bits 62:0 to equal
//! `physBase + memSize - tag bytes` rounded down to 1 MiB and bit 63 to be
//! set, and types that range `MTE_TAG_STORAGE` at the top of the range it
//! hands XNU (XNU's `vm_mteinfo.c`: iBoot places the tag storage "at the
//! end of the managed address space"). [`hand_off`] gives that value.
//!
//! The tags themselves stay in `machine::tags`, apart from RAM. XNU moves
//! tags only with the tag instructions (its compressor and tag copy use
//! `LDGM`/`STGM`, `osfmk/arm64/mte.c`, `mte_xnu.h:191-198`), and uses a tag
//! storage page as ordinary memory only while it stores no tags (its
//! `CLAIMED` state, `osfmk/vm/vm_mteinfo.c`), so those paths observe the
//! same values. What differs: a tag storage page's DRAM bytes are not the
//! tags of the pages it covers, so a tag read after activation without a
//! tag write returns the last tags (0 from reset) instead of stale bytes,
//! and a DRAM image of active tag storage (a hibernation image) does not
//! carry tags.
/// Bit 63 locks the register.
pub const LOCK: u64 = 1 << 63;
/// Bits 41:20: the tag storage's physical base.
pub const BASE_MASK: u64 = 0x3f_ffff << ALIGNMENT_SHIFT;
const ALIGNMENT_SHIFT: u32 = 20;
/// DRAM bytes one tag storage byte covers: two 4-bit tags of 16 bytes.
pub const COVERAGE: u64 = 32;
/// The tag storage's bytes for `dram_size` bytes of DRAM.
pub const fn bytes(dram_size: u64) -> u64 {
dram_size / COVERAGE
}
/// The locked value iBoot leaves for the managed range `phys_base` to
/// `phys_base + mem_size` in `dram_size` bytes of DRAM, or `None` when its
/// base does not fit the register.
pub fn hand_off(phys_base: u64, mem_size: u64, dram_size: u64) -> Option<u64> {
let end = phys_base.checked_add(mem_size)?;
let base = end.checked_sub(bytes(dram_size))? >> ALIGNMENT_SHIFT << ALIGNMENT_SHIFT;
(base & !BASE_MASK == 0).then_some(base | LOCK)
}
/// The tag storage's first byte in a TAG_OFFSET_EL2 value.
pub const fn base(value: u64) -> u64 {
value & BASE_MASK
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_handoff_matches_what_sptm_checks() {
// The J813 qemu-sptm trace: 8 GiB at 0x100_0000_0000 with a 31/32
// memSize reads 0x80000101e0000000.
let dram = 0x2_0000_0000;
assert_eq!(
hand_off(0x100_0000_0000, dram / 32 * 31, dram),
Some(0x8000_0101_e000_0000)
);
// The managed range to the end of DRAM puts it in DRAM's last 1/32.
let value = hand_off(0x100_0200_0000, dram - 0x200_0000, dram).unwrap();
assert_eq!(base(value), 0x100_0000_0000 + dram - bytes(dram));
assert_ne!(value & LOCK, 0);
// An unaligned end rounds down to 1 MiB; bases above bit 41 do not fit.
assert_eq!(
hand_off(0x100_0000_0000, dram - 0x4000, dram).map(base),
Some(0x101_eff0_0000)
);
assert_eq!(hand_off(1 << 42, dram, dram), None);
}
}
+2
View File
@@ -11,6 +11,8 @@ name = "stela-dev"
path = "src/main.rs"
[dependencies]
stela-contracts = { path = "../stela-contracts" }
stela-formats = { path = "../stela-formats", default-features = false }
anyhow.workspace = true
clap.workspace = true
serde = { workspace = true, features = ["std"] }
+4 -4
View File
@@ -227,9 +227,9 @@ impl CompileBlock {
let preparation_requirements = plan.memory_requirements();
let compiled = plan.compile()?;
let mut manifest = serde_json::json!({"schema_version":1,"kind":"raw_arm64_block_aot","target_cpu":cpu_target.id(),
"source_bytes":compiled.source_bytes,"source_sha256":stela_runtime::sha256(&source[..compiled.source_bytes]),
"source_bytes":compiled.source_bytes,"source_sha256":stela_formats::sha256(&source[..compiled.source_bytes]),
"guest_base":guest_base,"abi":options.profile().abi(),
"native_sha256":stela_runtime::sha256(&compiled.native.x86_64_code),
"native_sha256":stela_formats::sha256(&compiled.native.x86_64_code),
"native_bytes":compiled.native.x86_64_code.len(),"source_map":compiled.native.source_map,
"compiler_source_sha256":stela_compiler::SOURCE_SHA256,
"verified":false});
@@ -313,10 +313,10 @@ impl CompileLeaf {
"schema_version": 1,
"kind": "raw_arm64_leaf_aot",
"target_cpu":cpu_target.id(),
"source_sha256": stela_runtime::sha256(source),
"source_sha256": stela_formats::sha256(source),
"guest_base": guest_base,
"guest_instructions": source.len() / 4,
"native_sha256": stela_runtime::sha256(&block.x86_64_code),
"native_sha256": stela_formats::sha256(&block.x86_64_code),
"native_bytes": block.x86_64_code.len(),
"source_map": block.source_map,
"abi": options.profile().abi(),
+6 -6
View File
@@ -105,7 +105,7 @@ fn bootstrap_windows(
bytes.extend(instruction(data, plan, pc)?.to_le_bytes());
}
ensure!(
stela_runtime::sha256(&bytes) == hash,
stela_formats::sha256(&bytes) == hash,
"unreviewed dyld clock bootstrap window at {start:#x}"
);
windows.push((
@@ -283,7 +283,7 @@ pub fn probe(
Ok((
r.guest_address,
r.virtual_bytes,
stela_runtime::sha256(
stela_formats::sha256(
&memory
.read_snapshot(r.guest_address, usize::try_from(r.virtual_bytes)?)?,
),
@@ -399,7 +399,7 @@ pub fn probe(
};
let memory_effects = image_before.iter().map(|(address, bytes, initial)| {
Ok(serde_json::json!({"address":address,"bytes":bytes,"initial_sha256":initial,
"final_sha256":stela_runtime::sha256(&memory.read_snapshot(*address, usize::try_from(*bytes)?)?)}))
"final_sha256":stela_formats::sha256(&memory.read_snapshot(*address, usize::try_from(*bytes)?)?)}))
}).collect::<Result<Vec<_>>>()?;
let clock_report = clock.as_ref().map(|c| -> Result<serde_json::Value> {
Ok(serde_json::json!({"profile_id":c.profile_id(),"source_id":c.source_id(),"frequency":c.frequency(),
@@ -413,11 +413,11 @@ pub fn probe(
.transpose()?;
let mut report = serde_json::json!({
"schema_version":1,"kind":"original_dyld_startup_prefix_probe",
"dyld":{"path":dyld_path,"container_sha256":stela_runtime::sha256(&dyld_data),"slice_offset":dyld_offset,"plan":dyld,"slide":options.dyld_slide},
"main":{"path":executable,"container_sha256":stela_runtime::sha256(&main_data),"slice_offset":main_offset,"plan":main,"load_base":options.image_base},
"dyld":{"path":dyld_path,"container_sha256":stela_formats::sha256(&dyld_data),"slice_offset":dyld_offset,"plan":dyld,"slide":options.dyld_slide},
"main":{"path":executable,"container_sha256":stela_formats::sha256(&main_data),"slice_offset":main_offset,"plan":main,"load_base":options.image_base},
"arguments":arguments,"process_arguments":args,"stack":stack,"mapped_regions":memory.regions(),
"unreserved_guards":{"main":main_mapping.unreserved_guards,"dyld":dyld_mapping.unreserved_guards},
"argument_payload_sha256":stela_runtime::sha256(&before),"argument_payload_after_sha256":stela_runtime::sha256(&after),
"argument_payload_sha256":stela_formats::sha256(&before),"argument_payload_after_sha256":stela_formats::sha256(&after),
"entry_pc":entry,"stop_pc":stop,"target_pc":target_pc,"original_prefix_words":words,
"software_pauth_profile":context.as_ref().map(|context| context.profile_id()),
"pauth_instruction_executed":context.is_some(),"abi":runtime.profile().abi(),
+5 -5
View File
@@ -264,7 +264,7 @@ impl RunLinkedImages {
macho::select_slice(&container, &path, architecture.as_deref())?;
inputs.push(ImageInput {
data: slice.to_vec(),
container_sha256: stela_runtime::sha256(&container),
container_sha256: stela_formats::sha256(&container),
slice_offset,
load_base: base,
});
@@ -425,7 +425,7 @@ impl RunMappedImage {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({"kind":"mapped_macho_entry_probe",
"container_sha256":stela_runtime::sha256(&data),"slice_offset":slice_offset,"plan":image.plan(),
"container_sha256":stela_formats::sha256(&data),"slice_offset":slice_offset,"plan":image.plan(),
"memory_regions":image.regions(),"guard_segments_not_reserved":image.unreserved_guards(),
"fixups":image.fixups(),"image_base":image.fixups().load_base,"mapped_entry":image.mapped_entry(),
"applied_rebases":image.fixups().rebases.len(),
@@ -511,7 +511,7 @@ impl RunBlocks {
},
};
let source = std::fs::read(input)?;
let source_hash = stela_runtime::sha256(&source);
let source_hash = stela_formats::sha256(&source);
let context = if let Some(path) = software_pauth_keys.as_deref() {
Some(pauth_all_keys_context(path, ADDRESS_SPACE_ID)?)
} else {
@@ -653,7 +653,7 @@ impl RunBlocks {
"source_id":clock.source_id(),"frequency":clock.frequency(),"region":clock.region(),
"legacy_configuration":clock.legacy_configuration(),
"legacy_commpage_profile":clock.legacy_configuration().profile_id(),
"page_sha256":clock.snapshot_bytes(0, stela_runtime::clock::GUEST_BYTES).map(|bytes| stela_runtime::sha256(&bytes))?
"page_sha256":clock.snapshot_bytes(0, stela_runtime::clock::GUEST_BYTES).map(|bytes| stela_formats::sha256(&bytes))?
})) }).transpose()?;
println!(
"{}",
@@ -684,7 +684,7 @@ impl RunBlocks {
"page_size_commpage":commpage.as_ref().map(|page| -> Result<_> { Ok(serde_json::json!({
"profile_id":page.profile_id(),"address_space":page.address_space(),
"region":page.region(),"supported_fields":page.supported_fields(),
"page_sha256":stela_runtime::sha256(&page.snapshot_bytes()?)
"page_sha256":stela_formats::sha256(&page.snapshot_bytes()?)
})) }).transpose()?,
"data_vm_profile":data_vm_services.then_some(stela_runtime::darwin::DATA_VM_PROFILE),"data_vm_events":service_run.services,
"software_pauth_profile":context.as_ref().map(|context| context.profile_id()),
+3 -3
View File
@@ -189,7 +189,7 @@ impl ImageManifest {
write_json(&output, &value)?;
if let Some(path) = payload_manifest {
// The block hashes go beside the manifest, which names them.
let blocks = path.with_file_name(stela_runtime::payload::BLOCK_HASHES_FILE);
let blocks = path.with_file_name(stela_formats::payload::BLOCK_HASHES_FILE);
std::fs::File::create_new(&blocks)
.with_context(|| format!("{} exists", blocks.display()))?
.write_all(&inventory.blocks)?;
@@ -368,8 +368,8 @@ impl ImagesCommand {
let inventory = restore::remote_inventory(&image, &model, aea_keys_in.as_deref())?;
std::fs::create_dir(&output_dir)
.with_context(|| format!("{} exists", output_dir.display()))?;
let manifest = output_dir.join(stela_runtime::payload::MANIFEST_FILE);
let blocks = output_dir.join(stela_runtime::payload::BLOCK_HASHES_FILE);
let manifest = output_dir.join(stela_formats::payload::MANIFEST_FILE);
let blocks = output_dir.join(stela_formats::payload::BLOCK_HASHES_FILE);
std::fs::write(&blocks, &inventory.blocks)?;
std::fs::write(&manifest, inventory.manifest.to_json() + "\n")?;
eprintln!(
+7 -7
View File
@@ -153,7 +153,7 @@ pub(crate) fn raw_initial_bytes(
file.seek(SeekFrom::Start(source.offset))?;
file.read_exact(&mut bytes)?;
ensure!(
stela_runtime::sha256(&bytes) == source.sha256,
stela_formats::sha256(&bytes) == source.sha256,
"raw memory file hash differs"
);
Ok(bytes)
@@ -226,7 +226,7 @@ pub(crate) fn memory_hashes(
) -> Result<Vec<serde_json::Value>> {
memory.regions().iter().filter(|r| r.readable).map(|r| Ok(serde_json::json!({
"address":r.guest_address,"bytes":r.virtual_bytes,
"sha256":stela_runtime::sha256(&memory.read_snapshot(r.guest_address, usize::try_from(r.virtual_bytes)?)?),
"sha256":stela_formats::sha256(&memory.read_snapshot(r.guest_address, usize::try_from(r.virtual_bytes)?)?),
}))).collect()
}
@@ -297,10 +297,10 @@ mod tests {
let context = pauth_all_keys_context(&path, 92)?;
assert_eq!(context.address_space(), 92);
for key in [
stela_runtime::pauth::Key::Ia,
stela_runtime::pauth::Key::Ib,
stela_runtime::pauth::Key::Da,
stela_runtime::pauth::Key::Db,
stela_contracts::pauth::Key::Ia,
stela_contracts::pauth::Key::Ib,
stela_contracts::pauth::Key::Da,
stela_contracts::pauth::Key::Db,
] {
assert!(context.has_key(key));
}
@@ -369,7 +369,7 @@ mod tests {
let region = serde_json::json!({"guest_address":0,"virtual_bytes":4096,
"readable":true,"writable":false,
"initial_file":{"path":"payload.bin","offset":2,"bytes":3,
"sha256":stela_runtime::sha256(&[7,6,5])}});
"sha256":stela_formats::sha256(&[7,6,5])}});
let parsed: RawMemoryRegionInput = serde_json::from_value(region.clone())?;
assert_eq!(raw_initial_bytes(&parsed, folder.path())?, [7, 6, 5]);
for change in [
+2 -2
View File
@@ -117,7 +117,7 @@ impl PlanFixups {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"kind":"chained_fixup_plan","container_sha256":stela_runtime::sha256(&data),
"kind":"chained_fixup_plan","container_sha256":stela_formats::sha256(&data),
"slice_offset":slice_offset,"plan":plan,"fixups":fixups,"decoded_fixups":decoded_fixups,
"fixups_applied":false,"native_executed":false,"complete_binary_verified":false
}))?
@@ -138,7 +138,7 @@ impl PlanExecutable {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"kind": "macho_executable_load_plan", "container_sha256": stela_runtime::sha256(&data),
"kind": "macho_executable_load_plan", "container_sha256": stela_formats::sha256(&data),
"slice_offset": offset, "plan": plan
}))?
);
+1 -1
View File
@@ -479,7 +479,7 @@ fn boot_prepare_writes_a_bundle_the_mount_can_copy_and_patch() {
let start = region["file_offset"].as_u64().unwrap() as usize;
let end = start + region["bytes"].as_u64().unwrap() as usize;
assert_eq!(
stela_runtime::sha256(&file[start..end]),
stela_formats::sha256(&file[start..end]),
region["sha256"].as_str().unwrap()
);
}
+2 -2
View File
@@ -66,11 +66,11 @@ fn executable_plan_selects_apple_slices_and_preserves_guest_identity() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(report["container_sha256"], stela_runtime::sha256(&fat));
assert_eq!(report["container_sha256"], stela_formats::sha256(&fat));
assert_eq!(report["slice_offset"], 8192);
assert_eq!(
report["plan"]["slice_sha256"],
stela_runtime::sha256(&arm64e)
stela_formats::sha256(&arm64e)
);
assert_eq!(report["plan"]["cpu_subtype"], 0x80000002u32);
assert_eq!(report["plan"]["entry"]["guest_address"], 0x1_0000_0200u64);
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "stela-formats"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[features]
default = ["std"]
test-support = []
std = ["serde/std", "serde_json/std", "stela-contracts/std"]
[dependencies]
stela-contracts = { path = "../stela-contracts", default-features = false }
serde.workspace = true
serde_json = { version = "1", default-features = false, features = ["alloc"] }
sha1 = { version = "0.10", default-features = false }
sha2 = { version = "0.10", default-features = false }
crypto-bigint = { version = "0.5", default-features = false }
hex = { version = "0.4", default-features = false, features = ["alloc"] }
miniz_oxide = { version = "0.9", default-features = false, features = ["with-alloc"] }
[dev-dependencies]
lzfse_rust = "0.2"
File renamed without changes.
@@ -130,7 +130,7 @@ impl Manifest {
/// The cores' lock registers iBoot leaves on `machine`. Where the chip
/// keeps memory tags, SPTM requires TAG_OFFSET_EL2 at the top of the
/// managed range, sized for `/chosen dram-size`
/// ([`crate::machine::tag_storage`]), so its value follows the machine's
/// ([`stela_contracts::tag_storage`]), so its value follows the machine's
/// DRAM rather than the prepared one.
pub fn core_locks(&self, machine: &Machine) -> Result<Option<CoreLocks>, BundleError> {
let Some(mut locks) = self.core_locks.clone() else {
@@ -141,9 +141,9 @@ impl Manifest {
let phys_base = self.options.phys_base;
let managed = machine.managed_end().map_err(fail)? - phys_base;
locks.tag_offset =
crate::machine::tag_storage::hand_off(phys_base, managed, machine.dram_bytes)
stela_contracts::tag_storage::hand_off(phys_base, managed, machine.dram_bytes)
.ok_or_else(|| fail("its base does not fit TAG_OFFSET_EL2"))?;
if crate::machine::tag_storage::base(locks.tag_offset) < self.top_of_kernel_data {
if stela_contracts::tag_storage::base(locks.tag_offset) < self.top_of_kernel_data {
return Err(fail("it overlaps the loaded regions"));
}
}
File renamed without changes.
@@ -3,7 +3,7 @@
//! best code directory's flags, platform and identifiers, its cdhash, and
//! the entitlements blobs, and whether a verified CMS signature shows
//! Apple signed it ([`cms`]). Page hashes are not checked here.
use anyhow::{Context, Result, ensure};
use alloc::{format, string::String, vec::Vec};
use serde::Serialize;
use sha1::{Digest as _, Sha1};
use sha2::Sha256;
@@ -60,22 +60,103 @@ const CS_SUPPORTSTEAMID: u32 = 0x20200;
/// `SC_Scatter.base`, in hash pages.
const SCATTER_BASE: usize = 4;
/// An invalid field or extent in a Mach-O embedded signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeSignatureError {
Truncated {
offset: usize,
needed: usize,
available: usize,
},
RangeOverflow {
offset: usize,
bytes: usize,
},
MachOMagic {
found: u32,
},
SuperblobMagic {
found: u32,
},
LoadCommandSize {
command: u32,
bytes: usize,
minimum: usize,
},
MissingCodeDirectory,
PageShift {
value: u8,
},
HashType {
value: u8,
},
}
impl core::fmt::Display for CodeSignatureError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Truncated {
offset,
needed,
available,
} => write!(
f,
"code signature needs {needed} bytes at {offset:#x}, container has {available}"
),
Self::RangeOverflow { offset, bytes } => {
write!(f, "code signature extent {offset:#x}+{bytes:#x} overflows")
}
Self::MachOMagic { found } => write!(f, "not a 64-bit Mach-O slice: magic {found:#x}"),
Self::SuperblobMagic { found } => {
write!(f, "not an embedded signature superblob: magic {found:#x}")
}
Self::LoadCommandSize {
command,
bytes,
minimum,
} => write!(
f,
"load command {command:#x} has {bytes} bytes, requires at least {minimum}"
),
Self::MissingCodeDirectory => f.write_str("code signature has no code directory"),
Self::PageShift { value } => {
write!(f, "code directory page shift {value} is out of range")
}
Self::HashType { value } => write!(f, "unsupported code directory hash type {value}"),
}
}
}
impl core::error::Error for CodeSignatureError {}
pub type Result<T> = core::result::Result<T, CodeSignatureError>;
fn extent(bytes: &[u8], offset: usize, length: usize) -> Result<&[u8]> {
let end = offset
.checked_add(length)
.ok_or(CodeSignatureError::RangeOverflow {
offset,
bytes: length,
})?;
bytes.get(offset..end).ok_or(CodeSignatureError::Truncated {
offset,
needed: length,
available: bytes.len(),
})
}
fn byte(bytes: &[u8], at: usize) -> Result<u8> {
Ok(extent(bytes, at, 1)?[0])
}
fn be32(bytes: &[u8], at: usize) -> Result<u32> {
Ok(u32::from_be_bytes(
bytes
.get(at..at + 4)
.context("truncated code signature")?
.try_into()?,
))
let b = extent(bytes, at, 4)?;
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
fn le32(bytes: &[u8], at: usize) -> Result<u32> {
Ok(u32::from_le_bytes(
bytes
.get(at..at + 4)
.context("truncated load command")?
.try_into()?,
))
let b = extent(bytes, at, 4)?;
Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
fn c_string(bytes: &[u8], at: usize) -> Option<String> {
@@ -147,7 +228,10 @@ impl CodeSignature {
}
mod hex_bytes {
pub fn serialize<S: serde::Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
pub fn serialize<S: serde::Serializer>(
bytes: &[u8],
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
serializer.serialize_str(&hex::encode(bytes))
}
}
@@ -228,14 +312,25 @@ fn ber_children(mut contents: &[u8]) -> impl Iterator<Item = (u8, &[u8], &[u8])>
/// The signature of a thin 64-bit Mach-O slice, or `None` without one.
pub fn read(slice: &[u8]) -> Result<Option<CodeSignature>> {
ensure!(le32(slice, 0)? == MH_MAGIC_64, "not a 64-bit Mach-O slice");
let found = le32(slice, 0)?;
if found != MH_MAGIC_64 {
return Err(CodeSignatureError::MachOMagic { found });
}
let count = le32(slice, 16)? as usize;
let mut offset = MACH_HEADER_64_BYTES;
let mut blob = None;
for _ in 0..count {
let command = le32(slice, offset)?;
let size = le32(slice, offset + 4)? as usize;
ensure!(size >= 8, "load command too small");
let minimum = if command == LC_CODE_SIGNATURE { 16 } else { 8 };
if size < minimum {
return Err(CodeSignatureError::LoadCommandSize {
command,
bytes: size,
minimum,
});
}
extent(slice, offset, size)?;
if command == LC_CODE_SIGNATURE {
blob = Some((
le32(slice, offset + 8)? as usize,
@@ -247,18 +342,16 @@ pub fn read(slice: &[u8]) -> Result<Option<CodeSignature>> {
let Some((start, size)) = blob else {
return Ok(None);
};
let blob = slice
.get(start..start + size)
.context("code signature outside the slice")?;
let blob = extent(slice, start, size)?;
parse(blob).map(Some)
}
/// An embedded signature superblob, as `F_ADDFILESIGS` reads it from a file.
pub fn parse(blob: &[u8]) -> Result<CodeSignature> {
ensure!(
be32(blob, 0)? == CSMAGIC_EMBEDDED_SIGNATURE,
"code signature is not an embedded signature superblob"
);
let found = be32(blob, 0)?;
if found != CSMAGIC_EMBEDDED_SIGNATURE {
return Err(CodeSignatureError::SuperblobMagic { found });
}
let slots = be32(blob, 8)? as usize;
let mut best: Option<(u8, &[u8])> = None;
let mut entitlements = None;
@@ -270,15 +363,13 @@ pub fn parse(blob: &[u8]) -> Result<CodeSignature> {
let at = be32(blob, 16 + index * 8)? as usize;
let magic = be32(blob, at)?;
let length = be32(blob, at + 4)? as usize;
let body = blob
.get(at..at + length)
.context("truncated signature blob")?;
let body = extent(blob, at, length)?;
match magic {
CSMAGIC_CODEDIRECTORY
if slot == CSSLOT_CODEDIRECTORY
|| (CSSLOT_ALTERNATE_FIRST..=CSSLOT_ALTERNATE_LAST).contains(&slot) =>
{
let hash_type = *body.get(CD_HASH_TYPE).context("truncated code directory")?;
let hash_type = byte(body, CD_HASH_TYPE)?;
if slot == CSSLOT_CODEDIRECTORY {
signed = Some(body);
}
@@ -286,13 +377,17 @@ pub fn parse(blob: &[u8]) -> Result<CodeSignature> {
best = Some((hash_type, body));
}
}
CSMAGIC_EMBEDDED_ENTITLEMENTS => entitlements = Some(body[8..].to_vec()),
CSMAGIC_EMBEDDED_DER_ENTITLEMENTS => der_entitlements = Some(body[8..].to_vec()),
CSMAGIC_EMBEDDED_ENTITLEMENTS => {
entitlements = Some(extent(body, 8, length.saturating_sub(8))?.to_vec())
}
CSMAGIC_EMBEDDED_DER_ENTITLEMENTS => {
der_entitlements = Some(extent(body, 8, length.saturating_sub(8))?.to_vec())
}
CSMAGIC_BLOBWRAPPER if slot == CSSLOT_SIGNATURESLOT => cms = body.get(8..),
_ => {}
}
}
let (hash_type, directory) = best.context("code signature has no code directory")?;
let (hash_type, directory) = best.ok_or(CodeSignatureError::MissingCodeDirectory)?;
let apple_signed = matches!((cms, signed), (Some(cms), Some(signed))
if cms::verify(cms, signed, directory, hash_type, &APPLE_ANCHORS).is_ok());
let version = be32(directory, CD_VERSION)?;
@@ -305,10 +400,10 @@ pub fn parse(blob: &[u8]) -> Result<CodeSignature> {
} else {
None
};
let page_shift = *directory
.get(CD_PAGE_SIZE)
.context("truncated code directory")?;
ensure!(page_shift < 32, "code directory page size out of range");
let page_shift = byte(directory, CD_PAGE_SIZE)?;
if page_shift >= 32 {
return Err(CodeSignatureError::PageShift { value: page_shift });
}
let page_mask = (1u64 << page_shift) - 1;
let end_offset = (u64::from(be32(directory, CD_CODE_LIMIT)?) + page_mask) & !page_mask;
let scatter = if version >= CS_SUPPORTSSCATTER {
@@ -323,13 +418,12 @@ pub fn parse(blob: &[u8]) -> Result<CodeSignature> {
};
Ok(CodeSignature {
flags: be32(directory, CD_FLAGS)?,
platform: *directory
.get(CD_PLATFORM)
.context("truncated code directory")?,
platform: byte(directory, CD_PLATFORM)?,
hash_type,
identifier,
team_identifier,
cdhash: cdhash(hash_type, directory).context("unsupported code directory hash")?,
cdhash: cdhash(hash_type, directory)
.ok_or(CodeSignatureError::HashType { value: hash_type })?,
entitlements,
der_entitlements,
start_offset,
@@ -358,6 +452,60 @@ mod tests {
cd
}
#[test]
fn rejects_short_signature_command() {
let directory = directory(CS_HASHTYPE_SHA256, 0, 0);
let mut blob = Vec::new();
blob.extend(CSMAGIC_EMBEDDED_SIGNATURE.to_be_bytes());
blob.extend((20u32 + directory.len() as u32).to_be_bytes());
blob.extend(1u32.to_be_bytes());
blob.extend(CSSLOT_CODEDIRECTORY.to_be_bytes());
blob.extend(20u32.to_be_bytes());
blob.extend(directory);
let mut slice = vec![0u8; MACH_HEADER_64_BYTES + 16];
slice[..4].copy_from_slice(&MH_MAGIC_64.to_le_bytes());
slice[16..20].copy_from_slice(&1u32.to_le_bytes());
slice[20..24].copy_from_slice(&8u32.to_le_bytes());
slice[32..36].copy_from_slice(&LC_CODE_SIGNATURE.to_le_bytes());
slice[36..40].copy_from_slice(&8u32.to_le_bytes());
// These fields lie outside the declared command, although the image
// contains enough trailing bytes to make their values look valid.
slice[40..44].copy_from_slice(&48u32.to_le_bytes());
slice[44..48].copy_from_slice(&(blob.len() as u32).to_le_bytes());
slice.extend(blob);
assert!(matches!(
read(&slice),
Err(CodeSignatureError::LoadCommandSize {
command: LC_CODE_SIGNATURE,
bytes: 8,
minimum: 16,
})
));
}
#[test]
fn rejects_short_entitlement_blob() {
for (slot, magic) in [
(5u32, CSMAGIC_EMBEDDED_ENTITLEMENTS),
(7, CSMAGIC_EMBEDDED_DER_ENTITLEMENTS),
] {
for length in 0..8u32 {
let mut blob = Vec::new();
blob.extend(CSMAGIC_EMBEDDED_SIGNATURE.to_be_bytes());
blob.extend(28u32.to_be_bytes());
blob.extend(1u32.to_be_bytes());
blob.extend(slot.to_be_bytes());
blob.extend(20u32.to_be_bytes());
blob.extend(magic.to_be_bytes());
blob.extend(length.to_be_bytes());
assert!(
matches!(parse(&blob), Err(CodeSignatureError::Truncated { .. })),
"magic {magic:#x}, declared bytes {length}"
);
}
}
}
#[test]
fn best_directory_supplies_flags_and_cdhash() {
let sha1 = directory(CS_HASHTYPE_SHA1, 0, 1);
@@ -9,9 +9,77 @@
//! validity periods are not checked, as code signing does not expire
//! signed code.
use super::{CS_HASHTYPE_SHA1, CS_HASHTYPE_SHA256, CS_HASHTYPE_SHA384, ber_children, ber_element};
use crate::platform::apple::sep::image::rsa::{Hash, Key};
use crate::rsa::{self, Hash, Key};
use alloc::vec::Vec;
use sha2::{Digest as _, Sha256, Sha384};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Error {
Rsa(rsa::Error),
Element,
Field,
DigestAlgorithm,
SignatureAlgorithm,
UnusedBits,
CertificateAlgorithms,
CertificateKey,
CertificateIssuer,
ContentType,
SignerCount,
MessageDigest,
CodeDirectoryHash,
CodeDirectoryBinding,
SignerVersion,
SignerCertificate,
ChainAnchor,
}
impl From<rsa::Error> for Error {
fn from(error: rsa::Error) -> Self {
Self::Rsa(error)
}
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Rsa(error) => write!(f, "CMS: {error}"),
Self::Element => f.write_str("CMS element missing or mistagged"),
Self::Field => f.write_str("CMS field missing or mistagged"),
Self::DigestAlgorithm => f.write_str("unsupported CMS digest algorithm"),
Self::SignatureAlgorithm => f.write_str("unsupported CMS signature algorithm"),
Self::UnusedBits => f.write_str("BIT STRING with unused bits"),
Self::CertificateAlgorithms => f.write_str("certificate signature algorithms differ"),
Self::CertificateKey => f.write_str("certificate key is not RSA"),
Self::CertificateIssuer => {
f.write_str("certificate issuer does not name its issuer's subject")
}
Self::ContentType => f.write_str("CMS content is not SignedData"),
Self::SignerCount => f.write_str("CMS has more than one signer"),
Self::MessageDigest => {
f.write_str("CMS messageDigest does not match the code directory")
}
Self::CodeDirectoryHash => f.write_str("unsupported code directory hash type"),
Self::CodeDirectoryBinding => {
f.write_str("CMS CDHashes2 does not bind the chosen code directory")
}
Self::SignerVersion => f.write_str("CMS signer version is not 1"),
Self::SignerCertificate => f.write_str("CMS signer certificate is missing"),
Self::ChainAnchor => f.write_str("CMS chain lacks a pinned certificate"),
}
}
}
impl core::error::Error for Error {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Rsa(error) => Some(error),
_ => None,
}
}
}
const SEQUENCE: u8 = 0x30;
const SET: u8 = 0x31;
const INTEGER: u8 = 0x02;
@@ -39,10 +107,10 @@ pub(super) struct Anchors {
}
/// The contents of the one element at the start of `bytes`, if it has `tag`.
fn expect(bytes: &[u8], tag: u8) -> Result<&[u8], &'static str> {
fn expect(bytes: &[u8], tag: u8) -> Result<&[u8], Error> {
match ber_element(bytes) {
Some((found, contents, _)) if found == tag => Ok(contents),
_ => Err("CMS element missing or mistagged"),
_ => Err(Error::Element),
}
}
@@ -50,35 +118,35 @@ fn expect(bytes: &[u8], tag: u8) -> Result<&[u8], &'static str> {
fn next<'a>(
children: &mut impl Iterator<Item = (u8, &'a [u8], &'a [u8])>,
tag: u8,
) -> Result<(&'a [u8], &'a [u8]), &'static str> {
) -> Result<(&'a [u8], &'a [u8]), Error> {
match children.next() {
Some((found, contents, whole)) if found == tag => Ok((contents, whole)),
_ => Err("CMS field missing or mistagged"),
_ => Err(Error::Field),
}
}
/// An `AlgorithmIdentifier`'s OID.
fn algorithm(contents: &[u8]) -> Result<&[u8], &'static str> {
fn algorithm(contents: &[u8]) -> Result<&[u8], Error> {
expect(contents, OBJECT_IDENTIFIER)
}
fn digest(oid: &[u8], message: &[u8]) -> Result<Vec<u8>, &'static str> {
fn digest(oid: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
Ok(match oid {
SHA1 => sha1::Sha1::digest(message).to_vec(),
SHA256 => Sha256::digest(message).to_vec(),
SHA384 => Sha384::digest(message).to_vec(),
_ => return Err("unsupported CMS digest algorithm"),
_ => return Err(Error::DigestAlgorithm),
})
}
/// The hash an RSA signature algorithm signs with; plain `rsaEncryption`
/// takes the signer's digest algorithm.
fn rsa_hash(signature: &[u8], digest: Option<&[u8]>) -> Result<Hash, &'static str> {
fn rsa_hash(signature: &[u8], digest: Option<&[u8]>) -> Result<Hash, Error> {
match (signature, digest) {
(RSA_SHA1, _) | (RSA_ENCRYPTION, Some(SHA1)) => Ok(Hash::Sha1),
(RSA_SHA256, _) | (RSA_ENCRYPTION, Some(SHA256)) => Ok(Hash::Sha256),
(RSA_SHA384, _) | (RSA_ENCRYPTION, Some(SHA384)) => Ok(Hash::Sha384),
_ => Err("unsupported CMS signature algorithm"),
_ => Err(Error::SignatureAlgorithm),
}
}
@@ -96,14 +164,14 @@ struct Certificate<'a> {
}
/// A BIT STRING's bytes, which must have no unused bits.
fn bits(contents: &[u8]) -> Result<&[u8], &'static str> {
fn bits(contents: &[u8]) -> Result<&[u8], Error> {
match contents.split_first() {
Some((0, bytes)) => Ok(bytes),
_ => Err("BIT STRING with unused bits"),
_ => Err(Error::UnusedBits),
}
}
fn certificate(whole: &[u8]) -> Result<Certificate<'_>, &'static str> {
fn certificate(whole: &[u8]) -> Result<Certificate<'_>, Error> {
let mut parts = ber_children(expect(whole, SEQUENCE)?);
let (tbs_contents, tbs) = next(&mut parts, SEQUENCE)?;
let (signature_algorithm, outer_algorithm) = next(&mut parts, SEQUENCE)?;
@@ -114,7 +182,7 @@ fn certificate(whole: &[u8]) -> Result<Certificate<'_>, &'static str> {
}
let (serial, _) = next(&mut fields, INTEGER)?;
if next(&mut fields, SEQUENCE)?.1 != outer_algorithm {
return Err("certificate signature algorithms differ");
return Err(Error::CertificateAlgorithms);
}
let (_, issuer) = next(&mut fields, SEQUENCE)?;
next(&mut fields, SEQUENCE)?;
@@ -123,7 +191,7 @@ fn certificate(whole: &[u8]) -> Result<Certificate<'_>, &'static str> {
let mut public_key = ber_children(public_key_info);
let (key_algorithm, _) = next(&mut public_key, SEQUENCE)?;
if algorithm(key_algorithm)? != RSA_ENCRYPTION {
return Err("certificate key is not RSA");
return Err(Error::CertificateKey);
}
let (key, _) = next(&mut public_key, BIT_STRING)?;
Ok(Certificate {
@@ -144,11 +212,13 @@ impl Certificate<'_> {
}
/// Whether `issuer` signed this certificate.
fn issued_by(&self, issuer: &Certificate<'_>) -> Result<(), &'static str> {
fn issued_by(&self, issuer: &Certificate<'_>) -> Result<(), Error> {
if self.issuer != issuer.subject {
return Err("certificate issuer does not name its issuer's subject");
return Err(Error::CertificateIssuer);
}
Key::parse(issuer.key)?.verify(self.tbs, self.signature, rsa_hash(self.algorithm, None)?)
Key::parse(issuer.key)?
.verify(self.tbs, self.signature, rsa_hash(self.algorithm, None)?)
.map_err(Error::Rsa)
}
}
@@ -158,10 +228,10 @@ struct SignedData<'a> {
signer: &'a [u8],
}
fn signed_data(cms: &[u8]) -> Result<SignedData<'_>, &'static str> {
fn signed_data(cms: &[u8]) -> Result<SignedData<'_>, Error> {
let mut info = ber_children(expect(cms, SEQUENCE)?);
if next(&mut info, OBJECT_IDENTIFIER)?.0 != SIGNED_DATA {
return Err("CMS content is not SignedData");
return Err(Error::ContentType);
}
let (explicit, _) = next(&mut info, CONTEXT_0)?;
let mut fields = ber_children(expect(explicit, SEQUENCE)?);
@@ -174,7 +244,7 @@ fn signed_data(cms: &[u8]) -> Result<SignedData<'_>, &'static str> {
let mut signers = ber_children(signers);
let (signer, _) = next(&mut signers, SEQUENCE)?;
if signers.next().is_some() {
return Err("CMS has more than one signer");
return Err(Error::SignerCount);
}
Ok(SignedData {
certificates: ber_children(certificates)
@@ -225,17 +295,17 @@ fn binds(
signed: &[u8],
chosen: &[u8],
hash_type: u8,
) -> Result<(), &'static str> {
) -> Result<(), Error> {
let mut digests = attribute_values(attributes, MESSAGE_DIGEST);
let expected = digest(digest_algorithm, signed)?;
match (digests.next(), digests.next()) {
(Some((OCTET_STRING, found, _)), None) if found == expected.as_slice() => {}
_ => return Err("CMS messageDigest does not match the code directory"),
_ => return Err(Error::MessageDigest),
}
if chosen == signed {
return Ok(());
}
let algorithm = cdhash_algorithm(hash_type).ok_or("unsupported code directory hash type")?;
let algorithm = cdhash_algorithm(hash_type).ok_or(Error::CodeDirectoryHash)?;
let wanted = digest(algorithm, chosen)?;
let bound = attribute_values(attributes, CDHASHES2).any(|(tag, entry, _)| {
let mut parts = ber_children(entry);
@@ -246,7 +316,7 @@ fn binds(
if bound {
Ok(())
} else {
Err("CMS CDHashes2 does not bind the chosen code directory")
Err(Error::CodeDirectoryBinding)
}
}
@@ -259,7 +329,7 @@ pub(super) fn verify(
chosen: &[u8],
hash_type: u8,
anchors: &Anchors,
) -> Result<(), &'static str> {
) -> Result<(), Error> {
let data = signed_data(cms)?;
let certificates = data
.certificates
@@ -268,7 +338,7 @@ pub(super) fn verify(
.collect::<Result<Vec<_>, _>>()?;
let mut fields = ber_children(data.signer);
if next(&mut fields, INTEGER)?.0 != [1] {
return Err("CMS signer version is not 1");
return Err(Error::SignerVersion);
}
// `sid`: `issuerAndSerialNumber`, as version 1 requires.
let (sid, _) = next(&mut fields, SEQUENCE)?;
@@ -284,7 +354,7 @@ pub(super) fn verify(
let leaf = certificates
.iter()
.find(|certificate| certificate.issuer == sid_issuer && certificate.serial == sid_serial)
.ok_or("CMS signer certificate is missing")?;
.ok_or(Error::SignerCertificate)?;
// The signature covers the attributes' DER with the SET OF tag.
let mut message = signed_attributes.to_vec();
message[0] = SET;
@@ -297,7 +367,7 @@ pub(super) fn verify(
certificates
.iter()
.find(|certificate| certificate.fingerprint() == *fingerprint)
.ok_or("CMS chain lacks a pinned certificate")
.ok_or(Error::ChainAnchor)
.and_then(|issuer| child.issued_by(issuer).map(|()| issuer))
};
let authority = issuer_of(leaf, &anchors.authority)?;
+235
View File
@@ -0,0 +1,235 @@
//! Bounded DER cursor for firmware, certificates, and signed containers.
//! X.690 definite, minimal lengths/tags; no BER normalization before hashing.
/// A structural DER failure, including the offending field when available.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
Truncated {
offset: usize,
},
NonMinimalTag,
TagOverflow,
LengthWidth {
bytes: usize,
},
NonMinimalLength,
LengthOverflow,
ExtentOverflow,
ValueTruncated {
header: usize,
bytes: usize,
available: usize,
},
UnexpectedTag {
expected: u32,
found: u32,
class: u8,
constructed: bool,
},
TrailingFields {
bytes: usize,
},
EmptyInteger,
NegativeInteger,
NonMinimalInteger,
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Truncated { offset } => write!(f, "DER is truncated at {offset:#x}"),
Self::NonMinimalTag => f.write_str("DER tag is not minimal"),
Self::TagOverflow => f.write_str("DER tag overflows"),
Self::LengthWidth { bytes } => {
write!(f, "DER length width {bytes} is indefinite or oversized")
}
Self::NonMinimalLength => f.write_str("DER length is not minimal"),
Self::LengthOverflow => f.write_str("DER length overflows"),
Self::ExtentOverflow => f.write_str("DER extent overflows"),
Self::ValueTruncated {
header,
bytes,
available,
} => write!(
f,
"DER value needs {bytes} bytes after header {header}, container has {available}"
),
Self::UnexpectedTag {
expected,
found,
class,
constructed,
} => write!(
f,
"DER expected tag {expected}, found class {class} tag {found} constructed={constructed}"
),
Self::TrailingFields { bytes } => write!(f, "DER has {bytes} trailing bytes"),
Self::EmptyInteger => f.write_str("DER integer is empty"),
Self::NegativeInteger => f.write_str("DER integer is negative"),
Self::NonMinimalInteger => f.write_str("DER integer is not minimal"),
}
}
}
impl core::error::Error for Error {}
#[derive(Clone, Copy, Debug)]
pub struct Element<'a> {
pub tag: u32,
pub class: u8,
pub constructed: bool,
pub value: &'a [u8],
pub encoded: &'a [u8],
}
pub struct Cursor<'a>(pub &'a [u8]);
impl<'a> Cursor<'a> {
pub fn next_element(&mut self) -> Result<Element<'a>, Error> {
let original = self.0;
let mut at = 0;
let mut byte = || {
let b = *original.get(at).ok_or(Error::Truncated { offset: at })?;
at += 1;
Ok::<_, Error>(b)
};
let first = byte()?;
let mut tag = u32::from(first & 31);
if tag == 31 {
tag = 0;
let mut b = byte()?;
if b & 127 == 0 {
return Err(Error::NonMinimalTag);
}
loop {
tag = tag
.checked_mul(128)
.and_then(|n| n.checked_add(u32::from(b & 127)))
.ok_or(Error::TagOverflow)?;
if b & 128 == 0 {
break;
}
b = byte()?;
}
if tag < 31 {
return Err(Error::NonMinimalTag);
}
}
let first_length = byte()?;
let length = if first_length < 128 {
usize::from(first_length)
} else {
let width = usize::from(first_length & 127);
if !(1..=4).contains(&width) {
return Err(Error::LengthWidth { bytes: width });
}
let mut length = 0usize;
for index in 0..width {
let b = byte()?;
if index == 0 && b == 0 {
return Err(Error::NonMinimalLength);
}
length = length
.checked_mul(256)
.and_then(|n| n.checked_add(usize::from(b)))
.ok_or(Error::LengthOverflow)?;
}
if length < 128 {
return Err(Error::NonMinimalLength);
}
length
};
let end = at.checked_add(length).ok_or(Error::ExtentOverflow)?;
let encoded = original.get(..end).ok_or(Error::ValueTruncated {
header: at,
bytes: length,
available: original.len(),
})?;
self.0 = &original[end..];
Ok(Element {
tag,
class: first >> 6,
constructed: first & 32 != 0,
value: &encoded[at..],
encoded,
})
}
pub fn take(&mut self, tag: u32) -> Result<Element<'a>, Error> {
let element = self.next_element()?;
let constructed = matches!(tag, 16 | 17);
if element.class != 0 || element.tag != tag || element.constructed != constructed {
return Err(Error::UnexpectedTag {
expected: tag,
found: element.tag,
class: element.class,
constructed: element.constructed,
});
}
Ok(element)
}
pub fn end(self) -> Result<(), Error> {
if self.0.is_empty() {
Ok(())
} else {
Err(Error::TrailingFields {
bytes: self.0.len(),
})
}
}
}
pub fn sequence(bytes: &[u8]) -> Result<Cursor<'_>, Error> {
let mut cursor = Cursor(bytes);
let element = cursor.take(16)?;
cursor.end()?;
Ok(Cursor(element.value))
}
pub fn unsigned(bytes: &[u8]) -> Result<&[u8], Error> {
let first = *bytes.first().ok_or(Error::EmptyInteger)?;
if first & 128 != 0 {
return Err(Error::NegativeInteger);
}
if bytes.len() > 1 && first == 0 {
if bytes[1] & 128 == 0 {
return Err(Error::NonMinimalInteger);
}
Ok(&bytes[1..])
} else {
Ok(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn der_preserves_signed_encoding_and_rejects_noncanonical_inputs() {
let bytes = b"\x30\x03\x02\x01\x7f";
let mut cursor = sequence(bytes).unwrap();
let field = cursor.take(2).unwrap();
assert_eq!(field.encoded, &bytes[2..]);
assert_eq!(unsigned(field.value), Ok(b"\x7f".as_slice()));
cursor.end().unwrap();
for bad in [
b"\x30\x80\0\0".as_slice(),
b"\x30\x81\x03\x02\x01\0",
b"\x30\x82\0\x80",
b"\x30\x02\0",
b"\xff\x80\x1f\0",
b"\x1f\x01\0",
b"\x30\0\0",
] {
assert!(sequence(bad).is_err());
}
for bad in [b"".as_slice(), b"\x80", b"\0\x7f"] {
assert!(unsigned(bad).is_err());
}
assert_eq!(unsigned(b"\0\x80"), Ok(b"\x80".as_slice()));
assert!(Cursor(b"\x10\0").take(16).is_err());
assert!(Cursor(b"\x22\0").take(2).is_err());
}
}
File renamed without changes.
@@ -33,6 +33,8 @@ impl core::fmt::Display for Img4Error {
}
}
impl core::error::Error for Img4Error {}
const SEQUENCE: u8 = 0x30;
const IA5_STRING: u8 = 0x16;
const CONTEXT_0: u8 = 0xa0;
@@ -330,49 +332,14 @@ pub fn tail_manifest(mut tail: &[u8]) -> Result<Option<&[u8]>, Img4Error> {
Ok(manifest)
}
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use alloc::vec::Vec;
pub(crate) fn der(tag: u8, value: &[u8]) -> Vec<u8> {
let mut out = alloc::vec![tag];
if value.len() < 0x80 {
out.push(value.len() as u8);
} else {
let length = (value.len() as u32).to_be_bytes();
let skip = length.iter().take_while(|&&b| b == 0).count();
out.push(0x80 | (4 - skip) as u8);
out.extend(&length[skip..]);
}
out.extend(value);
out
}
pub(crate) fn im4p(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
der(
SEQUENCE,
&[
der(IA5_STRING, b"IM4P"),
der(IA5_STRING, kind),
der(IA5_STRING, b"synthetic"),
der(0x04, payload),
]
.concat(),
)
}
pub(crate) fn img4(payload: &[u8], manifest: &[u8]) -> Vec<u8> {
der(
SEQUENCE,
&[
der(IA5_STRING, b"IMG4"),
payload.to_vec(),
der(CONTEXT_0, manifest),
]
.concat(),
)
}
use super::test_support::{der, im4p, img4};
#[test]
fn splits_img4_and_accepts_bare_im4p() {
@@ -0,0 +1,42 @@
//! Synthetic Image4 fixtures shared by downstream tests.
use super::*;
use alloc::vec::Vec;
pub fn der(tag: u8, value: &[u8]) -> Vec<u8> {
let mut out = alloc::vec![tag];
if value.len() < 0x80 {
out.push(value.len() as u8);
} else {
let length = (value.len() as u32).to_be_bytes();
let skip = length.iter().take_while(|&&b| b == 0).count();
out.push(0x80 | (4 - skip) as u8);
out.extend(&length[skip..]);
}
out.extend(value);
out
}
pub fn im4p(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
der(
SEQUENCE,
&[
der(IA5_STRING, b"IM4P"),
der(IA5_STRING, kind),
der(IA5_STRING, b"synthetic"),
der(0x04, payload),
]
.concat(),
)
}
pub fn img4(payload: &[u8], manifest: &[u8]) -> Vec<u8> {
der(
SEQUENCE,
&[
der(IA5_STRING, b"IMG4"),
payload.to_vec(),
der(CONTEXT_0, manifest),
]
.concat(),
)
}
+18
View File
@@ -0,0 +1,18 @@
//! Disk, firmware, signing, and boot-bundle formats shared by preparation and execution.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg_attr(all(test, not(feature = "std")), macro_use)]
extern crate alloc;
pub mod apfs;
pub mod boot_bundle;
pub mod builds;
pub mod code_signature;
pub mod der;
mod hash;
pub mod img4;
pub mod lzfse;
pub mod payload;
pub mod preboot;
pub mod rsa;
pub use hash::sha256;
File renamed without changes.
@@ -609,96 +609,15 @@ impl PayloadManifest {
}
}
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use alloc::{vec, vec::Vec};
use alloc::vec::Vec;
/// An in-memory file.
pub(crate) struct Memory(pub Vec<u8>);
impl ReadAt for Memory {
type Error = &'static str;
fn len(&self) -> u64 {
self.0.len() as u64
}
fn read_at(&mut self, offset: u64, buffer: &mut [u8]) -> Result<(), &'static str> {
let start = offset as usize;
let bytes = self.0.get(start..start + buffer.len()).ok_or("past end")?;
buffer.copy_from_slice(bytes);
Ok(())
}
}
/// A three-identity manifest and the members' contents.
pub(crate) fn manifest() -> (PayloadManifest, Vec<(String, Vec<u8>)>) {
let contents: Vec<(String, Vec<u8>)> = [
("kernelcache.release.test", vec![1u8; 3000]),
(
"Firmware/os.dmg.aea",
(0..2_500_000u32).map(|i| i as u8).collect(),
),
("update.dmg", vec![9u8; 10]),
(
"Firmware/Manifests/restore/macOS Customer/apticket.test.im4m",
vec![],
),
]
.into_iter()
.map(|(name, data)| (name.to_string(), data))
.collect();
let pem = "-----BEGIN PRIVATE KEY-----\nAA==\n-----END PRIVATE KEY-----\n";
let manifest = PayloadManifest {
schema_version: 1,
kind: KIND.into(),
product_version: "27.0.1".into(),
product_build: "26A434".into(),
model: "Mac14,3".into(),
device_class: "j473ap".into(),
source: SourceImage {
file_name: "Test.ipsw".into(),
bytes: 1,
sha256: Some("0".repeat(64)),
build_manifest_sha256: "1".repeat(64),
catalog_sha1: None,
},
layout: Layout::Split { slice_bytes: 1000 },
members: contents
.iter()
.map(|(name, data)| Member {
name: name.clone(),
bytes: data.len() as u64,
sha256: Some(crate::sha256(data)),
sha384: None,
})
.collect(),
identities: vec![
IdentitySet {
index: 20,
variant: "Customer Erase Install (IPSW)".into(),
purpose: Purpose::Erase,
members: vec![contents[0].0.clone(), contents[1].0.clone()],
},
IdentitySet {
index: 80,
variant: "Customer Upgrade Install (IPSW)".into(),
purpose: Purpose::Update,
members: vec![contents[0].0.clone(), contents[2].0.clone()],
},
],
global_manifests: vec![contents[3].0.clone()],
aea_keys: vec![AeaKey {
member: contents[1].0.clone(),
header_sha256: "2".repeat(64),
url: "https://wkms-public.apple.com/fcs-keys/x".into(),
key_pem: pem.into(),
key_sha256: crate::sha256(pem.as_bytes()),
url_asset_sha256: None,
}],
block_hashes: None,
};
(manifest, contents)
}
use super::test_support::manifest;
#[test]
fn manifests_round_trip_and_reject_unsafe_or_inconsistent_fields() {
@@ -218,7 +218,9 @@ impl<R: ReadAt> ReadAt for Joined<R> {
#[cfg(test)]
mod tests {
use super::*;
use crate::payload::{BlockHashes, PIECE_HASHES_FILE, Piece, piece_sizes, tests::Memory};
use crate::payload::{
BlockHashes, PIECE_HASHES_FILE, Piece, piece_sizes, test_support::Memory,
};
const BLOCK: u64 = 512;
@@ -229,7 +231,7 @@ mod tests {
ipsw: &[u8],
piece_bytes: u64,
) -> (Memory, PayloadManifest, Vec<Vec<Extent>>, Vec<u8>) {
let (mut manifest, _) = crate::payload::tests::manifest();
let (mut manifest, _) = crate::payload::test_support::manifest();
manifest.source.bytes = ipsw.len() as u64;
let mut device = vec![0xeeu8; 64];
let mut pieces = Vec::new();
@@ -184,7 +184,9 @@ impl<R: ReadAt> super::PayloadSource for StagedSource<R> {
#[cfg(test)]
mod tests {
use super::*;
use crate::payload::{PayloadSource, copy_verified, tests::Memory, tests::manifest};
use crate::payload::{
PayloadSource, copy_verified, test_support::Memory, test_support::manifest,
};
#[test]
fn staged_members_are_aligned_and_read_back_verified() {
@@ -0,0 +1,89 @@
//! Synthetic payload fixtures shared by downstream tests.
use super::*;
use alloc::{vec, vec::Vec};
/// An in-memory file.
pub struct Memory(pub Vec<u8>);
impl ReadAt for Memory {
type Error = &'static str;
fn len(&self) -> u64 {
self.0.len() as u64
}
fn read_at(&mut self, offset: u64, buffer: &mut [u8]) -> Result<(), &'static str> {
let start = offset as usize;
let bytes = self.0.get(start..start + buffer.len()).ok_or("past end")?;
buffer.copy_from_slice(bytes);
Ok(())
}
}
/// A three-identity manifest and the members' contents.
pub fn manifest() -> (PayloadManifest, Vec<(String, Vec<u8>)>) {
let contents: Vec<(String, Vec<u8>)> = [
("kernelcache.release.test", vec![1u8; 3000]),
(
"Firmware/os.dmg.aea",
(0..2_500_000u32).map(|i| i as u8).collect(),
),
("update.dmg", vec![9u8; 10]),
(
"Firmware/Manifests/restore/macOS Customer/apticket.test.im4m",
vec![],
),
]
.into_iter()
.map(|(name, data)| (name.to_string(), data))
.collect();
let pem = "-----BEGIN PRIVATE KEY-----\nAA==\n-----END PRIVATE KEY-----\n";
let manifest = PayloadManifest {
schema_version: 1,
kind: KIND.into(),
product_version: "27.0.1".into(),
product_build: "26A434".into(),
model: "Mac14,3".into(),
device_class: "j473ap".into(),
source: SourceImage {
file_name: "Test.ipsw".into(),
bytes: 1,
sha256: Some("0".repeat(64)),
build_manifest_sha256: "1".repeat(64),
catalog_sha1: None,
},
layout: Layout::Split { slice_bytes: 1000 },
members: contents
.iter()
.map(|(name, data)| Member {
name: name.clone(),
bytes: data.len() as u64,
sha256: Some(crate::sha256(data)),
sha384: None,
})
.collect(),
identities: vec![
IdentitySet {
index: 20,
variant: "Customer Erase Install (IPSW)".into(),
purpose: Purpose::Erase,
members: vec![contents[0].0.clone(), contents[1].0.clone()],
},
IdentitySet {
index: 80,
variant: "Customer Upgrade Install (IPSW)".into(),
purpose: Purpose::Update,
members: vec![contents[0].0.clone(), contents[2].0.clone()],
},
],
global_manifests: vec![contents[3].0.clone()],
aea_keys: vec![AeaKey {
member: contents[1].0.clone(),
header_sha256: "2".repeat(64),
url: "https://wkms-public.apple.com/fcs-keys/x".into(),
key_pem: pem.into(),
key_sha256: crate::sha256(pem.as_bytes()),
url_asset_sha256: None,
}],
block_hashes: None,
};
(manifest, contents)
}
@@ -472,95 +472,15 @@ impl<R: ReadAt> MemberRead for MemberStream<'_, R> {
}
}
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::payload::tests::Memory;
use crate::payload::test_support::Memory;
/// Build an archive; `zip64` forces the ZIP64 end records and extra fields.
pub(crate) fn archive(members: &[(&str, &[u8], bool)], zip64: bool) -> Vec<u8> {
let mut out = Vec::new();
let mut central = Vec::new();
for (name, data, deflate) in members {
let body = if *deflate {
miniz_oxide::deflate::compress_to_vec(data, 6)
} else {
data.to_vec()
};
let offset = out.len() as u64;
let crc = crate::payload::gpt::crc32(data);
let method: u16 = if *deflate { 8 } else { 0 };
let small = |v: u64| if zip64 { 0xffff_ffff } else { v as u32 };
out.extend_from_slice(&LOCAL.to_le_bytes());
out.extend_from_slice(&[20, 0, 0, 0]);
out.extend_from_slice(&method.to_le_bytes());
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(&crc.to_le_bytes());
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
out.extend_from_slice(&[3, 0]);
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(b"xyz");
out.extend_from_slice(&body);
let extra: Vec<u8> = if zip64 {
[1u16.to_le_bytes(), 24u16.to_le_bytes()]
.concat()
.into_iter()
.chain((data.len() as u64).to_le_bytes())
.chain((body.len() as u64).to_le_bytes())
.chain(offset.to_le_bytes())
.collect()
} else {
Vec::new()
};
central.extend_from_slice(&CENTRAL.to_le_bytes());
central.extend_from_slice(&[45, 0, 45, 0, 0, 0]);
central.extend_from_slice(&method.to_le_bytes());
central.extend_from_slice(&[0; 4]);
central.extend_from_slice(&crc.to_le_bytes());
central.extend_from_slice(&small(body.len() as u64).to_le_bytes());
central.extend_from_slice(&small(data.len() as u64).to_le_bytes());
central.extend_from_slice(&(name.len() as u16).to_le_bytes());
central.extend_from_slice(&(extra.len() as u16).to_le_bytes());
central.extend_from_slice(&[0; 10]);
central.extend_from_slice(&small(offset).to_le_bytes());
central.extend_from_slice(name.as_bytes());
central.extend_from_slice(&extra);
}
let start = out.len() as u64;
out.extend_from_slice(&central);
let count = members.len() as u64;
if zip64 {
let record = out.len() as u64;
out.extend_from_slice(&END64.to_le_bytes());
out.extend_from_slice(&44u64.to_le_bytes());
out.extend_from_slice(&[45, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
out.extend_from_slice(&count.to_le_bytes());
out.extend_from_slice(&count.to_le_bytes());
out.extend_from_slice(&(central.len() as u64).to_le_bytes());
out.extend_from_slice(&start.to_le_bytes());
out.extend_from_slice(&LOCATOR64.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes());
out.extend_from_slice(&record.to_le_bytes());
out.extend_from_slice(&1u32.to_le_bytes());
}
out.extend_from_slice(&END.to_le_bytes());
out.extend_from_slice(&[0; 4]);
let n = if zip64 { 0xffff } else { count as u16 };
out.extend_from_slice(&n.to_le_bytes());
out.extend_from_slice(&n.to_le_bytes());
let (size, offset) = if zip64 {
(0xffff_ffffu32, 0xffff_ffffu32)
} else {
(central.len() as u32, start as u32)
};
out.extend_from_slice(&size.to_le_bytes());
out.extend_from_slice(&offset.to_le_bytes());
out.extend_from_slice(&5u16.to_le_bytes());
out.extend_from_slice(b"notes");
out
}
use super::test_support::archive;
fn drain(stream: &mut impl MemberRead, chunk: usize) -> Result<Vec<u8>, PayloadError> {
let mut out = Vec::new();
Loaded 100 of 480 files, more files were not shown because too many files have changed in this diff. Show more