diff --git a/Cargo.lock b/Cargo.lock index 17a7b50594..915b57a8b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index 3123cbae3a..8db4cc1cd1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/crates/stela-boot/Cargo.toml b/crates/stela-boot/Cargo.toml index b531b66ce0..449f84e65a 100644 --- a/crates/stela-boot/Cargo.toml +++ b/crates/stela-boot/Cargo.toml @@ -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"] } diff --git a/crates/stela-boot/src/audio_check.rs b/crates/stela-boot/src/audio_check.rs index 33f34e9c26..42bfe89731 100644 --- a/crates/stela-boot/src/audio_check.rs +++ b/crates/stela-boot/src/audio_check.rs @@ -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()); diff --git a/crates/stela-boot/src/engine.rs b/crates/stela-boot/src/engine.rs index b7b4f8cbcb..5019c7a5a1 100644 --- a/crates/stela-boot/src/engine.rs +++ b/crates/stela-boot/src/engine.rs @@ -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()) diff --git a/crates/stela-boot/src/engine/bundle.rs b/crates/stela-boot/src/engine/bundle.rs index add49122d8..ab66c92677 100644 --- a/crates/stela-boot/src/engine/bundle.rs +++ b/crates/stela-boot/src/engine/bundle.rs @@ -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::{ diff --git a/crates/stela-boot/src/engine/bundle/live_tree.rs b/crates/stela-boot/src/engine/bundle/live_tree.rs index 0e223e9f80..1cf98c2687 100644 --- a/crates/stela-boot/src/engine/bundle/live_tree.rs +++ b/crates/stela-boot/src/engine/bundle/live_tree.rs @@ -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; diff --git a/crates/stela-boot/src/engine/bundle/source.rs b/crates/stela-boot/src/engine/bundle/source.rs index 1c9bb173ed..1c7aeb9cba 100644 --- a/crates/stela-boot/src/engine/bundle/source.rs +++ b/crates/stela-boot/src/engine/bundle/source.rs @@ -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!([{ diff --git a/crates/stela-boot/src/engine/bundle/source/cpus.rs b/crates/stela-boot/src/engine/bundle/source/cpus.rs index d348a5e096..7f03a09d9f 100644 --- a/crates/stela-boot/src/engine/bundle/source/cpus.rs +++ b/crates/stela-boot/src/engine/bundle/source/cpus.rs @@ -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 { diff --git a/crates/stela-boot/src/engine/display.rs b/crates/stela-boot/src/engine/display.rs index 73ad265ccc..3b944688d8 100644 --- a/crates/stela-boot/src/engine/display.rs +++ b/crates/stela-boot/src/engine/display.rs @@ -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 diff --git a/crates/stela-boot/src/engine/fdr.rs b/crates/stela-boot/src/engine/fdr.rs index d169bca625..e2bf210110 100644 --- a/crates/stela-boot/src/engine/fdr.rs +++ b/crates/stela-boot/src/engine/fdr.rs @@ -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(()) })) diff --git a/crates/stela-boot/src/engine/install.rs b/crates/stela-boot/src/engine/install.rs index 769ae30fb8..77d6dd16d8 100644 --- a/crates/stela-boot/src/engine/install.rs +++ b/crates/stela-boot/src/engine/install.rs @@ -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. diff --git a/crates/stela-boot/src/engine/nor.rs b/crates/stela-boot/src/engine/nor.rs index 8a320dd06c..4743f76ce9 100644 --- a/crates/stela-boot/src/engine/nor.rs +++ b/crates/stela-boot/src/engine/nor.rs @@ -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 diff --git a/crates/stela-boot/src/engine/remote.rs b/crates/stela-boot/src/engine/remote.rs index 7105720475..05660334b1 100644 --- a/crates/stela-boot/src/engine/remote.rs +++ b/crates/stela-boot/src/engine/remote.rs @@ -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; diff --git a/crates/stela-boot/src/engine/restore.rs b/crates/stela-boot/src/engine/restore.rs index f0ced44038..2e2ab13a50 100644 --- a/crates/stela-boot/src/engine/restore.rs +++ b/crates/stela-boot/src/engine/restore.rs @@ -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() { diff --git a/crates/stela-boot/src/engine/topology.rs b/crates/stela-boot/src/engine/topology.rs index 2e7fec625d..285b7258bc 100644 --- a/crates/stela-boot/src/engine/topology.rs +++ b/crates/stela-boot/src/engine/topology.rs @@ -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!( diff --git a/crates/stela-boot/src/host_firmware.rs b/crates/stela-boot/src/host_firmware.rs index 351c62d479..977162e824 100644 --- a/crates/stela-boot/src/host_firmware.rs +++ b/crates/stela-boot/src/host_firmware.rs @@ -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, diff --git a/crates/stela-boot/src/installer.rs b/crates/stela-boot/src/installer.rs index 5783ea23f1..f00626b64f 100644 --- a/crates/stela-boot/src/installer.rs +++ b/crates/stela-boot/src/installer.rs @@ -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 { }; 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), diff --git a/crates/stela-boot/src/native_smp/kernel_check.rs b/crates/stela-boot/src/native_smp/kernel_check.rs index 3bad67a459..6eebb2b60c 100644 --- a/crates/stela-boot/src/native_smp/kernel_check.rs +++ b/crates/stela-boot/src/native_smp/kernel_check.rs @@ -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, diff --git a/crates/stela-boot/src/native_smp/kernel_check/cold/tree.rs b/crates/stela-boot/src/native_smp/kernel_check/cold/tree.rs index 6289ac3117..2e7828f661 100644 --- a/crates/stela-boot/src/native_smp/kernel_check/cold/tree.rs +++ b/crates/stela-boot/src/native_smp/kernel_check/cold/tree.rs @@ -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. diff --git a/crates/stela-boot/src/payload.rs b/crates/stela-boot/src/payload.rs index f57600bb7e..4860984e03 100644 --- a/crates/stela-boot/src/payload.rs +++ b/crates/stela-boot/src/payload.rs @@ -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", diff --git a/crates/stela-boot/src/selection.rs b/crates/stela-boot/src/selection.rs index 5700fc736e..c1cd9176e3 100644 --- a/crates/stela-boot/src/selection.rs +++ b/crates/stela-boot/src/selection.rs @@ -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}, diff --git a/crates/stela-boot/src/storage.rs b/crates/stela-boot/src/storage.rs index a5fc3546d1..6d24f1aab2 100644 --- a/crates/stela-boot/src/storage.rs +++ b/crates/stela-boot/src/storage.rs @@ -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 { diff --git a/crates/stela-cli/Cargo.toml b/crates/stela-cli/Cargo.toml index fa3922cf37..a2a080f24a 100644 --- a/crates/stela-cli/Cargo.toml +++ b/crates/stela-cli/Cargo.toml @@ -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"] } diff --git a/crates/stela-cli/src/apfs.rs b/crates/stela-cli/src/apfs.rs index 1e9459cb7d..5f8e25ecbc 100644 --- a/crates/stela-cli/src/apfs.rs +++ b/crates/stela-cli/src/apfs.rs @@ -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)}) ); } } diff --git a/crates/stela-cli/src/boot.rs b/crates/stela-cli/src/boot.rs index 0cd433762a..08083d411e 100644 --- a/crates/stela-cli/src/boot.rs +++ b/crates/stela-cli/src/boot.rs @@ -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(), diff --git a/crates/stela-cli/src/boot/board_firmware.rs b/crates/stela-cli/src/boot/board_firmware.rs index 9498312a53..15d6cc690b 100644 --- a/crates/stela-cli/src/boot/board_firmware.rs +++ b/crates/stela-cli/src/boot/board_firmware.rs @@ -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 diff --git a/crates/stela-cli/src/boot/disk.rs b/crates/stela-cli/src/boot/disk.rs index 787274353f..8fba81d820 100644 --- a/crates/stela-cli/src/boot/disk.rs +++ b/crates/stela-cli/src/boot/disk.rs @@ -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<()> { diff --git a/crates/stela-cli/src/efi.rs b/crates/stela-cli/src/efi.rs index e71b1b04ac..803b6bca63 100644 --- a/crates/stela-cli/src/efi.rs +++ b/crates/stela-cli/src/efi.rs @@ -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). diff --git a/crates/stela-cli/src/guest_system.rs b/crates/stela-cli/src/guest_system.rs index b1e2bc1556..2fc2edf552 100644 --- a/crates/stela-cli/src/guest_system.rs +++ b/crates/stela-cli/src/guest_system.rs @@ -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")))] diff --git a/crates/stela-cli/src/guest_system/install.rs b/crates/stela-cli/src/guest_system/install.rs index 982471d0d8..67d7af99b1 100644 --- a/crates/stela-cli/src/guest_system/install.rs +++ b/crates/stela-cli/src/guest_system/install.rs @@ -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(); diff --git a/crates/stela-cli/src/guest_system/install/metadata.rs b/crates/stela-cli/src/guest_system/install/metadata.rs index 4d199179dd..0ffbfc3677 100644 --- a/crates/stela-cli/src/guest_system/install/metadata.rs +++ b/crates/stela-cli/src/guest_system/install/metadata.rs @@ -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![], }; diff --git a/crates/stela-cli/src/restore.rs b/crates/stela-cli/src/restore.rs index 4045cdf04f..4cc63e50bc 100644 --- a/crates/stela-cli/src/restore.rs +++ b/crates/stela-cli/src/restore.rs @@ -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(), }; diff --git a/crates/stela-cli/src/restore/aea.rs b/crates/stela-cli/src/restore/aea.rs index c4e6e27a42..68b4a30efe 100644 --- a/crates/stela-cli/src/restore/aea.rs +++ b/crates/stela-cli/src/restore/aea.rs @@ -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; diff --git a/crates/stela-cli/src/restore/aea/container.rs b/crates/stela-cli/src/restore/aea/container.rs index 9a638f22d2..4c3379365a 100644 --- a/crates/stela-cli/src/restore/aea/container.rs +++ b/crates/stela-cli/src/restore/aea/container.rs @@ -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")?; diff --git a/crates/stela-cli/src/restore/components.rs b/crates/stela-cli/src/restore/components.rs index 9d5287cf70..0486af5548 100644 --- a/crates/stela-cli/src/restore/components.rs +++ b/crates/stela-cli/src/restore/components.rs @@ -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`. diff --git a/crates/stela-cli/src/restore/manifest.rs b/crates/stela-cli/src/restore/manifest.rs index a4ef0702c8..d54b257011 100644 --- a/crates/stela-cli/src/restore/manifest.rs +++ b/crates/stela-cli/src/restore/manifest.rs @@ -152,7 +152,7 @@ pub fn inspect(bytes: &[u8], model: Option<&str>) -> Result { .collect::>()?; 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, diff --git a/crates/stela-cli/src/restore/payload.rs b/crates/stela-cli/src/restore/payload.rs index 5937ed2e2e..d247544346 100644 --- a/crates/stela-cli/src/restore/payload.rs +++ b/crates/stela-cli/src/restore/payload.rs @@ -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( .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, 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 { 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; diff --git a/crates/stela-cli/src/setup.rs b/crates/stela-cli/src/setup.rs index c1cf982f0e..0b985c226b 100644 --- a/crates/stela-cli/src/setup.rs +++ b/crates/stela-cli/src/setup.rs @@ -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 ", - 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, diff --git a/crates/stela-cli/src/setup/bundle.rs b/crates/stela-cli/src/setup/bundle.rs index c893fea362..974347e576 100644 --- a/crates/stela-cli/src/setup/bundle.rs +++ b/crates/stela-cli/src/setup/bundle.rs @@ -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)] diff --git a/crates/stela-cli/src/setup/create.rs b/crates/stela-cli/src/setup/create.rs index 8106376322..90a975eed6 100644 --- a/crates/stela-cli/src/setup/create.rs +++ b/crates/stela-cli/src/setup/create.rs @@ -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 diff --git a/crates/stela-cli/src/setup/doctor.rs b/crates/stela-cli/src/setup/doctor.rs index 9c5e9ffc87..be8bec08c2 100644 --- a/crates/stela-cli/src/setup/doctor.rs +++ b/crates/stela-cli/src/setup/doctor.rs @@ -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. diff --git a/crates/stela-cli/src/setup/format.rs b/crates/stela-cli/src/setup/format.rs index 99909a307a..fab44256e1 100644 --- a/crates/stela-cli/src/setup/format.rs +++ b/crates/stela-cli/src/setup/format.rs @@ -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 { diff --git a/crates/stela-cli/src/setup/installed.rs b/crates/stela-cli/src/setup/installed.rs index affb03b1c8..6e64b6256a 100644 --- a/crates/stela-cli/src/setup/installed.rs +++ b/crates/stela-cli/src/setup/installed.rs @@ -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"; diff --git a/crates/stela-cli/src/setup/medium.rs b/crates/stela-cli/src/setup/medium.rs index 29d1932283..4dbca4b6c8 100644 --- a/crates/stela-cli/src/setup/medium.rs +++ b/crates/stela-cli/src/setup/medium.rs @@ -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); - 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 { diff --git a/crates/stela-cli/src/setup/medium/download.rs b/crates/stela-cli/src/setup/medium/download.rs index b9395a6405..2a1c3313be 100644 --- a/crates/stela-cli/src/setup/medium/download.rs +++ b/crates/stela-cli/src/setup/medium/download.rs @@ -57,7 +57,7 @@ fn write_from( ) -> Result { 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(); diff --git a/crates/stela-cli/src/setup/prepare.rs b/crates/stela-cli/src/setup/prepare.rs index bf13616e5b..74ea08413c 100644 --- a/crates/stela-cli/src/setup/prepare.rs +++ b/crates/stela-cli/src/setup/prepare.rs @@ -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 { diff --git a/crates/stela-cli/src/setup/tests.rs b/crates/stela-cli/src/setup/tests.rs index 77c9b80a13..8ca657b6c1 100644 --- a/crates/stela-cli/src/setup/tests.rs +++ b/crates/stela-cli/src/setup/tests.rs @@ -317,7 +317,7 @@ fn fake_inventory(ipsw: &Path, model: &str) -> Result Result { - 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!( diff --git a/crates/stela-cli/src/setup/wizard.rs b/crates/stela-cli/src/setup/wizard.rs index a917b07f11..6b7221e57d 100644 --- a/crates/stela-cli/src/setup/wizard.rs +++ b/crates/stela-cli/src/setup/wizard.rs @@ -242,7 +242,7 @@ fn configure_inner(command: &mut Request, host: &dyn Host) -> Result { 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; diff --git a/crates/stela-cli/src/setup/wizard/choices.rs b/crates/stela-cli/src/setup/wizard/choices.rs index 1e8ce78126..dd2eea0a3b 100644 --- a/crates/stela-cli/src/setup/wizard/choices.rs +++ b/crates/stela-cli/src/setup/wizard/choices.rs @@ -15,9 +15,9 @@ fn majors(images: &[Image]) -> Vec<(String, Vec)> { 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"), diff --git a/crates/stela-contracts/Cargo.toml b/crates/stela-contracts/Cargo.toml new file mode 100644 index 0000000000..d5b4aad670 --- /dev/null +++ b/crates/stela-contracts/Cargo.toml @@ -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 diff --git a/crates/stela-runtime/src/machine/adt.rs b/crates/stela-contracts/src/adt.rs similarity index 99% rename from crates/stela-runtime/src/machine/adt.rs rename to crates/stela-contracts/src/adt.rs index 816a0dd5bb..655e549337 100644 --- a/crates/stela-runtime/src/machine/adt.rs +++ b/crates/stela-contracts/src/adt.rs @@ -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]) -> Vec { +#[cfg(any(test, feature = "test-support"))] +pub fn encode(properties: &[(&str, &[u8])], children: &[Vec]) -> Vec { let mut out = Vec::new(); out.extend((properties.len() as u32).to_le_bytes()); out.extend((children.len() as u32).to_le_bytes()); diff --git a/crates/stela-runtime/src/platform/apple/bus.rs b/crates/stela-contracts/src/bus.rs similarity index 99% rename from crates/stela-runtime/src/platform/apple/bus.rs rename to crates/stela-contracts/src/bus.rs index 9a5b1f089a..b34b82aa58 100644 --- a/crates/stela-runtime/src/platform/apple/bus.rs +++ b/crates/stela-contracts/src/bus.rs @@ -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]); diff --git a/crates/stela-runtime/src/platform/apple/bus/advance_tests.rs b/crates/stela-contracts/src/bus/advance_tests.rs similarity index 99% rename from crates/stela-runtime/src/platform/apple/bus/advance_tests.rs rename to crates/stela-contracts/src/bus/advance_tests.rs index d518b96564..ae81f70dfd 100644 --- a/crates/stela-runtime/src/platform/apple/bus/advance_tests.rs +++ b/crates/stela-contracts/src/bus/advance_tests.rs @@ -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; diff --git a/crates/stela-runtime/src/platform/apple/bus/container.rs b/crates/stela-contracts/src/bus/container.rs similarity index 96% rename from crates/stela-runtime/src/platform/apple/bus/container.rs rename to crates/stela-contracts/src/bus/container.rs index 4da2c2f397..3f9a03f551 100644 --- a/crates/stela-runtime/src/platform/apple/bus/container.rs +++ b/crates/stela-contracts/src/bus/container.rs @@ -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; diff --git a/crates/stela-runtime/src/machine/caches.rs b/crates/stela-contracts/src/caches.rs similarity index 99% rename from crates/stela-runtime/src/machine/caches.rs rename to crates/stela-contracts/src/caches.rs index bec85942d5..62048c5fbc 100644 --- a/crates/stela-runtime/src/machine/caches.rs +++ b/crates/stela-contracts/src/caches.rs @@ -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; diff --git a/crates/stela-runtime/src/machine/chip.rs b/crates/stela-contracts/src/chip.rs similarity index 83% rename from crates/stela-runtime/src/machine/chip.rs rename to crates/stela-contracts/src/chip.rs index e67103943c..5a5d0c9cc4 100644 --- a/crates/stela-runtime/src/machine/chip.rs +++ b/crates/stela-contracts/src/chip.rs @@ -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::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 { - 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] diff --git a/crates/stela-runtime/src/machine/chip/check_index.rs b/crates/stela-contracts/src/chip/check_index.rs similarity index 99% rename from crates/stela-runtime/src/machine/chip/check_index.rs rename to crates/stela-contracts/src/chip/check_index.rs index 969871ee4d..2492a50499 100644 --- a/crates/stela-runtime/src/machine/chip/check_index.rs +++ b/crates/stela-contracts/src/chip/check_index.rs @@ -101,7 +101,7 @@ pub(super) fn groups(word: u32) -> impl Iterator { #[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() { diff --git a/crates/stela-runtime/src/machine/chip/checks.rs b/crates/stela-contracts/src/chip/checks.rs similarity index 100% rename from crates/stela-runtime/src/machine/chip/checks.rs rename to crates/stela-contracts/src/chip/checks.rs diff --git a/crates/stela-runtime/src/machine/chip/forms.rs b/crates/stela-contracts/src/chip/forms.rs similarity index 100% rename from crates/stela-runtime/src/machine/chip/forms.rs rename to crates/stela-contracts/src/chip/forms.rs diff --git a/crates/stela-contracts/src/cpu_features.rs b/crates/stela-contracts/src/cpu_features.rs new file mode 100644 index 0000000000..3fd1b9d894 --- /dev/null +++ b/crates/stela-contracts/src/cpu_features.rs @@ -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], + } + } +} diff --git a/crates/stela-runtime/src/platform/dma.rs b/crates/stela-contracts/src/dma.rs similarity index 98% rename from crates/stela-runtime/src/platform/dma.rs rename to crates/stela-contracts/src/dma.rs index f873af0e4a..69e1aeec3d 100644 --- a/crates/stela-runtime/src/platform/dma.rs +++ b/crates/stela-contracts/src/dma.rs @@ -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, } @@ -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 diff --git a/crates/stela-contracts/src/identity.rs b/crates/stela-contracts/src/identity.rs new file mode 100644 index 0000000000..f30c492f93 --- /dev/null +++ b/crates/stela-contracts/src/identity.rs @@ -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, + /// 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, +} diff --git a/crates/stela-runtime/src/platform/apple/interrupt.rs b/crates/stela-contracts/src/interrupt.rs similarity index 99% rename from crates/stela-runtime/src/platform/apple/interrupt.rs rename to crates/stela-contracts/src/interrupt.rs index c39a974b7a..e1bf27535e 100644 --- a/crates/stela-runtime/src/platform/apple/interrupt.rs +++ b/crates/stela-contracts/src/interrupt.rs @@ -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) } diff --git a/crates/stela-contracts/src/lib.rs b/crates/stela-contracts/src/lib.rs new file mode 100644 index 0000000000..0322ee8772 --- /dev/null +++ b/crates/stela-contracts/src/lib.rs @@ -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; diff --git a/crates/stela-contracts/src/pauth.rs b/crates/stela-contracts/src/pauth.rs new file mode 100644 index 0000000000..58fa6bdbec --- /dev/null +++ b/crates/stela-contracts/src/pauth.rs @@ -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; +} diff --git a/crates/stela-contracts/src/tag_storage.rs b/crates/stela-contracts/src/tag_storage.rs new file mode 100644 index 0000000000..92201b7585 --- /dev/null +++ b/crates/stela-contracts/src/tag_storage.rs @@ -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 { + 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); + } +} diff --git a/crates/stela-dev/Cargo.toml b/crates/stela-dev/Cargo.toml index dbc8696093..9bd1f38c3e 100644 --- a/crates/stela-dev/Cargo.toml +++ b/crates/stela-dev/Cargo.toml @@ -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"] } diff --git a/crates/stela-dev/src/compile.rs b/crates/stela-dev/src/compile.rs index 094e5b2766..dc612052e3 100644 --- a/crates/stela-dev/src/compile.rs +++ b/crates/stela-dev/src/compile.rs @@ -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(), diff --git a/crates/stela-dev/src/dyld_entry.rs b/crates/stela-dev/src/dyld_entry.rs index 2e1be6bc93..9f3a0f6c77 100644 --- a/crates/stela-dev/src/dyld_entry.rs +++ b/crates/stela-dev/src/dyld_entry.rs @@ -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::>>()?; let clock_report = clock.as_ref().map(|c| -> Result { 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(), diff --git a/crates/stela-dev/src/execute.rs b/crates/stela-dev/src/execute.rs index dbf8185d8f..5998daca07 100644 --- a/crates/stela-dev/src/execute.rs +++ b/crates/stela-dev/src/execute.rs @@ -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()), diff --git a/crates/stela-dev/src/images.rs b/crates/stela-dev/src/images.rs index d0f5a9e38e..12acdc26dc 100644 --- a/crates/stela-dev/src/images.rs +++ b/crates/stela-dev/src/images.rs @@ -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!( diff --git a/crates/stela-dev/src/input.rs b/crates/stela-dev/src/input.rs index 47a36fad24..17d59ff02f 100644 --- a/crates/stela-dev/src/input.rs +++ b/crates/stela-dev/src/input.rs @@ -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> { 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 [ diff --git a/crates/stela-dev/src/loader.rs b/crates/stela-dev/src/loader.rs index e24e4c027f..6a416856ba 100644 --- a/crates/stela-dev/src/loader.rs +++ b/crates/stela-dev/src/loader.rs @@ -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 }))? ); diff --git a/crates/stela-dev/tests/boot.rs b/crates/stela-dev/tests/boot.rs index 514af41b68..83953f1cdf 100644 --- a/crates/stela-dev/tests/boot.rs +++ b/crates/stela-dev/tests/boot.rs @@ -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() ); } diff --git a/crates/stela-dev/tests/workflow.rs b/crates/stela-dev/tests/workflow.rs index 598b2d820d..574bb9486e 100644 --- a/crates/stela-dev/tests/workflow.rs +++ b/crates/stela-dev/tests/workflow.rs @@ -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); diff --git a/crates/stela-formats/Cargo.toml b/crates/stela-formats/Cargo.toml new file mode 100644 index 0000000000..05bf303e05 --- /dev/null +++ b/crates/stela-formats/Cargo.toml @@ -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" diff --git a/crates/stela-runtime/src/apfs.rs b/crates/stela-formats/src/apfs.rs similarity index 100% rename from crates/stela-runtime/src/apfs.rs rename to crates/stela-formats/src/apfs.rs diff --git a/crates/stela-runtime/src/apfs/btree.rs b/crates/stela-formats/src/apfs/btree.rs similarity index 100% rename from crates/stela-runtime/src/apfs/btree.rs rename to crates/stela-formats/src/apfs/btree.rs diff --git a/crates/stela-runtime/src/apfs/container.rs b/crates/stela-formats/src/apfs/container.rs similarity index 100% rename from crates/stela-runtime/src/apfs/container.rs rename to crates/stela-formats/src/apfs/container.rs diff --git a/crates/stela-runtime/src/apfs/decmpfs.rs b/crates/stela-formats/src/apfs/decmpfs.rs similarity index 100% rename from crates/stela-runtime/src/apfs/decmpfs.rs rename to crates/stela-formats/src/apfs/decmpfs.rs diff --git a/crates/stela-runtime/src/apfs/object.rs b/crates/stela-formats/src/apfs/object.rs similarity index 100% rename from crates/stela-runtime/src/apfs/object.rs rename to crates/stela-formats/src/apfs/object.rs diff --git a/crates/stela-runtime/src/apfs/volume.rs b/crates/stela-formats/src/apfs/volume.rs similarity index 100% rename from crates/stela-runtime/src/apfs/volume.rs rename to crates/stela-formats/src/apfs/volume.rs diff --git a/crates/stela-runtime/src/boot_bundle.rs b/crates/stela-formats/src/boot_bundle.rs similarity index 99% rename from crates/stela-runtime/src/boot_bundle.rs rename to crates/stela-formats/src/boot_bundle.rs index d1b576c24e..99fe18ad1c 100644 --- a/crates/stela-runtime/src/boot_bundle.rs +++ b/crates/stela-formats/src/boot_bundle.rs @@ -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, 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")); } } diff --git a/crates/stela-runtime/src/boot_bundle/schema.rs b/crates/stela-formats/src/boot_bundle/schema.rs similarity index 100% rename from crates/stela-runtime/src/boot_bundle/schema.rs rename to crates/stela-formats/src/boot_bundle/schema.rs diff --git a/crates/stela-runtime/src/builds.rs b/crates/stela-formats/src/builds.rs similarity index 100% rename from crates/stela-runtime/src/builds.rs rename to crates/stela-formats/src/builds.rs diff --git a/crates/stela-runtime/src/code_signature.rs b/crates/stela-formats/src/code_signature.rs similarity index 70% rename from crates/stela-runtime/src/code_signature.rs rename to crates/stela-formats/src/code_signature.rs index ea0e4140fe..eb065cd86d 100644 --- a/crates/stela-runtime/src/code_signature.rs +++ b/crates/stela-formats/src/code_signature.rs @@ -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 = core::result::Result; + +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 { + Ok(extent(bytes, at, 1)?[0]) +} + fn be32(bytes: &[u8], at: usize) -> Result { - 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 { - 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 { @@ -147,7 +228,10 @@ impl CodeSignature { } mod hex_bytes { - pub fn serialize(bytes: &[u8], serializer: S) -> Result { + pub fn serialize( + bytes: &[u8], + serializer: S, + ) -> core::result::Result { serializer.serialize_str(&hex::encode(bytes)) } } @@ -228,14 +312,25 @@ fn ber_children(mut contents: &[u8]) -> impl Iterator /// The signature of a thin 64-bit Mach-O slice, or `None` without one. pub fn read(slice: &[u8]) -> Result> { - 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> { 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 { - 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 { 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 { 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 { } 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 { }; 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); diff --git a/crates/stela-runtime/src/code_signature/cms.rs b/crates/stela-formats/src/code_signature/cms.rs similarity index 84% rename from crates/stela-runtime/src/code_signature/cms.rs rename to crates/stela-formats/src/code_signature/cms.rs index 860b1f7273..d4913c40af 100644 --- a/crates/stela-runtime/src/code_signature/cms.rs +++ b/crates/stela-formats/src/code_signature/cms.rs @@ -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 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, 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, &'static str> { +fn digest(oid: &[u8], message: &[u8]) -> Result, 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 { +fn rsa_hash(signature: &[u8], digest: Option<&[u8]>) -> Result { 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, &'static str> { +fn certificate(whole: &[u8]) -> Result, 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, &'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, &'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, &'static str> { +fn signed_data(cms: &[u8]) -> Result, 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, &'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::, _>>()?; 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)?; diff --git a/crates/stela-formats/src/der.rs b/crates/stela-formats/src/der.rs new file mode 100644 index 0000000000..33192abfef --- /dev/null +++ b/crates/stela-formats/src/der.rs @@ -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, 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, 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, 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()); + } +} diff --git a/crates/stela-runtime/src/hash.rs b/crates/stela-formats/src/hash.rs similarity index 100% rename from crates/stela-runtime/src/hash.rs rename to crates/stela-formats/src/hash.rs diff --git a/crates/stela-runtime/src/img4.rs b/crates/stela-formats/src/img4.rs similarity index 93% rename from crates/stela-runtime/src/img4.rs rename to crates/stela-formats/src/img4.rs index 73f7465cec..16bb757244 100644 --- a/crates/stela-runtime/src/img4.rs +++ b/crates/stela-formats/src/img4.rs @@ -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, 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 { - 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 { - 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 { - 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() { diff --git a/crates/stela-formats/src/img4/test_support.rs b/crates/stela-formats/src/img4/test_support.rs new file mode 100644 index 0000000000..6b9090efd1 --- /dev/null +++ b/crates/stela-formats/src/img4/test_support.rs @@ -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 { + 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 { + 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 { + der( + SEQUENCE, + &[ + der(IA5_STRING, b"IMG4"), + payload.to_vec(), + der(CONTEXT_0, manifest), + ] + .concat(), + ) +} diff --git a/crates/stela-formats/src/lib.rs b/crates/stela-formats/src/lib.rs new file mode 100644 index 0000000000..bb8382b29b --- /dev/null +++ b/crates/stela-formats/src/lib.rs @@ -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; diff --git a/crates/stela-runtime/src/lzfse.rs b/crates/stela-formats/src/lzfse.rs similarity index 100% rename from crates/stela-runtime/src/lzfse.rs rename to crates/stela-formats/src/lzfse.rs diff --git a/crates/stela-runtime/src/payload.rs b/crates/stela-formats/src/payload.rs similarity index 90% rename from crates/stela-runtime/src/payload.rs rename to crates/stela-formats/src/payload.rs index 18a14667ab..6569c61df1 100644 --- a/crates/stela-runtime/src/payload.rs +++ b/crates/stela-formats/src/payload.rs @@ -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); - - 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)>) { - let contents: Vec<(String, Vec)> = [ - ("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() { diff --git a/crates/stela-runtime/src/payload/gpt.rs b/crates/stela-formats/src/payload/gpt.rs similarity index 100% rename from crates/stela-runtime/src/payload/gpt.rs rename to crates/stela-formats/src/payload/gpt.rs diff --git a/crates/stela-runtime/src/payload/pieces.rs b/crates/stela-formats/src/payload/pieces.rs similarity index 98% rename from crates/stela-runtime/src/payload/pieces.rs rename to crates/stela-formats/src/payload/pieces.rs index ff7dc61da3..43b3fa2167 100644 --- a/crates/stela-runtime/src/payload/pieces.rs +++ b/crates/stela-formats/src/payload/pieces.rs @@ -218,7 +218,9 @@ impl ReadAt for Joined { #[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) { - 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(); diff --git a/crates/stela-runtime/src/payload/staging.rs b/crates/stela-formats/src/payload/staging.rs similarity index 98% rename from crates/stela-runtime/src/payload/staging.rs rename to crates/stela-formats/src/payload/staging.rs index 45426c3734..5406ab213a 100644 --- a/crates/stela-runtime/src/payload/staging.rs +++ b/crates/stela-formats/src/payload/staging.rs @@ -184,7 +184,9 @@ impl super::PayloadSource for StagedSource { #[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() { diff --git a/crates/stela-formats/src/payload/test_support.rs b/crates/stela-formats/src/payload/test_support.rs new file mode 100644 index 0000000000..2d25359a8e --- /dev/null +++ b/crates/stela-formats/src/payload/test_support.rs @@ -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); + +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)>) { + let contents: Vec<(String, Vec)> = [ + ("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) +} diff --git a/crates/stela-runtime/src/payload/zip.rs b/crates/stela-formats/src/payload/zip.rs similarity index 85% rename from crates/stela-runtime/src/payload/zip.rs rename to crates/stela-formats/src/payload/zip.rs index 5f72c06663..e52e840efa 100644 --- a/crates/stela-runtime/src/payload/zip.rs +++ b/crates/stela-formats/src/payload/zip.rs @@ -472,95 +472,15 @@ impl 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 { - 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 = 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(¢ral); - 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, PayloadError> { let mut out = Vec::new(); diff --git a/crates/stela-formats/src/payload/zip/test_support.rs b/crates/stela-formats/src/payload/zip/test_support.rs new file mode 100644 index 0000000000..800f82d601 --- /dev/null +++ b/crates/stela-formats/src/payload/zip/test_support.rs @@ -0,0 +1,87 @@ +//! Synthetic ZIP archives used by downstream streaming tests. +use super::*; + +/// Build an archive; `zip64` forces the ZIP64 end records and extra fields. +pub fn archive(members: &[(&str, &[u8], bool)], zip64: bool) -> Vec { + 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 = 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(¢ral); + 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 +} diff --git a/crates/stela-runtime/src/preboot.rs b/crates/stela-formats/src/preboot.rs similarity index 100% rename from crates/stela-runtime/src/preboot.rs rename to crates/stela-formats/src/preboot.rs diff --git a/crates/stela-runtime/src/platform/apple/sep/image/rsa.rs b/crates/stela-formats/src/rsa.rs similarity index 66% rename from crates/stela-runtime/src/platform/apple/sep/image/rsa.rs rename to crates/stela-formats/src/rsa.rs index 95e0208f57..1f2f52b0ec 100644 --- a/crates/stela-runtime/src/platform/apple/sep/image/rsa.rs +++ b/crates/stela-formats/src/rsa.rs @@ -1,40 +1,87 @@ //! Public RSA PKCS#1 v1.5 verification (RFC 8017 §§5.2.2, 8.2, 9.2). //! Bounded to 2048..4096-bit, whole-octet moduli and exponent 65537. //! No private keys, signing, padding recovery or permissive ASN.1 decoding. -use super::der::{sequence, unsigned}; +use crate::der::{self, sequence, unsigned}; use crypto_bigint::{ Encoding, U4096, modular::runtime_mod::{DynResidue, DynResidueParams}, }; use sha2::{Digest, Sha256, Sha384}; +/// RSA public-key or PKCS#1 v1.5 verification failure. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + Der(der::Error), + Modulus { bytes: usize, first: u8, last: u8 }, + Exponent { bytes: usize, prefix: [u8; 8] }, + SignatureLength { bytes: usize, expected: usize }, + RepresentativeRange, + SignatureMismatch, +} + +impl From for Error { + fn from(error: der::Error) -> Self { + Self::Der(error) + } +} + +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Der(error) => write!(f, "RSA key: {error}"), + Self::Modulus { bytes, first, last } => write!( + f, + "RSA modulus is unsupported: {bytes} bytes, edge bytes {first:#x}/{last:#x}" + ), + Self::Exponent { bytes, prefix } => write!( + f, + "RSA exponent is unsupported: {bytes} bytes, prefix {prefix:x?}" + ), + Self::SignatureLength { bytes, expected } => { + write!(f, "RSA signature has {bytes} bytes, expected {expected}") + } + Self::RepresentativeRange => { + f.write_str("RSA signature representative is out of range") + } + Self::SignatureMismatch => f.write_str("RSA PKCS1 signature verification failed"), + } + } +} + +impl core::error::Error for Error { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Der(error) => Some(error), + _ => None, + } + } +} + const MAX_BYTES: usize = 512; const MIN_BYTES: usize = 256; const PUBLIC_EXPONENT: &[u8] = &[1, 0, 1]; -#[cfg(feature = "std")] const SHA1_INFO: &[u8] = b"\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\0\x04\x14"; const SHA256_INFO: &[u8] = b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\0\x04\x20"; const SHA384_INFO: &[u8] = b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\0\x04\x30"; -#[derive(Clone, Copy)] -pub(crate) enum Hash { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Hash { /// For certificate chains that still sign with it (code signing's). - #[cfg(feature = "std")] Sha1, Sha256, Sha384, } -pub(crate) struct Key { +pub struct Key { modulus: U4096, bytes: usize, } impl Key { /// The DER RSAPublicKey inside SubjectPublicKeyInfo's BIT STRING. - pub fn parse(der: &[u8]) -> Result { + pub fn parse(der: &[u8]) -> Result { let mut fields = sequence(der)?; let n = fields.take(2)?; let modulus = unsigned(n.value)?; @@ -42,11 +89,22 @@ impl Key { || modulus[0] & 128 == 0 || modulus[modulus.len() - 1] & 1 == 0 { - return Err("SEP RSA modulus size or parity is unsupported"); + return Err(Error::Modulus { + bytes: modulus.len(), + first: modulus[0], + last: modulus[modulus.len() - 1], + }); } let exponent = fields.take(2)?; - if unsigned(exponent.value)? != PUBLIC_EXPONENT { - return Err("SEP RSA exponent is unsupported"); + let exponent = unsigned(exponent.value)?; + if exponent != PUBLIC_EXPONENT { + let mut prefix = [0; 8]; + let copied = exponent.len().min(prefix.len()); + prefix[..copied].copy_from_slice(&exponent[..copied]); + return Err(Error::Exponent { + bytes: exponent.len(), + prefix, + }); } fields.end()?; let mut padded = [0; MAX_BYTES]; @@ -57,15 +115,18 @@ impl Key { }) } - pub fn verify(&self, message: &[u8], signature: &[u8], hash: Hash) -> Result<(), &'static str> { + pub fn verify(&self, message: &[u8], signature: &[u8], hash: Hash) -> Result<(), Error> { if signature.len() != self.bytes { - return Err("SEP RSA signature has the wrong length"); + return Err(Error::SignatureLength { + bytes: signature.len(), + expected: self.bytes, + }); } let mut padded = [0; MAX_BYTES]; padded[MAX_BYTES - self.bytes..].copy_from_slice(signature); let s = U4096::from_be_bytes(padded); if s >= self.modulus { - return Err("SEP RSA signature representative is out of range"); + return Err(Error::RepresentativeRange); } let params = DynResidueParams::new(&self.modulus); let recovered = DynResidue::new(&s, params) @@ -74,7 +135,6 @@ impl Key { .to_be_bytes(); let mut expected = [0xff; MAX_BYTES]; let (prefix, digest) = match hash { - #[cfg(feature = "std")] Hash::Sha1 => (SHA1_INFO, sha1::Sha1::digest(message).to_vec()), Hash::Sha256 => (SHA256_INFO, Sha256::digest(message).to_vec()), Hash::Sha384 => (SHA384_INFO, Sha384::digest(message).to_vec()), @@ -88,7 +148,7 @@ impl Key { expected[separator + 1..separator + 1 + prefix.len()].copy_from_slice(prefix); expected[MAX_BYTES - digest.len()..].copy_from_slice(&digest); if recovered != expected { - return Err("SEP RSA PKCS1 signature verification failed"); + return Err(Error::SignatureMismatch); } Ok(()) } diff --git a/crates/stela-runtime/tests/fixtures/apfs/make-preboot-tree.py b/crates/stela-formats/tests/fixtures/apfs/make-preboot-tree.py similarity index 100% rename from crates/stela-runtime/tests/fixtures/apfs/make-preboot-tree.py rename to crates/stela-formats/tests/fixtures/apfs/make-preboot-tree.py diff --git a/crates/stela-runtime/tests/fixtures/apfs/make-preboot.sh b/crates/stela-formats/tests/fixtures/apfs/make-preboot.sh similarity index 100% rename from crates/stela-runtime/tests/fixtures/apfs/make-preboot.sh rename to crates/stela-formats/tests/fixtures/apfs/make-preboot.sh diff --git a/crates/stela-runtime/tests/fixtures/apfs/make-sealed.sh b/crates/stela-formats/tests/fixtures/apfs/make-sealed.sh similarity index 100% rename from crates/stela-runtime/tests/fixtures/apfs/make-sealed.sh rename to crates/stela-formats/tests/fixtures/apfs/make-sealed.sh diff --git a/crates/stela-runtime/tests/fixtures/apfs/preboot.img.gz b/crates/stela-formats/tests/fixtures/apfs/preboot.img.gz similarity index 100% rename from crates/stela-runtime/tests/fixtures/apfs/preboot.img.gz rename to crates/stela-formats/tests/fixtures/apfs/preboot.img.gz diff --git a/crates/stela-runtime/tests/fixtures/apfs/sealed.img.gz b/crates/stela-formats/tests/fixtures/apfs/sealed.img.gz similarity index 100% rename from crates/stela-runtime/tests/fixtures/apfs/sealed.img.gz rename to crates/stela-formats/tests/fixtures/apfs/sealed.img.gz diff --git a/crates/stela-runtime/tests/fixtures/apfs/sealed.root_hash b/crates/stela-formats/tests/fixtures/apfs/sealed.root_hash similarity index 100% rename from crates/stela-runtime/tests/fixtures/apfs/sealed.root_hash rename to crates/stela-formats/tests/fixtures/apfs/sealed.root_hash diff --git a/crates/stela-runtime/tests/fixtures/lzfse/make-samples.py b/crates/stela-formats/tests/fixtures/lzfse/make-samples.py similarity index 100% rename from crates/stela-runtime/tests/fixtures/lzfse/make-samples.py rename to crates/stela-formats/tests/fixtures/lzfse/make-samples.py diff --git a/crates/stela-runtime/tests/fixtures/lzfse/make-samples.sh b/crates/stela-formats/tests/fixtures/lzfse/make-samples.sh similarity index 100% rename from crates/stela-runtime/tests/fixtures/lzfse/make-samples.sh rename to crates/stela-formats/tests/fixtures/lzfse/make-samples.sh diff --git a/crates/stela-runtime/tests/fixtures/lzfse/sample-3000.lzfse b/crates/stela-formats/tests/fixtures/lzfse/sample-3000.lzfse similarity index 100% rename from crates/stela-runtime/tests/fixtures/lzfse/sample-3000.lzfse rename to crates/stela-formats/tests/fixtures/lzfse/sample-3000.lzfse diff --git a/crates/stela-runtime/tests/fixtures/lzfse/sample-300000.lzfse b/crates/stela-formats/tests/fixtures/lzfse/sample-300000.lzfse similarity index 100% rename from crates/stela-runtime/tests/fixtures/lzfse/sample-300000.lzfse rename to crates/stela-formats/tests/fixtures/lzfse/sample-300000.lzfse diff --git a/crates/stela-loader/Cargo.toml b/crates/stela-loader/Cargo.toml index d459648be6..82561e03ea 100644 --- a/crates/stela-loader/Cargo.toml +++ b/crates/stela-loader/Cargo.toml @@ -9,7 +9,7 @@ default = ["std"] # Without `std` only the kernel boot-bundle builder (`boot_bundle` and the # formats it reads) is built, for `stela.efi`. std = [ - "anyhow/std", + "anyhow/std", "stela-contracts/std", "stela-formats/std", "hex/std", "object/std", "serde/std", @@ -19,6 +19,8 @@ std = [ ] [dependencies] +stela-contracts = { path = "../stela-contracts", default-features = false } +stela-formats = { path = "../stela-formats", default-features = false } stela-drivers.workspace = true anyhow = { version = "1", default-features = false } hex = { version = "0.4", default-features = false, features = ["alloc"] } diff --git a/crates/stela-loader/src/apple_device_tree.rs b/crates/stela-loader/src/apple_device_tree.rs index 1d382dbbb3..86958c24d7 100644 --- a/crates/stela-loader/src/apple_device_tree.rs +++ b/crates/stela-loader/src/apple_device_tree.rs @@ -18,7 +18,7 @@ pub mod assigned; use alloc::{borrow::ToOwned, format, string::String, vec, vec::Vec}; use anyhow::{Context, Result, bail, ensure}; use serde::Serialize; -pub use stela_runtime::boot_bundle::schema::Placeholder; +pub use stela_formats::boot_bundle::schema::Placeholder; /// `kPropNameLength`: the NUL-padded property name field. pub const PROPERTY_NAME_BYTES: usize = 32; diff --git a/crates/stela-loader/src/apple_device_tree/assigned.rs b/crates/stela-loader/src/apple_device_tree/assigned.rs index 5e61e374a9..b324bd9aef 100644 --- a/crates/stela-loader/src/apple_device_tree/assigned.rs +++ b/crates/stela-loader/src/apple_device_tree/assigned.rs @@ -577,14 +577,26 @@ mod tests { use super::*; use alloc::vec; use core::cell::Cell; - use stela_runtime::machine::{ - Chip, - caches::Cache, - soc::assigned::{ - AssignedCore, Assignment, Capacity, CapacityKind, ClusterId, ClusterSlot, CoreKind, - InterruptTarget, KindId, PeSlot, PowerResource, RegisterRange, ResourceProfile, - Resources, RetainedResources, RetainedRoster, SharedCache, StartResource, - }, + use { + stela_contracts::Chip, stela_contracts::caches::Cache, + stela_runtime::machine::soc::assigned::AssignedCore, + stela_runtime::machine::soc::assigned::Assignment, + 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::InterruptTarget, + stela_runtime::machine::soc::assigned::KindId, + stela_runtime::machine::soc::assigned::PeSlot, + stela_runtime::machine::soc::assigned::PowerResource, + stela_runtime::machine::soc::assigned::RegisterRange, + stela_runtime::machine::soc::assigned::ResourceProfile, + stela_runtime::machine::soc::assigned::Resources, + stela_runtime::machine::soc::assigned::RetainedResources, + stela_runtime::machine::soc::assigned::RetainedRoster, + stela_runtime::machine::soc::assigned::SharedCache, + stela_runtime::machine::soc::assigned::StartResource, }; struct Roster { cores: Vec, @@ -1442,7 +1454,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(); @@ -1562,7 +1574,7 @@ mod tests { let original_table = bytes(immutable.node("/arm-io/wdt").unwrap(), "trigger-config").unwrap(); assert_eq!( - stela_runtime::sha256(original_table), + stela_formats::sha256(original_table), "e9e9875ee26054ce3129dcb658d3d39b819819ef5bc568ad885d15bca048980c" ); assert_eq!( diff --git a/crates/stela-loader/src/boot_args.rs b/crates/stela-loader/src/boot_args.rs index f264fa3c7b..1d85000214 100644 --- a/crates/stela-loader/src/boot_args.rs +++ b/crates/stela-loader/src/boot_args.rs @@ -8,7 +8,7 @@ //! 1024-byte command line, so that is the revision emitted here. use alloc::string::String; use anyhow::{Result, ensure}; -pub use stela_runtime::boot_bundle::schema::{BootArgs, Video}; +pub use {stela_formats::boot_bundle::schema::BootArgs, stela_formats::boot_bundle::schema::Video}; pub const BOOT_LINE_LENGTH: usize = 1024; pub const REVISION: u16 = 3; diff --git a/crates/stela-loader/src/boot_bundle.rs b/crates/stela-loader/src/boot_bundle.rs index 528da94365..7a48d45bdc 100644 --- a/crates/stela-loader/src/boot_bundle.rs +++ b/crates/stela-loader/src/boot_bundle.rs @@ -29,12 +29,21 @@ use crate::root_selection; use crate::soc_variant; use crate::trust_cache; use anyhow::{Context, Result, bail, ensure}; -use stela_runtime::machine::{ctrr, identification, soc, tag_storage}; -use stela_runtime::sha256; +use stela_contracts::tag_storage; +use stela_formats::sha256; +use stela_runtime::machine::{ctrr, identification, soc}; -pub use stela_runtime::boot_bundle::schema::{ - BootCpu, BootCpuSelection, Encoding, Entry, File, Image, Manifest, Options, OverlayProperty, - Patch, PatchSource, PlaceholderDecision, Region, SCHEMA_VERSION, Source, Target, +pub use { + stela_formats::boot_bundle::schema::BootCpu, + stela_formats::boot_bundle::schema::BootCpuSelection, + stela_formats::boot_bundle::schema::Encoding, stela_formats::boot_bundle::schema::Entry, + stela_formats::boot_bundle::schema::File, stela_formats::boot_bundle::schema::Image, + stela_formats::boot_bundle::schema::Manifest, stela_formats::boot_bundle::schema::Options, + stela_formats::boot_bundle::schema::OverlayProperty, stela_formats::boot_bundle::schema::Patch, + stela_formats::boot_bundle::schema::PatchSource, + stela_formats::boot_bundle::schema::PlaceholderDecision, + stela_formats::boot_bundle::schema::Region, stela_formats::boot_bundle::schema::SCHEMA_VERSION, + stela_formats::boot_bundle::schema::Source, stela_formats::boot_bundle::schema::Target, }; /// The revision of the content [`prepare`] writes within its schema; a @@ -413,7 +422,7 @@ fn page_round(bytes: u64) -> u64 { /// the restore host delivers to `seputil` and the largest form `seputil` /// can pass to `AppleSEPManager::setFirmwareBytes`. fn sep_firmware_region_bytes(image: &[u8]) -> u64 { - stela_runtime::img4::container_bytes(image.len()) as u64 + stela_formats::img4::container_bytes(image.len()) as u64 } fn range_value(base: u64, length: u64) -> Vec { @@ -567,7 +576,7 @@ pub fn prepare_owned(inputs: &Inputs, ramdisk: OwnedRamdisk, options: &Options) } fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> Result { - stela_runtime::builds::find(&inputs.target.product_build)?; + stela_formats::builds::find(&inputs.target.product_build)?; let ramdisk_bytes = owned .as_ref() .map(|ramdisk| ramdisk.bytes.len()) @@ -1436,7 +1445,7 @@ fn sources(inputs: &Inputs, ramdisk_source: Option) -> Vec { /// (`stela_runtime::machine::tag_storage`), which must lie above every /// placed region. fn tag_offset( - chip: Option, + chip: Option, options: &Options, dram_end: u64, top_of_kernel_data: u64, @@ -2787,13 +2796,13 @@ mod tests { .unwrap(); for error in [borrowed, owned] { let error = error - .downcast_ref::() + .downcast_ref::() .unwrap(); assert_eq!(error.build, "unsupported-build"); assert!( error .supported - .contains(&stela_runtime::builds::DEFAULT.build) + .contains(&stela_formats::builds::DEFAULT.build) ); } } @@ -3186,7 +3195,7 @@ mod tests { // reproduces the layout. assert_eq!(manifest.revision, REVISION); let json = serde_json::to_vec(manifest)?; - let consumed = stela_runtime::boot_bundle::Manifest::parse(&json)?; + let consumed = stela_formats::boot_bundle::Manifest::parse(&json)?; let mut changed_source = file(ORIGINAL_DEVICE_TREE_FILE).clone(); changed_source[0] ^= 1; assert!( @@ -3203,7 +3212,7 @@ mod tests { let verified = consumed.verify(&|name| Some(file(name).as_slice()))?; let span = (manifest.top_of_kernel_data - options.dram_base) as usize; let mut ram = vec![0u8; span]; - let machine = stela_runtime::boot_bundle::Machine { + let machine = stela_formats::boot_bundle::Machine { dram_base: options.dram_base, ram_bytes: span as u64, dram_bytes: span as u64, @@ -3277,7 +3286,7 @@ mod tests { // The policy enables kernel CTRR, so CTRR-D is locked too. assert_eq!(core_locks.locked.len(), 6); let consumed = - stela_runtime::boot_bundle::Manifest::parse(&serde_json::to_vec(m4_manifest)?)?; + stela_formats::boot_bundle::Manifest::parse(&serde_json::to_vec(m4_manifest)?)?; assert_eq!(consumed.core_locks.as_ref(), Some(core_locks)); assert_eq!(core_locks.tag_offset, 0); // An M5 bundle also locks TAG_OFFSET_EL2 at the top of the managed @@ -3319,7 +3328,7 @@ mod tests { .unwrap(); assert_eq!(sepfw.bytes, 0); assert_eq!(sepfw.memory_bytes, 4 * PAGE); - assert!(sepfw.memory_bytes >= stela_runtime::img4::container(&sep).len() as u64); + assert!(sepfw.memory_bytes >= stela_formats::img4::container(&sep).len() as u64); let file = |name: &str| &staged.files.iter().find(|(n, _)| n == name).unwrap().1; assert_eq!(file(SEP_FILE), &sep); let tree = DeviceTree::parse(file(DEVICE_TREE_FILE))?; diff --git a/crates/stela-loader/src/boot_policy.rs b/crates/stela-loader/src/boot_policy.rs index 653f9b207c..f2c34265f0 100644 --- a/crates/stela-loader/src/boot_policy.rs +++ b/crates/stela-loader/src/boot_policy.rs @@ -20,8 +20,11 @@ use crate::apple_device_tree::DeviceTree; use crate::im4m::{Manifest, Value}; use alloc::{borrow::ToOwned, format, string::String, vec, vec::Vec}; use anyhow::{Context, Result, ensure}; -pub use stela_runtime::boot_bundle::schema::{ - Decision, OsEnvironment, SecurityMode, SecurityPolicy, +pub use { + stela_formats::boot_bundle::schema::Decision, + stela_formats::boot_bundle::schema::OsEnvironment, + stela_formats::boot_bundle::schema::SecurityMode, + stela_formats::boot_bundle::schema::SecurityPolicy, }; pub mod mcc; @@ -482,7 +485,7 @@ pub fn apply_root_hash( } }; let tag = volume.payload_type(); - let kind = stela_runtime::img4::payload_type(im4p) + let kind = stela_formats::img4::payload_type(im4p) .map_err(|e| anyhow::anyhow!("the {tag} root hash: {e}"))?; ensure!( kind == tag.as_bytes(), diff --git a/crates/stela-loader/src/boot_selection.rs b/crates/stela-loader/src/boot_selection.rs index 4094c33dbe..9a8f99c42b 100644 --- a/crates/stela-loader/src/boot_selection.rs +++ b/crates/stela-loader/src/boot_selection.rs @@ -720,7 +720,7 @@ mod tests { assert_eq!(parse_uuid(b"A304C51B+D22F-4CDD-829D-3E30CB5BD87B"), None); // The APFS partition type, 7C3457EF-0000-11AA-AA11-00306543ECAC, // as a GPT entry stores it. - let apfs = stela_runtime::payload::gpt::Guid::parse("7C3457EF-0000-11AA-AA11-00306543ECAC") + let apfs = stela_formats::payload::gpt::Guid::parse("7C3457EF-0000-11AA-AA11-00306543ECAC") .unwrap(); assert_eq!(VolumeType::Apfs.guid_bytes(), apfs.0); } diff --git a/crates/stela-loader/src/carveouts.rs b/crates/stela-loader/src/carveouts.rs index c6dcd3aebe..3a5f1ab018 100644 --- a/crates/stela-loader/src/carveouts.rs +++ b/crates/stela-loader/src/carveouts.rs @@ -51,7 +51,7 @@ use crate::apple_device_tree::DeviceTree; use crate::kernel_collection::PAGE_BYTES; use alloc::{format, string::String, vec::Vec}; use anyhow::{Context, Result, ensure}; -pub use stela_runtime::boot_bundle::schema::Placed; +pub use stela_formats::boot_bundle::schema::Placed; use stela_runtime::machine::soc; pub const MEMORY_MAP: &str = "/chosen/carveout-memory-map"; @@ -741,7 +741,7 @@ mod tests { let directory = std::path::PathBuf::from(std::env::var_os("STELA_TEST_IBOOT_DIR").unwrap()); for (chip_id, file, sha256, offset, stride, count) in ORIGINAL_TABLES { let input = std::fs::read(directory.join(file)).unwrap(); - assert_eq!(stela_runtime::sha256(&input), sha256, "{file}"); + assert_eq!(stela_formats::sha256(&input), sha256, "{file}"); let (mut fixed, mut special) = (Vec::new(), Vec::new()); for record in input[offset..offset + count * stride].chunks_exact(stride) { let word = |at: usize| u64::from_le_bytes(record[at..at + 8].try_into().unwrap()); diff --git a/crates/stela-loader/src/chained_fixups.rs b/crates/stela-loader/src/chained_fixups.rs index 9458df47fd..c306aee011 100644 --- a/crates/stela-loader/src/chained_fixups.rs +++ b/crates/stela-loader/src/chained_fixups.rs @@ -58,7 +58,7 @@ pub struct BindFixup { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct Authentication { - pub key: stela_runtime::pauth::Key, + pub key: stela_contracts::pauth::Key, pub diversity: u16, pub address_diversity: bool, } @@ -111,7 +111,13 @@ pub struct SignedFixupPlan { impl DecodedFixups { /// Compute signed values for every rebase under one process key set. /// Nothing is written and no bind is resolved. - pub fn sign_rebases(&self, context: &stela_runtime::pauth::Context) -> Result { + pub fn sign_rebases( + &self, + context: &S, + ) -> Result + where + S::Error: Into, + { ensure!( self.binds.is_empty() && self.authenticated_binds.is_empty(), "authenticated rebase planning requires explicit bind resolution first" @@ -130,7 +136,9 @@ impl DecodedFixups { let value = if fixup.target == 0 { 0 } else { - context.sign(fixup.authentication.key, fixup.target, modifier)? + context + .sign(fixup.authentication.key, fixup.target, modifier) + .map_err(Into::into)? }; Ok(SignedRebaseFixup { fixup: fixup.clone(), @@ -372,10 +380,10 @@ fn decode_pointer( ); let authentication = Authentication { key: match (raw >> 49) & 3 { - 0 => stela_runtime::pauth::Key::Ia, - 1 => stela_runtime::pauth::Key::Ib, - 2 => stela_runtime::pauth::Key::Da, - _ => stela_runtime::pauth::Key::Db, + 0 => stela_contracts::pauth::Key::Ia, + 1 => stela_contracts::pauth::Key::Ib, + 2 => stela_contracts::pauth::Key::Da, + _ => stela_contracts::pauth::Key::Db, }, diversity: ((raw >> 32) & 0xffff) as u16, address_diversity: raw & (1 << 48) != 0, @@ -507,7 +515,7 @@ fn decode_impl( allow_authentication: bool, ) -> Result { ensure!( - image.slice_bytes == data.len() as u64 && image.slice_sha256 == stela_runtime::sha256(data), + image.slice_bytes == data.len() as u64 && image.slice_sha256 == stela_formats::sha256(data), "chained-fixup image identity differs from load plan" ); let text: Vec<_> = image @@ -631,7 +639,7 @@ fn payload<'a>(data: &'a [u8], image: &LoadPlan) -> Result> { "chained-fixup payload exceeds planner limit" ); ensure!( - source.sha256 == stela_runtime::sha256(payload), + source.sha256 == stela_formats::sha256(payload), "chained-fixup payload differs from load plan" ); Ok(Some(payload)) @@ -1042,12 +1050,12 @@ mod tests { data[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); } fn refresh(data: &[u8], image: &mut LoadPlan) { - image.slice_sha256 = stela_runtime::sha256(data); + image.slice_sha256 = stela_formats::sha256(data); image.slice_bytes = data.len() as u64; for payload in &mut image.payloads { let start = payload.file.offset as usize; payload.sha256 = - stela_runtime::sha256(&data[start..start + payload.file.bytes as usize]); + stela_formats::sha256(&data[start..start + payload.file.bytes as usize]); } } fn raw(format: u16, target: u64, high: u8, next: u64) -> u64 { @@ -1631,7 +1639,7 @@ mod tests { } #[test] fn authenticated_rebases_preserve_all_metadata_and_always_use_image_relative_targets() { - use stela_runtime::pauth::Key; + use stela_contracts::pauth::Key; for format in [1, 9, 12] { for (key, domain) in [(0, Key::Ia), (1, Key::Ib), (2, Key::Da), (3, Key::Db)] { for diversity in [0, 0x1234, u16::MAX] { @@ -1698,7 +1706,7 @@ mod tests { assert_eq!(decoded.authenticated_binds[0].addend, -7); assert_eq!( decoded.authenticated_binds[0].authentication.key, - stela_runtime::pauth::Key::Da + stela_contracts::pauth::Key::Da ); assert_eq!( decoded.authenticated_binds[0].authentication.diversity, @@ -1762,10 +1770,10 @@ mod tests { null.sign_rebases(&ib_only).unwrap().authenticated_rebases[0].value, 0 ); - assert_ne!(full.sign(stela_runtime::pauth::Key::Ia, 0, 0).unwrap(), 0); + assert_ne!(full.sign(stela_contracts::pauth::Key::Ia, 0, 0).unwrap(), 0); assert_eq!( Authentication { - key: stela_runtime::pauth::Key::Ia, + key: stela_contracts::pauth::Key::Ia, diversity: 0x4321, address_diversity: true } diff --git a/crates/stela-loader/src/coprocessor.rs b/crates/stela-loader/src/coprocessor.rs index d56bdfe19a..8e585f9344 100644 --- a/crates/stela-loader/src/coprocessor.rs +++ b/crates/stela-loader/src/coprocessor.rs @@ -8,7 +8,7 @@ use crate::{boot_bundle::Source, im4p, kernel_collection::Segment, thread_state: use alloc::{string::String, vec, vec::Vec}; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::{pauth, sha256}; +use {stela_formats::sha256, stela_runtime::pauth}; pub mod configuration; mod fixups; diff --git a/crates/stela-loader/src/coprocessor/configuration.rs b/crates/stela-loader/src/coprocessor/configuration.rs index 39965f13b7..c72a5efc6c 100644 --- a/crates/stela-loader/src/coprocessor/configuration.rs +++ b/crates/stela-loader/src/coprocessor/configuration.rs @@ -6,7 +6,7 @@ use super::{Plan, Staged, digest, label, macho::file_bytes}; use alloc::{collections::BTreeSet, string::String, vec::Vec}; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; pub mod arguments; pub mod entropy; diff --git a/crates/stela-loader/src/coprocessor/configuration/entropy.rs b/crates/stela-loader/src/coprocessor/configuration/entropy.rs index d099af272a..779f87af69 100644 --- a/crates/stela-loader/src/coprocessor/configuration/entropy.rs +++ b/crates/stela-loader/src/coprocessor/configuration/entropy.rs @@ -74,7 +74,7 @@ mod tests { configuration::tests::{config_policy, provenance}, tests::{fixture, prepare, w32, w64}, }; - use stela_runtime::sha256; + use stela_formats::sha256; fn input(choice: u8) -> Input { Input { diff --git a/crates/stela-loader/src/coprocessor/configuration/finalization.rs b/crates/stela-loader/src/coprocessor/configuration/finalization.rs index 88e8ada871..adffdb8839 100644 --- a/crates/stela-loader/src/coprocessor/configuration/finalization.rs +++ b/crates/stela-loader/src/coprocessor/configuration/finalization.rs @@ -7,7 +7,7 @@ use crate::coprocessor::publication; use alloc::{collections::BTreeSet, string::String, vec::Vec}; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; const DSEG: u32 = u32::from_le_bytes(*b"dseg"); const RECORD_BYTES: usize = 16; diff --git a/crates/stela-loader/src/coprocessor/configuration/heap.rs b/crates/stela-loader/src/coprocessor/configuration/heap.rs index 99174be79d..35f5067da5 100644 --- a/crates/stela-loader/src/coprocessor/configuration/heap.rs +++ b/crates/stela-loader/src/coprocessor/configuration/heap.rs @@ -248,9 +248,9 @@ mod tests { let prepared = prepare(&image(0x4001))?; let mut complete = config_policy(prepared.plan()); let staged = prepared.stage(0x800000, 0x3000)?; - let hash = stela_runtime::sha256(staged.bytes()); + let hash = stela_formats::sha256(staged.bytes()); let fields = staged.heap_fields(&policy(BankState::Allocate), mapping(0x8000))?; - assert_eq!(stela_runtime::sha256(staged.bytes()), hash); + assert_eq!(stela_formats::sha256(staged.bytes()), hash); for field in [fields.base, fields.size] { let tag = field.tag; *complete.fields.iter_mut().find(|f| f.tag == tag).unwrap() = field; @@ -307,7 +307,7 @@ mod tests { fn original_t6000_heap_policy_coordinates() -> Result<()> { let b = std::fs::read(std::env::var("STELA_TEST_J314S_IBOOT")?)?; assert_eq!( - stela_runtime::sha256(&b), + stela_formats::sha256(&b), "20dfa3a5e6d4e4b2844c7558e6d4f8ab74397d11eae63312f00a559cf9612b03" ); let q = |at| u64::from_le_bytes(b[at..at + 8].try_into().unwrap()); diff --git a/crates/stela-loader/src/coprocessor/configuration/native.rs b/crates/stela-loader/src/coprocessor/configuration/native.rs index 51996ecc42..2a760ffeea 100644 --- a/crates/stela-loader/src/coprocessor/configuration/native.rs +++ b/crates/stela-loader/src/coprocessor/configuration/native.rs @@ -7,7 +7,7 @@ use crate::coprocessor::{HardwareIdentity, Staged}; use alloc::string::String; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; const CHAIN_STARTS: u32 = u32::from_be_bytes(*b"CSSS"); const SLIDE: u32 = u32::from_be_bytes(*b"SLID"); diff --git a/crates/stela-loader/src/coprocessor/configuration/tuning.rs b/crates/stela-loader/src/coprocessor/configuration/tuning.rs index a870fbafe5..af9c1cba4c 100644 --- a/crates/stela-loader/src/coprocessor/configuration/tuning.rs +++ b/crates/stela-loader/src/coprocessor/configuration/tuning.rs @@ -7,7 +7,7 @@ use crate::coprocessor::Staged; use alloc::vec::Vec; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; pub mod source; diff --git a/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs b/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs index ca226e0001..22eec3cc5b 100644 --- a/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs +++ b/crates/stela-loader/src/coprocessor/configuration/tuning/source.rs @@ -4,7 +4,7 @@ use crate::coprocessor::configuration::Provenance; use alloc::{string::String, vec::Vec}; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; const GROUP_BYTES: usize = 0x38; const REVISION_BYTES: usize = 0x58; diff --git a/crates/stela-loader/src/coprocessor/fixups.rs b/crates/stela-loader/src/coprocessor/fixups.rs index 444a4cba1b..57cf8d34bf 100644 --- a/crates/stela-loader/src/coprocessor/fixups.rs +++ b/crates/stela-loader/src/coprocessor/fixups.rs @@ -8,7 +8,7 @@ use super::macho::{Layout, end, file_bytes}; use alloc::{collections::BTreeMap, vec, vec::Vec}; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::{pauth, sha256}; +use {stela_formats::sha256, stela_runtime::pauth}; const FORMAT_ARM64E_KERNEL: u32 = 7; const STARTS_USE_VM_OFFSET: u32 = 2; @@ -17,7 +17,7 @@ const STRIDE: u64 = 4; #[derive(Debug, Clone, Copy, Serialize)] pub struct Authentication { - pub key: pauth::Key, + pub key: stela_contracts::pauth::Key, pub diversity: u16, pub address_diversity: bool, } @@ -139,10 +139,10 @@ pub(super) fn parse(data: &[u8], layout: &Layout, maximum: usize) -> Result> 49) & 3 { - 0 => pauth::Key::Ia, - 1 => pauth::Key::Ib, - 2 => pauth::Key::Da, - _ => pauth::Key::Db, + 0 => stela_contracts::pauth::Key::Ia, + 1 => stela_contracts::pauth::Key::Ib, + 2 => stela_contracts::pauth::Key::Da, + _ => stela_contracts::pauth::Key::Db, }, diversity: (value >> 32) as u16, address_diversity: value & (1 << 48) != 0, @@ -231,7 +231,7 @@ mod tests { let s = prepare(&fixture())?.stage(0x800000, 0x3000)?; assert_eq!(s.plan().chains.pointers.len(), 2); let ctx = context(); - let expected = ctx.sign(pauth::Key::Da, 8, 0x1234_0000_0000_2000)?; + let expected = ctx.sign(stela_contracts::pauth::Key::Da, 8, 0x1234_0000_0000_2000)?; let r = s.relocate(0, ctx, 16)?; let signed = u64::from_le_bytes(r.bytes()[0x2000..0x2008].try_into()?); assert_eq!(signed, expected); diff --git a/crates/stela-loader/src/coprocessor/macho.rs b/crates/stela-loader/src/coprocessor/macho.rs index e6936e3bbd..daad1e3278 100644 --- a/crates/stela-loader/src/coprocessor/macho.rs +++ b/crates/stela-loader/src/coprocessor/macho.rs @@ -11,7 +11,7 @@ use object::{ read::macho::{LoadCommandVariant, MachHeader, Segment}, }; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; #[derive(Debug, Clone, Serialize)] pub struct Section { diff --git a/crates/stela-loader/src/coprocessor/publication.rs b/crates/stela-loader/src/coprocessor/publication.rs index c544c177e4..1d115a911d 100644 --- a/crates/stela-loader/src/coprocessor/publication.rs +++ b/crates/stela-loader/src/coprocessor/publication.rs @@ -12,7 +12,7 @@ use super::{ use alloc::{collections::BTreeSet, string::String, vec::Vec}; use anyhow::{Context, Result, ensure}; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; /// Actual selected native policy inputs, before packing the wire flag word. /// These internal flags are not Mach-O protections. Their other allocation, diff --git a/crates/stela-loader/src/dependency_graph.rs b/crates/stela-loader/src/dependency_graph.rs index 4a7f96ed0c..4e81c96523 100644 --- a/crates/stela-loader/src/dependency_graph.rs +++ b/crates/stela-loader/src/dependency_graph.rs @@ -146,7 +146,7 @@ fn read_input( Ok(( ImageInput { data: slice.to_vec(), - container_sha256: stela_runtime::sha256(&bytes), + container_sha256: stela_formats::sha256(&bytes), slice_offset, load_base: Some(load_base), }, diff --git a/crates/stela-loader/src/devices.rs b/crates/stela-loader/src/devices.rs index c9f802293f..9f2a3b0b6f 100644 --- a/crates/stela-loader/src/devices.rs +++ b/crates/stela-loader/src/devices.rs @@ -1310,7 +1310,7 @@ mod tests { ), ] { let input = std::fs::read(format!("{directory}/DeviceTree.{board}")).unwrap(); - assert_eq!(stela_runtime::sha256(&input), digest); + assert_eq!(stela_formats::sha256(&input), digest); let mut tree = DeviceTree::parse(&input).unwrap(); let original = tree.clone(); let hidden = hide_unmodeled(&mut tree); @@ -1793,7 +1793,7 @@ mod tests { fn original_j314s_preparation_keeps_the_complete_external_display_graph() { let bytes = std::fs::read(std::env::var("STELA_TEST_DART_DT").unwrap()).unwrap(); assert_eq!( - stela_runtime::sha256(&bytes), + stela_formats::sha256(&bytes), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let mut tree = DeviceTree::parse(&bytes).unwrap(); @@ -2040,7 +2040,7 @@ mod tests { fn original_direct_memory_preserves_source_while_pmp_dma_stays_hidden() { let bytes = std::fs::read(std::env::var("STELA_T6000_MCC_DEVICE_TREE").unwrap()).unwrap(); assert_eq!( - stela_runtime::sha256(&bytes), + stela_formats::sha256(&bytes), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let original = DeviceTree::parse(&bytes).unwrap(); diff --git a/crates/stela-loader/src/exports.rs b/crates/stela-loader/src/exports.rs index 0f3b4f76b5..480e3e4d8b 100644 --- a/crates/stela-loader/src/exports.rs +++ b/crates/stela-loader/src/exports.rs @@ -181,7 +181,7 @@ fn payload_bytes<'a>(data: &'a [u8], source: &Payload) -> Result<&'a [u8]> { .get(start..end) .context("export payload exceeds image")?; ensure!( - source.sha256 == stela_runtime::sha256(bytes), + source.sha256 == stela_formats::sha256(bytes), "export payload differs from load plan" ); Ok(bytes) @@ -221,7 +221,7 @@ fn regular_address(image: &LoadPlan, preferred: u64, loaded: u64, value: u64) -> /// payload size and total name length are bounded. pub fn parse(data: &[u8], image: &LoadPlan, load_base: u64) -> Result> { ensure!( - image.slice_bytes == data.len() as u64 && image.slice_sha256 == stela_runtime::sha256(data), + image.slice_bytes == data.len() as u64 && image.slice_sha256 == stela_formats::sha256(data), "export image identity differs from load plan" ); let mut selected = None; @@ -636,7 +636,7 @@ mod tests { let (mut data, mut image) = fixture(&trie(&[(b"a", 0, 0x300)]), false); image.payloads[0].sha256 = "wrong".into(); assert!(parse(&data, &image, BASE).is_err()); - image.payloads[0].sha256 = stela_runtime::sha256( + image.payloads[0].sha256 = stela_formats::sha256( &data[TRIE_OFFSET..TRIE_OFFSET + image.payloads[0].file.bytes as usize], ); let mut duplicate = image.payloads[0].clone(); diff --git a/crates/stela-loader/src/handoff.rs b/crates/stela-loader/src/handoff.rs index 2d6c7a823a..90b7f092ee 100644 --- a/crates/stela-loader/src/handoff.rs +++ b/crates/stela-loader/src/handoff.rs @@ -7,7 +7,7 @@ use crate::{apple_device_tree::DeviceTree, boot_policy::Decision}; use alloc::{format, string::String, vec, vec::Vec}; use anyhow::{Result, ensure}; -pub use stela_runtime::boot_bundle::schema::BootCommand; +pub use stela_formats::boot_bundle::schema::BootCommand; use stela_runtime::machine::soc; const ROOT: &str = "/"; diff --git a/crates/stela-loader/src/im4p.rs b/crates/stela-loader/src/im4p.rs index a7d9cfb217..f95df3dc96 100644 --- a/crates/stela-loader/src/im4p.rs +++ b/crates/stela-loader/src/im4p.rs @@ -214,14 +214,14 @@ pub fn decode(bytes: &[u8], maximum: u64) -> Result<(Vec, DecodeReceipt)> { "declared output exceeds configured limit" ); let mut decoded = vec![]; - let compression = if stela_runtime::lzfse::is_lzfse(im4p.payload) { + let compression = if stela_formats::lzfse::is_lzfse(im4p.payload) { ensure!( im4p.compression_algorithm .is_none_or(|n| n == COMPRESSION_LZFSE), "compression record disagrees with LZFSE marker" ); let limit = usize::try_from(maximum).unwrap_or(usize::MAX); - decoded = stela_runtime::lzfse::decode(im4p.payload, limit) + decoded = stela_formats::lzfse::decode(im4p.payload, limit) .map_err(|error| anyhow::anyhow!("{error}"))?; "lzfse" } else { @@ -245,15 +245,15 @@ pub fn decode(bytes: &[u8], maximum: u64) -> Result<(Vec, DecodeReceipt)> { let receipt = DecodeReceipt { schema_version: 1, container_bytes: bytes.len(), - container_sha256: stela_runtime::sha256(bytes), + container_sha256: stela_formats::sha256(bytes), payload_type: im4p.payload_type, description: im4p.description, compression: compression.into(), payload_bytes: im4p.payload.len(), - payload_sha256: stela_runtime::sha256(im4p.payload), + payload_sha256: stela_formats::sha256(im4p.payload), declared_uncompressed_bytes: im4p.declared_uncompressed_bytes, decoded_bytes: decoded.len(), - decoded_sha256: stela_runtime::sha256(&decoded), + decoded_sha256: stela_formats::sha256(&decoded), opaque_extensions: im4p.opaque_extensions, signature_validated: false, }; @@ -307,7 +307,7 @@ mod tests { assert_eq!(decoded, raw); assert_eq!(receipt.payload_type, "dtre"); assert_eq!(receipt.compression, "lzfse"); - assert_eq!(receipt.decoded_sha256, stela_runtime::sha256(raw)); + assert_eq!(receipt.decoded_sha256, stela_formats::sha256(raw)); assert!(!receipt.signature_validated); assert!(decode(&container, 2).is_err()); diff --git a/crates/stela-loader/src/installed.rs b/crates/stela-loader/src/installed.rs index 5084d6af4d..d69d9c96a5 100644 --- a/crates/stela-loader/src/installed.rs +++ b/crates/stela-loader/src/installed.rs @@ -1,5 +1,5 @@ //! The kernel boot bundle of an installed system, built from its APFS -//! container's Preboot volume (`stela_runtime::preboot`), in `no_std` so +//! container's Preboot volume (`stela_formats::preboot`), in `no_std` so //! `stela.efi` builds the same bundle `stela-dev boot prepare --disk` writes. //! //! The volume group is the one NVRAM's boot volume names @@ -44,12 +44,11 @@ use crate::{ }; use alloc::{format, string::String, vec::Vec}; use anyhow::{Context, Result, anyhow, bail, ensure}; -use stela_runtime::{ - apfs::{self, Container, Volume, btree::Hash}, - img4, - payload::ReadAt, - preboot::{self, BootSet, SYSTEM_VERSION}, - sha256, +use { + stela_formats::apfs, stela_formats::apfs::Container, stela_formats::apfs::Volume, + stela_formats::apfs::btree::Hash, stela_formats::img4, stela_formats::payload::ReadAt, + stela_formats::preboot, stela_formats::preboot::BootSet, + stela_formats::preboot::SYSTEM_VERSION, stela_formats::sha256, }; /// The variant recorded for a bundle read from an installed system. diff --git a/crates/stela-loader/src/lib.rs b/crates/stela-loader/src/lib.rs index 693c8ffb68..57a32c2221 100644 --- a/crates/stela-loader/src/lib.rs +++ b/crates/stela-loader/src/lib.rs @@ -20,7 +20,7 @@ pub mod carveouts; pub mod chained_fixups; pub mod coprocessor; #[cfg(feature = "std")] -pub use stela_runtime::code_signature; +pub use stela_formats::code_signature; pub mod darts; #[cfg(feature = "std")] pub mod dependency_graph; @@ -62,7 +62,7 @@ use anyhow::{Context, Result, ensure}; #[cfg(feature = "std")] use object::{Object, ObjectSection}; #[cfg(feature = "std")] -use stela_runtime::sha256; +use stela_formats::sha256; /// One Mach-O slice of a file, as [`inspect`] names it. #[cfg(feature = "std")] diff --git a/crates/stela-loader/src/load_plan.rs b/crates/stela-loader/src/load_plan.rs index c4d342973b..551a4d8c27 100644 --- a/crates/stela-loader/src/load_plan.rs +++ b/crates/stela-loader/src/load_plan.rs @@ -5,7 +5,7 @@ use object::{ }; use serde::Serialize; use std::{collections::BTreeSet, error::Error, fmt}; -use stela_runtime::sha256; +use stela_formats::sha256; #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(tag = "kind", content = "detail", rename_all = "snake_case")] diff --git a/crates/stela-loader/src/local_policy.rs b/crates/stela-loader/src/local_policy.rs index 4dcc0254a0..6dc93f70b7 100644 --- a/crates/stela-loader/src/local_policy.rs +++ b/crates/stela-loader/src/local_policy.rs @@ -91,7 +91,7 @@ fn data<'a>(properties: &'a [Property], name: &str, bytes: usize) -> Result Result { - let manifest = match stela_runtime::img4::parse(file) { + let manifest = match stela_formats::img4::parse(file) { Ok(parts) => parts .manifest .with_context(|| format!("{path} is an IMG4 without a manifest"))? diff --git a/crates/stela-loader/src/lock_regs.rs b/crates/stela-loader/src/lock_regs.rs index 04f470da3e..6b6981e3b6 100644 --- a/crates/stela-loader/src/lock_regs.rs +++ b/crates/stela-loader/src/lock_regs.rs @@ -72,7 +72,7 @@ use crate::apple_device_tree::DeviceTree; use alloc::{format, string::String, vec::Vec}; use anyhow::{Context, Result, ensure}; use core::ops::Range; -pub use stela_runtime::boot_bundle::schema::Programmed; +pub use stela_formats::boot_bundle::schema::Programmed; use stela_runtime::machine::ctrr::{CoreLocks, LockRegion, Locked}; pub const AMCC: &str = "/chosen/lock-regs/amcc"; diff --git a/crates/stela-loader/src/mapped_image.rs b/crates/stela-loader/src/mapped_image.rs index 18497fd17a..a30ecf8f5b 100644 --- a/crates/stela-loader/src/mapped_image.rs +++ b/crates/stela-loader/src/mapped_image.rs @@ -371,7 +371,7 @@ mod tests { schema_version: 1, file_type: 7, dylib_identity: None, - slice_sha256: stela_runtime::sha256(&data), + slice_sha256: stela_formats::sha256(&data), slice_bytes: 16, cpu_type: 0x100000c, cpu_subtype: 0x80000002, @@ -447,7 +447,7 @@ mod tests { offset: 0, bytes: 1, }, - sha256: stela_runtime::sha256(&data[..1]), + sha256: stela_formats::sha256(&data[..1]), }); assert!(prepare_segments(&data, &legacy, base, &[]).is_err()); assert!(prepare_raw_segments(&data, &legacy, base).is_ok()); diff --git a/crates/stela-loader/src/mount_interface.rs b/crates/stela-loader/src/mount_interface.rs index 2a4c1e271a..084cea8f4e 100644 --- a/crates/stela-loader/src/mount_interface.rs +++ b/crates/stela-loader/src/mount_interface.rs @@ -80,7 +80,7 @@ const TIMEOUT: &str = "timeout"; /// What one `stela.efi` build reads. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Interface { - /// `stela_runtime::boot_bundle::SCHEMA_VERSION`. + /// `stela_formats::boot_bundle::SCHEMA_VERSION`. pub bundle_schema: u32, pub options_revision: u32, /// The NOR image at the machine-state partition's start. @@ -91,7 +91,7 @@ pub struct Interface { /// The interface of this source tree. pub const CURRENT: Interface = Interface { - bundle_schema: stela_runtime::boot_bundle::SCHEMA_VERSION, + bundle_schema: stela_formats::boot_bundle::SCHEMA_VERSION, options_revision: OPTIONS_REVISION, nor_bytes: stela_runtime::machine::apple::nor::CAPACITY as u32, sep_bytes: stela_runtime::machine::apple::sep_state::BYTES as u32, diff --git a/crates/stela-loader/src/recovery.rs b/crates/stela-loader/src/recovery.rs index 7e23f8d316..55192cbe93 100644 --- a/crates/stela-loader/src/recovery.rs +++ b/crates/stela-loader/src/recovery.rs @@ -19,7 +19,7 @@ //! `System/Library/Caches/com.apple.kernelcaches/` and iBoot, the //! DeviceTree, `base_system_root_hash.img4`, the monitors and trust caches //! (`FUD/`) and `arm64eBaseSystem.dmg` under `usr/standalone/firmware/`. -//! Objects are identified by Image4 payload type (`stela_runtime::preboot`); +//! Objects are identified by Image4 payload type (`stela_formats::preboot`); //! the J473 iBoot names the image and the BaseSystem trust cache by path //! (`base-system-path`, `bs-tc-path`). //! @@ -57,15 +57,13 @@ use crate::{ }; use alloc::{format, string::String, vec, vec::Vec}; use anyhow::{Context, Result, anyhow, bail, ensure}; -use stela_runtime::{ - apfs::{ - self, ApfsError, Container, FileKind, Volume, uuid_text as apfs_uuid, - volume::APFS_VOL_ROLE_RECOVERY, - }, - img4, - payload::{ReadAt, gpt::Guid}, - preboot::{self, BootSet, SYSTEM_VERSION}, - sha256, +use { + stela_formats::apfs, stela_formats::apfs::ApfsError, stela_formats::apfs::Container, + stela_formats::apfs::FileKind, stela_formats::apfs::Volume, + stela_formats::apfs::uuid_text as apfs_uuid, + stela_formats::apfs::volume::APFS_VOL_ROLE_RECOVERY, stela_formats::img4, + stela_formats::payload::ReadAt, stela_formats::payload::gpt::Guid, stela_formats::preboot, + stela_formats::preboot::BootSet, stela_formats::preboot::SYSTEM_VERSION, stela_formats::sha256, }; /// The RecoveryOSContainer (`Apple_APFS_Recovery`) partition type. @@ -705,7 +703,7 @@ pub fn prepare_disk( #[cfg(test)] mod tests { use super::*; - use stela_runtime::{apfs::object::fletcher64, payload::gpt}; + use {stela_formats::apfs::object::fletcher64, stela_formats::payload::gpt}; const GROUP: &str = "A304C51B-D22F-4CDD-829D-3E30CB5BD87B"; const BLOCK: usize = 4096; diff --git a/crates/stela-loader/src/root_selection.rs b/crates/stela-loader/src/root_selection.rs index 4225d4d894..badc67eda8 100644 --- a/crates/stela-loader/src/root_selection.rs +++ b/crates/stela-loader/src/root_selection.rs @@ -33,7 +33,7 @@ use crate::{apple_device_tree::DeviceTree, boot_policy::Decision}; use alloc::{format, string::String, vec::Vec}; use anyhow::{Result, ensure}; -pub use stela_runtime::boot_bundle::schema::Root; +pub use stela_formats::boot_bundle::schema::Root; const CHOSEN: &str = "/chosen"; pub const APFS_PREBOOT_UUID: &str = "apfs-preboot-uuid"; diff --git a/crates/stela-loader/src/thread_state.rs b/crates/stela-loader/src/thread_state.rs index bb98ea03af..6629f7a252 100644 --- a/crates/stela-loader/src/thread_state.rs +++ b/crates/stela-loader/src/thread_state.rs @@ -3,7 +3,7 @@ use alloc::string::String; use anyhow::{Result, ensure}; use object::macho; use serde::Serialize; -use stela_runtime::sha256; +use stela_formats::sha256; const WORD_BYTES: usize = core::mem::size_of::(); const REGISTER_BYTES: usize = core::mem::size_of::(); diff --git a/crates/stela-loader/src/upgrade.rs b/crates/stela-loader/src/upgrade.rs index 574ad72167..8178621241 100644 --- a/crates/stela-loader/src/upgrade.rs +++ b/crates/stela-loader/src/upgrade.rs @@ -31,11 +31,11 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use stela_runtime::{ - apfs::{self, ApfsError, Container, FileKind, Volume, volume::ROOT_DIR_INO_NUM}, - img4, - payload::ReadAt, - sha256, +use { + stela_formats::apfs, stela_formats::apfs::ApfsError, stela_formats::apfs::Container, + stela_formats::apfs::FileKind, stela_formats::apfs::Volume, + stela_formats::apfs::volume::ROOT_DIR_INO_NUM, stela_formats::img4, + stela_formats::payload::ReadAt, stela_formats::sha256, }; /// The variant recorded for a bundle read from an Update volume. diff --git a/crates/stela-loader/tests/images.rs b/crates/stela-loader/tests/images.rs index 4b43561ec8..ea21843115 100644 --- a/crates/stela-loader/tests/images.rs +++ b/crates/stela-loader/tests/images.rs @@ -171,7 +171,7 @@ fn quads(bytes: &[u8]) -> Vec { fn input(data: Vec, load_base: u64) -> ImageInput { ImageInput { - container_sha256: stela_runtime::sha256(&data), + container_sha256: stela_formats::sha256(&data), data, slice_offset: 0, load_base: Some(load_base), diff --git a/crates/stela-runtime/Cargo.toml b/crates/stela-runtime/Cargo.toml index 984921dd84..b0cb2df9eb 100644 --- a/crates/stela-runtime/Cargo.toml +++ b/crates/stela-runtime/Cargo.toml @@ -9,10 +9,12 @@ workspace = true [features] default = ["std"] -native-profile = [] -std = ["anyhow/std", "serde/std", "serde_json/std", "stela-compiler/std", "dep:tempfile", "dep:libc"] +native-profile = ["stela-contracts/native-profile"] +std = ["anyhow/std", "stela-contracts/std", "stela-formats/std", "serde/std", "serde_json/std", "stela-compiler/std", "dep:tempfile", "dep:libc"] [dependencies] +stela-contracts = { path = "../stela-contracts", default-features = false } +stela-formats = { path = "../stela-formats", default-features = false } anyhow = { version = "1", default-features = false } serde.workspace = true serde_json = { version = "1", default-features = false, features = ["alloc"] } @@ -45,6 +47,8 @@ httparse = { version = "1.10", default-features = false } stela-fingerprint.workspace = true [dev-dependencies] +stela-formats = { path = "../stela-formats", features = ["test-support"] } +stela-contracts = { path = "../stela-contracts", features = ["test-support"] } # The drivers' RAM disk, which the device model tests run on. stela-drivers = { path = "../stela-drivers", features = ["ram-disk"] } # The reference LZFSE encoder the no_std decoder is checked against. diff --git a/crates/stela-runtime/examples/restore_replay.rs b/crates/stela-runtime/examples/restore_replay.rs index e5c18b59ff..0572e3ec05 100644 --- a/crates/stela-runtime/examples/restore_replay.rs +++ b/crates/stela-runtime/examples/restore_replay.rs @@ -7,16 +7,14 @@ use std::{ path::Path, task::Poll, }; -use stela_runtime::{ - payload::{PayloadManifest, ReadAt}, - restore::{ - Error, - answers::Answers, - plist::{self, Limits, Value}, - session::{Action, Session}, - store::Store, - stream::{ByteStream, Endian, Framed}, - }, +use { + stela_formats::payload::PayloadManifest, stela_formats::payload::ReadAt, + stela_runtime::restore::Error, stela_runtime::restore::answers::Answers, + stela_runtime::restore::plist, stela_runtime::restore::plist::Limits, + stela_runtime::restore::plist::Value, stela_runtime::restore::session::Action, + stela_runtime::restore::session::Session, stela_runtime::restore::store::Store, + stela_runtime::restore::stream::ByteStream, stela_runtime::restore::stream::Endian, + stela_runtime::restore::stream::Framed, }; struct ArchiveFile(File, u64); impl ReadAt for ArchiveFile { diff --git a/crates/stela-runtime/src/artifact.rs b/crates/stela-runtime/src/artifact.rs index b8bfb214bd..81485b0a8a 100644 --- a/crates/stela-runtime/src/artifact.rs +++ b/crates/stela-runtime/src/artifact.rs @@ -60,7 +60,9 @@ pub(crate) fn validate_native_snapshot( manifest: &Manifest, native: &[u8], ) -> Result<(), ArtifactError> { - if native.len() != manifest.native_bytes || crate::sha256(native) != manifest.native_sha256 { + if native.len() != manifest.native_bytes + || stela_formats::sha256(native) != manifest.native_sha256 + { return Err(ArtifactError("native snapshot checksum mismatch")); } Ok(()) diff --git a/crates/stela-runtime/src/artifact/prepare.rs b/crates/stela-runtime/src/artifact/prepare.rs index ccc031ae9a..f6b253a756 100644 --- a/crates/stela-runtime/src/artifact/prepare.rs +++ b/crates/stela-runtime/src/artifact/prepare.rs @@ -23,7 +23,7 @@ pub(crate) fn generate( ); let manifest = Manifest { identity, - native_sha256: crate::sha256(&x86_64_code), + native_sha256: stela_formats::sha256(&x86_64_code), native_bytes: x86_64_code.len(), source_map, verified: false, @@ -40,7 +40,7 @@ pub(crate) fn validate_manifest_bytes( if manifest_bytes.len() > MAX_CACHE_MANIFEST_BYTES { return Err(ArtifactError("cache file exceeds size limit")); } - if crate::sha256(manifest_bytes) != expected_sha256 { + if stela_formats::sha256(manifest_bytes) != expected_sha256 { return Err(ArtifactError("cached manifest checksum mismatch")); } Ok(()) @@ -163,7 +163,7 @@ mod tests { let native = b"immutable original native snapshot"; let manifest = Manifest { identity: identity.clone(), - native_sha256: crate::sha256(native), + native_sha256: stela_formats::sha256(native), native_bytes: native.len(), source_map: vec![(GuestAddress(0x1000), 0)], verified: false, @@ -176,7 +176,7 @@ mod tests { fn shared_validation_accepts_original_descriptive_inputs() { let (identity, manifest, native) = fixture(); let serialized = b"original serialized manifest bytes"; - validate_manifest_bytes(serialized, &crate::sha256(serialized)).unwrap(); + validate_manifest_bytes(serialized, &stela_formats::sha256(serialized)).unwrap(); validate_preparation_metadata(&manifest, &identity, manifest.memory_requirements).unwrap(); validate_preparation_native(&manifest, native).unwrap(); validate_preparation_claim(&manifest).unwrap(); diff --git a/crates/stela-runtime/src/blocks.rs b/crates/stela-runtime/src/blocks.rs index de8e3222e5..c9fb19414e 100644 --- a/crates/stela-runtime/src/blocks.rs +++ b/crates/stela-runtime/src/blocks.rs @@ -1192,7 +1192,10 @@ mod tests { -> Result<()> { let context = full_context(); let cache = tempfile::tempdir()?; - for key in [pauth::Key::Ia, pauth::Key::Ib] { + for key in [ + stela_contracts::pauth::Key::Ia, + stela_contracts::pauth::Key::Ib, + ] { for link in [false, true] { for (target, rm, zero) in [ (0, 1, false), @@ -1204,7 +1207,7 @@ mod tests { let word = 0xd61f0800 | (u32::from(!zero) << 24) | (u32::from(link) << 21) - | (u32::from(key == pauth::Key::Ib) << 10) + | (u32::from(key == stela_contracts::pauth::Key::Ib) << 10) | (target << 5) | rm; let mut vm = runtime(cache.path(), &[0x910004e7, word])?; @@ -1299,7 +1302,8 @@ mod tests { ] { let mut vm = runtime(cache.path(), &[0x910004e7, word, 0])?; // ADD X7,X7,#1 let mut state = initial(11); - state.registers.x[30] = full.sign(pauth::Key::Ia, STOP.0, state.registers.sp)?; + state.registers.x[30] = + full.sign(stela_contracts::pauth::Key::Ia, STOP.0, state.registers.sp)?; let mut expected = state.registers.clone(); expected.x[7] = expected.x[7].wrapping_add(1); // SAFETY: register prefix/helper only; missing key cannot touch guest RAM. @@ -1342,11 +1346,15 @@ mod tests { let cache = tempfile::tempdir()?; let mut vm = runtime(cache.path(), &[0xd65f0bff])?; let mut state = initial(8); - let signed = context.sign(pauth::Key::Ia, STOP.0, state.registers.sp)?; + let signed = + context.sign(stela_contracts::pauth::Key::Ia, STOP.0, state.registers.sp)?; state.registers.x[30] = signed ^ (1 << 47); let expected = state.registers.clone(); - let target = - context.authenticate(pauth::Key::Ia, state.registers.x[30], state.registers.sp)?; + let target = context.authenticate( + stela_contracts::pauth::Key::Ia, + state.registers.x[30], + state.registers.sp, + )?; assert!(!target.authenticated); // SAFETY: helper-only RETAA, no target is fetched by failed completion. let outcome = unsafe { vm.run_with_pauth(&mut state, None, 1, &context)? }; diff --git a/crates/stela-runtime/src/blocks/aot.rs b/crates/stela-runtime/src/blocks/aot.rs index 2db8d5bb57..e7215c3a5f 100644 --- a/crates/stela-runtime/src/blocks/aot.rs +++ b/crates/stela-runtime/src/blocks/aot.rs @@ -227,7 +227,7 @@ mod tests { let native = plan.compile()?.native; let manifest = crate::Manifest { identity, - native_sha256: crate::sha256(&native.x86_64_code), + native_sha256: stela_formats::sha256(&native.x86_64_code), native_bytes: native.x86_64_code.len(), source_map: native.source_map, verified: false, @@ -238,7 +238,7 @@ mod tests { fn serialized(manifest: &crate::Manifest) -> Result<(Vec, Vec)> { let bytes = serde_json::to_vec(manifest)?; - let checksum = serde_json::to_vec(&crate::sha256(&bytes))?; + let checksum = serde_json::to_vec(&stela_formats::sha256(&bytes))?; Ok((bytes, checksum)) } diff --git a/crates/stela-runtime/src/blocks/discovery.rs b/crates/stela-runtime/src/blocks/discovery.rs index dd8b246cda..01e3b20ed2 100644 --- a/crates/stela-runtime/src/blocks/discovery.rs +++ b/crates/stela-runtime/src/blocks/discovery.rs @@ -8,7 +8,6 @@ use super::validate::validate_source_map; use crate::Prepared; #[cfg(feature = "std")] use crate::prepare_runtime_block_for_target; -use crate::sha256; use alloc::collections::{BTreeSet, VecDeque}; #[cfg(not(feature = "std"))] use alloc::{string::String, vec::Vec}; @@ -20,6 +19,7 @@ use stela_compiler::{ BlockAnalysis, BlockProfile, DynamicEdge, MAX_BLOCK_INSTRUCTIONS, analyze_with_profile, }, }; +use stela_formats::sha256; /// Persistent preparation artifact shared by ahead-of-time discovery and JIT. /// Preparing it performs no native mapping, invocation or guest memory access. diff --git a/crates/stela-runtime/src/blocks/retirement/checked/pauth_lr.rs b/crates/stela-runtime/src/blocks/retirement/checked/pauth_lr.rs index 3822bc12b0..5c1c1bc49a 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/pauth_lr.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/pauth_lr.rs @@ -83,8 +83,14 @@ pub(super) fn service<'a>( .map_err(|error| anyhow::anyhow!("LR service: {error:?}"))?; if let Some(key) = instruction.operation.required_key() { let (selected, actual) = match key { - Key::Ia => (pauth::lr_context::InstructionKey::A, pauth::Key::Ia), - Key::Ib => (pauth::lr_context::InstructionKey::B, pauth::Key::Ib), + Key::Ia => ( + pauth::lr_context::InstructionKey::A, + stela_contracts::pauth::Key::Ia, + ), + Key::Ib => ( + pauth::lr_context::InstructionKey::B, + stela_contracts::pauth::Key::Ib, + ), _ => anyhow::bail!("LR service requires an instruction key"), }; if service.key_selection(selected) == KeySelection::UseKey { diff --git a/crates/stela-runtime/src/blocks/retirement/checked/pauth_policy.rs b/crates/stela-runtime/src/blocks/retirement/checked/pauth_policy.rs index 1c344d8226..0101a9da54 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/pauth_policy.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/pauth_policy.rs @@ -78,10 +78,10 @@ pub(super) fn qualify( } if let Some(key) = operation.required_key() { let (key, enable) = match key { - Key::Ia => (pauth::Key::Ia, SCTLR_ENIA), - Key::Ib => (pauth::Key::Ib, SCTLR_ENIB), - Key::Da => (pauth::Key::Da, SCTLR_ENDA), - Key::Db => (pauth::Key::Db, SCTLR_ENDB), + Key::Ia => (stela_contracts::pauth::Key::Ia, SCTLR_ENIA), + Key::Ib => (stela_contracts::pauth::Key::Ib, SCTLR_ENIB), + Key::Da => (stela_contracts::pauth::Key::Da, SCTLR_ENDA), + Key::Db => (stela_contracts::pauth::Key::Db, SCTLR_ENDB), }; anyhow::ensure!( sctlr_el1 & enable != 0 && context.has_key(key), diff --git a/crates/stela-runtime/src/blocks/retirement/checked/source.rs b/crates/stela-runtime/src/blocks/retirement/checked/source.rs index 6f54c57aa9..e07e4e652c 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/source.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/source.rs @@ -197,7 +197,7 @@ impl<'code> BoundSource<'code> { identity.guest_base == pc.0 && identity.abi == runtime.profile.abi() && identity.target_cpu == runtime.target_cpu().id() - && identity.source_sha256 == crate::sha256(source) + && identity.source_sha256 == stela_formats::sha256(source) && identity.compiler_source_sha256 == crate::compiler_source_sha256(), "source/compiler/profile/target differs" ); diff --git a/crates/stela-runtime/src/blocks/services.rs b/crates/stela-runtime/src/blocks/services.rs index 3e97f85de3..817b8a155b 100644 --- a/crates/stela-runtime/src/blocks/services.rs +++ b/crates/stela-runtime/src/blocks/services.rs @@ -119,12 +119,12 @@ pub(super) fn serialize_instruction_execution() -> Result<()> { anyhow::bail!("instruction synchronization requires the x86-64 runtime") } -pub(super) fn runtime_pauth_key(key: PointerAuthenticationKey) -> pauth::Key { +pub(super) fn runtime_pauth_key(key: PointerAuthenticationKey) -> stela_contracts::pauth::Key { match key { - PointerAuthenticationKey::Ia => pauth::Key::Ia, - PointerAuthenticationKey::Ib => pauth::Key::Ib, - PointerAuthenticationKey::Da => pauth::Key::Da, - PointerAuthenticationKey::Db => pauth::Key::Db, + PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, + PointerAuthenticationKey::Ib => stela_contracts::pauth::Key::Ib, + PointerAuthenticationKey::Da => stela_contracts::pauth::Key::Da, + PointerAuthenticationKey::Db => stela_contracts::pauth::Key::Db, } } @@ -206,7 +206,7 @@ pub(crate) fn complete_pauth_with_memory( } PointerAuthenticationOperation::AuthenticateIbSp => { let result = context.authenticate_operation( - pauth::Key::Ib, + stela_contracts::pauth::Key::Ib, registers.x[30], registers.sp, false, @@ -216,9 +216,9 @@ pub(crate) fn complete_pauth_with_memory( } PointerAuthenticationOperation::ReturnIbSp | PointerAuthenticationOperation::ReturnIaSp => { let key = if instruction.operation == PointerAuthenticationOperation::ReturnIbSp { - pauth::Key::Ib + stela_contracts::pauth::Key::Ib } else { - pauth::Key::Ia + stela_contracts::pauth::Key::Ia }; let result = context.authenticate_operation(key, registers.x[30], registers.sp, true)?; @@ -307,8 +307,12 @@ pub(crate) fn complete_pauth_with_memory( registers, |key, pointer| -> core::result::Result { let key = match key { - stela_compiler::block::pauth_memory::DataKey::A => pauth::Key::Da, - stela_compiler::block::pauth_memory::DataKey::B => pauth::Key::Db, + stela_compiler::block::pauth_memory::DataKey::A => { + stela_contracts::pauth::Key::Da + } + stela_compiler::block::pauth_memory::DataKey::B => { + stela_contracts::pauth::Key::Db + } }; let result = context.authenticate_operation(key, pointer, 0, true)?; authenticated = result.authenticated; @@ -362,8 +366,14 @@ pub(crate) fn complete_pauth_with_memory( }; // XPAC selects an address domain, not a key, so no key needs to // exist. - let value = - context.strip(if data { pauth::Key::Da } else { pauth::Key::Ia }, pointer)?; + let value = context.strip( + if data { + stela_contracts::pauth::Key::Da + } else { + stela_contracts::pauth::Key::Ia + }, + pointer, + )?; if destination != ZERO_REGISTER_INDEX { registers.x[usize::from(destination)] = value; } diff --git a/crates/stela-runtime/src/dispatch.rs b/crates/stela-runtime/src/dispatch.rs index 7b10d5d616..79509743f6 100644 --- a/crates/stela-runtime/src/dispatch.rs +++ b/crates/stela-runtime/src/dispatch.rs @@ -1,7 +1,6 @@ //! Lazy resolution of registered leaf entry points. Handles must be revalidated //! before each execution; invalidation does not interrupt running code. -use crate::sha256; use crate::{Identity, Prepared, prepare_leaf}; use alloc::collections::BTreeMap; use alloc::sync::Arc; @@ -10,6 +9,7 @@ use alloc::{string::String, vec::Vec}; use anyhow::{Result, ensure}; use std::path::PathBuf; use stela_compiler::GuestAddress; +use stela_formats::sha256; #[derive(Debug, Clone, PartialEq, Eq)] pub struct DispatchIdentity { diff --git a/crates/stela-runtime/src/execution.rs b/crates/stela-runtime/src/execution.rs index bff8a73e45..566f0f44fb 100644 --- a/crates/stela-runtime/src/execution.rs +++ b/crates/stela-runtime/src/execution.rs @@ -15,8 +15,6 @@ pub(crate) use native_image::ReachedCall as ObservedNativeCall; #[cfg(feature = "std")] use crate::dispatch::{LeafDispatcher, ResolvedLeaf}; #[cfg(feature = "std")] -use crate::sha256; -#[cfg(feature = "std")] use alloc::rc::Rc; #[cfg(feature = "std")] use anyhow::{Context, Result, ensure}; @@ -26,6 +24,8 @@ use core::marker::PhantomData; use std::io::Read; #[cfg(feature = "std")] use stela_compiler::GuestState; +#[cfg(feature = "std")] +use stela_formats::sha256; // Bounds a cached artifact so it cannot force an unbounded allocation or // mapping. diff --git a/crates/stela-runtime/src/execution/checked_memory.rs b/crates/stela-runtime/src/execution/checked_memory.rs index 6370dff045..1a6f4c0829 100644 --- a/crates/stela-runtime/src/execution/checked_memory.rs +++ b/crates/stela-runtime/src/execution/checked_memory.rs @@ -174,8 +174,8 @@ impl CheckedMemoryBlock { let identity = Identity { address_space, entry, - source_sha256: crate::sha256(&source), - native_sha256: crate::sha256(&compiled.native.x86_64_code), + source_sha256: stela_formats::sha256(&source), + native_sha256: stela_formats::sha256(&compiled.native.x86_64_code), native_bytes: compiled.native.x86_64_code.len(), compiler_source_sha256: stela_compiler::SOURCE_SHA256, target, @@ -994,7 +994,7 @@ mod tests { .compile() .unwrap(); assert_eq!( - crate::sha256(&emitted.native.x86_64_code), + stela_formats::sha256(&emitted.native.x86_64_code), body.identity.native_sha256 ); for (name, bytes) in [ @@ -1985,7 +1985,7 @@ mod tests { .compile() .unwrap(); assert_eq!( - crate::sha256(&emitted.native.x86_64_code), + stela_formats::sha256(&emitted.native.x86_64_code), body.identity.native_sha256 ); for (name, bytes) in [ diff --git a/crates/stela-runtime/src/hosted/commpage.rs b/crates/stela-runtime/src/hosted/commpage.rs index 96b59f8a3d..071fc1f8fb 100644 --- a/crates/stela-runtime/src/hosted/commpage.rs +++ b/crates/stela-runtime/src/hosted/commpage.rs @@ -516,7 +516,7 @@ pub fn watch_calendar() { #[cfg(test)] mod tests { use super::*; - use crate::machine::Chip; + use stela_contracts::Chip; #[test] fn data_page_carries_the_declared_fields() { diff --git a/crates/stela-runtime/src/hosted/hardware.rs b/crates/stela-runtime/src/hosted/hardware.rs index 14d1e3254c..4bc9eea9db 100644 --- a/crates/stela-runtime/src/hosted/hardware.rs +++ b/crates/stela-runtime/src/hosted/hardware.rs @@ -13,8 +13,8 @@ mod availability; pub use availability::DarwinAvailability; use availability::SharedScheduler; -use crate::machine::{Chip, identification, soc}; use anyhow::{Context, Result, bail, ensure}; +use {crate::machine::identification, crate::machine::soc, stela_contracts::Chip}; pub const CPU_TYPE_ARM64: u32 = 0x0100_000c; pub const CPU_SUBTYPE_ARM64E: u32 = 2; diff --git a/crates/stela-runtime/src/hosted/kernel/bsd/codesign.rs b/crates/stela-runtime/src/hosted/kernel/bsd/codesign.rs index 890486ccb3..03f4cff68a 100644 --- a/crates/stela-runtime/src/hosted/kernel/bsd/codesign.rs +++ b/crates/stela-runtime/src/hosted/kernel/bsd/codesign.rs @@ -12,12 +12,12 @@ //! (`cs_process_enforcement`). Page hashes are not validated; the //! signature's trust is the host file system's. use super::{Call, Kernel, Outcome, forward}; -use crate::code_signature; use crate::hosted::darwin::{EFAULT, EINVAL, ENOENT, ERANGE, ESRCH}; use crate::hosted::pe::UserJop; use crate::hosted::{memory, threads::lock}; pub(crate) use crate::hosted_registry::bsd::codesign::CALLS; use anyhow::{Context, Result, bail, ensure}; +use stela_formats::code_signature; const CS_OPS_STATUS: u64 = 0; const CS_OPS_MARKINVALID: u64 = 1; diff --git a/crates/stela-runtime/src/hosted/kernel/bsd/linking.rs b/crates/stela-runtime/src/hosted/kernel/bsd/linking.rs index 98c68856f6..e484eea75f 100644 --- a/crates/stela-runtime/src/hosted/kernel/bsd/linking.rs +++ b/crates/stela-runtime/src/hosted/kernel/bsd/linking.rs @@ -240,7 +240,7 @@ fn sign( location: u64, address_diversity: bool, diversity: u64, - key: pauth::Key, + key: stela_contracts::pauth::Key, ) -> Option { if target == 0 { return Some(0); @@ -297,9 +297,9 @@ fn fix_page( let target = (value & 0x3_ffff_ffff) + link.image; let fixed = if value >> 63 != 0 { let key = if value & 1 << 51 != 0 { - pauth::Key::Da + stela_contracts::pauth::Key::Da } else { - pauth::Key::Ia + stela_contracts::pauth::Key::Ia }; sign( signer, @@ -318,8 +318,8 @@ fn fix_page( let is_bind = value & 1 << 62 != 0; let fixed = if value >> 63 != 0 { let key = match (value >> 49) & 3 { - 0 => Some(pauth::Key::Ia), - 2 => Some(pauth::Key::Da), + 0 => Some(stela_contracts::pauth::Key::Ia), + 2 => Some(stela_contracts::pauth::Key::Da), // The pager signs only with the A keys. _ => None, }; diff --git a/crates/stela-runtime/src/hosted/kernel/bsd/signal/frame.rs b/crates/stela-runtime/src/hosted/kernel/bsd/signal/frame.rs index d789d8c608..6d33be64c7 100644 --- a/crates/stela-runtime/src/hosted/kernel/bsd/signal/frame.rs +++ b/crates/stela-runtime/src/hosted/kernel/bsd/signal/frame.rs @@ -17,8 +17,8 @@ use crate::hosted::darwin::{ blend_discriminator, }; use crate::hosted::kernel::status; -use crate::pauth::{Context, Key}; use anyhow::Result; +use {crate::pauth::Context, stela_contracts::pauth::Key}; /// `user64_siginfo_t`, `struct user_ucontext64` and `mcontext64_t`. pub(super) const SIGINFO_BYTES: usize = 104; diff --git a/crates/stela-runtime/src/hosted/kernel/bsd/signatures.rs b/crates/stela-runtime/src/hosted/kernel/bsd/signatures.rs index 6e68d01883..57c01fff1c 100644 --- a/crates/stela-runtime/src/hosted/kernel/bsd/signatures.rs +++ b/crates/stela-runtime/src/hosted/kernel/bsd/signatures.rs @@ -19,11 +19,11 @@ //! its own Team ID. use super::codesign::{CS_PLATFORM_BINARY, CS_REQUIRE_LV, CS_RUNTIME}; use super::{Call, Kernel, Outcome}; -use crate::code_signature::{self, CodeSignature}; use crate::hosted::darwin::{E2BIG, EBADEXEC, EBADF, EFAULT, EINVAL, ENOENT, ENOTSUP, EPERM}; use crate::hosted::{memory, threads::lock}; pub(crate) use crate::hosted_registry::bsd::signatures::CALLS; use anyhow::Result; +use {stela_formats::code_signature, stela_formats::code_signature::CodeSignature}; const F_ADDSIGS: u64 = 59; const F_ADDFILESIGS: u64 = 61; diff --git a/crates/stela-runtime/src/hosted/kernel/bsd/sysctl.rs b/crates/stela-runtime/src/hosted/kernel/bsd/sysctl.rs index d9562c2c5c..ef800de3b0 100644 --- a/crates/stela-runtime/src/hosted/kernel/bsd/sysctl.rs +++ b/crates/stela-runtime/src/hosted/kernel/bsd/sysctl.rs @@ -94,10 +94,13 @@ pub(crate) struct Release { impl Release { pub(crate) fn read(roots: &[PathBuf]) -> Result { - let path = [OS_CRYPTEX_SYSTEM_VERSION, crate::preboot::SYSTEM_VERSION] - .iter() - .flat_map(|path| roots.iter().map(move |root| root.join(path))) - .find(|path| path.is_file()); + let path = [ + OS_CRYPTEX_SYSTEM_VERSION, + stela_formats::preboot::SYSTEM_VERSION, + ] + .iter() + .flat_map(|path| roots.iter().map(move |root| root.join(path))) + .find(|path| path.is_file()); let Some(path) = path else { return Ok(Self::default()); }; @@ -698,7 +701,7 @@ fn meta(kernel: &mut Kernel, call: &Call, oid: &[i32], request: &Request) -> Res #[cfg(test)] mod tests { use super::*; - use crate::machine::Chip; + use stela_contracts::Chip; /// A synthetic kernel version, as an install records it, and release. const VERSION: &str = "Darwin Kernel Version 1.2.3: synthetic; root:test~1/RELEASE_TEST"; @@ -724,7 +727,7 @@ mod tests { #[test] fn the_release_is_the_guest_systems_version_file() -> Result<()> { let root = tempfile::tempdir()?; - let path = root.path().join(crate::preboot::SYSTEM_VERSION); + let path = root.path().join(stela_formats::preboot::SYSTEM_VERSION); std::fs::create_dir_all(path.parent().unwrap())?; std::fs::write( &path, diff --git a/crates/stela-runtime/src/hosted/kernel/bsd/thread.rs b/crates/stela-runtime/src/hosted/kernel/bsd/thread.rs index 799bb99411..4bed76399d 100644 --- a/crates/stela-runtime/src/hosted/kernel/bsd/thread.rs +++ b/crates/stela-runtime/src/hosted/kernel/bsd/thread.rs @@ -668,7 +668,7 @@ fn set32(bytes: &mut [u8], at: u64, value: u32) { #[cfg(test)] mod tests { use super::*; - use crate::{hosted::hardware::Hardware, machine::Chip}; + use {crate::hosted::hardware::Hardware, stela_contracts::Chip}; #[test] fn parallelism_follows_the_edge_scheduler_over_the_m2() { diff --git a/crates/stela-runtime/src/hosted/kernel/control.rs b/crates/stela-runtime/src/hosted/kernel/control.rs index e4294b50e9..158513bffc 100644 --- a/crates/stela-runtime/src/hosted/kernel/control.rs +++ b/crates/stela-runtime/src/hosted/kernel/control.rs @@ -27,12 +27,12 @@ use crate::hosted::darwin::{ FLAGS_NO_PTRAUTH, PSR64_NZCV_MASK, USER_DIVERSIFIER_MASK, blend_discriminator, user_cpsr, }; use crate::machine::system::Register; -use crate::pauth::{Context, Key}; use anyhow::Result; use std::sync::{ Condvar, Mutex, MutexGuard, atomic::{AtomicBool, AtomicU64, Ordering}, }; +use {crate::pauth::Context, stela_contracts::pauth::Key}; mod exception; pub(crate) use exception::ExceptionState; diff --git a/crates/stela-runtime/src/hosted/kernel/mach/server.rs b/crates/stela-runtime/src/hosted/kernel/mach/server.rs index 8da5f908e8..73e0f57820 100644 --- a/crates/stela-runtime/src/hosted/kernel/mach/server.rs +++ b/crates/stela-runtime/src/hosted/kernel/mach/server.rs @@ -1564,7 +1564,7 @@ fn host_info(hardware: &hardware::Hardware, flavor: u32, count: u32) -> Reply { #[cfg(test)] mod tests { use super::*; - use crate::machine::Chip; + use stela_contracts::Chip; fn words(reply: Reply) -> Vec { let Reply::Success(body) = reply else { diff --git a/crates/stela-runtime/src/hosted/kernel/status.rs b/crates/stela-runtime/src/hosted/kernel/status.rs index a2766206f6..a8288887d8 100644 --- a/crates/stela-runtime/src/hosted/kernel/status.rs +++ b/crates/stela-runtime/src/hosted/kernel/status.rs @@ -8,8 +8,8 @@ //! Without a signer (an arm64 image, or user JOP disabled) the pointers //! pass through unchanged, as `ARM_MACHINE_THREAD_DISABLE_USER_JOP` makes //! the conversions return early. -use crate::pauth::{AuthenticationError, Context, Key}; use anyhow::{Result, bail}; +use {crate::pauth::AuthenticationError, crate::pauth::Context, stela_contracts::pauth::Key}; /// `ptrauth_key_function_pointer`'s discriminator: none. const FUNCTION_POINTER_DISCRIMINATOR: u64 = 0; diff --git a/crates/stela-runtime/src/hosted/pe.rs b/crates/stela-runtime/src/hosted/pe.rs index ffe98b1bf4..1d65b5d48c 100644 --- a/crates/stela-runtime/src/hosted/pe.rs +++ b/crates/stela-runtime/src/hosted/pe.rs @@ -10,14 +10,14 @@ //! clear, so EL0 exceptions reach EL1. use super::hardware::{CPU_SUBTYPE_ARM64E, CPU_SUBTYPE_MASK, Hardware}; use super::tables::{T0SZ, Tables}; -use crate::machine::{ - Chip, Cpu, CpuProfile, - exception::Pstate, - registers::encodings::{DCZID_EL0, ID_AA64PFR1_EL1, ID_AA64SMFR0_EL1}, - soc, - system::Register, -}; use stela_compiler::TargetCpu; +use { + crate::machine::Cpu, crate::machine::CpuProfile, crate::machine::exception::Pstate, + crate::machine::registers::encodings::DCZID_EL0, + crate::machine::registers::encodings::ID_AA64PFR1_EL1, + crate::machine::registers::encodings::ID_AA64SMFR0_EL1, crate::machine::soc, + crate::machine::system::Register, stela_contracts::Chip, +}; /// EL1's vector base. Nothing executes there: the host stops at each entry /// (`Machine::set_breakpoints`) and returns with `return_from_exception`. diff --git a/crates/stela-runtime/src/hosted/shared_region.rs b/crates/stela-runtime/src/hosted/shared_region.rs index caba34f381..376ff26b80 100644 --- a/crates/stela-runtime/src/hosted/shared_region.rs +++ b/crates/stela-runtime/src/hosted/shared_region.rs @@ -428,9 +428,9 @@ fn slide_page( diversity }; let key = if raw & KEY_IS_DATA != 0 { - pauth::Key::Da + stela_contracts::pauth::Key::Da } else { - pauth::Key::Ia + stela_contracts::pauth::Key::Ia }; // A region without pointer authentication (`si_ptrauth` // false: a process whose user JOP is disabled) keeps the @@ -585,7 +585,7 @@ mod tests { let location = base + 24; let expected = signer .sign( - pauth::Key::Da, + stela_contracts::pauth::Key::Da, 0x1_8000_0200 + slide, (location & BLEND_ADDRESS_MASK) | 0x1234 << 48, ) diff --git a/crates/stela-runtime/src/hosted/threads.rs b/crates/stela-runtime/src/hosted/threads.rs index 651d452051..e609399c3c 100644 --- a/crates/stela-runtime/src/hosted/threads.rs +++ b/crates/stela-runtime/src/hosted/threads.rs @@ -31,7 +31,6 @@ use super::{ use crate::hosted::darwin::THREAD_SELF_TRAP; use crate::hosted::unsupported::{self, Failure, Kind}; use crate::machine::engine::RequirementKind; -use crate::machine::{Chip, CpuProfile, Machine, NoDevices, Stop, system::Register}; use anyhow::{Context as _, Result, anyhow, bail}; use std::{ collections::BTreeMap, @@ -42,6 +41,10 @@ use std::{ }, }; use stela_compiler::TargetCpu; +use { + crate::machine::CpuProfile, crate::machine::Machine, crate::machine::NoDevices, + crate::machine::Stop, crate::machine::system::Register, stela_contracts::Chip, +}; #[cfg(feature = "native-profile")] mod profile_output; diff --git a/crates/stela-runtime/src/lib.rs b/crates/stela-runtime/src/lib.rs index b118a88a5d..90395a6f03 100644 --- a/crates/stela-runtime/src/lib.rs +++ b/crates/stela-runtime/src/lib.rs @@ -10,36 +10,26 @@ compile_error!( "freestanding runtime requires aborting panic; platform must terminate the machine on panic" ); pub mod amx; -pub mod apfs; pub mod blocks; -pub mod boot_bundle; -pub mod builds; mod checksum; pub mod clock; -#[cfg(feature = "std")] -pub mod code_signature; pub mod commpage; pub mod darwin; #[cfg(feature = "std")] pub mod dispatch; pub mod execution; mod floating; -mod hash; #[cfg(all(feature = "std", target_os = "macos", target_arch = "x86_64"))] pub mod hosted; #[cfg(feature = "std")] pub mod hosted_registry; -pub mod img4; #[cfg(feature = "std")] mod json; -pub mod lzfse; pub mod mach; pub mod machine; pub mod memory; pub mod pauth; -pub mod payload; mod platform; -pub mod preboot; pub mod restore; /// Stela's own IPv4 client stack over any raw Ethernet link. pub use platform::net; @@ -60,7 +50,6 @@ pub mod translations; #[cfg(feature = "std")] use anyhow::ensure; use anyhow::{Context, Result}; -pub use hash::sha256; #[cfg(feature = "std")] pub use json::{read_json, write_json}; use serde::Serialize; @@ -71,6 +60,7 @@ use std::path::{Path, PathBuf}; use stela_compiler::GuestAddress; #[cfg(feature = "std")] use stela_compiler::NativeBlock; +use stela_formats::sha256; fn compiler_source_sha256() -> &'static str { stela_compiler::SOURCE_SHA256 diff --git a/crates/stela-runtime/src/machine.rs b/crates/stela-runtime/src/machine.rs index 05649956cf..dc25d479c8 100644 --- a/crates/stela-runtime/src/machine.rs +++ b/crates/stela-runtime/src/machine.rs @@ -3,12 +3,10 @@ //! and System registers implemented here and the x86 mechanisms supplied by a //! [`Host`]. //! The design is in `docs/design/system.md#system-mode-execution`. -pub mod adt; pub mod amu; pub mod amx; pub mod apple; -pub mod caches; -pub mod chip; +mod capabilities; pub mod cpu; pub mod ctrr; pub mod debug; @@ -31,9 +29,9 @@ pub mod tags; pub mod timer; pub mod vgic; -pub use chip::Chip; -#[cfg(test)] -pub(crate) use chip::test_chip; +use stela_contracts::Chip; +use stela_contracts::caches; +pub mod cram; pub use cpu::{Cpu, Exception}; #[cfg(test)] pub(crate) use engine::test_preparation; @@ -43,4 +41,6 @@ pub use engine::{ Prepared, Refused, Regime, Requirement, RequirementKind, Reset, StaleCode, Statistics, Stop, Transition, Translations, window, }; -pub use registers::{CpuProfile, Identity, Lines}; +pub use registers::{CpuProfile, Lines}; +#[cfg(test)] +pub(crate) use stela_contracts::chip::test_chip; diff --git a/crates/stela-runtime/src/machine/apple.rs b/crates/stela-runtime/src/machine/apple.rs index 3811304fb3..513b8daa51 100644 --- a/crates/stela-runtime/src/machine/apple.rs +++ b/crates/stela-runtime/src/machine/apple.rs @@ -11,58 +11,6 @@ use super::{ soc::PowerOwner, }; pub use crate::platform::apple::pmu::{RtcEpoch, WallClock}; -use crate::platform::apple::{ - aes::{self, Aes}, - agx::{ - firmware::Coprocessor as GfxCoprocessor, - sgx::Sgx, - uat::{self, Agent}, - }, - aic::{Aic2, Aic2Config}, - aic1::Aic1, - amcc::{self, Amcc}, - ans::{self, Ans}, - asc::{self, Asc}, - atc_phy::{self, AtcPhy}, - bridge::Bridge, - bus::{Access, Bus, DeviceId, LifecycleState, MapError, MmioDevice, MmioError, Width}, - cluster::{self, Cluster}, - core_counters::{self, CoreCounters}, - coresight::{self, PcSampler, SoftwareLock}, - cpm::Cpm, - cpustart::{self, CpuStart}, - dart::{self, Dart}, - dcp, display as display_hw, - dpe::Dpe, - dwc3::{self, Dwc3, PortState}, - energy::{self, Energy}, - fuse::{self, AonFuses}, - gpio::{Gpio, Net, OpenDrain}, - hpm::{Firmware, Hpm, Summary}, - i2c::{self, I2c}, - interrupt::{CpuIndex, InterruptLatch}, - ipi::{self, Affinity, FastIpi}, - lockdown::{self, Lockdown}, - perf::PerfCounters, - pmgr::{ - ACTIVE, DomainState, POWER_GATED, Pmgr, PowerState, - coverage::{self, Consumer, LifecycleSinks}, - }, - pmp, - pmu::{self, Pmu}, - power::{self, Power}, - ptd, - rtkit::RtKit, - sart::{self, Sart}, - sep::{self, Sep}, - smc::{self, Smc}, - spi::Spi, - spmi::{self, Spmi}, - uart::S5lUart, - wake::{self, WakeMasks}, - wdt::{self, AppleWdt}, -}; -use crate::platform::dma::{Physical, Port}; use crate::platform::usb::{ Function, Speed, ecm::Ecm, @@ -81,6 +29,54 @@ use crate::system::access::{AccessKind, Encoding}; use alloc::{boxed::Box, format, string::String, vec, vec::Vec}; use core::cell::Cell; use stela_drivers::{block::BlockDevice, input::Input, net::Mac}; +use { + crate::platform::apple::aes, crate::platform::apple::aes::Aes, + crate::platform::apple::agx::firmware::Coprocessor as GfxCoprocessor, + crate::platform::apple::agx::sgx::Sgx, crate::platform::apple::agx::uat, + crate::platform::apple::agx::uat::Agent, crate::platform::apple::aic::Aic2, + crate::platform::apple::aic::Aic2Config, crate::platform::apple::aic1::Aic1, + crate::platform::apple::amcc, crate::platform::apple::amcc::Amcc, crate::platform::apple::ans, + crate::platform::apple::ans::Ans, crate::platform::apple::asc, + crate::platform::apple::asc::Asc, crate::platform::apple::atc_phy, + crate::platform::apple::atc_phy::AtcPhy, crate::platform::apple::bridge::Bridge, + crate::platform::apple::cluster, crate::platform::apple::cluster::Cluster, + crate::platform::apple::core_counters, crate::platform::apple::core_counters::CoreCounters, + crate::platform::apple::coresight, crate::platform::apple::coresight::PcSampler, + crate::platform::apple::coresight::SoftwareLock, crate::platform::apple::cpm::Cpm, + crate::platform::apple::cpustart, crate::platform::apple::cpustart::CpuStart, + crate::platform::apple::dart, crate::platform::apple::dart::Dart, crate::platform::apple::dcp, + crate::platform::apple::display as display_hw, crate::platform::apple::dpe::Dpe, + crate::platform::apple::dwc3, crate::platform::apple::dwc3::Dwc3, + crate::platform::apple::dwc3::PortState, crate::platform::apple::energy, + crate::platform::apple::energy::Energy, crate::platform::apple::fuse, + crate::platform::apple::fuse::AonFuses, crate::platform::apple::gpio::Gpio, + crate::platform::apple::gpio::Net, crate::platform::apple::gpio::OpenDrain, + crate::platform::apple::hpm::Firmware, crate::platform::apple::hpm::Hpm, + crate::platform::apple::hpm::Summary, crate::platform::apple::i2c, + crate::platform::apple::i2c::I2c, crate::platform::apple::ipi, + crate::platform::apple::ipi::Affinity, crate::platform::apple::ipi::FastIpi, + crate::platform::apple::lockdown, crate::platform::apple::lockdown::Lockdown, + crate::platform::apple::perf::PerfCounters, crate::platform::apple::pmgr::ACTIVE, + crate::platform::apple::pmgr::DomainState, crate::platform::apple::pmgr::POWER_GATED, + crate::platform::apple::pmgr::Pmgr, crate::platform::apple::pmgr::PowerState, + crate::platform::apple::pmgr::coverage, crate::platform::apple::pmgr::coverage::Consumer, + crate::platform::apple::pmgr::coverage::LifecycleSinks, crate::platform::apple::pmp, + crate::platform::apple::pmu, crate::platform::apple::pmu::Pmu, crate::platform::apple::power, + crate::platform::apple::power::Power, crate::platform::apple::ptd, + crate::platform::apple::rtkit::RtKit, crate::platform::apple::sart, + crate::platform::apple::sart::Sart, crate::platform::apple::sep, + crate::platform::apple::sep::Sep, crate::platform::apple::smc, + crate::platform::apple::smc::Smc, crate::platform::apple::spi::Spi, + crate::platform::apple::spmi, crate::platform::apple::spmi::Spmi, + crate::platform::apple::uart::S5lUart, crate::platform::apple::wake, + crate::platform::apple::wake::WakeMasks, crate::platform::apple::wdt, + crate::platform::apple::wdt::AppleWdt, stela_contracts::bus::Access, stela_contracts::bus::Bus, + stela_contracts::bus::DeviceId, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MapError, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::interrupt::CpuIndex, stela_contracts::interrupt::InterruptLatch, +}; +use {stela_contracts::dma::Physical, stela_contracts::dma::Port}; mod canonical_reads; mod canonical_writes; @@ -97,27 +93,26 @@ pub use service::{AicDelivery, ServiceBatch, ServiceInput}; pub use sleep::PowerLog; pub use t8112_memory::cold as t8112_cold; -pub use crate::platform::apple::{ - aic::{AIC2_IRQ_CFG, AIC3_IRQ_CFG, AicLayout}, - aic1::AIC1_EVENT, - asc::Lines as AscLines, - dart::Profile as DartProfile, - dcp::Log as DisplayLog, - interrupt::AicInput, - nor, - pmp::native::{self as native_pmp, services::Clock as NativePmpClock}, - scanout::{ - ChannelMasks as ScanoutMasks, Mode as ScanoutMode, PixelFormat as ScanoutFormat, Scanout, - }, - sep::Entropy as SepEntropy, - sep::image::signature::{ - Evidence as SepSignatureEvidence, ManifestEvidence as SepManifestEvidence, - inspect as inspect_sep_signature, verify_manifest as verify_sep_manifest_signature, - }, - sep::state as sep_state, - smc::WriteLog as SmcWriteLog, - typec, - uart::{ConsoleBusy, ConsoleSink}, +pub use { + crate::platform::apple::aic::AIC2_IRQ_CFG, crate::platform::apple::aic::AIC3_IRQ_CFG, + crate::platform::apple::aic::AicLayout, crate::platform::apple::aic1::AIC1_EVENT, + crate::platform::apple::asc::Lines as AscLines, + crate::platform::apple::dart::Profile as DartProfile, + crate::platform::apple::dcp::Log as DisplayLog, crate::platform::apple::nor, + crate::platform::apple::pmp::native as native_pmp, + crate::platform::apple::pmp::native::services::Clock as NativePmpClock, + crate::platform::apple::scanout::ChannelMasks as ScanoutMasks, + crate::platform::apple::scanout::Mode as ScanoutMode, + crate::platform::apple::scanout::PixelFormat as ScanoutFormat, + crate::platform::apple::scanout::Scanout, crate::platform::apple::sep::Entropy as SepEntropy, + crate::platform::apple::sep::image::signature::Evidence as SepSignatureEvidence, + crate::platform::apple::sep::image::signature::ManifestEvidence as SepManifestEvidence, + crate::platform::apple::sep::image::signature::inspect as inspect_sep_signature, + crate::platform::apple::sep::image::signature::verify_manifest as verify_sep_manifest_signature, + crate::platform::apple::sep::state as sep_state, + crate::platform::apple::smc::WriteLog as SmcWriteLog, crate::platform::apple::typec, + crate::platform::apple::uart::ConsoleBusy, crate::platform::apple::uart::ConsoleSink, + stela_contracts::interrupt::AicInput, }; /// One guest physical range of a device: DeviceTree `reg` translated @@ -478,7 +473,7 @@ impl Default for AppleDevices { impl AppleDevices { #[cfg(feature = "native-profile")] - pub fn advance_statistics(&self) -> crate::platform::apple::bus::AdvanceStatistics { + pub fn advance_statistics(&self) -> stela_contracts::bus::AdvanceStatistics { self.bus.advance_statistics() } @@ -1017,7 +1012,7 @@ impl AppleDevices { &mut self, placement: &super::soc::AnsController, backing: Box, - build: &crate::builds::Build, + build: &stela_formats::builds::Build, ) -> Result<(), String> { let irq = |n| AicInput::new(0, n); let rtkit = RtKit::new( @@ -1107,7 +1102,7 @@ impl AppleDevices { pub fn add_smc( &mut self, placement: &super::soc::SmcController, - build: &crate::builds::Build, + build: &stela_formats::builds::Build, ) -> Result<(), String> { let sram = smc::Sram::default(); let keys = placement @@ -1155,7 +1150,7 @@ impl AppleDevices { pub fn add_pmp( &mut self, placement: &super::soc::PmpController, - build: &crate::builds::Build, + build: &stela_formats::builds::Build, ) -> Result<(), String> { let mut rtkit = RtKit::new( vec![(pmp::ENDPOINT, Box::new(pmp::Pmp::default()))], @@ -1185,7 +1180,7 @@ impl AppleDevices { pub fn add_gfx( &mut self, placement: &super::soc::GfxController, - build: &crate::builds::Build, + build: &stela_formats::builds::Build, ) -> Result<(), String> { let sgx_physical = placement .sgx @@ -1261,7 +1256,7 @@ impl AppleDevices { (dart, stream): (DartId, usize), window: Option, surface: Option<(DartId, usize)>, - build: &crate::builds::Build, + build: &stela_formats::builds::Build, ) -> Result<(), String> { if wrapper.bytes < asc::WRAPPER_BYTES { return Err("DCPEXT register aperture is incomplete".into()); @@ -3604,12 +3599,12 @@ mod tests { }, } } - use crate::platform::{ - apple::bus::MmioDevice, - dma::{Iommu, tests::Ram}, - }; use alloc::{rc::Rc, vec::Vec}; use core::cell::RefCell; + use { + stela_contracts::bus::MmioDevice, stela_contracts::dma::Iommu, + stela_contracts::dma::test_support::Ram, + }; #[test] fn a_board_entry_given_an_earlier_count_is_named_in_the_stop_reason() { @@ -3623,7 +3618,10 @@ mod tests { #[test] fn native_dart_mounts_program_the_selected_register_bank_and_transfer_real_dma_bytes() { - use crate::platform::dma::{Memory as _, Port, tests::Ram}; + use { + stela_contracts::dma::Memory as _, stela_contracts::dma::Port, + stela_contracts::dma::test_support::Ram, + }; const ROOT: u64 = 0x8_0000_0000; const PAGE: u64 = 0x4000; for profile in [ @@ -4075,7 +4073,7 @@ mod tests { reject: bool, committed: Vec, } - impl crate::platform::apple::bus::Lifecycle for CheckedPowerBank { + impl stela_contracts::bus::Lifecycle for CheckedPowerBank { fn check_lifecycle(&self, state: LifecycleState) -> Result<(), &'static str> { if self.reject && (!state.powered || state.reset) { Err("native bank destructive transition remains unqualified") @@ -4088,7 +4086,7 @@ mod tests { } } impl MmioDevice for CheckedPowerBank { - fn lifecycle(&mut self) -> Option<&mut dyn crate::platform::apple::bus::Lifecycle> { + fn lifecycle(&mut self) -> Option<&mut dyn stela_contracts::bus::Lifecycle> { Some(self) } fn name(&self) -> &'static str { @@ -4337,7 +4335,7 @@ mod tests { #[test] fn mounted_t6000_groups_preserve_each_fault_on_the_same_physical_wire() { - use crate::platform::apple::interrupt::Wire; + use stela_contracts::interrupt::Wire; let mut d = AppleDevices::new(); let input = AicInput::new(0, 873); d.add_aic(0x2_3b0c_0000, 1152, AicLayout::aic2(0x8000, 16)) @@ -4736,7 +4734,7 @@ mod tests { #[test] fn pmgr_accepted_edges_survive_a_later_wire_delivery_failure() { - use crate::platform::apple::interrupt::{InterruptSink, Wire}; + use {stela_contracts::interrupt::InterruptSink, stela_contracts::interrupt::Wire}; let (mut d, _, supply, base) = powered_dart(false, 1); d.write(0, base + 0x1000, 4, 1, 0).unwrap(); d.latch.set_level(Wire::Aic(AicInput::new(0, 1)), true); @@ -4973,7 +4971,7 @@ mod tests { fn ans_dma_and_sart_idle_share_the_nvme_aperture_without_aliasing() { use crate::machine::soc::AnsController; use crate::platform::apple::{ans, sart}; - use crate::platform::dma::tests::Ram; + use stela_contracts::dma::test_support::Ram; use stela_drivers::block::RamDisk; const NVME: u64 = 0x2_7bcc_0000; const SART: u64 = 0x2_7bc5_0000; @@ -5015,7 +5013,7 @@ mod tests { .add_ans( &placement, Box::new(RamDisk::new("backing", 16, 4096)), - crate::builds::DEFAULT, + stela_formats::builds::DEFAULT, ) .unwrap(); assert_eq!(devices.power_devices.len(), 4); @@ -5206,7 +5204,7 @@ mod tests { quiesced: false, mapper: None, }, - crate::builds::DEFAULT, + stela_formats::builds::DEFAULT, ) .unwrap(); assert_eq!(devices.power_devices.len(), 2); @@ -5250,7 +5248,7 @@ mod tests { })); devices.bus.map(foreign, base, bytes, 0).unwrap(); assert_eq!( - devices.add_gfx(&placement, crate::builds::DEFAULT), + devices.add_gfx(&placement, stela_formats::builds::DEFAULT), Err("GFX native ASC control is not wholly owned by its mounted SGX bank".into()) ); assert!(devices.gfx_masters.is_empty()); @@ -5287,7 +5285,9 @@ mod tests { shared_l2: 0x100_0000_8000, }; let mut devices = AppleDevices::new(); - devices.add_gfx(&placement, crate::builds::DEFAULT).unwrap(); + devices + .add_gfx(&placement, stela_formats::builds::DEFAULT) + .unwrap(); let (asc, block) = devices.gfx_masters[0]; assert_eq!( devices.bus.route(WRAPPER + 0x8110, Width::Word), @@ -5313,7 +5313,7 @@ mod tests { fn gfx_firmware_reads_its_initdata_through_the_uat_the_sgx_mmu_roots() { use crate::machine::soc::GfxController; use crate::platform::apple::agx::{firmware, generation, uat as table}; - use crate::platform::dma::tests::Ram; + use stela_contracts::dma::test_support::Ram; const WRAPPER: u64 = 0x2_0640_0000; const SGX: u64 = 0x2_0400_0000; const RAM: u64 = 0x8_0000_0000; @@ -5330,7 +5330,9 @@ mod tests { devices .add_aic(0x2_3b0c_0000, 1152, AicLayout::aic2(0x8000, 0)) .unwrap(); - devices.add_gfx(&placement, crate::builds::DEFAULT).unwrap(); + devices + .add_gfx(&placement, stela_formats::builds::DEFAULT) + .unwrap(); assert_eq!(devices.power_devices.len(), 3); assert_eq!(devices.power_devices[1].physical, WRAPPER); assert_eq!(devices.power_devices[2].physical, SGX); @@ -5466,7 +5468,9 @@ mod tests { .add_aic(0x2_3b0c_0000, 1152, AicLayout::aic2(0x8000, 0)) .unwrap(); assert!(devices.power_button(true).is_err()); - devices.add_smc(&placement, crate::builds::DEFAULT).unwrap(); + devices + .add_smc(&placement, stela_formats::builds::DEFAULT) + .unwrap(); // The press waits in the key endpoint until the AP enables // notifications. devices.power_button(true).unwrap(); @@ -5592,7 +5596,7 @@ mod tests { (dart, input), None, None, - crate::builds::DEFAULT + stela_formats::builds::DEFAULT ) .unwrap_err() .contains("DART") @@ -5653,7 +5657,7 @@ mod tests { (owner, 1), None, Some((owner, 2)), - crate::builds::DEFAULT + stela_formats::builds::DEFAULT ) .unwrap_err() .contains("DCP surface") @@ -5793,7 +5797,7 @@ mod tests { (dart, 5), Some(RAM), Some((dart, 5)), - crate::builds::DEFAULT, + stela_formats::builds::DEFAULT, ) .unwrap(); connect_native_power(&mut d, SUPPLY, &[("/arm-io/dcpext", WRAPPER)], true); @@ -5903,7 +5907,7 @@ mod tests { (dart, 5), Some(0x8_0000_0000), None, - crate::builds::DEFAULT, + stela_formats::builds::DEFAULT, ) .unwrap(); devices @@ -6397,7 +6401,7 @@ mod tests { /// DART stream: here a bypassed one, ECB with the FIPS-197 C.1 key. #[test] fn aes_writes_move_data_through_the_dart_stream() { - use crate::platform::dma::tests::Ram; + use stela_contracts::dma::test_support::Ram; const DART: u64 = 0x2_3500_4000; const AES: u64 = 0x2_3500_c000; const RAM: u64 = 0x8_0000_0000; @@ -6626,7 +6630,7 @@ mod tests { reply }; let mut ram = Ram::new(RAM, 0x8000); - let image = crate::img4::tests::im4p(b"sepi", b"stela-sepos"); + let image = stela_formats::img4::test_support::im4p(b"sepi", b"stela-sepos"); ram.bytes[..image.len()].copy_from_slice(&image); assert_eq!(send(&mut d, &mut ram, 5, 0).opcode, 105); assert_eq!(send(&mut d, &mut ram, 6, (RAM >> 12) as u32).opcode, 106); @@ -6635,9 +6639,9 @@ mod tests { #[test] fn sep_rom_accepts_firmware_under_stela_policy_and_reaches_os_active() { - use crate::platform::{ - apple::sep::message::{self, Frame, ROM}, - dma::tests::Ram, + use { + crate::platform::apple::sep::message, crate::platform::apple::sep::message::Frame, + crate::platform::apple::sep::message::ROM, stela_contracts::dma::test_support::Ram, }; const DART: u64 = 0x25d2c0000; const SEP: u64 = 0x25e400000; @@ -6708,7 +6712,7 @@ mod tests { // The real IPSW SEP payload is a bare encrypted `sepi`; Stela accepts // it under its own policy and boots its native sepOS. - let image = crate::img4::tests::im4p(b"sepi", b"stela-sepos"); + let image = stela_formats::img4::test_support::im4p(b"sepi", b"stela-sepos"); let mut devices = board(); let mut ram = Ram::new(RAM, 0x8000); ram.bytes[..image.len()].copy_from_slice(&image); @@ -7335,7 +7339,7 @@ mod tests { }; devices.set_connection(1, Some(host)).unwrap(); assert_eq!(devices.dma_deadline(), Some(0)); - let mut ram = crate::platform::dma::tests::Ram::new(0x800000000, 0x10000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x800000000, 0x10000); devices.transfer(0, &mut ram, 0).unwrap(); assert_eq!(devices.dma_deadline(), Some(USB_POLL_TICKS)); assert!(devices.usb_client(id).unwrap().open(62078).is_err()); diff --git a/crates/stela-runtime/src/machine/apple/canonical_reads.rs b/crates/stela-runtime/src/machine/apple/canonical_reads.rs index c8a29ed06c..1080e7819a 100644 --- a/crates/stela-runtime/src/machine/apple/canonical_reads.rs +++ b/crates/stela-runtime/src/machine/apple/canonical_reads.rs @@ -82,9 +82,9 @@ impl AppleDevices { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::Wire; use alloc::rc::Rc; use core::cell::Cell; + use stela_contracts::interrupt::Wire; struct Reader(Rc>, bool); impl MmioDevice for Reader { @@ -105,11 +105,11 @@ mod tests { .set_level(Wire::Aic(AicInput::new(0, 1)), true); if self.1 { access.request_reset(self.name(), "reached read before refusal"); - return Err(crate::platform::apple::bus::refuse( + return Err(stela_contracts::bus::refuse( self.name(), offset, width, - crate::platform::apple::bus::Direction::Read, + stela_contracts::bus::Direction::Read, "retained read prefix", )); } @@ -122,11 +122,11 @@ mod tests { _value: u64, _access: &mut Access<'_>, ) -> Result<(), MmioError> { - Err(crate::platform::apple::bus::refuse( + Err(stela_contracts::bus::refuse( self.name(), offset, width, - crate::platform::apple::bus::Direction::Write, + stela_contracts::bus::Direction::Write, "read-only consuming test register", )) } diff --git a/crates/stela-runtime/src/machine/apple/canonical_writes.rs b/crates/stela-runtime/src/machine/apple/canonical_writes.rs index 01e76a45cc..6eefec1949 100644 --- a/crates/stela-runtime/src/machine/apple/canonical_writes.rs +++ b/crates/stela-runtime/src/machine/apple/canonical_writes.rs @@ -121,9 +121,9 @@ impl AppleDevices { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::Wire; use alloc::rc::Rc; use core::cell::Cell; + use stela_contracts::interrupt::Wire; struct Writer { count: Rc>, @@ -139,11 +139,11 @@ mod tests { width: Width, _: &mut Access<'_>, ) -> Result { - Err(crate::platform::apple::bus::refuse( + Err(stela_contracts::bus::refuse( self.name(), offset, width, - crate::platform::apple::bus::Direction::Read, + stela_contracts::bus::Direction::Read, "write-only test register", )) } @@ -160,11 +160,11 @@ mod tests { access .interrupts .set_level(Wire::Aic(AicInput::new(0, 1)), true); - return Err(crate::platform::apple::bus::refuse( + return Err(stela_contracts::bus::refuse( self.name(), offset, width, - crate::platform::apple::bus::Direction::Write, + stela_contracts::bus::Direction::Write, "retained peripheral prefix", )); } diff --git a/crates/stela-runtime/src/machine/apple/display_resources.rs b/crates/stela-runtime/src/machine/apple/display_resources.rs index f833b4394b..c9411a8399 100644 --- a/crates/stela-runtime/src/machine/apple/display_resources.rs +++ b/crates/stela-runtime/src/machine/apple/display_resources.rs @@ -53,7 +53,7 @@ impl AppleDevices { // The PMGR/AP full PTD bank and display's update view name the same // physical resource. Only the actual prepared owner can supply this // subview; a bare overlap or matching name never qualifies it. - let mut shared: Vec = Vec::new(); + let mut shared: Vec = Vec::new(); if let Some(device) = self.memory_publication.or(self.memory_controller) && let Some(owner) = memory_resources::resource_for(&self.bus, device) { @@ -192,7 +192,7 @@ mod tests { (owners[1], 5), None, Some((owners[0], 0)), - crate::builds::DEFAULT, + stela_formats::builds::DEFAULT, ) .unwrap(); let views = [ @@ -289,15 +289,14 @@ mod tests { assert!(devices.bus.route(PRIMARY, Width::Word).is_err()); assert!(devices.bus.route(SHARED, Width::Word).is_err()); } - use crate::{ - machine::soc::{DirectMemoryCache, MemoryController, PtdBank}, - platform::apple::{ - amcc::{Layout, LockGroup, Register}, - bus::{Lifecycle, LifecycleState, MmioError}, - interrupt::InterruptLatch, - mcc::{self, Configuration}, - ptd, - }, + use { + crate::machine::soc::DirectMemoryCache, crate::machine::soc::MemoryController, + crate::machine::soc::PtdBank, crate::platform::apple::amcc::Layout, + crate::platform::apple::amcc::LockGroup, crate::platform::apple::amcc::Register, + crate::platform::apple::mcc, crate::platform::apple::mcc::Configuration, + crate::platform::apple::ptd, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioError, + stela_contracts::interrupt::InterruptLatch, }; fn prepared() -> memory_resources::Prepared { let reg = |offset, mask, value| Register { @@ -639,12 +638,12 @@ mod tests { #[test] #[ignore = "requires unchanged original 26A434 J314s DeviceTree"] fn original_j314s_display_ptd_view_is_the_actual_pmgr_pmp_update_bank() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let input = std::env::var("STELA_T6000_MCC_DEVICE_TREE").expect("explicit original ADT input"); let bytes = std::fs::read(&input).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let io = Node::root(&bytes).unwrap().child("arm-io").unwrap(); diff --git a/crates/stela-runtime/src/machine/apple/memory_resources.rs b/crates/stela-runtime/src/machine/apple/memory_resources.rs index 3b1d6c90d7..aa8beab181 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources.rs @@ -1,20 +1,23 @@ //! Prepared direct MCC/AMCC/PTD resources. No native RAM/DSB authority is //! manufactured here and no engine mount is enabled by constructing this object. -use crate::{ - machine::soc::{DirectMemoryCache, MemoryController}, - platform::apple::{ - amcc::{Amcc, Layout, Register}, - bus::{Access, Direction, Lifecycle, MmioDevice, MmioError, Width, refuse}, - interrupt::Wire, - mcc::{Configuration, Controller}, - ptd::{Ptd, transport::notifications::LocalNotifications}, - }, -}; use alloc::vec::Vec; +use { + crate::machine::soc::DirectMemoryCache, crate::machine::soc::MemoryController, + crate::platform::apple::amcc::Amcc, crate::platform::apple::amcc::Layout, + crate::platform::apple::amcc::Register, crate::platform::apple::mcc::Configuration, + crate::platform::apple::mcc::Controller, crate::platform::apple::ptd::Ptd, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, stela_contracts::interrupt::Wire, +}; // The mount configures these actual resources; it must be able to name their // typed configuration, lifecycle and original register/publication geometry. -pub use crate::platform::apple::{amcc, bus::LifecycleState, mcc, ptd}; +pub use { + crate::platform::apple::amcc, crate::platform::apple::mcc, crate::platform::apple::ptd, + stela_contracts::bus::LifecycleState, +}; mod canonical; pub mod dcs; @@ -466,13 +469,12 @@ impl MmioDevice for Router { #[cfg(test)] mod tests { use super::*; - use crate::{ - machine::soc::PtdBank, - platform::apple::{ - amcc::LockGroup, bus::Bus, interrupt::InterruptLatch, mcc::RequestKind, ptd, - }, - }; use alloc::{boxed::Box, vec}; + use { + crate::machine::soc::PtdBank, crate::platform::apple::amcc::LockGroup, + crate::platform::apple::mcc::RequestKind, crate::platform::apple::ptd, + stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch, + }; pub(super) fn prepared() -> Prepared { let reg = |offset, mask, value| Register { @@ -825,9 +827,9 @@ mod tests { #[test] fn paired_read_keeps_data_and_pending_service_after_wire_forwarding_refusal() { - use crate::{ - machine::Devices, - platform::apple::interrupt::{AicInput, InterruptSink}, + use { + crate::machine::Devices, stela_contracts::interrupt::AicInput, + stela_contracts::interrupt::InterruptSink, }; let owner = prepared(); let publication = owner.publication_bank().clone(); diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/canonical.rs b/crates/stela-runtime/src/machine/apple/memory_resources/canonical.rs index 2cc23e932a..43beb5b22c 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/canonical.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/canonical.rs @@ -135,11 +135,11 @@ impl Prepared { #[cfg(test)] mod tests { use super::*; - use crate::{ - memory::{ReservedSystemRamRange, system_ram::fixture}, - platform::apple::interrupt::InterruptLatch, - }; use core::{cell::UnsafeCell, ptr::NonNull}; + use { + crate::memory::ReservedSystemRamRange, crate::memory::system_ram::fixture, + stela_contracts::interrupt::InterruptLatch, + }; #[repr(C, align(16))] struct Storage(UnsafeCell<[u8; 128]>); diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/dcs.rs b/crates/stela-runtime/src/machine/apple/memory_resources/dcs.rs index 680da19f1c..6562074723 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/dcs.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/dcs.rs @@ -1,14 +1,16 @@ //! Canonical RAM service join for the actual T8112 DCS channel owner. //! This component is composed into the prepared memory resource; it does not //! create another AMCC/PTD owner or qualify missing PMP service producers. -use crate::{ - memory::{CanonicalRamService, RegisteredSystemRam}, - platform::apple::{ - bus::{Access, Lifecycle, LifecycleState, MmioDevice, MmioError, Width}, - dcs::native::{CHANNELS, ChannelConfiguration, ChannelProgress, Controller}, - }, -}; use alloc::{sync::Arc, vec::Vec}; +use { + crate::memory::CanonicalRamService, crate::memory::RegisteredSystemRam, + crate::platform::apple::dcs::native::CHANNELS, + crate::platform::apple::dcs::native::ChannelConfiguration, + crate::platform::apple::dcs::native::ChannelProgress, + crate::platform::apple::dcs::native::Controller, stela_contracts::bus::Access, + stela_contracts::bus::Lifecycle, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, +}; /// Exact channel backing and canonical guest RAM association. Clones retain /// the same controller, lifecycle, pending effects and actual memory identity. @@ -128,11 +130,11 @@ mod tests { const GATING: u64 = 0x18; const REFRESH: u64 = 0x41c; const DRAIN: u64 = 0xa40; - use crate::{ - memory::{ReservedSystemRamRange, system_ram::fixture}, - platform::apple::interrupt::InterruptLatch, - }; use core::{cell::UnsafeCell, ptr::NonNull}; + use { + crate::memory::ReservedSystemRamRange, crate::memory::system_ram::fixture, + stela_contracts::interrupt::InterruptLatch, + }; const LIVE: LifecycleState = LifecycleState { powered: true, diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/resource.rs b/crates/stela-runtime/src/machine/apple/memory_resources/resource.rs index 4ec5fd1de1..bbb4356325 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/resource.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/resource.rs @@ -1,8 +1,8 @@ //! Borrowed dispatch to the actual placed memory resource, never copied state. use super::{Prepared, amcc, t6020, t8112}; -use crate::{ - memory::CanonicalRamService, - platform::apple::bus::{Access, Bus, DeviceId, Width}, +use { + crate::memory::CanonicalRamService, stela_contracts::bus::Access, stela_contracts::bus::Bus, + stela_contracts::bus::DeviceId, stela_contracts::bus::Width, }; pub(in crate::machine::apple) enum Resource<'a> { diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/t6000_cold.rs b/crates/stela-runtime/src/machine/apple/memory_resources/t6000_cold.rs index 57dee7c511..e73a667e63 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/t6000_cold.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/t6000_cold.rs @@ -10,22 +10,17 @@ //! reset, capacity, timing or completed DRAM programming. Source cacheless //! disable_mcc command/waiter evidence is retained in t6000-mcc-backend-20261021-1. use super::{Prepared, amcc, mcc, ptd}; -use crate::{ - machine::{ - Chip, - apple::AppleDevices, - soc::{Board, DirectMemoryCache, MemoryController, PowerOwner, PowerStates}, - }, - memory::RegisteredSystemRam, - platform::apple::{ - bus::{LifecycleState, Width}, - pmgr::{ - self, Pmgr, - coverage::{self, Consumer, LifecycleSinks}, - }, - }, -}; use alloc::{format, string::String, sync::Arc, vec, vec::Vec}; +use { + crate::machine::apple::AppleDevices, crate::machine::soc::Board, + crate::machine::soc::DirectMemoryCache, crate::machine::soc::MemoryController, + crate::machine::soc::PowerOwner, crate::machine::soc::PowerStates, + crate::memory::RegisteredSystemRam, crate::platform::apple::pmgr, + crate::platform::apple::pmgr::Pmgr, crate::platform::apple::pmgr::coverage, + crate::platform::apple::pmgr::coverage::Consumer, + crate::platform::apple::pmgr::coverage::LifecycleSinks, stela_contracts::Chip, + stela_contracts::bus::LifecycleState, stela_contracts::bus::Width, +}; /// Entire new-software control image, independent of RAM capacity and opaque /// DT config-data/alternate dramcfg-data. Every weight is an explicit policy. @@ -451,20 +446,17 @@ fn geometry( #[cfg(test)] mod tests { use super::*; - use crate::{ - machine::soc::{ClockRole, PowerResource}, - memory::{ReservedSystemRamRange, system_ram::fixture}, - platform::apple::{ - bus::Access, - interrupt::InterruptLatch, - pmgr::{ - PowerState, - coverage::{Admission, Domain, DomainId}, - }, - }, - }; use alloc::{boxed::Box, vec}; use core::{cell::UnsafeCell, ptr::NonNull}; + use { + crate::machine::soc::ClockRole, crate::machine::soc::PowerResource, + crate::memory::ReservedSystemRamRange, crate::memory::system_ram::fixture, + crate::platform::apple::pmgr::PowerState, + crate::platform::apple::pmgr::coverage::Admission, + crate::platform::apple::pmgr::coverage::Domain, + crate::platform::apple::pmgr::coverage::DomainId, stela_contracts::bus::Access, + stela_contracts::interrupt::InterruptLatch, + }; const SUPPLY: u64 = 0x1000; const RAM: u64 = 0x800000000; #[repr(C, align(16))] @@ -924,10 +916,10 @@ mod tests { #[cfg(feature = "std")] #[ignore = "requires original J314s ADT and mac13j KC via STELA_T6000_MCC_DEVICE_TREE/STELA_TEST_MCC_KERNELCACHE"] fn original_j314s_input_free_frontend_and_opaque_control_consumers_are_pinned() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let tree = std::fs::read(std::env::var("STELA_T6000_MCC_DEVICE_TREE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&tree), + stela_formats::sha256(&tree), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let io = Node::root(&tree).unwrap().child("arm-io").unwrap(); @@ -964,7 +956,7 @@ mod tests { ); let kernel = std::fs::read(std::env::var("STELA_TEST_MCC_KERNELCACHE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&kernel), + stela_formats::sha256(&kernel), "5109fca5209bdbb89cec29e3241cc42a90418cb737d65e31962b059b9879af90" ); for (start, bytes, expected) in [ @@ -994,7 +986,10 @@ mod tests { "358ae139074b063c2aef41e97d73a22fb1aff321074f3f0a92acd2caa672d1a2", ), ] { - assert_eq!(crate::sha256(&kernel[start..start + bytes]), expected); + assert_eq!( + stela_formats::sha256(&kernel[start..start + bytes]), + expected + ); } } } diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/t6020.rs b/crates/stela-runtime/src/machine/apple/memory_resources/t6020.rs index 59fe12c9e1..65c3e779fd 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/t6020.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/t6020.rs @@ -4,17 +4,18 @@ //! their service/interrupt state is not inferred from the original ADT's //! physical capacity. Construction is not native PMP admission, a cache grant //! or a source-supported initial CPU/PMGR handoff. Root owns those joins. -use crate::{ - machine::soc::{MemoryController, T6020Memory}, - memory::{CanonicalRamService, RegisteredSystemRam}, - platform::apple::{ - amcc::{self, Amcc}, - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - mcc::t6020::{self, Configuration, Controller, View}, - ptd, - }, -}; use alloc::{string::String, sync::Arc, vec::Vec}; +use { + crate::machine::soc::MemoryController, crate::machine::soc::T6020Memory, + crate::memory::CanonicalRamService, crate::memory::RegisteredSystemRam, + crate::platform::apple::amcc, crate::platform::apple::amcc::Amcc, + crate::platform::apple::mcc::t6020, crate::platform::apple::mcc::t6020::Configuration, + crate::platform::apple::mcc::t6020::Controller, crate::platform::apple::mcc::t6020::View, + crate::platform::apple::ptd, stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::Lifecycle, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; pub mod cold; @@ -398,15 +399,14 @@ impl crate::machine::apple::AppleDevices { #[cfg(test)] pub(in crate::machine::apple) mod tests { use super::*; - use crate::{ - machine::{Devices, apple::AppleDevices, engine::DeviceReadShape, soc::PtdBank}, - memory::{ReservedSystemRamRange, system_ram::fixture}, - platform::apple::{ - amcc::{Layout, LockGroup, Register}, - interrupt::InterruptLatch, - }, - }; use core::{cell::UnsafeCell, ptr::NonNull}; + use { + crate::machine::Devices, crate::machine::apple::AppleDevices, + crate::machine::engine::DeviceReadShape, crate::machine::soc::PtdBank, + crate::memory::ReservedSystemRamRange, crate::memory::system_ram::fixture, + crate::platform::apple::amcc::Layout, crate::platform::apple::amcc::LockGroup, + crate::platform::apple::amcc::Register, stela_contracts::interrupt::InterruptLatch, + }; const RAM: u64 = 0x10000000000; #[repr(C, align(16))] struct Storage(UnsafeCell<[u8; 0x10000]>); diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/t6020/cold.rs b/crates/stela-runtime/src/machine/apple/memory_resources/t6020/cold.rs index ebc9f9f0dd..d0b6b9cf53 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/t6020/cold.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/t6020/cold.rs @@ -6,21 +6,15 @@ //! Parent provider recipes, absent arrays and caller booleans are never //! controller/PMP/cache completion. Full source PowerStates remain retained. use super::{Configuration, MemoryController, Prepared, T6020Memory, amcc, validate_ram}; -use crate::{ - machine::{ - apple::AppleDevices, - soc::{PowerOwner, PowerStates}, - }, - memory::RegisteredSystemRam, - platform::apple::{ - bus::{LifecycleState, Width}, - pmgr::{ - self, Pmgr, - coverage::{self, Consumer, LifecycleSinks}, - }, - }, -}; use alloc::{format, string::String, sync::Arc, vec, vec::Vec}; +use { + crate::machine::apple::AppleDevices, crate::machine::soc::PowerOwner, + crate::machine::soc::PowerStates, crate::memory::RegisteredSystemRam, + crate::platform::apple::pmgr, crate::platform::apple::pmgr::Pmgr, + crate::platform::apple::pmgr::coverage, crate::platform::apple::pmgr::coverage::Consumer, + crate::platform::apple::pmgr::coverage::LifecycleSinks, stela_contracts::bus::LifecycleState, + stela_contracts::bus::Width, +}; /// Private inputs retain actual source identities. Construction supplies no /// lifecycle status, native topology, firmware PTD service or cache grant. @@ -345,18 +339,15 @@ fn contains(descriptor: &T6020Memory, address: u64) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::{ - machine::soc::{ClockRole, PowerResource}, - platform::apple::{ - bus::Access, - interrupt::InterruptLatch, - pmgr::{ - PowerState, - coverage::{Admission, Domain, DomainId}, - }, - }, - }; use alloc::boxed::Box; + use { + crate::machine::soc::ClockRole, crate::machine::soc::PowerResource, + crate::platform::apple::pmgr::PowerState, + crate::platform::apple::pmgr::coverage::Admission, + crate::platform::apple::pmgr::coverage::Domain, + crate::platform::apple::pmgr::coverage::DomainId, stela_contracts::bus::Access, + stela_contracts::interrupt::InterruptLatch, + }; const SUPPLY: u64 = 0x1000; fn id(device: u16) -> DomainId { DomainId { die: 0, device } diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/t8112.rs b/crates/stela-runtime/src/machine/apple/memory_resources/t8112.rs index 97016206c9..909597c608 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/t8112.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/t8112.rs @@ -10,24 +10,20 @@ //! the drivers wait for are modeled behaviorally (`pmp::duties`). use super::dcs::NativeDcs; pub use crate::platform::apple::dcs::native::{CHANNEL_STRIDE, CHANNELS, ChannelConfiguration}; -use crate::{ - machine::soc::MemoryCache, - memory::{CanonicalRamService, RegisteredSystemRam}, - platform::apple::{ - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - dcs::native::ChannelProgress, - pmp::duties::Duties, - ptd::{ - self, Geometry, Ptd, - transport::{ - IRQ_STATUS, - notifications::{LocalNotifications, NativeProfile}, - status, - }, - }, - }, -}; use alloc::{sync::Arc, vec::Vec}; +use { + crate::machine::soc::MemoryCache, crate::memory::CanonicalRamService, + crate::memory::RegisteredSystemRam, crate::platform::apple::dcs::native::ChannelProgress, + crate::platform::apple::pmp::duties::Duties, crate::platform::apple::ptd, + crate::platform::apple::ptd::Geometry, crate::platform::apple::ptd::Ptd, + crate::platform::apple::ptd::transport::IRQ_STATUS, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + crate::platform::apple::ptd::transport::notifications::NativeProfile, + crate::platform::apple::ptd::transport::status, stela_contracts::bus::Access, + stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const DCS_BYTES: u64 = CHANNEL_STRIDE * CHANNELS as u64; const PTD_OFFSET: u64 = DCS_BYTES; @@ -350,13 +346,13 @@ impl crate::machine::apple::AppleDevices { #[cfg(test)] mod tests { use super::*; - use crate::{ - machine::{Devices, apple::AppleDevices, soc::PtdBank}, - memory::{ReservedSystemRamRange, system_ram::fixture}, - platform::apple::{amcc, interrupt::InterruptLatch}, - }; use alloc::{boxed::Box, vec}; use core::{cell::UnsafeCell, ptr::NonNull}; + use { + crate::machine::Devices, crate::machine::apple::AppleDevices, crate::machine::soc::PtdBank, + crate::memory::ReservedSystemRamRange, crate::memory::system_ram::fixture, + crate::platform::apple::amcc, stela_contracts::interrupt::InterruptLatch, + }; const DCS: u64 = 0x201000000; const PTD: u64 = 0x23b3c0000; const DRAIN: u64 = 0xa40; @@ -740,10 +736,10 @@ mod tests { #[cfg(feature = "std")] #[ignore = "requires unchanged original J473 DeviceTree via STELA_TEST_MCC_J473_DT"] fn original_j473_dcs_and_ptd_placement_builds_one_source_profiled_resource() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let bytes = std::fs::read(std::env::var("STELA_TEST_MCC_J473_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); let io = Node::root(&bytes).unwrap().child("arm-io").unwrap(); diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/t8112/amcc.rs b/crates/stela-runtime/src/machine/apple/memory_resources/t8112/amcc.rs index 40cb89f52d..21d010058c 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/t8112/amcc.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/t8112/amcc.rs @@ -7,15 +7,16 @@ //! windows and DCS/PTD. See docs/research/apple-mcc.md for the source contract //! and missing all-access cache accounting. No Apple firmware is executed. use super::Prepared; -use crate::{ - machine::soc::MemoryController, - memory::{CanonicalRamService, RegisteredSystemRam}, - platform::apple::{ - amcc::{Amcc, Locked, Programmed, Register}, - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - }, -}; use alloc::sync::Arc; +use { + crate::machine::soc::MemoryController, crate::memory::CanonicalRamService, + crate::memory::RegisteredSystemRam, crate::platform::apple::amcc::Amcc, + crate::platform::apple::amcc::Locked, crate::platform::apple::amcc::Programmed, + crate::platform::apple::amcc::Register, stela_contracts::bus::Access, + stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const PLANES: u32 = 4; pub(super) const STRIDE: u64 = 0x40000; @@ -276,15 +277,13 @@ impl MmioDevice for LockResource { pub(in crate::machine::apple) mod tests { use super::super::tests::{configuration, descriptor, ram_at}; use super::*; - use crate::{ - memory::{ReservedSystemRamRange, system_ram::fixture}, - platform::apple::{ - amcc::{Layout, LockGroup}, - interrupt::InterruptLatch, - }, - }; use alloc::{boxed::Box, vec}; use core::{cell::UnsafeCell, ptr::NonNull}; + use { + crate::memory::ReservedSystemRamRange, crate::memory::system_ram::fixture, + crate::platform::apple::amcc::Layout, crate::platform::apple::amcc::LockGroup, + stela_contracts::interrupt::InterruptLatch, + }; const BASE: u64 = 0x200000000; const RAM: u64 = 0x800000000; const LIVE: LifecycleState = LifecycleState { @@ -370,7 +369,7 @@ pub(in crate::machine::apple) mod tests { ); assert_eq!(lock.source(), &source()); assert!(owner.notifications().owns(owner.publication_bank())); - let mut bus = crate::platform::apple::bus::Bus::new(); + let mut bus = stela_contracts::bus::Bus::new(); let memory = owner.bindings(); bus.install(Box::new(owner), &memory).unwrap(); let lock_binding = lock.binding(); @@ -543,10 +542,10 @@ pub(in crate::machine::apple) mod tests { #[cfg(feature = "std")] #[ignore = "requires original J473 DeviceTree and iBoot via STELA_TEST_MCC_J473_DT and STELA_TEST_IBOOT_J473"] fn original_j473_iboot_lock_map_and_mcc_views_qualify_the_independent_owner() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let data = std::fs::read(std::env::var("STELA_TEST_MCC_J473_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); let io = Node::root(&data).unwrap().child("arm-io").unwrap(); @@ -562,7 +561,7 @@ pub(in crate::machine::apple) mod tests { // complete source union grants no cache or additional lock semantics. let code = std::fs::read(std::env::var("STELA_TEST_IBOOT_J473").unwrap()).unwrap(); assert_eq!( - crate::sha256(&code), + stela_formats::sha256(&code), "082cf7b48f9827daefcb5a58e7fd0038aae00b3fe6d36db9ff1528ba3f3a3a3b" ); for (offset, value) in [ diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache.rs b/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache.rs index f5bb6b0b9c..ed9b737d01 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache.rs @@ -21,16 +21,16 @@ use super::amcc::{BROADCAST, LOCK_REGISTERS, LockResource, MMIO_BYTES, Placement, STRIDE}; use crate::platform::apple::pmp::native::cache::publisher; mod native; -use crate::{ - machine::{engine::CanonicalDeviceMemory, soc::MemoryController}, - memory::{CanonicalRamService, RegisteredSystemRam}, - platform::apple::{ - amcc::Locked, - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - }, -}; use alloc::{collections::BTreeMap, sync::Arc}; pub use native::QuotaView; +use { + crate::machine::engine::CanonicalDeviceMemory, crate::machine::soc::MemoryController, + crate::memory::CanonicalRamService, crate::memory::RegisteredSystemRam, + crate::platform::apple::amcc::Locked, stela_contracts::bus::Access, + stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const PLANES: usize = 4; const STATUS: u64 = 0x424; @@ -379,8 +379,8 @@ impl MmioDevice for EmptyResource { mod tests { use super::super::amcc::tests::{frontend, ram, source}; use super::*; - use crate::platform::apple::{bus::Bus, interrupt::InterruptLatch}; use alloc::boxed::Box; + use {stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch}; const LIVE: LifecycleState = LifecycleState { powered: true, @@ -795,7 +795,7 @@ mod tests { fn original_native_quota_seed_and_publisher_share_the_broadcast_full_word() { let code = std::fs::read(std::env::var("STELA_TEST_PMP_T8112").unwrap()).unwrap(); assert_eq!( - crate::sha256(&code), + stela_formats::sha256(&code), "b39ef494f808c6db0a2c4feab42497e466d270b0935b2e1e948dadf0b510716c" ); for (start, end, hash) in [ @@ -815,7 +815,7 @@ mod tests { "949295e2f93ed5c1f89e3e2712b07ba2a039d29dcb382a94ba003f35fb258601", ), ] { - assert_eq!(crate::sha256(&code[start..end]), hash); + assert_eq!(stela_formats::sha256(&code[start..end]), hash); } assert_eq!( u64::from_le_bytes(code[0x46360..0x46368].try_into().unwrap()), @@ -838,7 +838,7 @@ mod tests { let code = std::fs::read(std::env::var("STELA_TEST_MCC_J473_KERNELCACHE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&code), + stela_formats::sha256(&code), "06846c718a67715f540c7f5a5d5a183da6185d94b6fc01f1ce57a30b601be44d" ); for (start, end, hash) in [ @@ -878,7 +878,11 @@ mod tests { "e6aa987254d58eda768ef148602596c4e4583aa7cb77c2b9f2aacc679c7529cd", ), ] { - assert_eq!(crate::sha256(&code[start..end]), hash, "{start:x}..{end:x}"); + assert_eq!( + stela_formats::sha256(&code[start..end]), + hash, + "{start:x}..{end:x}" + ); } assert_eq!(&code[0x17dba3..0x17dbaf], b"disable-mcc\0"); assert_eq!(&code[0x17dbaf..0x17dbbc], b"-disable_mcc\0"); diff --git a/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache/native.rs b/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache/native.rs index 677bedb645..4938d6334b 100644 --- a/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache/native.rs +++ b/crates/stela-runtime/src/machine/apple/memory_resources/t8112/cache/native.rs @@ -85,15 +85,16 @@ mod tests { amcc::tests::{ram, source}, tests::{configuration, descriptor}, }; - use crate::platform::apple::{ - interrupt::InterruptLatch, - pmp::native::cache::{ - policy::Inputs, - publisher::{Bank, Configuration, Publisher}, - }, - ptd::{Range, transport::notifications::LocalNotifications}, - }; use alloc::{vec, vec::Vec}; + use { + crate::platform::apple::pmp::native::cache::policy::Inputs, + crate::platform::apple::pmp::native::cache::publisher::Bank, + crate::platform::apple::pmp::native::cache::publisher::Configuration, + crate::platform::apple::pmp::native::cache::publisher::Publisher, + crate::platform::apple::ptd::Range, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::interrupt::InterruptLatch, + }; const LIVE: LifecycleState = LifecycleState { powered: true, @@ -529,15 +530,15 @@ mod tests { #[cfg(feature = "std")] #[ignore = "requires original T8112 PMP and J473 DT via STELA_TEST_PMP_T8112 and STELA_TEST_MCC_J473_DT"] fn original_table_and_configuration_publish_through_actual_component_owners() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let pmp = std::fs::read(std::env::var("STELA_TEST_PMP_T8112").unwrap()).unwrap(); let dt = std::fs::read(std::env::var("STELA_TEST_MCC_J473_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&pmp), + stela_formats::sha256(&pmp), "b39ef494f808c6db0a2c4feab42497e466d270b0935b2e1e948dadf0b510716c" ); assert_eq!( - crate::sha256(&dt), + stela_formats::sha256(&dt), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); for (start, end, hash) in [ @@ -557,7 +558,7 @@ mod tests { "1c2780da3e5a1fdc46fb9bbbae82b5cd3721e8461bb5988a30a536dffcaac18f", ), ] { - assert_eq!(crate::sha256(&pmp[start..end]), hash); + assert_eq!(stela_formats::sha256(&pmp[start..end]), hash); } // Defaults tail-calls the actual publisher before allocation. // Its full source window is also pinned by the pure policy test. @@ -576,7 +577,7 @@ mod tests { .property("mcache-stream") .unwrap(); assert_eq!( - crate::sha256(raw), + stela_formats::sha256(raw), "1daa6222994ef3c8b22c87d2f4a3c3b2f224ec486093c42f8953a1544f1b8cab" ); let word = |offset| u32::from_le_bytes(pmp[offset..offset + 4].try_into().unwrap()); diff --git a/crates/stela-runtime/src/machine/apple/pmp_dma.rs b/crates/stela-runtime/src/machine/apple/pmp_dma.rs index 57791800ca..d0415ceb53 100644 --- a/crates/stela-runtime/src/machine/apple/pmp_dma.rs +++ b/crates/stela-runtime/src/machine/apple/pmp_dma.rs @@ -37,8 +37,8 @@ impl SourceProvenance { return Err("PMP native DMA static configuration changed or requires an unsupported address transformation".into()); } Ok(Self { - original_tree_sha256: crate::sha256(original), - prepared_tree_sha256: crate::sha256(prepared), + original_tree_sha256: stela_formats::sha256(original), + prepared_tree_sha256: stela_formats::sha256(prepared), pmp: *pmp, mapper_index_property: original_configuration.0, asc_dram_mask_property: original_configuration.1, @@ -470,9 +470,9 @@ impl dma::Coherence for WriteBackCoherence { #[cfg(test)] mod tests { use super::*; - use crate::{machine::adt::encode, memory::ReservedSystemRamRange}; use alloc::{boxed::Box, vec, vec::Vec}; use core::{cell::UnsafeCell, ptr::NonNull}; + use {crate::memory::ReservedSystemRamRange, stela_contracts::adt::encode}; fn pmp() -> soc::PmpController { soc::PmpController { @@ -523,7 +523,10 @@ mod tests { fn static_mapper_configuration_requires_both_source_coordinates_and_exact_properties() { let absent = tree(None, None, false, 0x7d); let source = SourceProvenance::from_trees(&absent, &absent, &pmp()).unwrap(); - assert_eq!(source.original_tree_sha256(), crate::sha256(&absent)); + assert_eq!( + source.original_tree_sha256(), + stela_formats::sha256(&absent) + ); assert_eq!(source.mapper_index_property, None); assert_eq!(source.asc_dram_mask_property, None); let zero = tree( @@ -615,7 +618,9 @@ mod tests { #[test] fn mounted_profile_and_actual_bus_identity_are_required_beside_numeric_geometry() { let mut devices = AppleDevices::new(); - devices.add_pmp(&pmp(), crate::builds::DEFAULT).unwrap(); + devices + .add_pmp(&pmp(), stela_formats::builds::DEFAULT) + .unwrap(); let asc = devices .coprocessors .iter() @@ -704,7 +709,7 @@ mod tests { ) .unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); let pmp = soc::board(&bytes).unwrap().pmp.unwrap(); diff --git a/crates/stela-runtime/src/machine/apple/pmp_services.rs b/crates/stela-runtime/src/machine/apple/pmp_services.rs index da94a1906e..fe3308801c 100644 --- a/crates/stela-runtime/src/machine/apple/pmp_services.rs +++ b/crates/stela-runtime/src/machine/apple/pmp_services.rs @@ -1,19 +1,13 @@ //! Native system services joined to the actual cold PMP ASC and DMA owners. use super::{AppleDevices, ExplicitRuntimeConfiguration}; -use crate::{ - machine::{engine::DeviceError, soc::Board}, - memory::RegisteredSystemRam, - platform::apple::{ - asc::Asc, - bus::{Access, DeviceId, Width}, - pmp::{ - self, - native::services::{Clock, Services}, - }, - rtkit::RtKit, - }, -}; use alloc::{format, string::String, sync::Arc}; +use { + crate::machine::engine::DeviceError, crate::machine::soc::Board, + crate::memory::RegisteredSystemRam, crate::platform::apple::asc::Asc, + crate::platform::apple::pmp, crate::platform::apple::pmp::native::services::Clock, + crate::platform::apple::pmp::native::services::Services, crate::platform::apple::rtkit::RtKit, + stela_contracts::bus::Access, stela_contracts::bus::DeviceId, stela_contracts::bus::Width, +}; pub(super) struct NativePmpServices { asc: DeviceId, diff --git a/crates/stela-runtime/src/machine/apple/processor_power.rs b/crates/stela-runtime/src/machine/apple/processor_power.rs index 982320ad70..0500dd86b1 100644 --- a/crates/stela-runtime/src/machine/apple/processor_power.rs +++ b/crates/stela-runtime/src/machine/apple/processor_power.rs @@ -5,14 +5,14 @@ mod projection; use super::*; -use crate::machine::{ - CpuProfile, - adt::Node, - engine::{CanonicalDeviceWrite, ConsumedWrite, ProcessorBinding, ProcessorWrite}, - soc::{PowerStates, assigned::Plan}, -}; pub(super) use projection::AssignedPower; use projection::Request; +use { + crate::machine::CpuProfile, crate::machine::engine::CanonicalDeviceWrite, + crate::machine::engine::ConsumedWrite, crate::machine::engine::ProcessorBinding, + crate::machine::engine::ProcessorWrite, crate::machine::soc::PowerStates, + crate::machine::soc::assigned::Plan, stela_contracts::adt::Node, +}; impl AppleDevices { /// Cold placement only. Retain `plan` and its source/roster owners through @@ -230,11 +230,11 @@ mod tests { engine::{InstallError, NativeCode, NativeExit}, exception::Pstate, }; - use crate::platform::apple::bus::Lifecycle; use alloc::{rc::Rc, vec}; use core::cell::Cell; use projection::tests::{BASE, COMPLEX, CORE}; use stela_compiler::{GuestState, TargetCpu}; + use stela_contracts::bus::Lifecycle; struct Local; impl Host for Local { diff --git a/crates/stela-runtime/src/machine/apple/processor_power/projection.rs b/crates/stela-runtime/src/machine/apple/processor_power/projection.rs index cbdd0ef86a..dd22fda06a 100644 --- a/crates/stela-runtime/src/machine/apple/processor_power/projection.rs +++ b/crates/stela-runtime/src/machine/apple/processor_power/projection.rs @@ -1,14 +1,12 @@ //! Physical CPU-domain identities projected through one retained assigned Plan. use super::*; -use crate::machine::{ - engine::{ProcessorChange, ProcessorTarget, Processors}, - registers::Identity, - soc::{ - ProcessorAssociation, - assigned::{PlanIdentity, PlannedPe}, - }, -}; use crate::platform::apple::pmgr::{DomainTransition, coverage::DomainId}; +use { + crate::machine::engine::ProcessorChange, crate::machine::engine::ProcessorTarget, + crate::machine::engine::Processors, crate::machine::soc::ProcessorAssociation, + crate::machine::soc::assigned::PlanIdentity, crate::machine::soc::assigned::PlannedPe, + stela_contracts::identity::Identity, +}; struct Domain { identity: DomainId, @@ -217,8 +215,8 @@ impl AssignedPower { #[cfg(test)] pub(super) mod tests { use super::*; - use crate::machine::{Chip, caches::Cache, soc::assigned::*}; use alloc::vec; + use {crate::machine::soc::assigned::*, stela_contracts::Chip, stela_contracts::caches::Cache}; pub const BASE: u64 = 0x1000; pub const CORE: u64 = BASE + 8; @@ -549,7 +547,7 @@ pub(super) mod tests { let directory = std::path::PathBuf::from(std::env::var("STELA_TEST_CPU_DT_DIR").unwrap()); let raw = std::fs::read(directory.join("DeviceTree.j473ap.adt")).unwrap(); assert_eq!( - crate::sha256(&raw), + stela_formats::sha256(&raw), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); let mut prepared = raw.clone(); diff --git a/crates/stela-runtime/src/machine/apple/service.rs b/crates/stela-runtime/src/machine/apple/service.rs index 8a7c235ce9..e1fbd46f4d 100644 --- a/crates/stela-runtime/src/machine/apple/service.rs +++ b/crates/stela-runtime/src/machine/apple/service.rs @@ -223,9 +223,9 @@ impl AppleDevices { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::MmioDevice, - interrupt::{InterruptSink, Wire}, + use { + stela_contracts::bus::MmioDevice, stela_contracts::interrupt::InterruptSink, + stela_contracts::interrupt::Wire, }; const AIC: u64 = 0x7000_0000; @@ -439,7 +439,7 @@ mod tests { states: Vec, } - impl crate::platform::apple::bus::Lifecycle for ResettingClient { + impl stela_contracts::bus::Lifecycle for ResettingClient { fn check_lifecycle(&self, _: LifecycleState) -> Result<(), &'static str> { Ok(()) } @@ -454,7 +454,7 @@ mod tests { } impl MmioDevice for ResettingClient { - fn lifecycle(&mut self) -> Option<&mut dyn crate::platform::apple::bus::Lifecycle> { + fn lifecycle(&mut self) -> Option<&mut dyn stela_contracts::bus::Lifecycle> { Some(self) } @@ -625,11 +625,11 @@ mod tests { fn advance(&mut self, access: &mut Access<'_>) -> Result, MmioError> { if self.refuse { - return Err(crate::platform::apple::bus::refuse( + return Err(stela_contracts::bus::refuse( self.name(), 0, Width::Word, - crate::platform::apple::bus::Direction::Read, + stela_contracts::bus::Direction::Read, "advance refused", )); } diff --git a/crates/stela-runtime/src/machine/apple/sleep.rs b/crates/stela-runtime/src/machine/apple/sleep.rs index 1641595f45..479aa4af4a 100644 --- a/crates/stela-runtime/src/machine/apple/sleep.rs +++ b/crates/stela-runtime/src/machine/apple/sleep.rs @@ -30,12 +30,15 @@ //! the hardware's power domains would not: which blocks lose state, and //! how XNU's drivers restore them, is not yet established block by block. use super::{AppleDevices, Reset, Start, Transition}; -use crate::platform::apple::{bus::DeviceId, pmu, smc::WakeSource, wake::WakeMasks}; use alloc::{ collections::{BTreeSet, VecDeque}, format, string::String, }; +use { + crate::platform::apple::pmu, crate::platform::apple::smc::WakeSource, + crate::platform::apple::wake::WakeMasks, stela_contracts::bus::DeviceId, +}; /// One step of the SoC's sleep, for the host's log. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -240,7 +243,7 @@ mod tests { rtc: Some(48), }, }, - crate::builds::DEFAULT, + stela_formats::builds::DEFAULT, ) .unwrap(); devices diff --git a/crates/stela-runtime/src/machine/apple/t6000_pmgr.rs b/crates/stela-runtime/src/machine/apple/t6000_pmgr.rs index 2f6651cfa1..65d209d17c 100644 --- a/crates/stela-runtime/src/machine/apple/t6000_pmgr.rs +++ b/crates/stela-runtime/src/machine/apple/t6000_pmgr.rs @@ -1,16 +1,19 @@ //! Explicit private T6000 native resource assembly; no public PMGR admission. use super::AppleDevices; -use crate::{ - machine::soc::t6000_pmgr::Descriptor, - platform::apple::{ - bridge::Bridge, - bus::{DeviceId, LifecycleState, MmioDevice}, - cluster::t6000::{Complex, Snapshot, T6000}, - pmgr::t6000::{SRAM_BASE, SRAM_LIMIT, reconfiguration}, - power::t6000::{self as power, Controller, identity, native}, - }, -}; use alloc::{boxed::Box, format, string::String, vec::Vec}; +use { + crate::machine::soc::t6000_pmgr::Descriptor, crate::platform::apple::bridge::Bridge, + crate::platform::apple::cluster::t6000::Complex, + crate::platform::apple::cluster::t6000::Snapshot, + crate::platform::apple::cluster::t6000::T6000, crate::platform::apple::pmgr::t6000::SRAM_BASE, + crate::platform::apple::pmgr::t6000::SRAM_LIMIT, + crate::platform::apple::pmgr::t6000::reconfiguration, + crate::platform::apple::power::t6000 as power, + crate::platform::apple::power::t6000::Controller, + crate::platform::apple::power::t6000::identity, crate::platform::apple::power::t6000::native, + stela_contracts::bus::DeviceId, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MmioDevice, +}; /// Supplied provenance is not authenticated by naming it. No variant supplies /// omitted register bytes, PS states, lifecycle observations or completion. @@ -44,7 +47,7 @@ pub struct Inputs { pub clusters: [Snapshot; 3], /// Every original bridge in ID order; an empty image explicitly keeps /// that bank unknown. Missing entries cannot default into zero banks. - pub bridges: Vec>, + pub bridges: Vec>, pub requests: Requests, pub native: native::Handoff, pub ibootdata: IbootData, @@ -122,7 +125,7 @@ impl Prepared { .expected_sha256 .bytes() .all(|b| b.is_ascii_hexdigit()) - || !crate::sha256(&input.ibootdata.bytes) + || !stela_formats::sha256(&input.ibootdata.bytes) .eq_ignore_ascii_case(&input.ibootdata.expected_sha256) { return Err("T6000 iBootData provenance/digest does not bind the actual input".into()); @@ -138,7 +141,7 @@ impl Prepared { offset: source.offset(), bytes: source.bytes().len(), rows: source.rows().len(), - sha256: crate::sha256(source.bytes()), + sha256: stela_formats::sha256(source.bytes()), } }; if input.bridges.len() != descriptor.bridges.len() { @@ -394,8 +397,8 @@ pub struct Mounted { #[cfg(all(test, feature = "std"))] mod original { use super::*; - use crate::{machine::engine::Devices, platform::apple::bus::Access}; use alloc::vec; + use {crate::machine::engine::Devices, stela_contracts::bus::Access}; const ADT_SHA: &str = "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad"; const IBDT_SHA: &str = "6d38d4b30deedb1be526e36179205004957f10e23254392fc3645c63dfd2b095"; // These values declare a newly owned test resource, never Apple reset. @@ -437,7 +440,7 @@ mod original { }) .collect(); let bytes = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_IBOOTDATA").unwrap()).unwrap(); - assert_eq!(crate::sha256(&bytes), IBDT_SHA); + assert_eq!(stela_formats::sha256(&bytes), IBDT_SHA); Inputs { authority: Authority::DeclaredStela { entry: "explicit test resource".into(), @@ -480,7 +483,7 @@ mod original { } fn adt() -> Vec { let bytes = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_ADT").unwrap()).unwrap(); - assert_eq!(crate::sha256(&bytes), ADT_SHA); + assert_eq!(stela_formats::sha256(&bytes), ADT_SHA); bytes } #[test] diff --git a/crates/stela-runtime/src/machine/apple/t8112_memory.rs b/crates/stela-runtime/src/machine/apple/t8112_memory.rs index 01d94c723d..5c4f5e32bd 100644 --- a/crates/stela-runtime/src/machine/apple/t8112_memory.rs +++ b/crates/stela-runtime/src/machine/apple/t8112_memory.rs @@ -2,8 +2,8 @@ pub mod cold; use super::{AppleDevices, memory_resources::t8112}; -use crate::platform::apple::bus::Width; use alloc::{boxed::Box, format, string::String, sync::Arc}; +use stela_contracts::bus::Width; impl AppleDevices { /// Install the actual component owners together, retaining separate device @@ -74,17 +74,15 @@ impl AppleDevices { #[cfg(test)] mod tests { use super::*; - use crate::{ - machine::Devices, - platform::apple::{ - bus::{Access, LifecycleState, MmioDevice}, - interrupt::InterruptLatch, - }, - }; use t8112::{ amcc::tests::{frontend, ram, source}, cache::{EmptyResource, SoftwareImage, ZeroWayConfiguration}, }; + use { + crate::machine::Devices, stela_contracts::bus::Access, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::interrupt::InterruptLatch, + }; fn components() -> (t8112::Prepared, EmptyResource) { let memory = frontend(ram()); diff --git a/crates/stela-runtime/src/machine/apple/t8112_memory/cold.rs b/crates/stela-runtime/src/machine/apple/t8112_memory/cold.rs index 2e0e809219..b823775717 100644 --- a/crates/stela-runtime/src/machine/apple/t8112_memory/cold.rs +++ b/crates/stela-runtime/src/machine/apple/t8112_memory/cold.rs @@ -6,23 +6,18 @@ use super::super::{ AppleDevices, memory_resources::{amcc, t8112}, }; -use crate::{ - machine::{ - Chip, - soc::{Board, MemoryCache, MemoryController, PowerOwner, PowerStates}, - }, - memory::RegisteredSystemRam, - platform::apple::{ - bus::{LifecycleState, Width}, - pmgr::{ - self, Pmgr, - coverage::{self, Consumer, LifecycleSinks}, - }, - ptd::{self, Geometry}, - }, -}; use alloc::{format, string::String, sync::Arc, vec, vec::Vec}; use t8112::cache::{EmptyResource, SoftwareImage, ZeroWayConfiguration}; +use { + crate::machine::soc::Board, crate::machine::soc::MemoryCache, + crate::machine::soc::MemoryController, crate::machine::soc::PowerOwner, + crate::machine::soc::PowerStates, crate::memory::RegisteredSystemRam, + crate::platform::apple::pmgr, crate::platform::apple::pmgr::Pmgr, + crate::platform::apple::pmgr::coverage, crate::platform::apple::pmgr::coverage::Consumer, + crate::platform::apple::pmgr::coverage::LifecycleSinks, crate::platform::apple::ptd, + crate::platform::apple::ptd::Geometry, stela_contracts::Chip, + stela_contracts::bus::LifecycleState, stela_contracts::bus::Width, +}; const SHARED: (u64, u64) = (0x100000, 0x80000); const BROADCAST: u64 = 0xf00000; @@ -516,21 +511,16 @@ fn geometry( #[cfg(test)] mod tests { use super::*; - use crate::{ - machine::{ - Devices, - soc::{ClockRole, PowerResource}, - }, - platform::apple::{ - bus::{Access, MmioDevice}, - interrupt::InterruptLatch, - pmgr::{ - DomainState, PowerState, - coverage::{Admission, Domain, DomainId}, - }, - }, - }; use alloc::boxed::Box; + use { + crate::machine::Devices, crate::machine::soc::ClockRole, + crate::machine::soc::PowerResource, crate::platform::apple::pmgr::DomainState, + crate::platform::apple::pmgr::PowerState, + crate::platform::apple::pmgr::coverage::Admission, + crate::platform::apple::pmgr::coverage::Domain, + crate::platform::apple::pmgr::coverage::DomainId, stela_contracts::bus::Access, + stela_contracts::bus::MmioDevice, stela_contracts::interrupt::InterruptLatch, + }; const SUPPLY: u64 = 0x1000; fn id(device: u16) -> DomainId { diff --git a/crates/stela-runtime/src/machine/capabilities.rs b/crates/stela-runtime/src/machine/capabilities.rs new file mode 100644 index 0000000000..d2a60a899a --- /dev/null +++ b/crates/stela-runtime/src/machine/capabilities.rs @@ -0,0 +1,106 @@ +//! Execution support policy for the immutable CPU feature descriptions. +use stela_contracts::{Chip, Feature}; + +/// 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(chip: Chip, feature: Feature) -> Result { + if !feature.on(chip) { + Ok(false) + } else if engine_implements(feature) { + Ok(true) + } else { + Err(feature.unimplemented()) + } +} + +/// 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::*; + #[test] + fn chips_are_ordered_and_the_m2_implements_all_it_has() { + 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!( + implemented(Chip::DEFAULT, feature), + Err(feature.unimplemented()) + ); + } + assert_eq!(implemented(Chip::AppleM2, Feature::FEAT_HCX), Ok(false)); + assert_eq!(implemented(Chip::AppleM3, Feature::FEAT_HCX), Ok(true)); + assert_eq!(implemented(Chip::AppleM4, Feature::FEAT_SME), Ok(true)); + assert_eq!(implemented(Chip::AppleM4, Feature::FEAT_MTE2), Ok(false)); + assert_eq!(implemented(Chip::AppleM5, Feature::FEAT_MTE2), Ok(true)); + assert_eq!(implemented(Chip::AppleM1, Feature::FEAT_FGT), Ok(false)); + } +} diff --git a/crates/stela-runtime/src/machine/cpu.rs b/crates/stela-runtime/src/machine/cpu.rs index cc751775ea..5e3053dcfc 100644 --- a/crates/stela-runtime/src/machine/cpu.rs +++ b/crates/stela-runtime/src/machine/cpu.rs @@ -5,19 +5,17 @@ //! exception is routed to its target EL as Arm's pseudocode routes it, and //! entry and return use that EL's ELR, SPSR, ESR, FAR, VBAR and SP (Arm //! `AArch64_TakeException`, `AArch64_ExceptionReturn`). -use super::{ - exception::{self, Class, IllegalReturn, Pstate, Vector}, - mmu::{self, Controls, Sprr}, - system::{ - Feature, File, Register, - helpers::{bits, effective_nvx}, - }, -}; use crate::scalable::ScalableState; use stela_compiler::{ GuestState, aarch64::scalable::{ScalableMode, VectorLength}, }; +use { + super::exception, super::exception::Class, super::exception::IllegalReturn, + super::exception::Pstate, super::exception::Vector, super::mmu, super::mmu::Controls, + super::mmu::Sprr, super::system::File, super::system::Register, super::system::helpers::bits, + super::system::helpers::effective_nvx, stela_contracts::Feature, +}; pub const HCR_VM: u32 = 0; pub const HCR_FMO: u32 = 3; @@ -404,7 +402,9 @@ impl Cpu { canonical_memory: None, amx: super::amx::Unit::on(chip), vgic: super::vgic::CpuInterface::default(), - scalable: (chip.implemented(Feature::FEAT_SME) == Ok(true)).then(|| { + scalable: (crate::machine::capabilities::implemented(chip, Feature::FEAT_SME) + == Ok(true)) + .then(|| { let length = VectorLength::from_bytes(STREAMING_VECTOR_BYTES) .expect("a 512-bit vector length"); ScalableState::new(length, Feature::FEAT_SME2.on(chip)) diff --git a/crates/stela-runtime/src/machine/caches/cram.rs b/crates/stela-runtime/src/machine/cram.rs similarity index 97% rename from crates/stela-runtime/src/machine/caches/cram.rs rename to crates/stela-runtime/src/machine/cram.rs index 78a73118e8..40b6caec20 100644 --- a/crates/stela-runtime/src/machine/caches/cram.rs +++ b/crates/stela-runtime/src/machine/cram.rs @@ -700,17 +700,27 @@ mod tests { #[cfg(all(feature = "std", target_os = "macos", target_arch = "x86_64"))] mod original { use super::*; - use crate::{ - execution::platform::Mapping, - hosted::host::NativeRunner, - machine::{ - Chip, Cpu, CpuProfile, DeviceError, Devices, FaultCause, Host, InstallError, Lines, - Machine, NativeCode, NativeExit, Regime, RequirementKind, Stop, - exception::Pstate, - registers::{Identity, encodings::MPIDR_EL1}, - }, - }; + use crate::execution::platform::Mapping; + use crate::hosted::host::NativeRunner; + use crate::machine::Cpu; + use crate::machine::CpuProfile; + use crate::machine::DeviceError; + use crate::machine::Devices; + use crate::machine::FaultCause; + use crate::machine::Host; + use crate::machine::InstallError; + use crate::machine::Lines; + use crate::machine::Machine; + use crate::machine::NativeCode; + use crate::machine::NativeExit; + use crate::machine::Regime; + use crate::machine::RequirementKind; + use crate::machine::Stop; + use crate::machine::exception::Pstate; + use crate::machine::registers::encodings::MPIDR_EL1; use stela_compiler::{GuestState, aarch64::system::registers::Encoding}; + use stela_contracts::Chip; + use stela_contracts::identity::Identity; const BASE: u64 = 0x8_0000_0000; #[derive(Clone, Copy)] @@ -993,7 +1003,7 @@ mod tests { fn original(input: Input) -> alloc::vec::Vec { let bytes = std::fs::read(std::env::var(input.environment).expect("original LLB path")) .unwrap(); - assert_eq!(crate::sha256(&bytes), input.sha256); + assert_eq!(stela_formats::sha256(&bytes), input.sha256); bytes } fn replay( @@ -1264,20 +1274,21 @@ mod tests { } struct EntryBus { ram: std::rc::Rc>, - peripherals: crate::platform::apple::bus::Bus, - interrupts: crate::platform::apple::interrupt::InterruptLatch, - sep: Option, + peripherals: stela_contracts::bus::Bus, + interrupts: stela_contracts::interrupt::InterruptLatch, + sep: Option, effects: Vec, irq_changes: Vec, entropy_calls: std::rc::Rc>, } impl EntryBus { fn new(ram: std::rc::Rc>, mount_sep: bool) -> Self { - use crate::platform::apple::{ - asc, bus, - interrupt::{AicInput, InterruptLatch}, - sep::{self, Sep}, - }; + use crate::platform::apple::asc; + use crate::platform::apple::sep; + use crate::platform::apple::sep::Sep; + use stela_contracts::bus; + use stela_contracts::interrupt::AicInput; + use stela_contracts::interrupt::InterruptLatch; let mut peripherals = bus::Bus::new(); let entropy_calls = std::rc::Rc::new(std::cell::Cell::new(0)); let sep = mount_sep.then(|| { @@ -1293,7 +1304,7 @@ mod tests { hex::encode(sha2::Sha256::digest(&adt)), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); - let root = crate::machine::adt::Node::root(&adt).unwrap(); + let root = stela_contracts::adt::Node::root(&adt).unwrap(); let io = root.child("arm-io").unwrap(); let node = io.child("sep").unwrap(); assert_eq!( @@ -1361,7 +1372,9 @@ mod tests { bytes: u8, now: u64, ) -> Result { - use crate::platform::apple::bus::{Access, MmioError, Width}; + use stela_contracts::bus::Access; + use stela_contracts::bus::MmioError; + use stela_contracts::bus::Width; let width = Width::from_bytes(u64::from(bytes)).ok_or_else(|| { DeviceError::Refused("original entry unsupported access width".into()) })?; @@ -1397,7 +1410,9 @@ mod tests { value: u64, now: u64, ) -> Result<(), DeviceError> { - use crate::platform::apple::bus::{Access, MmioError, Width}; + use stela_contracts::bus::Access; + use stela_contracts::bus::MmioError; + use stela_contracts::bus::Width; let width = Width::from_bytes(u64::from(bytes)).ok_or_else(|| { DeviceError::Refused("original entry unsupported access width".into()) })?; @@ -1431,10 +1446,11 @@ mod tests { fn transfer( &mut self, cpu: usize, - _: &mut dyn crate::platform::dma::Memory, + _: &mut dyn stela_contracts::dma::Memory, now: u64, ) -> Result<(), DeviceError> { - use crate::platform::apple::{bus::Access, sep::Sep}; + use crate::platform::apple::sep::Sep; + use stela_contracts::bus::Access; self.peripherals .advance(&mut Access::new(cpu, now, &mut self.interrupts)) .map_err(|error| DeviceError::TransferRefused(format!("{error:?}")))?; diff --git a/crates/stela-runtime/src/machine/ctrr.rs b/crates/stela-runtime/src/machine/ctrr.rs index b7a59f2206..07b046ffed 100644 --- a/crates/stela-runtime/src/machine/ctrr.rs +++ b/crates/stela-runtime/src/machine/ctrr.rs @@ -97,10 +97,13 @@ //! CTRR-A/B on these chips are iBoot-locked handoff values whose limits no //! component reads (m1n1 `src/kboot.c` reports a small CTRR-C region left //! enabled on secondary cores at power-on, not modeled). -use super::Chip; use super::mmu; use super::registers::encodings::Encoding; -pub use crate::boot_bundle::schema::{CoreLocks, LockRegion, Locked}; +use stela_contracts::Chip; +pub use { + stela_formats::boot_bundle::schema::CoreLocks, stela_formats::boot_bundle::schema::LockRegion, + stela_formats::boot_bundle::schema::Locked, +}; const fn sys(op1: u8, crn: u8, crm: u8, op2: u8) -> Encoding { Encoding::new(3, op1, crn, crm, op2) diff --git a/crates/stela-runtime/src/machine/engine.rs b/crates/stela-runtime/src/machine/engine.rs index 8e71f3fa90..b396f1641b 100644 --- a/crates/stela-runtime/src/machine/engine.rs +++ b/crates/stela-runtime/src/machine/engine.rs @@ -32,10 +32,10 @@ pub(crate) mod metrics; mod monitor; mod native_timing; mod parallel; -pub use crate::platform::dma::{DmaError, TransferFault}; pub use monitor::{MonitorEvent, MonitorKind, MonitorLocation}; pub use native_timing::{NativeInstructionSample, NativeTimingPhase, NativeTimingWork}; pub use parallel::{Call, Counts, Hub, Kick, SharedDevices}; +pub use {stela_contracts::dma::DmaError, stela_contracts::dma::TransferFault}; mod pointer; mod prepare; pub use device_read::{CanonicalDeviceMemory, ConsumedScalar, DeviceReadRequest, DeviceReadShape}; @@ -53,26 +53,6 @@ mod tags; mod unprivileged; mod watch; -use super::{ - chip::{AdmitTable, Check}, - cpu::{ - Cpu, Exception, HCR_AMO, HCR_API, HCR_FMO, HCR_HCD, HCR_IMO, HCR_TGE, HCR_TSC, HCR_VF, - HCR_VI, HCR_VSE, - }, - ctrr, debug, - exception::{ - Class, DAIF_A, DAIF_D, DAIF_F, DAIF_I, IllegalReturn, Pstate, SYNCHRONOUS_EXTERNAL_ABORT, - Vector, data_abort_iss, - }, - hacr, identification, - mmu::{self, Access, Controls, Outcome as Translated}, - registers::{self, CpuProfile, HCR_TIDCP, Lines, Outcome as RegisterOutcome, Refusal}, - streaming::{self, Denial}, - system::{Feature, Register as SystemRegister}, - timer, -}; -pub use crate::platform::apple::bus::Transition; -pub use crate::platform::dma::Memory; use crate::{pauth, scalable::ScalableState}; use alloc::{ collections::{BTreeMap, BTreeSet}, @@ -125,8 +105,25 @@ use stela_compiler::{ pointer as x86_64_pointer, register_read, zero_block, }, }; +pub use stela_contracts::bus::Transition; +pub use stela_contracts::dma::Memory; pub use stored::{Offer, Translations}; pub use system::FP_TRAPS_WRITABLE; +use { + super::cpu::Cpu, super::cpu::Exception, super::cpu::HCR_AMO, super::cpu::HCR_API, + super::cpu::HCR_FMO, super::cpu::HCR_HCD, super::cpu::HCR_IMO, super::cpu::HCR_TGE, + super::cpu::HCR_TSC, super::cpu::HCR_VF, super::cpu::HCR_VI, super::cpu::HCR_VSE, super::ctrr, + super::debug, super::exception::Class, super::exception::DAIF_A, super::exception::DAIF_D, + super::exception::DAIF_F, super::exception::DAIF_I, super::exception::IllegalReturn, + super::exception::Pstate, super::exception::SYNCHRONOUS_EXTERNAL_ABORT, + super::exception::Vector, super::exception::data_abort_iss, super::hacr, super::identification, + super::mmu, super::mmu::Access, super::mmu::Controls, super::mmu::Outcome as Translated, + super::registers, super::registers::CpuProfile, super::registers::HCR_TIDCP, + super::registers::Lines, super::registers::Outcome as RegisterOutcome, + super::registers::Refusal, super::streaming, super::streaming::Denial, + super::system::Register as SystemRegister, super::timer, stela_contracts::Feature, + stela_contracts::chip::AdmitTable, stela_contracts::chip::Check, +}; const PROFILE: BlockProfile = BlockProfile::new(Features::SYSTEM_MODE); const INSTRUCTION: u64 = 4; @@ -428,8 +425,8 @@ pub trait Host { _physical: u64, _bytes: usize, _write: bool, - ) -> Result<(), crate::platform::dma::DmaError> { - Err(crate::platform::dma::DmaError::Unsupported( + ) -> Result<(), stela_contracts::dma::DmaError> { + Err(stela_contracts::dma::DmaError::Unsupported( "host DMA range validation is unavailable", )) } @@ -439,11 +436,11 @@ pub trait Host { &mut self, physical: u64, buffer: &mut [u8], - ) -> Result<(), crate::platform::dma::TransferFault> { + ) -> Result<(), stela_contracts::dma::TransferFault> { self.read_ram(physical, buffer) .then_some(()) - .ok_or(crate::platform::dma::TransferFault { - error: crate::platform::dma::DmaError::Memory, + .ok_or(stela_contracts::dma::TransferFault { + error: stela_contracts::dma::DmaError::Memory, completed: 0, }) } @@ -451,11 +448,11 @@ pub trait Host { &mut self, physical: u64, data: &[u8], - ) -> Result<(), crate::platform::dma::TransferFault> { + ) -> Result<(), stela_contracts::dma::TransferFault> { self.write_ram(physical, data) .then_some(()) - .ok_or(crate::platform::dma::TransferFault { - error: crate::platform::dma::DmaError::Memory, + .ok_or(stela_contracts::dma::TransferFault { + error: stela_contracts::dma::DmaError::Memory, completed: 0, }) } @@ -849,19 +846,19 @@ impl Memory for HostMemory<'_, H> { physical: u64, bytes: usize, write: bool, - ) -> Result<(), crate::platform::dma::DmaError> { + ) -> Result<(), stela_contracts::dma::DmaError> { if write && bytes != 0 { let last = u64::try_from(bytes - 1) .ok() .and_then(|n| physical.checked_add(n)) - .ok_or(crate::platform::dma::DmaError::Memory)?; + .ok_or(stela_contracts::dma::DmaError::Memory)?; if self .lock .into_iter() .flatten() .any(|(first, end)| physical <= end && first <= last) { - return Err(crate::platform::dma::DmaError::Memory); + return Err(stela_contracts::dma::DmaError::Memory); } } self.host.check_ram_range(physical, bytes, write) @@ -870,16 +867,16 @@ impl Memory for HostMemory<'_, H> { &mut self, physical: u64, buffer: &mut [u8], - ) -> Result<(), crate::platform::dma::TransferFault> { + ) -> Result<(), stela_contracts::dma::TransferFault> { self.host.read_ram_progress(physical, buffer) } fn write_progress( &mut self, physical: u64, data: &[u8], - ) -> Result<(), crate::platform::dma::TransferFault> { - let refused = crate::platform::dma::TransferFault { - error: crate::platform::dma::DmaError::Memory, + ) -> Result<(), stela_contracts::dma::TransferFault> { + let refused = stela_contracts::dma::TransferFault { + error: stela_contracts::dma::DmaError::Memory, completed: 0, }; if !data.is_empty() { @@ -2219,10 +2216,22 @@ impl Machine { let stripping = self.pointer.revalidate(inputs); let trapped = self.pointer_authentication_trapped(); for (key, block) in [ - (pauth::Key::Ia, PointerAuthenticationKey::Ia), - (pauth::Key::Ib, PointerAuthenticationKey::Ib), - (pauth::Key::Da, PointerAuthenticationKey::Da), - (pauth::Key::Db, PointerAuthenticationKey::Db), + ( + stela_contracts::pauth::Key::Ia, + PointerAuthenticationKey::Ia, + ), + ( + stela_contracts::pauth::Key::Ib, + PointerAuthenticationKey::Ib, + ), + ( + stela_contracts::pauth::Key::Da, + PointerAuthenticationKey::Da, + ), + ( + stela_contracts::pauth::Key::Db, + PointerAuthenticationKey::Db, + ), ] { let enabled = self.key_enabled(block); self.pointer.reopen(key, enabled, trapped); @@ -3265,7 +3274,7 @@ impl Machine { pub fn strip_instruction_pointer(&self, pointer: u64) -> u64 { self.pointer_context() .ok() - .and_then(|context| context.strip(pauth::Key::Ia, pointer).ok()) + .and_then(|context| context.strip(stela_contracts::pauth::Key::Ia, pointer).ok()) .unwrap_or(pointer) } @@ -4983,7 +4992,7 @@ impl Machine { /// case, and every form under PSTATE.PACM, to the general path. fn implicit_pointer_authentication(&mut self, word: u32) -> Option { use PointerAuthenticationKey as Block; - use pauth::Key; + use stela_contracts::pauth::Key; #[derive(PartialEq)] enum Form { Sign, @@ -5095,10 +5104,10 @@ impl Machine { return None; } let key = match key { - PointerAuthenticationKey::Ia => pauth::Key::Ia, - PointerAuthenticationKey::Ib => pauth::Key::Ib, - PointerAuthenticationKey::Da => pauth::Key::Da, - PointerAuthenticationKey::Db => pauth::Key::Db, + PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, + PointerAuthenticationKey::Ib => stela_contracts::pauth::Key::Ib, + PointerAuthenticationKey::Da => stela_contracts::pauth::Key::Da, + PointerAuthenticationKey::Db => stela_contracts::pauth::Key::Db, }; let pc = self.cpu.pc; let pointer = self.cpu.state.x[usize::from(register)]; @@ -5134,7 +5143,7 @@ impl Machine { fn pointer_result( &mut self, operation: PointerOperation, - key: pauth::Key, + key: stela_contracts::pauth::Key, pointer: u64, modifier: u64, ) -> Result { @@ -5239,8 +5248,14 @@ impl Machine { use pauth::lr_instruction::{Action, Key}; let pc = self.cpu.pc; let (key, runtime_key) = match operands.key { - Key::Ia => (PointerAuthenticationKey::Ia, pauth::Key::Ia), - Key::Ib => (PointerAuthenticationKey::Ib, pauth::Key::Ib), + Key::Ia => ( + PointerAuthenticationKey::Ia, + stela_contracts::pauth::Key::Ia, + ), + Key::Ib => ( + PointerAuthenticationKey::Ib, + stela_contracts::pauth::Key::Ib, + ), }; if !self.key_enabled(key) { return self.disabled_pointer_authentication(word, instruction); @@ -5387,8 +5402,12 @@ impl Machine { &mut self.cpu.state, |key, pointer| { let key = match key { - stela_compiler::block::pauth_memory::DataKey::A => pauth::Key::Da, - stela_compiler::block::pauth_memory::DataKey::B => pauth::Key::Db, + stela_compiler::block::pauth_memory::DataKey::A => { + stela_contracts::pauth::Key::Da + } + stela_compiler::block::pauth_memory::DataKey::B => { + stela_contracts::pauth::Key::Db + } }; match context { Some(context) => context @@ -6297,8 +6316,8 @@ impl Machine { return self.pointer_authentication_trap(); } let runtime_key = match key { - PointerAuthenticationKey::Ia => pauth::Key::Ia, - _ => pauth::Key::Ib, + PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, + _ => stela_contracts::pauth::Key::Ib, }; // A combined authentication: a failure corrupts the pointer, // or with FEAT_FPACCOMBINE takes the PAC Fail exception at @@ -7006,7 +7025,7 @@ mod tests { Machine::table_base_changed, ]; for operation in operations { - let mut machine = board_on(crate::machine::Chip::AppleM1, &[], NoDevices, Vec::new()); + let mut machine = board_on(stela_contracts::Chip::AppleM1, &[], NoDevices, Vec::new()); machine.translation_generation = u64::MAX; assert!( std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| operation(&mut machine))) @@ -7204,10 +7223,10 @@ mod tests { /// The chip the tests run on, or the M2 where it has the Apple generic /// timer's two banks (`timer::agt`): for tests of one bank's /// architectural generic timer. - pub(super) fn one_timer_bank() -> crate::machine::Chip { + pub(super) fn one_timer_bank() -> stela_contracts::Chip { let chip = crate::machine::test_chip(); if crate::machine::timer::agt::present(chip) { - crate::machine::Chip::AppleM2 + stela_contracts::Chip::AppleM2 } else { chip } @@ -7215,7 +7234,7 @@ mod tests { /// [`machine`] on `chip`, for a test that fixes its chip. pub(super) fn machine_on( - chip: crate::machine::Chip, + chip: stela_contracts::Chip, words: &[u32], ) -> Machine { board_on(chip, words, NoDevices, Vec::new()) @@ -7260,17 +7279,17 @@ mod tests { pub(super) fn board( words: &[u32], devices: D, - processors: Vec, + processors: Vec, ) -> Machine { board_on(crate::machine::test_chip(), words, devices, processors) } /// [`board`] on `chip`. pub(super) fn board_on( - chip: crate::machine::Chip, + chip: stela_contracts::Chip, words: &[u32], devices: D, - processors: Vec, + processors: Vec, ) -> Machine { let mut ram = vec![0u8; 0x10000]; for (index, word) in words.iter().enumerate() { @@ -7421,7 +7440,7 @@ mod tests { const KEY_READ: u32 = 0xd53c_fdc0; const CONTROL_READ: u32 = 0xd53c_fc00; const CONTROL_WRITE: u32 = 0xd51c_fc00; - let mut machine = machine_on(crate::machine::Chip::AppleM2, &[]); + let mut machine = machine_on(stela_contracts::Chip::AppleM2, &[]); machine.cpu.set_pstate(Pstate::reset(1)); let run = |machine: &mut Machine<_, _>, word, x0| { machine.cpu.pc = BASE; @@ -7984,14 +8003,14 @@ mod tests { assert_eq!(machine.statistics.compiled, 1, "cached"); // An SVE instruction compiles as the UDF it is on a chip without SVE // or SME, such as the M2. - let mut machine = machine_on(crate::machine::Chip::AppleM2, &[0x9100_0400, 0x04a0_0000]); + let mut machine = machine_on(stela_contracts::Chip::AppleM2, &[0x9100_0400, 0x04a0_0000]); let Ok(Fetched::Block(index)) = machine.fetch_block(BASE, false) else { panic!("block with UDF") }; assert_eq!(machine.blocks[index].source_map.len(), 2); // On the M4, whose SME has it in streaming mode, the block ends // before it, and the engine applies its access checks on its own. - let mut machine = machine_on(crate::machine::Chip::AppleM4, &[0x9100_0400, 0x04a0_0000]); + let mut machine = machine_on(stela_contracts::Chip::AppleM4, &[0x9100_0400, 0x04a0_0000]); let Ok(Fetched::Block(index)) = machine.fetch_block(BASE, false) else { panic!("prefix block") }; @@ -8444,7 +8463,7 @@ mod tests { // The M2 kernel's JIT box: its range (S3_4_C15_C15_1) and mode // (S3_4_C15_C15_4) are held. A mode that enables the box, whose // enforcement is undocumented, is reported once. - let mut machine = machine_on(crate::machine::Chip::AppleM2, &[]); + let mut machine = machine_on(stela_contracts::Chip::AppleM2, &[]); machine.cpu.set_pstate(Pstate::reset(1)); machine.cpu.pc = BASE; machine.cpu.state.x[0] = 0x0000_0001_0200_0006; @@ -8468,7 +8487,7 @@ mod tests { const MRS_X0_HCRX_EL2: u32 = 0xd53c_1240; const NV: u64 = 1 << 42; const NV2: u64 = 1 << 45; - let chip = crate::machine::Chip::AppleM3; + let chip = stela_contracts::Chip::AppleM3; let mut machine = machine_on(chip, &[]); let registers = &mut machine.cpu.registers; registers.set(SystemRegister::VBAR_EL1, 0, 0x1_0000); @@ -8530,7 +8549,7 @@ mod tests { machine.system_instruction(MRS_X0_HCRX_EL2).unwrap(); assert_eq!(machine.take_unmodeled().len(), 1); // The M2 has no FEAT_NV: the bits are RES0 and ERET returns. - let mut machine = machine_on(crate::machine::Chip::AppleM2, &[]); + let mut machine = machine_on(stela_contracts::Chip::AppleM2, &[]); machine .cpu .registers @@ -8547,8 +8566,8 @@ mod tests { #[test] fn all_chip_performance_monitors_count_retirement_and_signal_their_overflow_fiq() { - for chip in crate::machine::Chip::ALL { - let overflow = if chip == crate::machine::Chip::AppleM1 { + for chip in stela_contracts::Chip::ALL { + let overflow = if chip == stela_contracts::Chip::AppleM1 { 1u64 << 47 } else { 1u64 << 63 @@ -8579,7 +8598,7 @@ mod tests { // The EL1 vectors at BASE + 0x800: current EL, SPx, synchronous. words.resize(0xa00 / 4, 0); words.extend([MRS_X5_PMC1, SVC]); - let identity = registers::Identity { + let identity = stela_contracts::identity::Identity { // No hardware identity is claimed by this synthetic PMU fixture. midr: 0, mpidr: 0x8001_0000, @@ -8594,7 +8613,7 @@ mod tests { .set(SystemRegister::VBAR_EL1, 0, BASE + 0x800); let programmable = matches!( chip, - crate::machine::Chip::AppleM1 | crate::machine::Chip::AppleM2 + stela_contracts::Chip::AppleM1 | stela_contracts::Chip::AppleM2 ); if programmable { machine.cpu.state.x[9] = 0x8c00; // INST_ALL on PMC7 only. @@ -9465,7 +9484,7 @@ mod tests { assert!(matches!(machine.peer_states()[0], PeerState::Down)); assert_eq!(machine.host.now, 2000); // A WFIT's local timeout would be the core's too. - let mut machine = machine_on(crate::machine::Chip::AppleM4, &[]); + let mut machine = machine_on(stela_contracts::Chip::AppleM4, &[]); machine.cpu.state.x[0] = 3 << 24; machine.system_instruction(MSR_CYC_OVRD_X0).unwrap(); machine.cpu.state.x[1] = u64::MAX; @@ -9480,7 +9499,7 @@ mod tests { const WFIT_X1: u32 = 0xd503_1021; const WFET_X2: u32 = 0xd503_1002; const HCR_TWI: u64 = 1 << 13; - let chip = crate::machine::Chip::AppleM4; + let chip = stela_contracts::Chip::AppleM4; let mut machine = machine_on(chip, &[]); machine .cpu @@ -9508,7 +9527,7 @@ mod tests { 0x0600_0000 | 1 << 24 | 0b1110 << 20 | 1 << 5 | 1 << 2 | 0b10 ); // The M2 has no FEAT_WFxT: the timeout forms are UNDEFINED. - let mut machine = machine_on(crate::machine::Chip::AppleM2, &[]); + let mut machine = machine_on(stela_contracts::Chip::AppleM2, &[]); machine .cpu .registers @@ -9996,8 +10015,8 @@ mod tests { const AT_S1E1RP_X2: u32 = 0xd508_7902; const EPAN: u64 = 1 << 57; for (chip, pan3) in [ - (crate::machine::Chip::AppleM2, false), - (crate::machine::Chip::AppleM4, true), + (stela_contracts::Chip::AppleM2, false), + (stela_contracts::Chip::AppleM4, true), ] { let mut machine = machine_on(chip, &[]); // A level-1 block maps VA 0-1 GiB at BASE, privileged @@ -10371,7 +10390,7 @@ mod tests { } /// [`pac_machine`] on `chip`, running `words` at BASE. - fn pac_machine_for(chip: crate::machine::Chip, words: &[u32]) -> Machine { + fn pac_machine_for(chip: stela_contracts::Chip, words: &[u32]) -> Machine { pac_setup(machine_on(chip, words)) } @@ -10446,7 +10465,7 @@ mod tests { let expected = machine .pointer_context() .unwrap() - .sign(pauth::Key::Ia, 0x4000, 0x8000) + .sign(stela_contracts::pauth::Key::Ia, 0x4000, 0x8000) .unwrap(); machine.pointer_authentication(PACIASP).unwrap(); assert_eq!(machine.cpu.state.x[30], expected); @@ -10505,7 +10524,7 @@ mod tests { machine .pointer_context() .unwrap() - .sign(pauth::Key::Ia, 0x4000, 0x8000) + .sign(stela_contracts::pauth::Key::Ia, 0x4000, 0x8000) .unwrap(), expected ); @@ -10524,7 +10543,7 @@ mod tests { // Original SPTM's early canary instruction, used here with authored // operands. Its preceding standard-name MSRs must feed actual EL2 PAC. const PACGA: u32 = 0x9ac0_33e1; - let mut machine = pac_machine_for(crate::machine::Chip::AppleM2, &[PACGA]); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM2, &[PACGA]); machine .cpu .registers @@ -10625,7 +10644,7 @@ mod tests { const AUTIASP: u32 = 0xd503_23bf; const NOP: u32 = 0xd503_201f; let code = [PACM, PACIASP, PACM, AUTIASP, PACM, NOP, PACIASP]; - let mut machine = pac_machine_for(crate::machine::Chip::AppleM6, &code); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM6, &code); let pointer = 0xffff_ff80_0000_4000_u64; let sp = 0xffff_ff80_0001_0000_u64; machine.cpu.state.x[30] = pointer; @@ -10649,7 +10668,7 @@ mod tests { pac(&mut machine, BASE + 4); let context = machine.pointer_context().unwrap(); let signed = context - .sign_two_modifiers(pauth::Key::Ia, pointer, sp, BASE + 4) + .sign_two_modifiers(stela_contracts::pauth::Key::Ia, pointer, sp, BASE + 4) .unwrap(); assert_eq!(machine.cpu.state.x[30], signed); assert!(!machine.cpu.pstate.pacm); @@ -10670,7 +10689,9 @@ mod tests { pac(&mut machine, BASE + 24); assert_eq!( machine.cpu.state.x[30], - context.sign(pauth::Key::Ia, pointer, sp).unwrap() + context + .sign(stela_contracts::pauth::Key::Ia, pointer, sp) + .unwrap() ); } @@ -10679,7 +10700,7 @@ mod tests { const PACIASP: u32 = 0xd503_233f; const ERET: u32 = 0xd69f_03e0; const SPSR_PACM: u64 = 1 << 35; - let mut machine = pac_machine_for(crate::machine::Chip::AppleM6, &[]); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM6, &[]); enable_pacm(&mut machine); machine.system_instruction_for_test(PACM); assert!(machine.cpu.pstate.pacm); @@ -10712,7 +10733,7 @@ mod tests { let retaasppc = |n: u32| 0x5500_001f | n << 5; let pointer = 0xffff_ff80_0000_4000_u64; let sp = 0xffff_ff80_0001_0000_u64; - let mut machine = pac_machine_for(crate::machine::Chip::AppleM6, &[]); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM6, &[]); let context = machine.pointer_context().unwrap(); let at = |machine: &mut Machine, pc: u64, word: u32| { machine.cpu.pc = pc; @@ -10722,7 +10743,7 @@ mod tests { machine.cpu.state.x[30] = pointer; at(&mut machine, BASE, PACIASPPC); let signed = context - .sign_two_modifiers(pauth::Key::Ia, pointer, sp, BASE) + .sign_two_modifiers(stela_contracts::pauth::Key::Ia, pointer, sp, BASE) .unwrap(); assert_eq!( (machine.cpu.state.x[30], machine.cpu.pc), @@ -10749,7 +10770,7 @@ mod tests { assert_eq!( machine.cpu.state.x[17], context - .sign_two_modifiers(pauth::Key::Ia, pointer, 0x1234, 0x5678) + .sign_two_modifiers(stela_contracts::pauth::Key::Ia, pointer, 0x1234, 0x5678) .unwrap() ); at(&mut machine, BASE + 4, AUTIA171615); @@ -10759,7 +10780,7 @@ mod tests { assert!(machine.branch_target_compatible(PACIASPPC)); assert!(!machine.branch_target_compatible(0xdac1_83fe)); // Without FEAT_PAuth_LR (the M5) they are UNDEFINED. - let mut machine = pac_machine_for(crate::machine::Chip::AppleM5, &[]); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM5, &[]); at(&mut machine, BASE, PACIASPPC); assert_eq!(machine.cpu.read(SystemRegister::ESR_EL1), 0x0200_0000); } @@ -10878,14 +10899,14 @@ mod tests { // and a failed AUT writes the key B error code without an exception, // at bits 62:61 without TBI (Arm `Auth`); the M2 XORs the PAC in and // faults. - let (classic, failed, taken) = run(crate::machine::Chip::AppleM1); + let (classic, failed, taken) = run(stela_contracts::Chip::AppleM1); assert_eq!( classic & 0x0000_007f_ffff_ffff, pointer & 0x0000_007f_ffff_ffff ); assert!(!taken); assert_eq!(failed, pointer & !(0b11 << 61) | 0b10 << 61); - let (enhanced, _, taken) = run(crate::machine::Chip::AppleM2); + let (enhanced, _, taken) = run(stela_contracts::Chip::AppleM2); assert_ne!(enhanced, classic); assert!(taken); } @@ -10899,8 +10920,8 @@ mod tests { const MADDPT: u32 = 0x9b62_1023; const MSUBPT: u32 = 0x9b62_9025; for (chip, cpa) in [ - (crate::machine::Chip::AppleM5, false), - (crate::machine::Chip::AppleM6, true), + (stela_contracts::Chip::AppleM5, false), + (stela_contracts::Chip::AppleM6, true), ] { let mut machine = machine_on(chip, &[]); machine @@ -10938,8 +10959,8 @@ mod tests { const LDRAA_X0_X1: u32 = 0xf820_0420; let pointer = 0xffff_ff80_0000_4000_u64; for (chip, faults) in [ - (crate::machine::Chip::AppleM2, false), - (crate::machine::Chip::AppleM6, true), + (stela_contracts::Chip::AppleM2, false), + (stela_contracts::Chip::AppleM6, true), ] { let mut machine = pac_machine_for(chip, &[]); machine.cpu.state.x[30] = pointer; @@ -10966,7 +10987,7 @@ mod tests { } } // LDRAA of an unsigned base faults with the data key A (ISS 0b10). - let mut machine = pac_machine_for(crate::machine::Chip::AppleM6, &[]); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM6, &[]); let registers = &mut machine.cpu.registers; registers.set(SystemRegister::APDAKeyLo_EL1, 0, 0x2468_ace0_1357_9bdf); registers.set(SystemRegister::APDAKeyHi_EL1, 0, 0x0f1e_2d3c_4b5a_6978); @@ -10980,7 +11001,7 @@ mod tests { // With EnDA clear AuthDA returns the unsigned base unchanged: // LDRAA reads through it, here an unmapped address, whose data // abort (EC 0x25) reports the base itself. - let mut machine = pac_machine_for(crate::machine::Chip::AppleM6, &[]); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM6, &[]); let registers = &mut machine.cpu.registers; let sctlr = registers.get(SystemRegister::SCTLR_EL1, 0) & !(1 << 27); registers.set(SystemRegister::SCTLR_EL1, 0, sctlr); @@ -11048,7 +11069,10 @@ mod tests { (0xd503_233f, 0xd503_23bf, 0xd65f_0bff, 0), (0xd503_237f, 0xd503_23ff, 0xd65f_0fff, 1), ] { - for chip in [crate::machine::Chip::AppleM2, crate::machine::Chip::AppleM6] { + for chip in [ + stela_contracts::Chip::AppleM2, + stela_contracts::Chip::AppleM6, + ] { for (word, combined) in [(authenticate, false), (ret, true)] { for btype in 1..=3 { let mut machine = pac_machine_for(chip, &[]); @@ -11066,7 +11090,7 @@ mod tests { // Invoke the actual implicit path after its source-entry // boundary; this fixture does not model a guarded leaf. machine.system_instruction_for_test(word); - let faults = !combined || chip == crate::machine::Chip::AppleM6; + let faults = !combined || chip == stela_contracts::Chip::AppleM6; if faults { assert_eq!(machine.cpu.read(SystemRegister::SPSR_EL1), saved); assert_eq!(machine.cpu.read(SystemRegister::ELR_EL1), pc); @@ -11108,7 +11132,11 @@ mod tests { let expected = machine .pointer_context() .unwrap() - .sign(pauth::Key::Ib, pointer, machine.cpu.state.sp) + .sign( + stela_contracts::pauth::Key::Ib, + pointer, + machine.cpu.state.sp, + ) .unwrap(); assert_eq!(signed, expected); assert_eq!(sign(&mut machine), signed, "remembered"); @@ -11125,7 +11153,9 @@ mod tests { let context = machine.pointer_context().unwrap(); assert_eq!( machine.cpu.state.x[17], - context.sign(pauth::Key::Ia, pointer, 0x55).unwrap() + context + .sign(stela_contracts::pauth::Key::Ia, pointer, 0x55) + .unwrap() ); // A key the guest writes changes every later result. machine @@ -11177,7 +11207,12 @@ mod tests { let mut machine = pac_machine(); assert_eq!(machine.pointer.tags, [0; 4]); machine - .pointer_result(PointerOperation::Sign, pauth::Key::Ib, 0x4000, 0x10) + .pointer_result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ib, + 0x4000, + 0x10, + ) .unwrap() .unwrap(); let ib = x86_64_pointer::key_index(PointerAuthenticationKey::Ib); @@ -11235,8 +11270,8 @@ mod tests { machine.cpu.registers.set(SystemRegister::TCR_EL1, 0, tcr); machine.derived_changed(); for (word, data, key) in [ - (0xdac1_43f1, false, pauth::Key::Ia), - (XPACD_X17, true, pauth::Key::Da), + (0xdac1_43f1, false, stela_contracts::pauth::Key::Ia), + (XPACD_X17, true, stela_contracts::pauth::Key::Da), ] { for pointer in [0xdead_1234_5678_aaaa, 0xdead_9234_5678_aaaa] { machine.cpu.state.x[17] = pointer; @@ -11560,7 +11595,7 @@ mod tests { let plain = machine.cpu.state.x[10] == machine.clock.last().wrapping_sub(offset); // The M2 reads both as the count less CNTVOFF_EL2. assert!( - plain || machine.cpu.registers.chip() != crate::machine::chip::Chip::AppleM2 + plain || machine.cpu.registers.chip() != stela_contracts::chip::Chip::AppleM2 ); assert_eq!( machine.mirrors[index], @@ -11679,7 +11714,12 @@ mod tests { .set(SystemRegister::APIBKeyLo_EL1, 0, key); machine.derived_changed(); let signed = machine - .pointer_result(PointerOperation::Sign, pauth::Key::Ib, pointer, modifier) + .pointer_result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ib, + pointer, + modifier, + ) .unwrap() .unwrap(); (signed, machine.pointer.generation) @@ -11688,10 +11728,12 @@ mod tests { let (other, other_generation) = sign(&mut machine, 2); assert_ne!((other, other_generation), (first, generation)); assert_eq!(sign(&mut machine, 1), (first, generation)); - let remembered = - machine - .pointer - .remembered(PointerOperation::Sign, pauth::Key::Ib, pointer, modifier); + let remembered = machine.pointer.remembered( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ib, + pointer, + modifier, + ); assert_eq!(remembered, Some(Ok(first))); for key in 0..pointer::POINTER_INPUTS_SEEN as u64 { sign(&mut machine, 0x1000 + key); @@ -11713,12 +11755,13 @@ mod tests { let combined = PointerOperation::Authenticate { combined: true }; let pointer = 0xffff_ff80_0000_4000; let (signed, _) = machine - .pointer_result(sign, pauth::Key::Ib, pointer, modifier) + .pointer_result(sign, stela_contracts::pauth::Key::Ib, pointer, modifier) .unwrap() .unwrap(); - let remembered = machine - .pointer - .remembered(plain, pauth::Key::Ib, signed, modifier); + let remembered = + machine + .pointer + .remembered(plain, stela_contracts::pauth::Key::Ib, signed, modifier); assert_eq!(remembered, Some(Ok((pointer, true)))); let context = machine.pointer_context().unwrap(); for operation in [plain, combined] { @@ -11726,27 +11769,38 @@ mod tests { unreachable!() }; let computed = context - .authenticate_operation(pauth::Key::Ib, signed, modifier, combined) + .authenticate_operation(stela_contracts::pauth::Key::Ib, signed, modifier, combined) .unwrap(); assert_eq!( - machine.pointer_result(operation, pauth::Key::Ib, signed, modifier), + machine.pointer_result( + operation, + stela_contracts::pauth::Key::Ib, + signed, + modifier + ), Ok(Ok((computed.pointer, computed.authenticated))) ); } // A pointer whose extension bits disagree does not strip back. let odd = 0x7fff_ff80_0000_4000; let (signed, _) = machine - .pointer_result(sign, pauth::Key::Ib, odd, modifier) + .pointer_result(sign, stela_contracts::pauth::Key::Ib, odd, modifier) .unwrap() .unwrap(); assert_eq!( machine .pointer - .remembered(plain, pauth::Key::Ib, signed, modifier), + .remembered(plain, stela_contracts::pauth::Key::Ib, signed, modifier), None ); - let computed = context.authenticate_operation(pauth::Key::Ib, signed, modifier, false); - let result = machine.pointer_result(plain, pauth::Key::Ib, signed, modifier); + let computed = context.authenticate_operation( + stela_contracts::pauth::Key::Ib, + signed, + modifier, + false, + ); + let result = + machine.pointer_result(plain, stela_contracts::pauth::Key::Ib, signed, modifier); match computed { Ok(computed) => assert_eq!(result, Ok(Ok((computed.pointer, computed.authenticated)))), Err(pauth::AuthenticationError::Failure { code }) => assert_eq!(result, Ok(Err(code))), @@ -11766,26 +11820,34 @@ mod tests { machine.cpu.state.x[0] = pointer; machine.cpu.state.x[1] = 0x1234; machine.system_instruction_for_test(PACIA_X0_X1); - let signed = context.sign(pauth::Key::Ia, pointer, 0x1234).unwrap(); + let signed = context + .sign(stela_contracts::pauth::Key::Ia, pointer, 0x1234) + .unwrap(); assert_eq!(machine.cpu.state.x[0], signed); machine.system_instruction_for_test(AUTIA_X0_X1); assert_eq!(machine.cpu.state.x[0], pointer); // BLRAA links after authenticating the target with X3. - machine.cpu.state.x[2] = context.sign(pauth::Key::Ia, pointer, 0x99).unwrap(); + machine.cpu.state.x[2] = context + .sign(stela_contracts::pauth::Key::Ia, pointer, 0x99) + .unwrap(); machine.cpu.state.x[3] = 0x99; let pc = machine.cpu.pc; machine.system_instruction_for_test(BLRAA_X2_X3); assert_eq!((machine.cpu.pc, machine.cpu.state.x[30]), (pointer, pc + 4)); // BRAAZ authenticates with a zero modifier; a wrong one corrupts // the target, as the general path's combined authentication does. - machine.cpu.state.x[2] = context.sign(pauth::Key::Ia, pointer, 0).unwrap(); + machine.cpu.state.x[2] = context + .sign(stela_contracts::pauth::Key::Ia, pointer, 0) + .unwrap(); machine.system_instruction_for_test(BRAAZ_X2); assert_eq!(machine.cpu.pc, pointer); - let wrong = context.sign(pauth::Key::Ia, pointer, 1).unwrap(); + let wrong = context + .sign(stela_contracts::pauth::Key::Ia, pointer, 1) + .unwrap(); machine.cpu.state.x[2] = wrong; let fault_pc = machine.cpu.pc; machine.system_instruction_for_test(BRAAZ_X2); - match context.authenticate_operation(pauth::Key::Ia, wrong, 0, true) { + match context.authenticate_operation(stela_contracts::pauth::Key::Ia, wrong, 0, true) { Ok(result) => assert_eq!(machine.cpu.pc, result.pointer), Err(pauth::AuthenticationError::Failure { code }) => { // FEAT_FPACCOMBINE (M6) faults the failed branch instead of @@ -11813,7 +11875,11 @@ mod tests { let signed = machine .pointer_context() .unwrap() - .sign(pauth::Key::Ia, target, machine.cpu.state.sp) + .sign( + stela_contracts::pauth::Key::Ia, + target, + machine.cpu.state.sp, + ) .unwrap(); machine .cpu @@ -11850,7 +11916,7 @@ mod tests { assert_eq!(machine.cpu.read(SystemRegister::ESR_EL2), 0x2600_0000); // With FEAT_FPACCOMBINE (M6) the failed combined check takes EC 0x1C, // ISS {data=0, key A=0}, at the ERETAA and the return is not made. - let mut machine = pac_machine_for(crate::machine::Chip::AppleM6, &[]); + let mut machine = pac_machine_for(stela_contracts::Chip::AppleM6, &[]); machine.cpu.state.sp = 0xffff_ff80_0002_0010; let registers = &mut machine.cpu.registers; registers.set(SystemRegister::ELR_EL1, 0, signed); @@ -12214,8 +12280,8 @@ mod tests { const MSR_FPCR_X0: u32 = 0xd51b_4400; const MRS_X1_FPCR: u32 = 0xd53b_4401; for (chip, afp) in [ - (crate::machine::Chip::AppleM2, false), - (crate::machine::Chip::AppleM4, true), + (stela_contracts::Chip::AppleM2, false), + (stela_contracts::Chip::AppleM4, true), ] { let mut machine = machine_on(chip, &[]); for register in [SystemRegister::CPACR_EL1, SystemRegister::CPTR_EL2] { @@ -12321,8 +12387,8 @@ mod tests { 0xd500_001f | u32::from(accessor.value) << 5 }; for (chip, xs) in [ - (crate::machine::Chip::AppleM2, false), - (crate::machine::Chip::AppleM4, true), + (stela_contracts::Chip::AppleM2, false), + (stela_contracts::Chip::AppleM4, true), ] { let fresh = |el| { let mut machine = machine_on(chip, &[]); @@ -12520,8 +12586,8 @@ mod tests { const COSP_RCTX_X0: u32 = 0xd50b_73c0; const SCTLR_ENRCTX: u64 = 1 << 10; for (chip, specres2) in [ - (crate::machine::Chip::AppleM4, false), - (crate::machine::Chip::AppleM5, true), + (stela_contracts::Chip::AppleM4, false), + (stela_contracts::Chip::AppleM5, true), ] { let fresh = |el| { let mut machine = machine_on(chip, &[]); diff --git a/crates/stela-runtime/src/machine/engine/amx.rs b/crates/stela-runtime/src/machine/engine/amx.rs index aacc6f71e9..4450dab2a6 100644 --- a/crates/stela-runtime/src/machine/engine/amx.rs +++ b/crates/stela-runtime/src/machine/engine/amx.rs @@ -244,12 +244,12 @@ impl Machine { mod tests { use super::super::tests::{BASE, machine_on}; use super::*; - use crate::machine::Chip; use crate::machine::system::Register as SystemRegister; use crate::machine::{ amx::{AMX_CTL_EL1, AMX_STATE_T, AmxView}, exception::syndrome, }; + use stela_contracts::Chip; fn machine(words: &[u32]) -> Machine { machine_on(Chip::AppleM2, words) diff --git a/crates/stela-runtime/src/machine/engine/apple_maintenance.rs b/crates/stela-runtime/src/machine/engine/apple_maintenance.rs index 83927455fe..3cb584c14b 100644 --- a/crates/stela-runtime/src/machine/engine/apple_maintenance.rs +++ b/crates/stela-runtime/src/machine/engine/apple_maintenance.rs @@ -3,11 +3,11 @@ //! SPTMs execute. The contracts and their evidence are in //! `docs/design/system.md` (GXF). use super::{Devices, Host, Machine, RequirementKind, Step}; -use crate::machine::{ - Chip, hacr, - mmu::tlbi::{Everywhere, Reach}, -}; use stela_compiler::block::system::AppleMaintenance; +use { + crate::machine::hacr, crate::machine::mmu::tlbi::Everywhere, crate::machine::mmu::tlbi::Reach, + stela_contracts::Chip, +}; /// The first chip with DC INCPA4K, operation 25 and `0x00201401`: XNU gives /// H16 and H17 `HAS_DC_INCPA`, the 26A434 SPTMs of the M4 to M6 (T8132, diff --git a/crates/stela-runtime/src/machine/engine/compression.rs b/crates/stela-runtime/src/machine/engine/compression.rs index 20bc234651..b90db863ec 100644 --- a/crates/stela-runtime/src/machine/engine/compression.rs +++ b/crates/stela-runtime/src/machine/engine/compression.rs @@ -13,15 +13,15 @@ //! MTE tag checking (the 26A434 kernel disables checking around the //! compressor). use super::{Devices, FETCH_PAGE, Host, Machine, RequirementKind, Step, Stop, Translated}; -use crate::machine::{ - Chip, debug, - mmu::{Access, MemoryType}, -}; use alloc::{format, vec, vec::Vec}; use stela_compiler::wkdm::{ self, Instruction, Operation, PAGE_BYTES, Population, Status, UNIT_BYTES, codec::{self, Compressed, HEADER_BYTES}, }; +use { + crate::machine::debug, crate::machine::mmu::Access, crate::machine::mmu::MemoryType, + stela_contracts::Chip, +}; /// What the population count field counts on `chip`. XNU names M1 (H13, /// `xnu-8792`) uncompressed and M4 and M5 (H16, H17, `xnu-12377`) diff --git a/crates/stela-runtime/src/machine/engine/guarded.rs b/crates/stela-runtime/src/machine/engine/guarded.rs index 69ce680994..1755e5bc55 100644 --- a/crates/stela-runtime/src/machine/engine/guarded.rs +++ b/crates/stela-runtime/src/machine/engine/guarded.rs @@ -76,7 +76,7 @@ pub(super) mod tests { use super::super::NoDevices; use super::super::tests::{BASE, FakeHost, machine_on}; use super::*; - use crate::machine::{Chip, system::Register as SystemRegister}; + use {crate::machine::system::Register as SystemRegister, stela_contracts::Chip}; const GENTER: u32 = 0x0020_1420; const GEXIT: u32 = 0x0020_1400; diff --git a/crates/stela-runtime/src/machine/engine/monitor.rs b/crates/stela-runtime/src/machine/engine/monitor.rs index 9ec28ae039..360c01caaa 100644 --- a/crates/stela-runtime/src/machine/engine/monitor.rs +++ b/crates/stela-runtime/src/machine/engine/monitor.rs @@ -92,8 +92,11 @@ mod tests { tests::{BASE, FakeHost}, }; use super::*; - use crate::machine::{Chip, Identity, exception::Pstate}; use alloc::{format, vec::Vec}; + use { + crate::machine::exception::Pstate, stela_contracts::Chip, + stela_contracts::identity::Identity, + }; const GENTER: u32 = 0x0020_1420; const GEXIT: u32 = 0x0020_1400; diff --git a/crates/stela-runtime/src/machine/engine/parallel.rs b/crates/stela-runtime/src/machine/engine/parallel.rs index cf3880acf1..b866ddb4f1 100644 --- a/crates/stela-runtime/src/machine/engine/parallel.rs +++ b/crates/stela-runtime/src/machine/engine/parallel.rs @@ -1532,7 +1532,7 @@ mod tests { match value { 1 => { self.reset = Some(Reset { - transition: crate::platform::apple::bus::Transition::Restart, + transition: stela_contracts::bus::Transition::Restart, reason: "test".into(), }) } diff --git a/crates/stela-runtime/src/machine/engine/pointer.rs b/crates/stela-runtime/src/machine/engine/pointer.rs index f3c4eb0202..adbda5d759 100644 --- a/crates/stela-runtime/src/machine/engine/pointer.rs +++ b/crates/stela-runtime/src/machine/engine/pointer.rs @@ -57,21 +57,21 @@ fn memo_result(operation: PointerOperation, result: PointerResult) -> (u64, u64) } /// The memo index of a key. -pub(super) fn memo_key(key: pauth::Key) -> u8 { +pub(super) fn memo_key(key: stela_contracts::pauth::Key) -> u8 { pointer::key_index(match key { - pauth::Key::Ia => PointerAuthenticationKey::Ia, - pauth::Key::Ib => PointerAuthenticationKey::Ib, - pauth::Key::Da => PointerAuthenticationKey::Da, - pauth::Key::Db => PointerAuthenticationKey::Db, + stela_contracts::pauth::Key::Ia => PointerAuthenticationKey::Ia, + stela_contracts::pauth::Key::Ib => PointerAuthenticationKey::Ib, + stela_contracts::pauth::Key::Da => PointerAuthenticationKey::Da, + stela_contracts::pauth::Key::Db => PointerAuthenticationKey::Db, }) } -fn key_of(key: PointerAuthenticationKey) -> pauth::Key { +fn key_of(key: PointerAuthenticationKey) -> stela_contracts::pauth::Key { match key { - PointerAuthenticationKey::Ia => pauth::Key::Ia, - PointerAuthenticationKey::Ib => pauth::Key::Ib, - PointerAuthenticationKey::Da => pauth::Key::Da, - PointerAuthenticationKey::Db => pauth::Key::Db, + PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, + PointerAuthenticationKey::Ib => stela_contracts::pauth::Key::Ib, + PointerAuthenticationKey::Da => stela_contracts::pauth::Key::Da, + PointerAuthenticationKey::Db => stela_contracts::pauth::Key::Db, } } @@ -143,7 +143,12 @@ impl PointerService { /// After [`Self::revalidate`], open `key`'s tag word as a PAC exit /// would: [`pointer::DISABLED`] while its SCTLR enable is clear, else, /// untrapped and present in the context, the memo's current tag. - pub(super) fn reopen(&mut self, key: pauth::Key, enabled: bool, trapped: bool) { + pub(super) fn reopen( + &mut self, + key: stela_contracts::pauth::Key, + enabled: bool, + trapped: bool, + ) { let index = memo_key(key); self.tags[usize::from(index)] = if !enabled { pointer::DISABLED @@ -235,7 +240,7 @@ impl PointerService { pub(super) fn result( &mut self, operation: PointerOperation, - key: pauth::Key, + key: stela_contracts::pauth::Key, pointer: u64, modifier: u64, ) -> Option { @@ -293,7 +298,7 @@ impl PointerService { pub(super) fn remembered( &self, operation: PointerOperation, - key: pauth::Key, + key: stela_contracts::pauth::Key, pointer: u64, modifier: u64, ) -> Option { @@ -318,7 +323,7 @@ impl PointerService { fn remember( &mut self, operation: PointerOperation, - key: pauth::Key, + key: stela_contracts::pauth::Key, pointer: u64, modifier: u64, result: PointerResult, @@ -378,7 +383,12 @@ mod tests { service.open(input); assert!( service - .result(PointerOperation::Sign, pauth::Key::Ia, 0x4000, 0x8000) + .result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 0x4000, + 0x8000 + ) .is_none() ); assert_eq!(service.tags, [0; 4]); @@ -388,7 +398,12 @@ mod tests { service.open(input); assert!( service - .result(PointerOperation::Sign, pauth::Key::Ia, 0x4000, 0x8000) + .result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 0x4000, + 0x8000 + ) .is_some() ); assert_ne!(service.generation, unknown_generation); @@ -399,7 +414,12 @@ mod tests { assert_eq!(service.generation, unknown_generation); assert!( service - .result(PointerOperation::Sign, pauth::Key::Ia, 0x4000, 0x8000) + .result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 0x4000, + 0x8000 + ) .is_none() ); assert_eq!(service.tags, [0; 4]); @@ -432,7 +452,11 @@ mod tests { for pointer in [0, u64::MAX, 1 << 55, 1 << 63, 0xdead_1234_5678_abcd] { let upper = pointer & (1 << 55) != 0; let keep = cell.keep[usize::from(upper)]; - let key = if data { pauth::Key::Da } else { pauth::Key::Ia }; + let key = if data { + stela_contracts::pauth::Key::Da + } else { + stela_contracts::pauth::Key::Ia + }; assert_eq!( (pointer & keep) | if upper { cell.upper_extension } else { 0 }, context.strip(key, pointer).unwrap() @@ -558,7 +582,12 @@ mod tests { assert!(!service.is_open()); assert_eq!(service.tags, [0; 4]); assert_eq!( - service.result(PointerOperation::Sign, pauth::Key::Ia, 1, 2), + service.result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 1, + 2 + ), None ); } diff --git a/crates/stela-runtime/src/machine/engine/prepare.rs b/crates/stela-runtime/src/machine/engine/prepare.rs index 1eeef4ba05..8f2fe36a69 100644 --- a/crates/stela-runtime/src/machine/engine/prepare.rs +++ b/crates/stela-runtime/src/machine/engine/prepare.rs @@ -9,16 +9,16 @@ //! those bytes in that variant, which is what lets the store key it by its //! page bytes and context alone. use super::{FETCH_PAGE, INSTRUCTION, MAX_BLOCK_BYTES, PROFILE, is_floating_point}; -use crate::{ - machine::chip::{AdmitTable, Check, Chip}, - translations::{self, Digest}, -}; use alloc::{format, string::String, sync::Arc, vec, vec::Vec}; use stela_compiler::{ CompileError, GuestAddress, TargetCpu, block::{self, CompilationPlan, CompiledBlock}, x86_64::{MemoryChecks, NativeSystem}, }; +use { + crate::translations, crate::translations::Digest, stela_contracts::chip::AdmitTable, + stela_contracts::chip::Check, stela_contracts::chip::Chip, +}; /// The bytes of the source window of a block at `pc`: to the end of its /// fetch page, which no block leaves, and at most a block's. @@ -322,7 +322,7 @@ pub(crate) fn test_preparation() -> Preparation { #[cfg(test)] mod tests { use super::*; - use crate::machine::system::Feature; + use stela_contracts::Feature; /// A description makes its preparation again, and one whose withheld set /// has no admit table is refused rather than trusted. diff --git a/crates/stela-runtime/src/machine/engine/processors.rs b/crates/stela-runtime/src/machine/engine/processors.rs index b347b99fa8..328e85f3db 100644 --- a/crates/stela-runtime/src/machine/engine/processors.rs +++ b/crates/stela-runtime/src/machine/engine/processors.rs @@ -877,9 +877,10 @@ fn pause_cpu(cpu: &mut Cpu, waiting: Option, now: u64, paused: bool) { mod tests { use super::super::tests::{BASE, FakeHost, board}; use super::*; - use crate::machine::{ - cpu::Reservation, engine::DeviceError, exception::DAIF_ALL, registers::Identity, - system::Register, + use { + crate::machine::cpu::Reservation, crate::machine::engine::DeviceError, + crate::machine::exception::DAIF_ALL, crate::machine::system::Register, + stela_contracts::identity::Identity, }; const WFE: u32 = 0xd503_205f; @@ -982,7 +983,7 @@ mod tests { fn transfer( &mut self, _: usize, - memory: &mut dyn crate::platform::dma::Memory, + memory: &mut dyn stela_contracts::dma::Memory, now: u64, ) -> Result<(), DeviceError> { if self.dma.is_some_and(|deadline| now >= deadline) { @@ -1175,16 +1176,16 @@ mod tests { } } - const RETAINED_ACTIVE: crate::platform::apple::bus::LifecycleState = - crate::platform::apple::bus::LifecycleState { + const RETAINED_ACTIVE: stela_contracts::bus::LifecycleState = + stela_contracts::bus::LifecycleState { powered: true, clocked: true, quiesced: false, reset: false, retention: false, }; - const RETAINED_GATED: crate::platform::apple::bus::LifecycleState = - crate::platform::apple::bus::LifecycleState { + const RETAINED_GATED: stela_contracts::bus::LifecycleState = + stela_contracts::bus::LifecycleState { clocked: false, ..RETAINED_ACTIVE }; @@ -1200,7 +1201,7 @@ mod tests { fn power_change( machine: &mut Machine, domain: u64, - state: crate::platform::apple::bus::LifecycleState, + state: stela_contracts::bus::LifecycleState, ) { let plan = machine .prepare_processor_power(&[ProcessorChange { domain, state }]) @@ -1248,7 +1249,7 @@ mod tests { }, ProcessorChange { domain: 2, - state: crate::platform::apple::bus::LifecycleState { + state: stela_contracts::bus::LifecycleState { quiesced: true, ..RETAINED_ACTIVE }, @@ -1785,7 +1786,7 @@ mod tests { #[test] fn original_m6_mixed_cluster_shares_live_or_parked_owners_in_either_start_order() { use super::super::tests::board_on; - use crate::machine::{Chip, ctrr::Field, impdef}; + use {crate::machine::ctrr::Field, crate::machine::impdef, stela_contracts::Chip}; const MPIDRS: [u64; 12] = [ 0x8000_0000, 0x8000_0001, @@ -1894,7 +1895,7 @@ mod tests { #[test] fn every_pe_and_new_cluster_starts_from_the_core_lock_handoff() { use super::super::tests::board_on; - use crate::machine::Chip; + use stela_contracts::Chip; let identities = [0x8000_0000, 0x8001_0100] .into_iter() .map(|mpidr| Identity { @@ -1949,7 +1950,7 @@ mod tests { }) .collect(); let mut machine = board_on( - crate::machine::Chip::AppleM2, + stela_contracts::Chip::AppleM2, &[], super::super::NoDevices, identities, @@ -1987,7 +1988,7 @@ mod tests { good, ProcessorChange { domain: 7, - state: crate::platform::apple::bus::LifecycleState { + state: stela_contracts::bus::LifecycleState { reset: true, ..RETAINED_ACTIVE } diff --git a/crates/stela-runtime/src/machine/engine/processors/publication.rs b/crates/stela-runtime/src/machine/engine/processors/publication.rs index a1607a7d6a..132b42ed0b 100644 --- a/crates/stela-runtime/src/machine/engine/processors/publication.rs +++ b/crates/stela-runtime/src/machine/engine/processors/publication.rs @@ -961,15 +961,16 @@ impl WorkerRelease { #[cfg(test)] mod tests { use super::*; - use crate::machine::{ - engine::NoDevices, - engine::tests::board, - engine::{FaultCause, InstallError, NativeCode, NativeExit, NativeFault, Regime}, - engine::{ProcessorBinding, ProcessorChange, ProcessorTarget}, - registers::Identity, - }; - use crate::platform::apple::bus::LifecycleState; use stela_compiler::GuestState; + use stela_contracts::bus::LifecycleState; + use { + crate::machine::engine::FaultCause, crate::machine::engine::InstallError, + crate::machine::engine::NativeCode, crate::machine::engine::NativeExit, + crate::machine::engine::NativeFault, crate::machine::engine::NoDevices, + crate::machine::engine::ProcessorBinding, crate::machine::engine::ProcessorChange, + crate::machine::engine::ProcessorTarget, crate::machine::engine::Regime, + crate::machine::engine::tests::board, stela_contracts::identity::Identity, + }; #[derive(Default)] struct LocalHost { diff --git a/crates/stela-runtime/src/machine/engine/processors/publication/service.rs b/crates/stela-runtime/src/machine/engine/processors/publication/service.rs index 6e9078e4f9..7adc1a6546 100644 --- a/crates/stela-runtime/src/machine/engine/processors/publication/service.rs +++ b/crates/stela-runtime/src/machine/engine/processors/publication/service.rs @@ -859,7 +859,7 @@ mod tests { let (mut inventory, mut owners, mut hosts, held) = held(); let mut services = inventory.open_services(&held, 1).unwrap(); let cpu = crate::machine::Cpu::of( - crate::machine::Chip::AppleM1, + stela_contracts::Chip::AppleM1, 0, crate::machine::exception::Pstate::reset(2), ); diff --git a/crates/stela-runtime/src/machine/engine/processors/retained.rs b/crates/stela-runtime/src/machine/engine/processors/retained.rs index 4eccdc4c89..01bb69ffc9 100644 --- a/crates/stela-runtime/src/machine/engine/processors/retained.rs +++ b/crates/stela-runtime/src/machine/engine/processors/retained.rs @@ -1,8 +1,8 @@ //! Retained CPU participants, independent of a board's PMGR record resolver. //! A caller must supply the positively qualified physical domain and exact PE //! membership. Neither record names, byte 2 nor MPIDR core-type bits select it. -use crate::platform::apple::bus::LifecycleState; use alloc::{collections::BTreeMap, vec, vec::Vec}; +use stela_contracts::bus::LifecycleState; /// An explicitly qualified CPU owner. A physical cluster can mix core types. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/stela-runtime/src/machine/engine/scalable.rs b/crates/stela-runtime/src/machine/engine/scalable.rs index e4532bef6a..d4a100a9cf 100644 --- a/crates/stela-runtime/src/machine/engine/scalable.rs +++ b/crates/stela-runtime/src/machine/engine/scalable.rs @@ -18,15 +18,6 @@ use super::{ DeviceError, Devices, FETCH_PAGE, Fetched, Host, InstallError, Machine, NativeCode, RamTables, RequirementKind, Step, Stop, Translated, Variant, tags::TagCheck, }; -use crate::machine::{ - cpu::{Exception, STREAMING_VECTOR_BYTES}, - debug, - exception::Class, - mmu::{self, Access, MemoryType, alignment}, - streaming::{self, VectorDestinations}, - system::Feature, - system::File, -}; use crate::scalable::ScalableState; use alloc::{format, string::String, vec::Vec}; use stela_compiler::{ @@ -56,6 +47,13 @@ use stela_compiler::{ }, scalable_context::ScalableProfile, }; +use { + crate::machine::cpu::Exception, crate::machine::cpu::STREAMING_VECTOR_BYTES, + crate::machine::debug, crate::machine::exception::Class, crate::machine::mmu, + crate::machine::mmu::Access, crate::machine::mmu::MemoryType, crate::machine::mmu::alignment, + crate::machine::streaming, crate::machine::streaming::VectorDestinations, + crate::machine::system::File, stela_contracts::Feature, +}; /// The numerical features of every Apple chip's identification: no /// FEAT_SME_FA64 (FullA64 off), FEAT_EBF16 or FEAT_RPRES. @@ -1078,7 +1076,7 @@ mod tests { /// the reserved encodings they hit. #[test] fn every_sve_and_sme_form_of_the_sme_chips_runs_or_is_undefined() { - use crate::machine::{Chip, chip::Check}; + use {stela_contracts::Chip, stela_contracts::chip::Check}; // BFSCALE, of FEAT_SVE_BFSCALE, which no Apple chip has, lies inside // FSCALE's encodings, and the compiler declines it as unknown: the // SVE form, and the multi-vector forms, FSCALE's with size 0. @@ -1154,7 +1152,7 @@ mod tests { #[test] fn features_the_chip_lacks_and_debug_state_movt_are_undefined_before_their_checks() { - use crate::machine::Chip; + use stela_contracts::Chip; const BFADD_Z0_Z1: u32 = 0x6500_8020; // bfadd z0.h, p0/m, z0.h, z1.h const MOVT_X0_ZT0: u32 = 0xc04c_03e0; // movt x0, zt0[0] const UNDEFINED: u64 = 1 << 25; @@ -1276,7 +1274,7 @@ mod tests { FSCALE, F1CVT, ]; - let mut machine = super::super::tests::machine_on(crate::machine::Chip::AppleM6, &words); + let mut machine = super::super::tests::machine_on(stela_contracts::Chip::AppleM6, &words); enable_streaming(&mut machine); for _ in 0..5 { machine.step().unwrap(); @@ -1326,7 +1324,10 @@ mod tests { const HCR_ATA: u64 = 1 << 56; const SCTLR_ATA_TCF_SYNC: u64 = 1 << 43 | 1 << 40; const TCR_TBI0: u64 = 1 << 37; - for chip in [crate::machine::Chip::AppleM5, crate::machine::Chip::AppleM6] { + for chip in [ + stela_contracts::Chip::AppleM5, + stela_contracts::Chip::AppleM6, + ] { let mut machine = super::super::tests::machine_on(chip, &[PTRUE_P0_B, LD1B_Z2_X5]); enable_streaming(&mut machine); normal_memory(&mut machine, false); diff --git a/crates/stela-runtime/src/machine/engine/shared_memory.rs b/crates/stela-runtime/src/machine/engine/shared_memory.rs index 51ddcc79e9..6e90ce3413 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory.rs @@ -441,7 +441,7 @@ mod tests { EventDomain, ) { let (cpu, profile, missing, ram) = policy::tests::fixture(); - let mut machine = board_on(crate::machine::Chip::AppleM1, &[], NoDevices, Vec::new()); + let mut machine = board_on(stela_contracts::Chip::AppleM1, &[], NoDevices, Vec::new()); machine.cpu = cpu; machine.profile = profile; machine.profile_missing = missing; @@ -638,9 +638,9 @@ mod tests { } fn clock_domain( machine: &mut Machine, - ) -> crate::platform::apple::bus::LifecycleState { + ) -> stela_contracts::bus::LifecycleState { use super::super::{ProcessorBinding, ProcessorTarget}; - let active = crate::platform::apple::bus::LifecycleState { + let active = stela_contracts::bus::LifecycleState { powered: true, clocked: true, quiesced: false, @@ -668,7 +668,7 @@ mod tests { let state = machine.cpu.state.clone(); let request = [ProcessorChange { domain: 1, - state: crate::platform::apple::bus::LifecycleState { + state: stela_contracts::bus::LifecycleState { clocked: false, ..active }, @@ -711,7 +711,7 @@ mod tests { ); let request = [ProcessorChange { domain: 1, - state: crate::platform::apple::bus::LifecycleState { + state: stela_contracts::bus::LifecycleState { clocked: false, ..active }, diff --git a/crates/stela-runtime/src/machine/engine/shared_memory/controls.rs b/crates/stela-runtime/src/machine/engine/shared_memory/controls.rs index 3b766854e8..a9f19da00c 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory/controls.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory/controls.rs @@ -131,7 +131,7 @@ impl Controls { let address_checks = ProcessMemoryFeatures::from_snapshot(&identification) .map_err(|_| MemoryStatus::Unsupported)? .unchecked_address_checks(); - let identity = crate::sha256( + let identity = stela_formats::sha256( alloc::format!( "{:?} {:?} {:?} {} {:?} {}", translation, @@ -221,7 +221,10 @@ impl Controls { #[cfg(test)] pub(super) mod tests { use super::*; - use crate::machine::{Chip, CpuProfile, exception::Pstate, identification}; + use { + crate::machine::CpuProfile, crate::machine::exception::Pstate, + crate::machine::identification, stela_contracts::Chip, + }; pub(in crate::machine::engine::shared_memory) fn captured() -> (Cpu, CpuProfile, Vec) { let chip = Chip::AppleM1; @@ -307,7 +310,7 @@ pub(super) mod tests { let controls = Controls::capture(&cpu, profile.name, &missing).unwrap(); // Preserve the prior serialization as a negative compatibility input; // the new source-qualified address policy must not reuse that key. - let legacy = crate::sha256( + let legacy = stela_formats::sha256( alloc::format!( "{:?} {:?} {:?} {} {}", controls.translation, diff --git a/crates/stela-runtime/src/machine/engine/shared_memory/host.rs b/crates/stela-runtime/src/machine/engine/shared_memory/host.rs index 27686e0fa6..ee5f108bd1 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory/host.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory/host.rs @@ -245,20 +245,20 @@ impl Host for ServiceHost { physical: u64, bytes: usize, write: bool, - ) -> Result<(), crate::platform::dma::DmaError> { + ) -> Result<(), stela_contracts::dma::DmaError> { self.ram .check_dma_range(physical, bytes, write) - .map_err(|_| crate::platform::dma::DmaError::Memory) + .map_err(|_| stela_contracts::dma::DmaError::Memory) } fn read_ram_progress( &mut self, physical: u64, buffer: &mut [u8], - ) -> Result<(), crate::platform::dma::TransferFault> { + ) -> Result<(), stela_contracts::dma::TransferFault> { // SAFETY: private DMA staging, same canonical reader/owner contract. unsafe { self.ram.read_physical_progress(physical, buffer) }.map_err(|fault| { - crate::platform::dma::TransferFault { - error: crate::platform::dma::DmaError::Memory, + stela_contracts::dma::TransferFault { + error: stela_contracts::dma::DmaError::Memory, completed: fault.completed, } }) @@ -267,11 +267,11 @@ impl Host for ServiceHost { &mut self, physical: u64, data: &[u8], - ) -> Result<(), crate::platform::dma::TransferFault> { + ) -> Result<(), stela_contracts::dma::TransferFault> { // SAFETY: private staging, every writer participates in this same domain. unsafe { self.ram.publish_physical(physical, data) }.map_err(|fault| { - crate::platform::dma::TransferFault { - error: crate::platform::dma::DmaError::Memory, + stela_contracts::dma::TransferFault { + error: stela_contracts::dma::DmaError::Memory, completed: fault.completed, } }) @@ -601,7 +601,7 @@ pub(in crate::machine::engine::shared_memory) mod tests { if count > 1 { // Synthetic modeled slots, not a claim about a physical Apple SKU. profile.processors = (0..count) - .map(|pe| crate::machine::registers::Identity { + .map(|pe| stela_contracts::identity::Identity { midr: 0x611f0220, mpidr: 0x80000000 | pe as u64, clock: None, diff --git a/crates/stela-runtime/src/machine/engine/shared_memory/lifecycle.rs b/crates/stela-runtime/src/machine/engine/shared_memory/lifecycle.rs index a2cfa34d90..1eaca89964 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory/lifecycle.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory/lifecycle.rs @@ -159,7 +159,7 @@ mod tests { fn fixture(count: usize) -> (Machine, Vec) { let (cpu, mut profile, missing, ram) = super::super::policy::tests::fixture(); profile.processors = (0..count) - .map(|pe| crate::machine::registers::Identity { + .map(|pe| stela_contracts::identity::Identity { midr: 0x611f0220, mpidr: 0x80000000 | pe as u64, clock: None, @@ -295,7 +295,7 @@ mod tests { let (mut cpu, mut profile, missing, ram) = super::super::policy::tests::fixture(); // Authored E,E,P,P roster; preserve the original indices and affinities. profile.processors = (0..4) - .map(|pe| crate::machine::registers::Identity { + .map(|pe| stela_contracts::identity::Identity { midr: if pe < FIRST_P { 0x611f0220 } else { 0x611f0230 }, mpidr: 0x80000000 | if pe < FIRST_P { diff --git a/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs b/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs index 7dea557f2f..0d71cc6fe3 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory/native_run.rs @@ -60,8 +60,8 @@ pub struct ArtifactCacheStats { /// the profile chip independently selects access checks. #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct AdmissionPolicy { - profile_chip: crate::machine::Chip, - table_chip: crate::machine::Chip, + profile_chip: stela_contracts::Chip, + table_chip: stela_contracts::Chip, withheld: u64, asimd: bool, } @@ -780,7 +780,7 @@ fn prepare<'a>( pe: usize, cpu_profile: &crate::machine::CpuProfile, missing: &[crate::machine::system::Register], - admit: &crate::machine::chip::AdmitTable, + admit: &stela_contracts::chip::AdmitTable, boundary: PreparationBoundary, ) -> Result, PreparationFailure> { let PreparationBoundary { @@ -869,7 +869,7 @@ fn prepare<'a>( && cpu_profile.chip.checks(word).iter().all(|check| { matches!( check, - crate::machine::chip::Check::Fp | crate::machine::chip::Check::FpAdvSimd + stela_contracts::chip::Check::Fp | stela_contracts::chip::Check::FpAdvSimd ) }) }; @@ -973,8 +973,8 @@ fn prepare<'a>( let identity = Identity { pe, pc, - source_sha256: crate::sha256(&input), - native_sha256: crate::sha256(&compiled.native.x86_64_code), + source_sha256: stela_formats::sha256(&input), + native_sha256: stela_formats::sha256(&compiled.native.x86_64_code), controls_sha256: key.controls_sha256.as_ref().into(), compiler_source_sha256: stela_compiler::SOURCE_SHA256, abi: profile.abi(), @@ -1657,7 +1657,7 @@ mod artifact_tests { let first = prepare_artifact(&mut machine, BINDING).unwrap(); let chip = machine.profile.chip; let table = Arc::clone(&machine.admit_table); - machine.profile.chip = crate::machine::Chip::AppleM2; + machine.profile.chip = stela_contracts::Chip::AppleM2; let profile = prepare_artifact(&mut machine, BINDING).unwrap(); assert!(!Arc::ptr_eq(&first, &profile)); assert_ne!( @@ -1671,7 +1671,7 @@ mod artifact_tests { assert_eq!(first.source, profile.source); machine.profile.chip = chip; machine.admit_table = Arc::new( - crate::machine::Chip::AppleM2 + stela_contracts::Chip::AppleM2 .admit_table(table.withheld()) .unwrap(), ); @@ -1682,7 +1682,7 @@ mod artifact_tests { table_chip.key.admission.table_chip ); assert_eq!(first.source, table_chip.source); - let withheld = table.withheld() ^ (1 << crate::machine::system::Feature::FEAT_WFxT as u64); + let withheld = table.withheld() ^ (1 << stela_contracts::Feature::FEAT_WFxT as u64); machine.admit_table = Arc::new(table.chip().admit_table(withheld).unwrap()); let features = prepare_artifact(&mut machine, BINDING).unwrap(); assert!(!Arc::ptr_eq(&first, &features)); @@ -2040,7 +2040,7 @@ mod artifact_tests { .unwrap() .native_artifact_stats(); machine.cpu.pc = PC; - machine.profile.chip = crate::machine::Chip::AppleM2; + machine.profile.chip = stela_contracts::Chip::AppleM2; let changed = prepare_artifact(&mut machine, BINDING).unwrap(); assert!(!Arc::ptr_eq(&changed, &artifacts[0])); let cache = &machine.cpu.canonical_memory.as_ref().unwrap().artifacts; diff --git a/crates/stela-runtime/src/machine/engine/shared_memory/native_run/access.rs b/crates/stela-runtime/src/machine/engine/shared_memory/native_run/access.rs index e2318346ce..a962d8595e 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory/native_run/access.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory/native_run/access.rs @@ -208,7 +208,7 @@ mod tests { })?; if self.clock { use engine::ProcessorChange; - let active = crate::platform::apple::bus::LifecycleState { + let active = stela_contracts::bus::LifecycleState { powered: true, clocked: true, quiesced: false, @@ -219,7 +219,7 @@ mod tests { .processors()? .apply(&[ProcessorChange { domain: 1, - state: crate::platform::apple::bus::LifecycleState { + state: stela_contracts::bus::LifecycleState { clocked: false, ..active }, @@ -423,7 +423,7 @@ mod tests { .bind_processor_power(&[engine::ProcessorBinding { domain: 1, target: engine::ProcessorTarget::Core { pe: 0 }, - initial: crate::platform::apple::bus::LifecycleState { + initial: stela_contracts::bus::LifecycleState { powered: true, clocked: true, quiesced: false, diff --git a/crates/stela-runtime/src/machine/engine/shared_memory/scheduler.rs b/crates/stela-runtime/src/machine/engine/shared_memory/scheduler.rs index 2c92749d34..abd5d9bbf9 100644 --- a/crates/stela-runtime/src/machine/engine/shared_memory/scheduler.rs +++ b/crates/stela-runtime/src/machine/engine/shared_memory/scheduler.rs @@ -647,7 +647,7 @@ impl Machine, D> { if checks.iter().any(|check| { !matches!( check, - crate::machine::chip::Check::Fp | crate::machine::chip::Check::FpAdvSimd + stela_contracts::chip::Check::Fp | stela_contracts::chip::Check::FpAdvSimd ) }) { return Err(self.unsupported(RequirementKind::Native( diff --git a/crates/stela-runtime/src/machine/engine/stored.rs b/crates/stela-runtime/src/machine/engine/stored.rs index bdc07c8634..3884b22b3c 100644 --- a/crates/stela-runtime/src/machine/engine/stored.rs +++ b/crates/stela-runtime/src/machine/engine/stored.rs @@ -229,8 +229,11 @@ pub(super) mod tests { #[test] fn cached_blocks_do_not_cross_presented_instruction_features() { - use crate::machine::system::{Feature, Register}; - use crate::machine::{Chip, identification, registers::encodings::ID_AA64ISAR1_EL1}; + use { + crate::machine::identification, crate::machine::registers::encodings::ID_AA64ISAR1_EL1, + stela_contracts::Chip, + }; + use {crate::machine::system::Register, stela_contracts::Feature}; const SMMLA: u32 = 0x4e9b_a781; let words = [0x9100_0400, SMMLA, 0xd400_0001]; diff --git a/crates/stela-runtime/src/machine/engine/system.rs b/crates/stela-runtime/src/machine/engine/system.rs index c175abc444..485552199d 100644 --- a/crates/stela-runtime/src/machine/engine/system.rs +++ b/crates/stela-runtime/src/machine/engine/system.rs @@ -18,27 +18,32 @@ use super::{ tlbi::{self, Reach, Scope}, }, }; -use crate::machine::{ - CpuProfile, - amu::{self, Amu}, - cpu::{ - Cpu, Exception, HCR_AMO, HCR_FMO, HCR_IMO, HCR_TGE, HCR_VF, HCR_VI, HCR_VSE, - TranslationRegime, - }, - debug::{self, DCC_FULL}, - exception::{self, Class, DAIF_A, DAIF_D, DAIF_F, DAIF_I, Pstate as PstateBits}, - pmu::Pmu, - registers::{Lines, Refusal, trap_iss}, - system::{ - ACCESSORS, AtAccess, CacheOp, CacheScope, CacheType, Chip, Context, Effect, ErrorRecord, - Feature, File, Limit, Operation, Pstate, Register, Stage, Tlbi, helpers::sign_extend, - }, - timer::{self, Channel, agt::Bank}, -}; use alloc::vec::Vec; use core::cell::Cell; use stela_compiler::aarch64::system::registers::{Encoding, RegisterAccess}; use stela_compiler::x86_64::cache_clean; +use { + crate::machine::CpuProfile, crate::machine::amu, crate::machine::amu::Amu, + crate::machine::cpu::Cpu, crate::machine::cpu::Exception, crate::machine::cpu::HCR_AMO, + crate::machine::cpu::HCR_FMO, crate::machine::cpu::HCR_IMO, crate::machine::cpu::HCR_TGE, + crate::machine::cpu::HCR_VF, crate::machine::cpu::HCR_VI, crate::machine::cpu::HCR_VSE, + crate::machine::cpu::TranslationRegime, crate::machine::debug, crate::machine::debug::DCC_FULL, + crate::machine::exception, crate::machine::exception::Class, crate::machine::exception::DAIF_A, + crate::machine::exception::DAIF_D, crate::machine::exception::DAIF_F, + crate::machine::exception::DAIF_I, crate::machine::exception::Pstate as PstateBits, + crate::machine::pmu::Pmu, crate::machine::registers::Lines, crate::machine::registers::Refusal, + crate::machine::registers::trap_iss, crate::machine::system::ACCESSORS, + crate::machine::system::AtAccess, crate::machine::system::CacheOp, + crate::machine::system::CacheScope, crate::machine::system::CacheType, + crate::machine::system::Context, crate::machine::system::Effect, + crate::machine::system::ErrorRecord, crate::machine::system::File, + crate::machine::system::Limit, crate::machine::system::Operation, + crate::machine::system::Pstate, crate::machine::system::Register, + crate::machine::system::Stage, crate::machine::system::Tlbi, + crate::machine::system::helpers::sign_extend, crate::machine::timer, + crate::machine::timer::Channel, crate::machine::timer::agt::Bank, stela_contracts::Chip, + stela_contracts::Feature, +}; /// The FPCR fields of every chip: AHP, DN, FZ, RMode and FZ16 (FEAT_FP16). /// The trap enables IOE, DZE, OFE, UFE, IXE and IDE are RAZ/WI because the M2 @@ -1512,13 +1517,13 @@ pub(super) fn identify( mod tests { use super::super::tests::{BASE, machine, machine_on, normal_memory, one_timer_bank}; use super::{ACTLR_EN_TSO, ACTLR_ICDSB, Code, Translation}; - use crate::machine::{ - Chip, Stop, - cpu::{HCR_HCD, HCR_TGE, HCR_TSC}, - exception::{Pstate, Vector}, - system::{Feature, Register}, - }; use stela_compiler::aarch64::system::registers::Encoding; + use { + crate::machine::Stop, crate::machine::cpu::HCR_HCD, crate::machine::cpu::HCR_TGE, + crate::machine::cpu::HCR_TSC, crate::machine::exception::Pstate, + crate::machine::exception::Vector, crate::machine::system::Register, stela_contracts::Chip, + stela_contracts::Feature, + }; /// Configure an unlocked authored CTRR region through the existing /// generation's register bank. This is not an original-image SMP test. @@ -1729,7 +1734,7 @@ mod tests { #[test] fn core_monitor_construction_needs_a_qualified_layout_and_an_explicit_pe_clock() { - use crate::machine::{Identity, pmu}; + use {crate::machine::pmu, stela_contracts::identity::Identity}; for chip in Chip::ALL { let mut machine = machine_on(chip, &[]); assert!(machine.cpu.pmu.is_none()); @@ -1893,9 +1898,9 @@ mod tests { #[test] fn ccsidr_reads_the_cache_csselr_selects() { - use crate::machine::{ - caches::{Cache, Caches}, - registers::Identity, + use { + stela_contracts::caches::Cache, stela_contracts::caches::Caches, + stela_contracts::identity::Identity, }; const CLIDR_EL1: Encoding = Encoding::new(3, 1, 0, 0, 1); const CCSIDR_EL1: Encoding = Encoding::new(3, 1, 0, 0, 0); @@ -2183,7 +2188,7 @@ mod tests { #[test] fn smidr_tpidr2_priority_mapping_and_mpamsm_follow_the_chips_sme() { - use crate::machine::registers::Identity; + use stela_contracts::identity::Identity; const SMIDR_EL1: Encoding = Encoding::new(3, 1, 0, 0, 6); const TPIDR2_EL0: Encoding = Encoding::new(3, 3, 13, 0, 5); const HCRX_EL2: Encoding = Encoding::new(3, 4, 1, 2, 2); @@ -3038,7 +3043,7 @@ mod tests { assert_eq!(machine.cpu.read(Register::ESR_EL1) >> 26, 0); // A board without one leaves the reset address unknown: the read is // reported once. - let mut bare = machine_on(crate::machine::Chip::AppleM2, &[]); + let mut bare = machine_on(stela_contracts::Chip::AppleM2, &[]); bare.cpu.pstate = Pstate::reset(2); bare.system_instruction(access(true, RVBAR_EL2, 1)).unwrap(); assert_eq!(bare.take_unmodeled().len(), 1); diff --git a/crates/stela-runtime/src/machine/engine/tags.rs b/crates/stela-runtime/src/machine/engine/tags.rs index 847d6eb73d..dcfea33796 100644 --- a/crates/stela-runtime/src/machine/engine/tags.rs +++ b/crates/stela-runtime/src/machine/engine/tags.rs @@ -9,26 +9,21 @@ //! and the memory is Tagged (`attributes::TAGGED`): elsewhere a tag reads 0 //! and a tag write has no effect. use super::{Devices, Host, Machine, RamTables, RequirementKind, Step, Stop, Translated}; -use crate::{ - machine::{ - cpu::Exception, - debug, - exception::Class, - mmu::{self, Access, Translation, alignment, attributes::TAGGED}, - system::{Feature, Register as SystemRegister}, - tags::GRANULE, - }, - memory::tags::{ - AllocationTag, TagGenerationControls, TagGenerationState, TagRandomization, - choose_non_excluded_tag, - }, -}; use alloc::vec::Vec; use stela_compiler::aarch64::{ AddressMode, Operation, Register, tag_arithmetic::{self, Kind as ArithmeticKind}, tag_memory::{BulkKind, Operand, StoreKind}, }; +use { + crate::machine::cpu::Exception, crate::machine::debug, crate::machine::exception::Class, + crate::machine::mmu, crate::machine::mmu::Access, crate::machine::mmu::Translation, + crate::machine::mmu::alignment, crate::machine::mmu::attributes::TAGGED, + crate::machine::system::Register as SystemRegister, crate::machine::tags::GRANULE, + crate::memory::tags::AllocationTag, crate::memory::tags::TagGenerationControls, + crate::memory::tags::TagGenerationState, crate::memory::tags::TagRandomization, + crate::memory::tags::choose_non_excluded_tag, stela_contracts::Feature, +}; /// GCR_EL1.Exclude and RRND. const GCR_EXCLUDE: u64 = 0xffff; @@ -629,11 +624,12 @@ mod tests { tests::{BASE, FakeHost, machine_on, normal_memory}, }; use super::*; - use crate::machine::{ - Chip, NoDevices, exception::Pstate, identification, registers::encodings, - system::Register as SystemRegister, - }; use stela_compiler::{TargetCpu, block::ExitKind}; + use { + crate::machine::NoDevices, crate::machine::exception::Pstate, + crate::machine::identification, crate::machine::registers::encodings, + crate::machine::system::Register as SystemRegister, stela_contracts::Chip, + }; type Test = Machine; diff --git a/crates/stela-runtime/src/machine/exception.rs b/crates/stela-runtime/src/machine/exception.rs index 91cf4374c3..f86073026a 100644 --- a/crates/stela-runtime/src/machine/exception.rs +++ b/crates/stela-runtime/src/machine/exception.rs @@ -271,7 +271,9 @@ pub fn entry_pstate(from: Pstate, sctlr: u64, target: u8, in_host: bool, mte: bo #[cfg(test)] mod tests { use super::*; - use crate::machine::system::{Feature, File, Register}; + use { + crate::machine::system::File, crate::machine::system::Register, stela_contracts::Feature, + }; /// `value` written to `register` of the test chip's register file and /// read back: the fields the chip lacks read 0, as the engine's MSR diff --git a/crates/stela-runtime/src/machine/identification.rs b/crates/stela-runtime/src/machine/identification.rs index d824bc59bf..0ca89558cc 100644 --- a/crates/stela-runtime/src/machine/identification.rs +++ b/crates/stela-runtime/src/machine/identification.rs @@ -14,13 +14,13 @@ //! level is EL2 as a VHE host, or is a speculation guarantee the host gives //! ([`Speculation`]). A field with no satisfied row reads its "not //! implemented" (or "not disclosed") value. -use super::{Chip, registers::encodings::*, system::Feature}; use alloc::vec::Vec; use stela_compiler::{ GuestAddress, TargetCpu, aarch64::system::registers::Encoding, block::{BlockProfile, CompilationPlan, Features}, }; +use {super::registers::encodings::*, stela_contracts::Chip, stela_contracts::Feature}; /// Why a row's level holds on this engine. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1718,7 +1718,7 @@ mod tests { for feature in Feature::ALL { if !Chip::ALL .iter() - .any(|chip| chip.implemented(feature) == Ok(true)) + .any(|chip| crate::machine::capabilities::implemented(*chip, feature) == Ok(true)) { continue; } @@ -2090,7 +2090,7 @@ mod tests { // The chip the tests run on advertises the prediction restrictions // of its FEAT_SPECRES2 and FEAT_LSE2's alignment. let chip = crate::machine::test_chip(); - let specres = 1 + u64::from(crate::machine::system::Feature::FEAT_SPECRES2.on(chip)); + let specres = 1 + u64::from(stela_contracts::Feature::FEAT_SPECRES2.on(chip)); assert_eq!(field(chip, ID_AA64ISAR1_EL1, 40), specres); assert_eq!(field(chip, ID_AA64MMFR2_EL1, 32), 1); } diff --git a/crates/stela-runtime/src/machine/impdef.rs b/crates/stela-runtime/src/machine/impdef.rs index b7ec6d854a..394cb4ba8e 100644 --- a/crates/stela-runtime/src/machine/impdef.rs +++ b/crates/stela-runtime/src/machine/impdef.rs @@ -72,9 +72,9 @@ //! has had the space enumerated, so neither an encoding's existence nor its //! reset value is observed. The run reports every entry the guest used, so none of //! these is silent. -use super::Chip; use alloc::collections::BTreeMap; use stela_compiler::aarch64::system::registers::Encoding; +use stela_contracts::Chip; mod census; mod objc; diff --git a/crates/stela-runtime/src/machine/mmu.rs b/crates/stela-runtime/src/machine/mmu.rs index 5fc46a8451..532b27cbb7 100644 --- a/crates/stela-runtime/src/machine/mmu.rs +++ b/crates/stela-runtime/src/machine/mmu.rs @@ -171,7 +171,7 @@ pub struct Stage2 { /// `Cpu::controls` states it in [`Controls::xs`] and [`Stage2::xs`]. #[cfg(test)] pub(crate) fn test_xs() -> bool { - super::system::Feature::FEAT_XS.on(super::test_chip()) + stela_contracts::Feature::FEAT_XS.on(super::test_chip()) } /// The chip the tests run on, after checking that its identification diff --git a/crates/stela-runtime/src/machine/mount.rs b/crates/stela-runtime/src/machine/mount.rs index e32eca0705..9b8decc4fa 100644 --- a/crates/stela-runtime/src/machine/mount.rs +++ b/crates/stela-runtime/src/machine/mount.rs @@ -152,7 +152,7 @@ pub struct Inputs<'f> { pub firmware: &'f dyn Fn(&str) -> Option<&'f [u8]>, /// The boot bundle's macOS build, whose firmware protocols the /// coprocessor models speak; `None` without a bundle. - pub build: Option<&'static crate::builds::Build>, + pub build: Option<&'static stela_formats::builds::Build>, } /// Place `board`'s devices, writing `DEVICES` summaries to `log`, and return diff --git a/crates/stela-runtime/src/machine/pmu.rs b/crates/stela-runtime/src/machine/pmu.rs index 6f981d086f..5cd45c5477 100644 --- a/crates/stela-runtime/src/machine/pmu.rs +++ b/crates/stela-runtime/src/machine/pmu.rs @@ -47,7 +47,7 @@ //! selectors within the layout's field masks. An enabled event/slot must //! have qualified semantics; unsupported reconfiguration refuses atomically. M6's new controls refuse every access until their effects //! are independently qualified. -use super::Chip; +use stela_contracts::Chip; mod events; mod layout; diff --git a/crates/stela-runtime/src/machine/pointer_keys.rs b/crates/stela-runtime/src/machine/pointer_keys.rs index 428f27acdd..32156f54c8 100644 --- a/crates/stela-runtime/src/machine/pointer_keys.rs +++ b/crates/stela-runtime/src/machine/pointer_keys.rs @@ -139,7 +139,7 @@ mod tests { fn original_t6000_llb_writes_all_five_typed_pairs_with_ordering() { let bytes = std::fs::read(std::env::var("STELA_TEST_PAUTH_LLB").unwrap()).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "f45549025d8cb4aa5e1cdb6107a25f90999f6b96da0b31a2f3cfb90561653ae1" ); for (pair, offset) in [0x22858, 0x2286c, 0x22880, 0x22894, 0x228a8] diff --git a/crates/stela-runtime/src/machine/registers.rs b/crates/stela-runtime/src/machine/registers.rs index 55df2bdc0e..cc21f80aa0 100644 --- a/crates/stela-runtime/src/machine/registers.rs +++ b/crates/stela-runtime/src/machine/registers.rs @@ -15,20 +15,27 @@ //! and `*_GL12` encodings reach the EL1 and GL1 state (inference from the //! names and from m1n1 `gxf_asm.S`). HCR_EL2.TIDCP traps the whole //! IMPLEMENTATION DEFINED space from EL1 to EL2. -use super::{ - cpu::{ - Cpu, GXF_CONFIG_EL1_LOCK, GXF_CONFIG_EN, GXF_CONFIG_LOCKS, GuardedBank, HCR_VM, - PERM_EL0_10, PERM_EL0_20, PERM_EL1, PERM_EL2, TranslationRegime, VM_TIMER_FIQ_PHYSICAL, - VM_TIMER_FIQ_VIRTUAL, - }, - exception::Pstate, - impdef, - pmu::Pmu, - system::{Feature, Register}, - timer::agt, -}; +use super::cpu::Cpu; +use super::cpu::GXF_CONFIG_EL1_LOCK; +use super::cpu::GXF_CONFIG_EN; +use super::cpu::GXF_CONFIG_LOCKS; +use super::cpu::GuardedBank; +use super::cpu::HCR_VM; +use super::cpu::PERM_EL0_10; +use super::cpu::PERM_EL0_20; +use super::cpu::PERM_EL1; +use super::cpu::PERM_EL2; +use super::cpu::TranslationRegime; +use super::cpu::VM_TIMER_FIQ_PHYSICAL; +use super::cpu::VM_TIMER_FIQ_VIRTUAL; +use super::exception::Pstate; +use super::impdef; +use super::pmu::Pmu; +use super::system::Register; +use super::timer::agt; use alloc::vec::Vec; use stela_compiler::aarch64::system::registers::{Direction, Encoding, RegisterAccess}; +use stela_contracts::Feature; /// Identification and fixed registers of one declared CPU profile. A register /// without a value refuses: profile values need evidence. @@ -45,19 +52,7 @@ pub struct CpuProfile { pub processors: Vec, } -/// 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, - /// 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, -} +use stela_contracts::identity::Identity; /// Encodings named by the Arm ARM and by m1n1 `cpu_regs.h`. pub mod encodings { @@ -733,7 +728,7 @@ impl Cpu { Outcome::Undefined } else if read { Outcome::Read(current) - } else if current & super::tag_storage::LOCK == 0 { + } else if current & stela_contracts::tag_storage::LOCK == 0 { Outcome::Refused(Refusal::UnsupportedSetting( "TAG_OFFSET_EL2 write without the boot firmware's locked value", )) @@ -1817,7 +1812,7 @@ mod tests { ); assert_eq!(metadata.len(), length); let bytes = std::fs::read(path).unwrap(); - assert_eq!(crate::sha256(&bytes), hash); + assert_eq!(stela_formats::sha256(&bytes), hash); bytes }; let version = read( @@ -1844,7 +1839,7 @@ mod tests { #[test] fn el0_apple_control_afpcr_uses_the_existing_pe_model_without_fp_effects() { - use crate::machine::Chip; + use stela_contracts::Chip; let encoding = impdef::AFPCR_EL0; let key = encoding.selector(); @@ -1910,7 +1905,7 @@ mod tests { #[test] fn el0_apple_control_afpcr_keeps_el1_tidcp_ordering_and_el2_access() { - use crate::machine::Chip; + use stela_contracts::Chip; let encoding = impdef::AFPCR_EL0; for chip in Chip::ALL { @@ -1946,7 +1941,7 @@ mod tests { #[test] fn el0_apple_control_trace_permissions_remain_explicitly_unqualified() { - use crate::machine::Chip; + use stela_contracts::Chip; let encoding = impdef::TRACE_CLEARED; for chip in Chip::ALL { @@ -2026,8 +2021,8 @@ mod tests { /// no rejected access can corrupt the PE's predictor configuration. #[test] fn objc_prediction_accesses_preserve_state_and_trap_before_writing() { - use crate::machine::Chip; use impdef::{BP_OBJC_ADR_EL1, BP_OBJC_CTL_EL1}; + use stela_contracts::Chip; for chip in Chip::ALL { let mut cpu = Cpu::of(chip, 0, Pstate::reset(1)); diff --git a/crates/stela-runtime/src/machine/soc.rs b/crates/stela-runtime/src/machine/soc.rs index f043e6c114..7ed1e0c38c 100644 --- a/crates/stela-runtime/src/machine/soc.rs +++ b/crates/stela-runtime/src/machine/soc.rs @@ -15,12 +15,6 @@ //! without that evidence refuses: the T6050's M cores, whose caches no //! source gives, the M6's M cores, and a T6050 template whose fused variant //! is not merged yet (the boot bundle merges it, `stela_loader::soc_variant`). -use super::{ - Chip, - adt::Node, - caches::{Cache, Caches}, - registers::Identity, -}; use crate::platform::apple::{ aes, agx, aic::{AIC2_DIE_STRIDE, AIC2_MAX_DIES, AIC3_IRQ_CFG, AIC3_TIMESTAMPS, AicLayout}, @@ -31,6 +25,10 @@ use crate::platform::apple::{ pmu, power, ptd, sart, smc, spi, spmi, wake, }; use alloc::{collections::BTreeMap, format, string::String, vec::Vec}; +use { + stela_contracts::Chip, stela_contracts::adt::Node, stela_contracts::caches::Cache, + stela_contracts::caches::Caches, stela_contracts::identity::Identity, +}; pub mod t6000_pmgr; @@ -2289,7 +2287,7 @@ mod tests { #[test] fn dart_supply_ids_and_retention_come_from_dt_properties() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let reg = [0x35004000u64, 0x4000] .into_iter() .flat_map(u64::to_le_bytes) @@ -2345,7 +2343,7 @@ mod tests { #[test] fn watchdog_side_words_use_independent_translated_dt_ranges() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let reg = [ 0x1000u64, 0x4000, 0xc218, 4, 0x8008, 4, 0x800c, 4, 0x8020, 4, ] @@ -2412,7 +2410,7 @@ mod tests { }; let data = std::fs::read(std::env::var("STELA_TEST_DART_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); @@ -2461,7 +2459,7 @@ mod tests { fn original_j314s_ap_gpio_qualifies_without_auxiliary_or_lifecycle_claims() { let data = std::fs::read(std::env::var("STELA_TEST_GPIO_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); @@ -2498,7 +2496,7 @@ mod tests { #[test] fn rtbuddy_endpoint_selection_uses_protocol_and_rejects_ambiguity() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let endpoint = |name: &str, compatible: &str| { let name = [name.as_bytes(), &[0]].concat(); let compatible = [compatible.as_bytes(), &[0]].concat(); @@ -2539,7 +2537,7 @@ mod tests { #[test] fn rtbuddy_nubs_the_ap_does_not_wait_for_refuse() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let name = b"iop-pmp-nub".to_vec(); let set = 1u32.to_le_bytes().to_vec(); let plain = encode(&[("name", &name)], &[]); @@ -2600,7 +2598,7 @@ mod tests { use crate::machine::Devices; let data = std::fs::read(std::env::var("STELA_TEST_SPMI_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); @@ -2634,7 +2632,9 @@ mod tests { }) .unwrap() .unwrap(); - devices.add_smc(&smc, crate::builds::DEFAULT).unwrap(); + devices + .add_smc(&smc, stela_formats::builds::DEFAULT) + .unwrap(); let epoch = pmu::RtcEpoch { counter: 100, ticks: 0, @@ -2997,7 +2997,7 @@ mod tests { aic_properties: &[(&str, u32)], io_children: &[Vec], ) -> Vec { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let u32s = |cells: &[u32]| { cells @@ -3112,7 +3112,7 @@ mod tests { #[test] fn a_board_states_its_dram_base_or_takes_its_socs() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let with_base = |base: Option<&[u8]>| { let mcc = base.map(|base| encode(&[("name", &z("mcc")), ("dram-base", base)], &[])); @@ -3268,7 +3268,7 @@ mod tests { /// J473AP's `dart-sio` and the AES engine behind its `mapper-aes`. #[test] fn a_board_places_its_darts_and_the_aes_engine_behind_one() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; const MODELED: [&str; 3] = ["uart-1,samsung", "wdt,s5l8960x", "aic,2"]; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let u32s = |cells: &[u32]| { @@ -3545,7 +3545,7 @@ mod tests { #[test] fn multiple_darts_preserve_numbered_windows_sids_and_remap_without_guessing_dma_routing() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let cells = |values: &[u32]| { values .iter() @@ -3665,7 +3665,7 @@ mod tests { /// ps-regs/devices. Virtual clocks have no hardware power-state word. #[test] fn ans_power_gates_are_placed_and_virtual_clocks_do_not_invent_registers() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let words = |v: &[u32]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); let pairs = |v: &[u64]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); let mut devices = Vec::new(); @@ -3717,7 +3717,7 @@ mod tests { /// block at its second, with a virtual device that has no register. #[test] fn a_pmgr_places_each_devices_power_state_register() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; const MODELED: [&str; 3] = ["uart-1,samsung", "wdt,s5l8960x", "aic,2"]; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let u32s = |cells: &[u32]| { @@ -3927,7 +3927,7 @@ mod tests { /// `/arm-io/pmgr/clpc`) that names the AIC (0x63) for its first three /// specifiers and the PTD for the four FourCCs after them. pub(super) fn clpc_with_ptd() -> Vec> { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let words = |cells: &[u32]| { cells @@ -3974,7 +3974,7 @@ mod tests { fn original_j314s_sep_preserves_sole_trad_with_sixteen_sid_capacity() { let data = std::fs::read(std::env::var("STELA_TEST_DART_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); @@ -4009,7 +4009,7 @@ mod tests { fn original_j314s_external_output_preserves_native_routes_and_identity() { let data = std::fs::read(std::env::var("STELA_TEST_DART_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); @@ -4093,7 +4093,7 @@ mod tests { dart.profile, &native, usize::from(dart.streams), - Some(crate::platform::apple::interrupt::AicInput::new( + Some(stela_contracts::interrupt::AicInput::new( 0, dart.irq as u16, )), @@ -4135,7 +4135,7 @@ mod tests { (owners[1], dcp.stream as usize), dcp.window, Some((owners[0], dcp.surface.unwrap().1 as usize)), - crate::builds::DEFAULT, + stela_formats::builds::DEFAULT, ) .unwrap(); let regions = dcp @@ -4272,7 +4272,7 @@ mod tests { fn original_j314s_ans_geometry_and_handoff_qualify_independently_of_whole_board() { let data = std::fs::read(std::env::var("STELA_TEST_ANS_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); diff --git a/crates/stela-runtime/src/machine/soc/apertures.rs b/crates/stela-runtime/src/machine/soc/apertures.rs index 05f59b007c..317b23b12e 100644 --- a/crates/stela-runtime/src/machine/soc/apertures.rs +++ b/crates/stela-runtime/src/machine/soc/apertures.rs @@ -69,8 +69,8 @@ pub(super) fn visit( #[cfg(test)] mod tests { use super::*; - use crate::machine::adt::encode; use alloc::vec; + use stela_contracts::adt::encode; fn ranges(rows: &[(u64, u64, u64)]) -> Vec { rows.iter() diff --git a/crates/stela-runtime/src/machine/soc/boot_processor.rs b/crates/stela-runtime/src/machine/soc/boot_processor.rs index ba68c86789..329fb2066d 100644 --- a/crates/stela-runtime/src/machine/soc/boot_processor.rs +++ b/crates/stela-runtime/src/machine/soc/boot_processor.rs @@ -73,8 +73,8 @@ pub(super) fn boot_processor( #[cfg(test)] mod tests { use super::*; - use crate::machine::adt::encode; use alloc::vec::Vec; + use stela_contracts::adt::encode; fn tree(states: &[Option<&[u8]>]) -> Vec { let children: Vec<_> = states diff --git a/crates/stela-runtime/src/machine/soc/dart_topology.rs b/crates/stela-runtime/src/machine/soc/dart_topology.rs index 1b89aba974..6502310d88 100644 --- a/crates/stela-runtime/src/machine/soc/dart_topology.rs +++ b/crates/stela-runtime/src/machine/soc/dart_topology.rs @@ -435,9 +435,9 @@ pub(super) fn legacy_requirements<'a>( #[cfg(test)] mod tests { use super::*; - use crate::machine::adt::encode; use crate::machine::soc::tests::flat_fixture_extent; use alloc::vec; + use stela_contracts::adt::encode; fn bytes64(values: &[u64]) -> Vec { values diff --git a/crates/stela-runtime/src/machine/soc/display_topology.rs b/crates/stela-runtime/src/machine/soc/display_topology.rs index b0587b99ad..ae98d30847 100644 --- a/crates/stela-runtime/src/machine/soc/display_topology.rs +++ b/crates/stela-runtime/src/machine/soc/display_topology.rs @@ -246,7 +246,7 @@ mod tests { #[test] fn dcp_placement_reads_the_wrapper_irqs_nub_and_display_apertures_without_admitting_it() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; const MODELED: [&str; 3] = [UART, WATCHDOG, "aic,2"]; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let words = |cells: &[u32]| { diff --git a/crates/stela-runtime/src/machine/soc/dma_routes.rs b/crates/stela-runtime/src/machine/soc/dma_routes.rs index 5bd3114ff3..86cab9c59f 100644 --- a/crates/stela-runtime/src/machine/soc/dma_routes.rs +++ b/crates/stela-runtime/src/machine/soc/dma_routes.rs @@ -139,7 +139,7 @@ mod tests { #[test] fn native_dma_owner_properties_keep_complete_lists_and_refuse_truncation() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; for bytes in [&[][..], &[1, 0, 0][..], &[0, 0, 0, 0][..], &[1; 8][..]] { let tree = encode(&[("AAPL,phandle", bytes)], &[]); assert!(native_dma_phandle(&Node::root(&tree).unwrap(), "AAPL,phandle").is_err()); diff --git a/crates/stela-runtime/src/machine/soc/gfx_topology.rs b/crates/stela-runtime/src/machine/soc/gfx_topology.rs index 3472f06bfb..41d53cbc0b 100644 --- a/crates/stela-runtime/src/machine/soc/gfx_topology.rs +++ b/crates/stela-runtime/src/machine/soc/gfx_topology.rs @@ -142,7 +142,7 @@ mod tests { #[test] fn gfx_placement_needs_the_coprocessor_and_the_gpu_together() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values diff --git a/crates/stela-runtime/src/machine/soc/gpio_topology.rs b/crates/stela-runtime/src/machine/soc/gpio_topology.rs index a8c965e88e..bc2ccaba50 100644 --- a/crates/stela-runtime/src/machine/soc/gpio_topology.rs +++ b/crates/stela-runtime/src/machine/soc/gpio_topology.rs @@ -282,7 +282,7 @@ mod tests { #[test] fn s5l_ap_geometry_preserves_validated_restoration_exclusions() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let make = |excluded: &[u8], override_key: Option<&str>| { let reg = [0x19b028000u64, 0x4000] .into_iter() @@ -367,7 +367,7 @@ mod tests { #[test] fn other_gpio_banks_carry_the_pins_their_clients_name() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let words = |v: &[u32]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); let pairs = |v: &[u64]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); // J473AP's aop-gpio, its dp2hdmi-gpio client and a hidden smc-gpio. @@ -431,7 +431,7 @@ mod tests { #[test] fn gpio_aperture_requires_complete_source_ranges_before_any_bank_is_returned() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let raw = [0u64, 0x1000] .into_iter() .flat_map(u64::to_le_bytes) diff --git a/crates/stela-runtime/src/machine/soc/interrupts.rs b/crates/stela-runtime/src/machine/soc/interrupts.rs index 899cf27677..43d289a964 100644 --- a/crates/stela-runtime/src/machine/soc/interrupts.rs +++ b/crates/stela-runtime/src/machine/soc/interrupts.rs @@ -304,7 +304,7 @@ mod tests { #[test] fn aic_vectors_follow_each_specifiers_own_parent() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let words = |cells: &[u32]| { cells @@ -376,7 +376,7 @@ mod tests { #[test] fn aic_inputs_split_vectors_into_dies() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let mask = |words: usize| { encode( diff --git a/crates/stela-runtime/src/machine/soc/memory_resources.rs b/crates/stela-runtime/src/machine/soc/memory_resources.rs index 3f075edbdf..a5cdd571b7 100644 --- a/crates/stela-runtime/src/machine/soc/memory_resources.rs +++ b/crates/stela-runtime/src/machine/soc/memory_resources.rs @@ -1,11 +1,8 @@ //! Direct T6000 MCC placement, qualified independently of T8112's PMP service. //! Descriptor parsing does not admit a native-memory completion capability. use super::{MemoryController, PTD_RANGE, PtdBank}; -use crate::{ - machine::adt::Node, - platform::apple::{mcc, ptd}, -}; use alloc::{collections::BTreeSet, format, string::String, vec::Vec}; +use {crate::platform::apple::mcc, crate::platform::apple::ptd, stela_contracts::adt::Node}; pub mod t6020; @@ -263,9 +260,9 @@ pub(super) fn direct_memory_cache( #[cfg(test)] mod tests { use super::*; - use crate::machine::adt::encode; use crate::machine::soc::tests::flat_fixture_extent; use alloc::vec; + use stela_contracts::adt::encode; fn tree(reg_suffix: &[u8], update_bytes: u64, interrupt: u32) -> Vec { let mut regs = Vec::new(); @@ -445,7 +442,7 @@ mod tests { let input = std::env::var("STELA_T6000_MCC_DEVICE_TREE").expect("explicit original ADT input"); let bytes = std::fs::read(&input).unwrap(); - let hash = crate::sha256(&bytes); + let hash = stela_formats::sha256(&bytes); assert_eq!( hash, "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" diff --git a/crates/stela-runtime/src/machine/soc/memory_resources/t6020.rs b/crates/stela-runtime/src/machine/soc/memory_resources/t6020.rs index 58fd3a5245..726f33a869 100644 --- a/crates/stela-runtime/src/machine/soc/memory_resources/t6020.rs +++ b/crates/stela-runtime/src/machine/soc/memory_resources/t6020.rs @@ -6,11 +6,8 @@ //! at two. MCC reg0 is the PTD bank, reg1 a separate auxiliary bank. These //! are not T6000 direct-aperture ordinals or its PMGR selector8 placement. use super::{MemoryController, PtdBank, publication_ranges, range_at, reg_pairs, scalar}; -use crate::{ - machine::adt::Node, - platform::apple::{mcc::t6020, ptd}, -}; use alloc::{collections::BTreeSet, format, string::String, vec::Vec}; +use {crate::platform::apple::mcc::t6020, crate::platform::apple::ptd, stela_contracts::adt::Node}; pub const COMPATIBLE: &str = "mcc,t6020"; const PREFIX_REGISTERS: usize = 2; @@ -243,7 +240,7 @@ pub fn from_io( #[cfg(test)] mod tests { use super::*; - use crate::machine::adt::encode; + use stela_contracts::adt::encode; fn z(s: &str) -> Vec { s.as_bytes().iter().copied().chain([0]).collect() } diff --git a/crates/stela-runtime/src/machine/soc/memory_topology.rs b/crates/stela-runtime/src/machine/soc/memory_topology.rs index 3fbc8a7fbc..3a9dacf1f6 100644 --- a/crates/stela-runtime/src/machine/soc/memory_topology.rs +++ b/crates/stela-runtime/src/machine/soc/memory_topology.rs @@ -291,7 +291,7 @@ mod tests { #[test] fn io_access_description_preserves_optional_controls_and_absolute_page_basis() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let chosen = |partial_enable: bool, extra_address_byte: bool| { let mut properties: Vec<(String, Vec)> = vec![ ("name".into(), b"ioa-ctrr-a\0".to_vec()), @@ -355,7 +355,7 @@ mod tests { #[test] fn every_filled_amcc_lock_group_is_described() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let word = |value: u32| value.to_le_bytes().to_vec(); let group = |name: &str, index: u32, filled: bool| { let mut properties = vec![("name".to_string(), [name.as_bytes(), &[0]].concat())]; @@ -432,7 +432,7 @@ mod tests { /// AMCC aperture. #[test] fn an_mcc_places_its_cache_channels_and_ptd_bank() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; const MODELED: [&str; 3] = ["uart-1,samsung", "wdt,s5l8960x", "aic,2"]; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let u32s = |cells: &[u32]| { diff --git a/crates/stela-runtime/src/machine/soc/pmp_topology.rs b/crates/stela-runtime/src/machine/soc/pmp_topology.rs index 5e4cd70960..977ea20b76 100644 --- a/crates/stela-runtime/src/machine/soc/pmp_topology.rs +++ b/crates/stela-runtime/src/machine/soc/pmp_topology.rs @@ -157,7 +157,7 @@ mod tests { #[test] fn pmp_placement_reads_its_wrapper_and_needs_a_user_managed_nub() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values @@ -235,7 +235,7 @@ mod tests { .join("DeviceTree.j473ap.adt"); let bytes = std::fs::read(path).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); let root = Node::root(&bytes).unwrap(); diff --git a/crates/stela-runtime/src/machine/soc/power_registers.rs b/crates/stela-runtime/src/machine/soc/power_registers.rs index 5ca2fa43e0..cb89a8c259 100644 --- a/crates/stela-runtime/src/machine/soc/power_registers.rs +++ b/crates/stela-runtime/src/machine/soc/power_registers.rs @@ -757,7 +757,7 @@ mod tests { use super::*; fn optional_fixture(performance: &[u8], extra: &[(&str, &[u8])]) -> Vec { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let reg = [0x1000u64, 0x1000] .into_iter() .flat_map(u64::to_le_bytes) @@ -888,7 +888,7 @@ mod tests { #[test] fn performance_bank_capacity_is_independent_of_byte_sized_source_selectors() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let mut group = direct_performance_group(); group[8..10].copy_from_slice(&306u16.to_le_bytes()); let mut source = [0; PMGR_DEVICE]; @@ -921,7 +921,7 @@ mod tests { #[test] fn special_acc_events_use_the_dt_selector_and_cluster_type() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let mut e = [0u8; 24]; e[2] = 2; e[6] = 12; @@ -942,7 +942,7 @@ mod tests { #[test] fn bridge_headers_configs_axi_and_dependencies_place_the_translated_window() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let cells = |v: &[u32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); let mut config = [0u8; 36]; config[1] = 7; @@ -976,7 +976,7 @@ mod tests { #[test] fn soc_dpe_samples_are_absolute_and_checked_against_the_selected_dt_bank() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let mut sample = [0u8; 40]; sample[..8].copy_from_slice(&0x5_0000_2708u64.to_le_bytes()); sample[16..24].copy_from_slice(&[0x1d, 0, 1, 0, 1, 1, 1, 64]); @@ -1015,7 +1015,7 @@ mod tests { #[test] fn wake_masks_derive_the_bank_and_validate_dt_sources_without_assuming_reset_masks() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let layout = SOCS .iter() .find(|soc| soc.chip_id == 0x8112) @@ -1074,7 +1074,7 @@ mod tests { #[test] fn perf_groups_derive_sparse_selectors_from_each_dt_record_kind() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let group = |index: u32, offset: u32, count: u16, class: u8| { let mut entry = [0u8; 16]; entry[..4].copy_from_slice(&index.to_le_bytes()); @@ -1191,7 +1191,7 @@ mod tests { #[test] fn cpu_start_registers_follow_the_pmgr_node_with_registers() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let reg = |base: u64, bytes: u64| [base.to_le_bytes(), bytes.to_le_bytes()].concat(); let io = |pmgr: &str, pmgr_reg: Option<(u64, u64)>, child: Option<(u64, u64)>| { diff --git a/crates/stela-runtime/src/machine/soc/power_resources.rs b/crates/stela-runtime/src/machine/soc/power_resources.rs index e49b985c97..4da2b87fc1 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources.rs @@ -87,9 +87,9 @@ impl PowerStates { /// no initial LifecycleState and never registers a participant or ACKs PMGR. pub fn processor_associations( &self, - chip: crate::machine::Chip, + chip: stela_contracts::Chip, root: &Node<'_>, - processors: &[crate::machine::registers::Identity], + processors: &[stela_contracts::identity::Identity], acc_harvesting: u32, ) -> Result, String> { let io = root.child("arm-io").ok_or("CPU PMGR requires arm-io")?; @@ -857,12 +857,12 @@ mod tests { .into_iter() .flat_map(u64::to_le_bytes) .collect::>(); - crate::machine::adt::encode(&[("name", b"arm-io"), ("ranges", &ranges)], children) + stela_contracts::adt::encode(&[("name", b"arm-io"), ("ranges", &ranges)], children) } use super::*; use crate::machine::soc::tests::flat_fixture_extent; - use crate::machine::{adt::encode, soc::DART}; + use {crate::machine::soc::DART, stela_contracts::adt::encode}; #[test] fn usb_and_phy_resource_owners_require_qualified_complete_lists() { @@ -1404,7 +1404,7 @@ mod tests { hex::encode(Sha256::digest(&bytes)), "d60dbd13b11a6188f6bfa19a6fe173d49950d5b619197a5a7f4e9d76734d1680" ); - let manifest = crate::boot_bundle::Manifest::parse( + let manifest = stela_formats::boot_bundle::Manifest::parse( &std::fs::read(directory.join("bundle.json")).unwrap(), ) .unwrap(); diff --git a/crates/stela-runtime/src/machine/soc/power_resources/bridges.rs b/crates/stela-runtime/src/machine/soc/power_resources/bridges.rs index 6957cbbea8..0fc51b25ae 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources/bridges.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources/bridges.rs @@ -99,7 +99,7 @@ fn dependency_ids(row: &[u8; 76]) -> impl Iterator + '_ { #[cfg(test)] mod tests { use super::*; - use crate::machine::adt::encode; + use stela_contracts::adt::encode; #[test] fn first_zero_is_a_bridge_and_later_zero_terminates_without_reading_tail() { diff --git a/crates/stela-runtime/src/machine/soc/power_resources/clock_role.rs b/crates/stela-runtime/src/machine/soc/power_resources/clock_role.rs index ea49fb9af5..2d47ec5c5c 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources/clock_role.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources/clock_role.rs @@ -142,11 +142,11 @@ pub(super) fn provider<'a>(root: &Node<'a>) -> Result>, mod tests { use super::super::{PowerStates, domain_id, inventory, validate_power_graph}; use super::*; - use crate::{ - machine::adt::encode, - platform::apple::pmgr::coverage::{Admission, Domain}, - }; use alloc::{string::ToString, vec}; + use { + crate::platform::apple::pmgr::coverage::Admission, + crate::platform::apple::pmgr::coverage::Domain, stela_contracts::adt::encode, + }; fn words(words: &[u32]) -> Vec { words.iter().flat_map(|word| word.to_le_bytes()).collect() @@ -417,7 +417,7 @@ mod tests { std::env::var("STELA_T6000_MCC_DEVICE_TREE").expect("explicit original ADT input"); let bytes = std::fs::read(&input).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&bytes).unwrap(); @@ -521,9 +521,12 @@ mod tests { ), ] { let bytes = std::fs::read(std::env::var(variable).unwrap()).unwrap(); - assert_eq!(crate::sha256(&bytes), hash); + assert_eq!(stela_formats::sha256(&bytes), hash); for &(offset, length, expected) in windows { - assert_eq!(crate::sha256(&bytes[offset..offset + length]), expected); + assert_eq!( + stela_formats::sha256(&bytes[offset..offset + length]), + expected + ); } for &(offset, expected) in pointers { assert_eq!( @@ -540,7 +543,7 @@ mod tests { std::env::var("STELA_TEST_PMGR_M1_KERNELCACHE").expect("explicit original KC input"); let bytes = std::fs::read(input).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "5109fca5209bdbb89cec29e3241cc42a90418cb737d65e31962b059b9879af90" ); // Full original functions: cached metadata, no-op processDevice, @@ -652,7 +655,10 @@ mod tests { "006d1c913997b6f4d6ece3c3256e2b95a0dec9021769d0d9e8248bc8abe6d588", ), // effective_device_id ] { - assert_eq!(crate::sha256(&bytes[offset..offset + length]), expected); + assert_eq!( + stela_formats::sha256(&bytes[offset..offset + length]), + expected + ); } // Actual selected vtable and GOT bindings, including PMGR super-start // to IOService::start. Authenticated source pointers are kept intact. diff --git a/crates/stela-runtime/src/machine/soc/power_resources/cpu.rs b/crates/stela-runtime/src/machine/soc/power_resources/cpu.rs index d9b03867a1..40c93f9d60 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources/cpu.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources/cpu.rs @@ -7,11 +7,11 @@ mod t6000; use super::records::{Layout, Record}; -use crate::{ - machine::{Chip, adt::Node, engine::ProcessorTarget, registers::Identity}, - platform::apple::pmgr::coverage::DomainId, -}; use alloc::{collections::BTreeSet, vec::Vec}; +use { + crate::machine::engine::ProcessorTarget, crate::platform::apple::pmgr::coverage::DomainId, + stela_contracts::Chip, stela_contracts::adt::Node, stela_contracts::identity::Identity, +}; /// The existing board reader supplies these normalized views in original /// record order. This module reuses that reader's record parser to check the diff --git a/crates/stela-runtime/src/machine/soc/power_resources/cpu/t6000.rs b/crates/stela-runtime/src/machine/soc/power_resources/cpu/t6000.rs index e48f0964e9..569897637f 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources/cpu/t6000.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources/cpu/t6000.rs @@ -258,7 +258,7 @@ mod tests { values.iter().flat_map(|v| v.to_le_bytes()).collect() } fn node(properties: Vec<(&str, Vec)>, children: &[Vec]) -> Vec { - crate::machine::adt::encode( + stela_contracts::adt::encode( &properties .iter() .map(|(k, v)| (*k, v.as_slice())) diff --git a/crates/stela-runtime/src/machine/soc/power_resources/implicit.rs b/crates/stela-runtime/src/machine/soc/power_resources/implicit.rs index 146f23b1d8..f667aac145 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources/implicit.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources/implicit.rs @@ -168,14 +168,16 @@ mod tests { .into_iter() .flat_map(u64::to_le_bytes) .collect::>(); - crate::machine::adt::encode(&[("name", b"arm-io"), ("ranges", &ranges)], children) + stela_contracts::adt::encode(&[("name", b"arm-io"), ("ranges", &ranges)], children) } use super::*; use crate::machine::soc::tests::flat_fixture_extent; - use crate::machine::{adt::encode, soc::power_resources::inventory_with_nodes}; use crate::platform::apple::pmgr::coverage::{self, Admission, Consumer, LifecycleSinks}; use alloc::vec; + use { + crate::machine::soc::power_resources::inventory_with_nodes, stela_contracts::adt::encode, + }; fn bank(binding: Binding) -> Vec { let reg = [binding.physical, binding.bytes] diff --git a/crates/stela-runtime/src/machine/soc/power_resources/pmp.rs b/crates/stela-runtime/src/machine/soc/power_resources/pmp.rs index 940ea54704..31517f4624 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources/pmp.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources/pmp.rs @@ -78,7 +78,7 @@ impl PowerStates { #[cfg(test)] mod tests { use super::*; - use crate::machine::adt::encode; + use stela_contracts::adt::encode; fn fixture() -> Vec { let mut records = [[0u8; PMGR_DEVICE]; 4]; @@ -316,10 +316,10 @@ mod tests { .join(alloc::format!("kernelcache.release.{family}")), ) .unwrap(); - assert_eq!(crate::sha256(&bytes), expected); + assert_eq!(stela_formats::sha256(&bytes), expected); let helper = &bytes[offset..offset + 156]; assert_eq!( - crate::sha256(helper), + stela_formats::sha256(helper), if family == "mac18g" { "a25fd16e0a9ce011af7761f805a2f7e165dc1090eb2cf81197601749be1ab24b" } else { diff --git a/crates/stela-runtime/src/machine/soc/power_resources/records.rs b/crates/stela-runtime/src/machine/soc/power_resources/records.rs index b10ea0f3db..9ac30398b6 100644 --- a/crates/stela-runtime/src/machine/soc/power_resources/records.rs +++ b/crates/stela-runtime/src/machine/soc/power_resources/records.rs @@ -192,7 +192,7 @@ mod tests { let bytes = std::fs::read(std::env::var("STELA_TEST_PMGR_M6_KERNELCACHE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "09746d1f442153956ba00b385f49bc245460c1ebea92cae7e9e0e4f240745b85" ); // SystemProp::_getDTDeviceList divides the devices property's byte @@ -216,7 +216,10 @@ mod tests { "7984c104d25466e4633e24a2eda944cbdb0675eb8f7dd30e3fb4e867314afe7a", ), ] { - assert_eq!(crate::sha256(&bytes[offset..offset + length]), expected); + assert_eq!( + stela_formats::sha256(&bytes[offset..offset + length]), + expected + ); } assert_eq!(&bytes[0x775c08..0x775c10], b"devices\0"); for (offset, expected) in [ diff --git a/crates/stela-runtime/src/machine/soc/processor_registers.rs b/crates/stela-runtime/src/machine/soc/processor_registers.rs index 8ed7d0fc92..00e19f6f17 100644 --- a/crates/stela-runtime/src/machine/soc/processor_registers.rs +++ b/crates/stela-runtime/src/machine/soc/processor_registers.rs @@ -70,7 +70,7 @@ pub(super) fn processor_registers(root: &Node<'_>) -> Result]) -> Vec { let children: Vec<_> = blocks diff --git a/crates/stela-runtime/src/machine/soc/sep_topology.rs b/crates/stela-runtime/src/machine/soc/sep_topology.rs index e9e122eb0f..fc0f05bf37 100644 --- a/crates/stela-runtime/src/machine/soc/sep_topology.rs +++ b/crates/stela-runtime/src/machine/soc/sep_topology.rs @@ -159,7 +159,7 @@ mod tests { #[test] fn sep_placement_uses_the_native_nub_and_is_admitted_by_its_sep_role() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; const MODELED: [&str; 3] = [UART, WATCHDOG, "aic,2"]; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let words = |cells: &[u32]| { diff --git a/crates/stela-runtime/src/machine/soc/smc_topology.rs b/crates/stela-runtime/src/machine/soc/smc_topology.rs index 2e07247020..2c18828997 100644 --- a/crates/stela-runtime/src/machine/soc/smc_topology.rs +++ b/crates/stela-runtime/src/machine/soc/smc_topology.rs @@ -134,7 +134,7 @@ mod tests { /// through `smc-pmu`. #[test] fn smc_placement_reads_its_banks_region_and_function_keys() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values diff --git a/crates/stela-runtime/src/machine/soc/spmi_topology.rs b/crates/stela-runtime/src/machine/soc/spmi_topology.rs index 3cb0bf5ad1..ff78c77bb2 100644 --- a/crates/stela-runtime/src/machine/soc/spmi_topology.rs +++ b/crates/stela-runtime/src/machine/soc/spmi_topology.rs @@ -520,7 +520,7 @@ mod tests { #[test] fn spmi_placement_reads_banks_aic_line_and_pmu_windows() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values @@ -627,7 +627,7 @@ mod tests { #[test] fn chapel_places_a_shared_alarm_byte_and_explicit_off_to_wake_history() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values @@ -763,7 +763,7 @@ mod tests { #[test] fn an_rtc_without_a_clock_offset_register_keeps_it_in_the_legacy_scratchpad() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values @@ -812,7 +812,7 @@ mod tests { #[test] fn a_firmware_mailbox_names_its_vector_registers_and_doorbell() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values @@ -918,7 +918,7 @@ mod tests { #[test] fn a_pmu_output_needs_no_rtc_but_the_primary_service_does() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values @@ -984,7 +984,7 @@ mod tests { #[test] fn gen3_and_gen4_spmi_controllers_place_their_arbiter_bank() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values diff --git a/crates/stela-runtime/src/machine/soc/storage_topology.rs b/crates/stela-runtime/src/machine/soc/storage_topology.rs index acd818ed30..670057e692 100644 --- a/crates/stela-runtime/src/machine/soc/storage_topology.rs +++ b/crates/stela-runtime/src/machine/soc/storage_topology.rs @@ -456,7 +456,7 @@ mod tests { #[test] fn spi_nor_placement_uses_dt_ranges_bank_proxy_and_gpio_function() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let words = |v: &[u32]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); let pairs = |v: &[u64]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); let partitions: Vec<_> = [ @@ -565,7 +565,7 @@ mod tests { #[test] fn ans2_placement_uses_phandles_interrupt_index_and_sparse_register_banks() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let z = |text: &str| [text.as_bytes(), &[0]].concat(); let cells = |values: &[u32]| { values diff --git a/crates/stela-runtime/src/machine/soc/t6000_pmgr.rs b/crates/stela-runtime/src/machine/soc/t6000_pmgr.rs index 52abf5f9f9..fe4fb35802 100644 --- a/crates/stela-runtime/src/machine/soc/t6000_pmgr.rs +++ b/crates/stela-runtime/src/machine/soc/t6000_pmgr.rs @@ -128,7 +128,7 @@ impl Descriptor { tuning, power, coverage_requirement, - source_sha256: crate::sha256(tree), + source_sha256: stela_formats::sha256(tree), }) } pub fn layout(&self) -> Result, &'static str> { @@ -152,7 +152,7 @@ mod original { fn original_complete_descriptor_and_sparse_ownership_have_no_fabricated_state() { let data = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_ADT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let d = Descriptor::parse(&data, 0x6000, 8, 0).unwrap(); @@ -219,7 +219,7 @@ mod original { fn original_descriptor_rejects_incomplete_or_crossed_resource_owners() { let original = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_ADT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&original), + stela_formats::sha256(&original), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); fn offset(bytes: &[u8], property: &str) -> usize { diff --git a/crates/stela-runtime/src/machine/soc/topology/assigned.rs b/crates/stela-runtime/src/machine/soc/topology/assigned.rs index 108c5a1000..9dce30249b 100644 --- a/crates/stela-runtime/src/machine/soc/topology/assigned.rs +++ b/crates/stela-runtime/src/machine/soc/topology/assigned.rs @@ -5,13 +5,12 @@ mod source; pub use source::{BspSource, SourceIdentity}; -use crate::machine::{ - Chip, - caches::{Cache, Caches}, - registers::Identity, -}; pub use crate::platform::apple::pmgr::coverage::DomainId; use alloc::{collections::BTreeSet, sync::Arc, vec::Vec}; +use { + stela_contracts::Chip, stela_contracts::caches::Cache, stela_contracts::caches::Caches, + stela_contracts::identity::Identity, +}; const AFFINITY_MASK: u32 = 0xffff; const AFFINITY_PART_MASK: u32 = 0xff; diff --git a/crates/stela-runtime/src/machine/soc/topology/assigned/source.rs b/crates/stela-runtime/src/machine/soc/topology/assigned/source.rs index ac914f27f7..00fc7ee9af 100644 --- a/crates/stela-runtime/src/machine/soc/topology/assigned/source.rs +++ b/crates/stela-runtime/src/machine/soc/topology/assigned/source.rs @@ -14,12 +14,9 @@ mod selected; mod t6000; mod t8112; use super::*; -use crate::machine::{ - adt::Node, - soc::{self, PowerStates}, -}; use alloc::{format, string::String, vec, vec::Vec}; use sha2::{Digest, Sha256}; +use {crate::machine::soc, crate::machine::soc::PowerStates, stela_contracts::adt::Node}; /// Actual selected restore/bundle identity, supplied by its retained owner. /// Original chosen IDs may be templates; this record never observes hardware @@ -503,7 +500,7 @@ mod tests { use super::*; #[test] fn source_retention_distinguishes_fill_in_recipes_from_structural_values() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let fixed = 7u32.to_le_bytes(); let mut original = encode(&[("fixed", &fixed), ("recipe", b"syscfg/ABCD\0")], &[]); let value = Node::root(&original).unwrap().property("recipe").unwrap(); @@ -543,7 +540,7 @@ mod tests { let input = std::env::var("STELA_TEST_ASSIGNED_DT").unwrap(); let bytes = std::fs::read(input).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let prepared = diff --git a/crates/stela-runtime/src/machine/soc/topology/assigned/source/t6000.rs b/crates/stela-runtime/src/machine/soc/topology/assigned/source/t6000.rs index 71f38596e5..8e3301ed7c 100644 --- a/crates/stela-runtime/src/machine/soc/topology/assigned/source/t6000.rs +++ b/crates/stela-runtime/src/machine/soc/topology/assigned/source/t6000.rs @@ -271,7 +271,7 @@ mod tests { fn original_t6000_assigned_prefix_preserves_all_source_coordinates_and_full_power_graph() { let original = std::fs::read(std::env::var("STELA_TEST_ASSIGNED_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&original), + stela_formats::sha256(&original), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let prepared = diff --git a/crates/stela-runtime/src/machine/soc/topology/assigned/source/t8112.rs b/crates/stela-runtime/src/machine/soc/topology/assigned/source/t8112.rs index a8e3fa9f31..884cb42a5f 100644 --- a/crates/stela-runtime/src/machine/soc/topology/assigned/source/t8112.rs +++ b/crates/stela-runtime/src/machine/soc/topology/assigned/source/t8112.rs @@ -340,7 +340,7 @@ mod tests { type Properties = Vec<(&'static str, Vec)>; fn encode(properties: Properties, children: &[Vec]) -> Vec { - crate::machine::adt::encode( + stela_contracts::adt::encode( &properties .iter() .map(|(name, value)| (*name, value.as_slice())) diff --git a/crates/stela-runtime/src/machine/soc/usb_topology.rs b/crates/stela-runtime/src/machine/soc/usb_topology.rs index 8b0e3d0300..a32e1bf77e 100644 --- a/crates/stela-runtime/src/machine/soc/usb_topology.rs +++ b/crates/stela-runtime/src/machine/soc/usb_topology.rs @@ -659,7 +659,7 @@ mod tests { #[test] fn typec_placement_distinguishes_i2c_addresses_from_mmio_and_preserves_phy_aliases() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let c = |v: &[u32]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); let r = |v: &[u64]| v.iter().flat_map(|v| v.to_le_bytes()).collect::>(); let hpm = |name: &[u8], address: u32, rid: u32, personality: Option<&[u8]>| { @@ -926,7 +926,7 @@ mod tests { #[test] fn usb_placement_uses_identity_ranges_mapper_and_all_interrupts() { - use crate::machine::adt::encode; + use stela_contracts::adt::encode; let words = |cells: &[u32]| { cells .iter() diff --git a/crates/stela-runtime/src/machine/streaming.rs b/crates/stela-runtime/src/machine/streaming.rs index 0af8bfc41f..f604c8414e 100644 --- a/crates/stela-runtime/src/machine/streaming.rs +++ b/crates/stela-runtime/src/machine/streaming.rs @@ -7,10 +7,9 @@ //! calls them ([`Chip::checks`](super::Chip::checks)). No Apple chip has //! FEAT_SVE or FEAT_SME_FA64, so streaming mode is what admits SVE, and //! there it makes the AdvSIMD and non-streaming SVE forms illegal. -use super::{ - chip::Check, - cpu::Cpu, - system::{Feature, Register}, +use { + super::cpu::Cpu, super::system::Register, stela_contracts::Feature, + stela_contracts::chip::Check, }; /// `SMEExceptionType`, as ISS[2:0] (SMTC) of EC 0x1D. @@ -341,7 +340,7 @@ pub struct VectorDestinations(pub [Option; 2]); #[cfg(test)] mod tests { use super::*; - use crate::machine::{Chip, exception::Pstate}; + use {crate::machine::exception::Pstate, stela_contracts::Chip}; #[test] fn every_scalar_fp_form_of_the_sme_chips_names_its_vector_destinations() { diff --git a/crates/stela-runtime/src/machine/system.rs b/crates/stela-runtime/src/machine/system.rs index bce8080074..9c87e2988f 100644 --- a/crates/stela-runtime/src/machine/system.rs +++ b/crates/stela-runtime/src/machine/system.rs @@ -13,9 +13,10 @@ pub mod file; pub mod generated; pub mod helpers; -pub use super::chip::Chip; pub use file::File; -pub use generated::{ACCESSORS, Feature, Register}; +pub use generated::{ACCESSORS, Register}; +use stela_contracts::Chip; +use stela_contracts::Feature; /// How an access ends. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/stela-runtime/src/machine/system/file.rs b/crates/stela-runtime/src/machine/system/file.rs index 8915434002..23e714f0ce 100644 --- a/crates/stela-runtime/src/machine/system/file.rs +++ b/crates/stela-runtime/src/machine/system/file.rs @@ -3,8 +3,11 @@ //! at 0 and RES1 at 1 in every layout the PE's profile allows //! (`Register::res0`, `Register::res1`, and `WITHHELD_LAYOUTS` for a PE that //! withholds some of its chip's features). -use super::{Chip, Feature, Register, WithheldLayout, generated::WITHHELD_LAYOUTS}; use alloc::{boxed::Box, vec, vec::Vec}; +use { + super::Register, super::WithheldLayout, super::generated::WITHHELD_LAYOUTS, + stela_contracts::Chip, stela_contracts::Feature, +}; #[derive(Debug, Clone)] pub struct File { @@ -96,7 +99,7 @@ impl File { if self.withheld & 1 << feature as u64 != 0 { Ok(false) } else { - self.chip.implemented(feature) + crate::machine::capabilities::implemented(self.chip, feature) } } diff --git a/crates/stela-runtime/src/machine/system/generated.rs b/crates/stela-runtime/src/machine/system/generated.rs index b929d9e596..7ddaa9d855 100644 --- a/crates/stela-runtime/src/machine/system/generated.rs +++ b/crates/stela-runtime/src/machine/system/generated.rs @@ -16,7 +16,8 @@ unused_parens, unused_variables, unreachable_code, - non_camel_case_types + non_camel_case_types, + reason = "Arm-derived output preserves vendor names, folded branches and helper shapes" )] use super::{ Accessor, AtAccess, Broadcast, CacheOp, CacheScope, CacheType, Chip, Context, Effect, @@ -5500,640 +5501,7 @@ pub static WITHHELD_LAYOUTS: [WithheldLayout; 234] = [ }, ]; -/// 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], - } - } -} +use stela_contracts::Feature; pub static ACCESSORS: [Accessor; 843] = [ Accessor { diff --git a/crates/stela-runtime/src/machine/system/helpers.rs b/crates/stela-runtime/src/machine/system/helpers.rs index cfd13d2664..c26e0e147e 100644 --- a/crates/stela-runtime/src/machine/system/helpers.rs +++ b/crates/stela-runtime/src/machine/system/helpers.rs @@ -2,7 +2,10 @@ //! the ASL of `ISA_A64_xml_A_profile-2026-06` `shared_pseudocode.xml` for the //! profile: EL2 is implemented and enabled (no EL3, Non-secure only) and //! FEAT_VHE without FEAT_E2H0 (HCR_EL2.E2H is RES1). -use super::{CacheOp, CacheScope, CacheType, Context, Effect, Feature, Register}; +use { + super::CacheOp, super::CacheScope, super::CacheType, super::Context, super::Effect, + super::Register, stela_contracts::Feature, +}; pub const HCR_TGE: u32 = 27; pub const VTTBR_VMID: u32 = 48; diff --git a/crates/stela-runtime/src/machine/tag_storage.rs b/crates/stela-runtime/src/machine/tag_storage.rs index b1f89d80ac..aaa073cd2c 100644 --- a/crates/stela-runtime/src/machine/tag_storage.rs +++ b/crates/stela-runtime/src/machine/tag_storage.rs @@ -14,7 +14,7 @@ //! `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. +//! end of the managed address space"). [`stela_contracts::tag_storage::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 @@ -26,66 +26,22 @@ //! 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. -use super::Chip; use super::identification; use super::registers::encodings::Encoding; +use stela_contracts::Chip; pub const TAG_OFFSET_EL2: Encoding = Encoding::new(3, 0, 11, 9, 0); -/// 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; -/// Whether `chip` has the register: the chips with memory tagging. +/// Whether the declared chip owns this implementation-defined register. pub fn owns(chip: Chip, encoding: Encoding) -> bool { encoding == TAG_OFFSET_EL2 && identification::memory_tagging(chip) } -/// 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 { - 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); + fn only_memory_tagging_chips_own_the_tag_storage_register() { assert!(owns(Chip::AppleM5, TAG_OFFSET_EL2) && owns(Chip::AppleM6, TAG_OFFSET_EL2)); assert!(!owns(Chip::AppleM4, TAG_OFFSET_EL2)); } diff --git a/crates/stela-runtime/src/machine/timer.rs b/crates/stela-runtime/src/machine/timer.rs index 99da806949..2d950fdec4 100644 --- a/crates/stela-runtime/src/machine/timer.rs +++ b/crates/stela-runtime/src/machine/timer.rs @@ -306,7 +306,7 @@ pub fn next_event(cpu: &Cpu, now: u64) -> Option { #[cfg(test)] mod tests { use super::*; - use crate::machine::{Chip, exception::Pstate}; + use {crate::machine::exception::Pstate, stela_contracts::Chip}; #[test] fn native_epoch_omits_stable_assertions_but_keeps_every_future_channel() { @@ -415,7 +415,7 @@ mod tests { // EVNTIS (FEAT_ECV) adds 8 to EVNTI; without it (the M1) the bit is // RES0 and EVNTI 0 signals every count. cpu.registers.set(Register::CNTHCTL_EL2, 0, EVNTEN | EVNTIS); - let ecv = cpu.registers.has(crate::machine::system::Feature::FEAT_ECV); + let ecv = cpu.registers.has(stela_contracts::Feature::FEAT_ECV); assert_eq!(next_event(&cpu, 0), Some(if ecv { 256 } else { 1 })); // The EL1 stream counts the virtual count and only outside the host. cpu.registers.set(Register::CNTHCTL_EL2, 0, 0); diff --git a/crates/stela-runtime/src/machine/timer/agt.rs b/crates/stela-runtime/src/machine/timer/agt.rs index 1f79957b1b..fb9274f94a 100644 --- a/crates/stela-runtime/src/machine/timer/agt.rs +++ b/crates/stela-runtime/src/machine/timer/agt.rs @@ -50,8 +50,11 @@ //! bank's EL1&0 CNTKCTL from EL1 and EL2 alike (inference: SPTM saves it, //! clears it for an EL1 guest whose CNTKCTL it then writes through //! AGTCNTKCTL_EL12, and restores it after). -use super::super::{Chip, cpu::Cpu, impdef, system::Register}; use stela_compiler::aarch64::system::registers::{CNTVCT_EL0, Encoding}; +use { + super::super::cpu::Cpu, super::super::impdef, super::super::system::Register, + stela_contracts::Chip, +}; macro_rules! encodings { ($($name:ident = $op0:literal, $op1:literal, $crn:literal, $crm:literal, $op2:literal;)*) => { diff --git a/crates/stela-runtime/src/pauth.rs b/crates/stela-runtime/src/pauth.rs index 718b6f264a..fec415ab6d 100644 --- a/crates/stela-runtime/src/pauth.rs +++ b/crates/stela-runtime/src/pauth.rs @@ -40,44 +40,21 @@ const DATA_EXTENSION_MASK: u64 = 0x00ff_ffff_ffff_ffff & !ADDRESS_MASK; #[cfg(test)] const DATA_PAC_MASK: u64 = DATA_EXTENSION_MASK & !REGION_BIT; -/// Cryptographic key and address domain; XPAC uses only the address domain. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum Key { - Ia, - Ib, - Da, - Db, +use stela_contracts::pauth::Key; + +const fn key_domain(key: Key) -> policy::Domain { + if key.is_data() { + policy::Domain::Data + } else { + policy::Domain::Instruction + } } -impl Key { - 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) - } - const fn is_b(self) -> bool { - matches!(self, Self::Ib | Self::Db) - } - const fn domain(self) -> policy::Domain { - if self.is_data() { - policy::Domain::Data - } else { - policy::Domain::Instruction - } - } - #[cfg(test)] - const fn pac_mask(self) -> u64 { - if self.is_data() { - DATA_PAC_MASK - } else { - PAC_MASK - } +#[cfg(test)] +const fn key_pac_mask(key: Key) -> u64 { + if key.is_data() { + DATA_PAC_MASK + } else { + PAC_MASK } } @@ -241,7 +218,7 @@ impl Context { /// than the older Unicorn invalid-extension behavior. Enhanced profiles XOR the PAC field. pub fn sign(&self, key: Key, pointer: u64, modifier: u64) -> Result { let words = self.keys.get(key)?; - let layout = self.layout(key.domain(), pointer, true); + let layout = self.layout(key_domain(key), pointer, true); let input = policy::signing_input(layout, pointer); Ok(policy::sign( self.version, @@ -266,7 +243,7 @@ impl Context { let words = self.keys.words[key.index()] .as_ref() .ok_or(AuthenticationError::KeyUnavailable { key })?; - let domain = key.domain(); + let domain = key_domain(key); let layout = self.layout(domain, pointer, false); let input = policy::authentication_input(layout, pointer); let result = policy::authenticate( @@ -307,7 +284,7 @@ impl Context { /// even when that domain's cryptographic key was not provided. pub fn strip(&self, key: Key, pointer: u64) -> Result { Ok(policy::authentication_input( - self.layout(key.domain(), pointer, false), + self.layout(key_domain(key), pointer, false), pointer, )) } @@ -362,6 +339,19 @@ pub(crate) mod lr_effects; #[cfg(feature = "std")] pub(crate) mod conditional; +impl stela_contracts::pauth::Signer for Context { + type Error = anyhow::Error; + fn address_space(&self) -> u64 { + self.address_space() + } + fn profile_id(&self) -> &'static str { + self.profile_id() + } + fn sign(&self, key: Key, pointer: u64, modifier: u64) -> Result { + self.sign(key, pointer, modifier) + } +} + #[cfg(test)] mod tests { use super::*; @@ -856,7 +846,7 @@ mod tests { let shift = if key.is_data() { 53 } else { 61 }; let poison = if key.is_b() { 2u64 } else { 1 }; for bit in 0..64 { - if key.pac_mask() & (1 << bit) != 0 { + if key_pac_mask(key) & (1 << bit) != 0 { assert_eq!( context.authenticate(key, signed ^ (1 << bit), 0x2000)?, AuthResult { @@ -901,7 +891,7 @@ mod tests { (tag << 56) | (DATA_EXTENSION_MASK & !(1 << bit)) | 0x1400, ] { let canonical = - policy::authentication_input(key.domain().layout(), pointer); + policy::authentication_input(key_domain(key).layout(), pointer); let signed = context.sign(key, pointer, 0x2000)?; assert_eq!(signed, context.sign(key, canonical, 0x2000)? ^ (1 << 54)); let failed = context.authenticate(key, signed, 0x2000)?; diff --git a/crates/stela-runtime/src/pauth/lr_context.rs b/crates/stela-runtime/src/pauth/lr_context.rs index dc74638c30..fae82b027c 100644 --- a/crates/stela-runtime/src/pauth/lr_context.rs +++ b/crates/stela-runtime/src/pauth/lr_context.rs @@ -1,9 +1,9 @@ //! QARMA5 key service for FEAT_PAuth_LR. -use super::{ - AuthResult, AuthenticationError, Context, Key, TwoModifierError, - features::LinkRegisterPauthCapability, -}; use crate::system::identification_snapshot::Snapshot; +use { + super::AuthResult, super::AuthenticationError, super::Context, super::TwoModifierError, + super::features::LinkRegisterPauthCapability, stela_contracts::pauth::Key, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum InstructionKey { diff --git a/crates/stela-runtime/src/pauth/two_modifier.rs b/crates/stela-runtime/src/pauth/two_modifier.rs index c009ff86a8..e9eb9283ba 100644 --- a/crates/stela-runtime/src/pauth/two_modifier.rs +++ b/crates/stela-runtime/src/pauth/two_modifier.rs @@ -1,6 +1,9 @@ //! Two-modifier instruction PAuth (FEAT_PAuth_LR forms). -use super::{AuthResult, AuthenticationError, Context, Key, Version}; +use { + super::AuthResult, super::AuthenticationError, super::Context, super::Version, + stela_contracts::pauth::Key, +}; const FIRST_MODIFIER_LOW_BIT: u32 = 4; const SECOND_MODIFIER_LOW_BIT: u32 = 5; diff --git a/crates/stela-runtime/src/platform.rs b/crates/stela-runtime/src/platform.rs index 2fd64bb112..e32ee9648f 100644 --- a/crates/stela-runtime/src/platform.rs +++ b/crates/stela-runtime/src/platform.rs @@ -2,7 +2,6 @@ //! build runs in ring 0 with an aborting panic and a loader-provided heap. pub(crate) mod apple; pub(crate) mod cpu; -pub(crate) mod dma; pub mod net; #[cfg(target_arch = "x86_64")] pub mod pc; diff --git a/crates/stela-runtime/src/platform/apple.rs b/crates/stela-runtime/src/platform/apple.rs index 29c7ccaa14..8bdf172096 100644 --- a/crates/stela-runtime/src/platform/apple.rs +++ b/crates/stela-runtime/src/platform/apple.rs @@ -17,7 +17,7 @@ pub mod ans; pub mod asc; pub mod atc_phy; pub mod bridge; -pub mod bus; +use stela_contracts::bus; pub mod cluster; pub mod core_counters; pub mod coresight; @@ -35,7 +35,7 @@ pub mod fuse; pub mod gpio; pub mod hpm; pub mod i2c; -pub mod interrupt; +use stela_contracts::interrupt; pub mod ipi; pub mod lockdown; pub mod mcc; diff --git a/crates/stela-runtime/src/platform/apple/aes.rs b/crates/stela-runtime/src/platform/apple/aes.rs index 25f72ee454..94c6a55888 100644 --- a/crates/stela-runtime/src/platform/apple/aes.rs +++ b/crates/stela-runtime/src/platform/apple/aes.rs @@ -81,15 +81,17 @@ //! key functions, HDCP keys, the DSB, SKG, WRITE_REG and H16 scrambled-key //! commands, DKey distribution, DATA bit 24 and the reserved bits of the //! address words are refused until their values or behavior are known. -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; -use super::interrupt::{AicInput, Wire}; -use crate::platform::dma::{DmaError, Port}; use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit}; use alloc::collections::VecDeque; #[cfg(not(feature = "std"))] use alloc::vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; +use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire}; const NAME: &str = "aes-s8000"; @@ -910,8 +912,11 @@ impl MmioDevice for Aes { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; - use crate::platform::dma::{Iommu, Memory, tests::Ram}; + use stela_contracts::interrupt::InterruptLatch; + use { + stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, + }; const RAM: u64 = 0x8_0000_0000; const FIFO: u64 = 0x200; diff --git a/crates/stela-runtime/src/platform/apple/agx/event.rs b/crates/stela-runtime/src/platform/apple/agx/event.rs index c6a32cea03..52bae5842d 100644 --- a/crates/stela-runtime/src/platform/apple/agx/event.rs +++ b/crates/stela-runtime/src/platform/apple/agx/event.rs @@ -181,8 +181,12 @@ pub(crate) mod tests { #[test] fn a_real_port_prefix_fault_never_publishes_or_replays_a_published_body() { use super::super::uat::PAGE_BYTES; - use crate::platform::apple::{bus::Access, interrupt::InterruptLatch}; - use crate::platform::dma::{DmaError, Iommu, Memory, Port, tests::Ram}; + use {stela_contracts::bus::Access, stela_contracts::interrupt::InterruptLatch}; + use { + stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, + stela_contracts::dma::Memory, stela_contracts::dma::Port, + stela_contracts::dma::test_support::Ram, + }; struct FaultOnce(Option); impl Iommu for FaultOnce { diff --git a/crates/stela-runtime/src/platform/apple/agx/firmware.rs b/crates/stela-runtime/src/platform/apple/agx/firmware.rs index 6ff82a05c6..e3c4c563bf 100644 --- a/crates/stela-runtime/src/platform/apple/agx/firmware.rs +++ b/crates/stela-runtime/src/platform/apple/agx/firmware.rs @@ -53,13 +53,13 @@ use super::initdata::{self, Root}; use super::ring::{self, Kind, Shared}; use super::signal; use super::uat; -use crate::builds::Build; -use crate::platform::dma::Port; use alloc::boxed::Box; use alloc::collections::{BTreeMap, VecDeque}; use alloc::rc::Rc; use alloc::vec::Vec; use core::cell::RefCell; +use stela_contracts::dma::Port; +use stela_formats::builds::Build; /// An RTKit application endpoint with its number, as [`RtKit::new`] takes them. /// @@ -1205,7 +1205,7 @@ mod tests { } fn booted_gfx(family: &'static Family) -> Coprocessor { - let mut firmware = Coprocessor::new(family, crate::builds::DEFAULT).unwrap(); + let mut firmware = Coprocessor::new(family, stela_formats::builds::DEFAULT).unwrap(); firmware.start(&mut Vec::new()).unwrap(); for payload in [ 2 << 52 | 12 | 12 << 16, @@ -1247,9 +1247,13 @@ mod tests { let mut sgx = Sgx::new(gpu).unwrap(); let power = sgx.firmware_power(&[(0x204000000, 0x4000000, 0)]).unwrap(); let mut firmware = - Coprocessor::with_power(family, power.clone(), crate::builds::DEFAULT).unwrap(); + Coprocessor::with_power(family, power.clone(), stela_formats::builds::DEFAULT) + .unwrap(); let other = if family == &G14G { &G13G } else { &G14G }; - assert!(Coprocessor::with_power(other, power.clone(), crate::builds::DEFAULT).is_err()); + assert!( + Coprocessor::with_power(other, power.clone(), stela_formats::builds::DEFAULT) + .is_err() + ); // A truthful target binding alone is not enough to acknowledge // unimplemented config-dependent callback effects. firmware.protocol.0.borrow_mut().initdata_va = Some(ROOT); @@ -1279,8 +1283,11 @@ mod tests { ); assert!(outbox.is_empty()); if family == &G13G || family == &G14G { - use crate::platform::apple::bus::{Access, MmioDevice, Width}; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; + use { + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, + }; let mut latch = InterruptLatch::new(); let mut access = Access::new(0, 0, &mut latch); sgx.write(0xd04074, Width::Word, 1, &mut access).unwrap(); @@ -1448,7 +1455,7 @@ mod tests { context: usize, va: u64, data: &mut [u8], - ) -> Result<(), crate::platform::dma::DmaError> { + ) -> Result<(), stela_contracts::dma::DmaError> { self.flat.gpu_read(context, va, data) } fn gpu_write( @@ -1456,7 +1463,7 @@ mod tests { context: usize, va: u64, data: &[u8], - ) -> Result<(), crate::platform::dma::DmaError> { + ) -> Result<(), stela_contracts::dma::DmaError> { self.flat.gpu_write(context, va, data) } } @@ -2206,7 +2213,7 @@ mod tests { _: usize, _: u64, _: &mut [u8], - ) -> Result<(), crate::platform::dma::DmaError> { + ) -> Result<(), stela_contracts::dma::DmaError> { panic!("a signal command cannot execute GPU reads"); } fn gpu_write( @@ -2214,7 +2221,7 @@ mod tests { _: usize, _: u64, _: &[u8], - ) -> Result<(), crate::platform::dma::DmaError> { + ) -> Result<(), stela_contracts::dma::DmaError> { panic!("a signal command cannot execute GPU writes"); } } @@ -2922,9 +2929,9 @@ mod tests { #[test] fn the_initdata_root_is_read_through_the_uat() { - use crate::platform::apple::bus::Access; - use crate::platform::apple::interrupt::InterruptLatch; - use crate::platform::dma::tests::Ram; + use stela_contracts::bus::Access; + use stela_contracts::dma::test_support::Ram; + use stela_contracts::interrupt::InterruptLatch; use uat::{Access as Ap, Agent, Flags, MemoryAttr, Uat}; // TTBAT, PCE, PDE, PTE and the initdata page. let base = 0x8_0000_0000; @@ -2992,7 +2999,7 @@ mod tests { } /// Write a kext-shaped root at physical `at` whose objects follow `va`. - pub(crate) fn put_root(ram: &mut crate::platform::dma::tests::Ram, at: u64, va: u64) { + pub(crate) fn put_root(ram: &mut stela_contracts::dma::test_support::Ram, at: u64, va: u64) { ram.put_u64(at, MAGIC_G13_G14G); ram.put_u64(at + 0x28, 1 << 32); for (n, field) in [0x08, 0x18, 0x20, 0xa8, 0xb0, 0xb8, 0xc0] diff --git a/crates/stela-runtime/src/platform/apple/agx/ring.rs b/crates/stela-runtime/src/platform/apple/agx/ring.rs index dbcf636ed1..722d2eb849 100644 --- a/crates/stela-runtime/src/platform/apple/agx/ring.rs +++ b/crates/stela-runtime/src/platform/apple/agx/ring.rs @@ -28,8 +28,8 @@ //! what an entry means belongs to its consumer ([`super::firmware`]). use super::uat; -use crate::platform::dma::{DmaError, Port}; use alloc::vec::Vec; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; /// Entries in every ring. pub const ENTRIES: u32 = 0x100; @@ -243,9 +243,9 @@ pub(crate) mod tests { #[test] fn an_invalid_gpu_context_cannot_alias_context_zero_or_access_its_memory() { - use crate::platform::apple::bus::Access; - use crate::platform::apple::interrupt::InterruptLatch; - use crate::platform::dma::tests::Ram; + use stela_contracts::bus::Access; + use stela_contracts::dma::test_support::Ram; + use stela_contracts::interrupt::InterruptLatch; let base = 0x8_0000_0000; let mut ram = Ram::new(base, 5 * uat::PAGE_BYTES as usize); diff --git a/crates/stela-runtime/src/platform/apple/agx/sgx.rs b/crates/stela-runtime/src/platform/apple/agx/sgx.rs index b0061f7b97..e09822d585 100644 --- a/crates/stela-runtime/src/platform/apple/agx/sgx.rs +++ b/crates/stela-runtime/src/platform/apple/agx/sgx.rs @@ -64,15 +64,17 @@ //! - The model has one performance state (0), no GPC power transitions and //! so no GPC host interrupts; none of the `sgx` interrupt lines is raised. //! Enables and dynamic gating are held as written. -use super::super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; use super::generation::{Family, Gpu, Identification, MMU_ENABLE, Mmu, Model}; use super::uat::{self, Uat}; use alloc::rc::Rc; use alloc::vec; use alloc::vec::Vec; use core::cell::{Cell, RefCell}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const NAME: &str = "agx-sgx"; @@ -354,7 +356,7 @@ impl FirmwarePower { #[cfg(test)] fn target( &self, - port: &mut crate::platform::dma::Port<'_, '_>, + port: &mut stela_contracts::dma::Port<'_, '_>, region: &super::pio::Region, offset: u32, write: bool, @@ -373,9 +375,9 @@ impl FirmwarePower { .iommu .translate(port.memory, port.stream, va, va + 3, write, port.access) .map_err(|error| match error { - crate::platform::dma::DmaError::Fault(_) => "GFX firmware PIO faults in the UAT", - crate::platform::dma::DmaError::Memory => "GFX firmware PIO page table is not RAM", - crate::platform::dma::DmaError::Unsupported(reason) => reason, + stela_contracts::dma::DmaError::Fault(_) => "GFX firmware PIO faults in the UAT", + stela_contracts::dma::DmaError::Memory => "GFX firmware PIO page table is not RAM", + stela_contracts::dma::DmaError::Unsupported(reason) => reason, })?; if physical != expected { return Err("GFX firmware PIO translation disagrees with its AP physical descriptor"); @@ -399,7 +401,7 @@ impl FirmwarePower { #[cfg(test)] pub fn read( &self, - port: &mut crate::platform::dma::Port<'_, '_>, + port: &mut stela_contracts::dma::Port<'_, '_>, region: &super::pio::Region, offset: u32, ) -> Result { @@ -409,7 +411,7 @@ impl FirmwarePower { #[cfg(test)] pub fn write( &self, - port: &mut crate::platform::dma::Port<'_, '_>, + port: &mut stela_contracts::dma::Port<'_, '_>, region: &super::pio::Region, offset: u32, value: u32, @@ -717,7 +719,7 @@ impl MmioDevice for Sgx { mod tests { use super::super::generation::{self, GPUS}; use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; const MMU_TTBAT: u64 = 0xd0_802c; const MMU_TTBA_INVALIDATE: u64 = 0xd0_8030; @@ -760,7 +762,7 @@ mod tests { #[test] fn native_firmware_pio_walks_the_uat_and_shares_the_actual_ap_register() { use super::super::generation::{G13G, G13X, G14G, G14X, G15G}; - use crate::platform::dma::{Port, tests::Ram}; + use {stela_contracts::dma::Port, stela_contracts::dma::test_support::Ram}; let physical = 0x204000000; let base = 0x800000000; for family in [&G13G, &G13X, &G14G, &G14X, &G15G] { @@ -875,7 +877,7 @@ mod tests { power.write(&mut port, ®ion, offset, value) }; let translate = |sgx: &mut Sgx, ram: &mut Ram, access: &mut Access<'_>, agent| { - use crate::platform::dma::Iommu; + use stela_contracts::dma::Iommu; sgx.uat() .agent(agent) .translate(ram, 0, 0x12030, 0x12033, false, access) @@ -897,7 +899,7 @@ mod tests { ); assert!( matches!(translate(&mut sgx, &mut ram, &mut access, uat::Agent::Gpu), - Err(crate::platform::dma::DmaError::Unsupported(reason)) if reason.contains("Fender sleep")) + Err(stela_contracts::dma::DmaError::Unsupported(reason)) if reason.contains("Fender sleep")) ); assert!(translate(&mut sgx, &mut ram, &mut access, uat::Agent::Firmware).is_ok()); assert!( @@ -994,7 +996,7 @@ mod tests { #[test] fn physical_gates_inhibit_the_mmu_and_preserve_boot_roots_until_released() { - use crate::platform::dma::{Iommu, tests::Ram}; + use {stela_contracts::dma::Iommu, stela_contracts::dma::test_support::Ram}; let mut sgx = Sgx::handed_off(t8112(), 0x8_0000_0000, 0x8_0000_4000).unwrap(); let active = sgx.lifecycle; let mut ram = Ram::new(0, 0x1000); @@ -1026,7 +1028,7 @@ mod tests { false, &mut access ), - Err(crate::platform::dma::DmaError::Unsupported( + Err(stela_contracts::dma::DmaError::Unsupported( "SGX DMA while PMGR inhibits execution" )) )); diff --git a/crates/stela-runtime/src/platform/apple/agx/uat.rs b/crates/stela-runtime/src/platform/apple/agx/uat.rs index 6e60daa340..d731fd8d46 100644 --- a/crates/stela-runtime/src/platform/apple/agx/uat.rs +++ b/crates/stela-runtime/src/platform/apple/agx/uat.rs @@ -55,10 +55,10 @@ //! The model walks the tables on every access and caches nothing, so a TLB or //! TTBA-cache invalidation has nothing to discard. -use super::super::bus::Access as BusAccess; -use crate::platform::dma::{DmaError, Iommu, Memory}; use alloc::rc::Rc; use core::cell::Cell; +use stela_contracts::bus::Access as BusAccess; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, stela_contracts::dma::Memory}; /// Page shift and size (`UAT_PGBIT`/`UAT_PGSZ`). pub const PAGE_SHIFT: u32 = 14; @@ -558,7 +558,7 @@ impl Uat { self.last_fault } - /// The translator as `agent` sees it, for a [`crate::platform::dma::Port`]. + /// The translator as `agent` sees it, for a [`stela_contracts::dma::Port`]. pub fn agent(&mut self, agent: Agent) -> AgentView<'_> { AgentView { uat: self, agent } } @@ -711,7 +711,7 @@ impl Iommu for AgentView<'_> { #[cfg(test)] mod tests { use super::*; - use crate::platform::dma::tests::Ram; + use stela_contracts::dma::test_support::Ram; #[test] fn leaf_flags_round_trip_and_match_the_kext_constants() { @@ -856,8 +856,8 @@ mod tests { context: usize, va: u64, ) -> Result { - use crate::platform::apple::interrupt::InterruptLatch; - use crate::platform::dma::Port; + use stela_contracts::dma::Port; + use stela_contracts::interrupt::InterruptLatch; let mut latch = InterruptLatch::new(); let mut access = BusAccess::new(0, 0, &mut latch); let mut view = uat.agent(agent); @@ -1107,7 +1107,7 @@ mod tests { assert_eq!(permits(&hidden, Agent::Firmware), None); // A firmware write to a read-only page faults on permission. let (mut ram, mut uat, va, _) = firmware_space(fw_ro); - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; let mut latch = InterruptLatch::new(); let mut access = BusAccess::new(0, 0, &mut latch); let mut view = uat.agent(Agent::Firmware); @@ -1343,8 +1343,8 @@ mod tests { #[test] fn protection_table_enforces_each_agent_and_direction_without_writing_denied_memory() { - use crate::platform::apple::interrupt::InterruptLatch; - use crate::platform::dma::Port; + use stela_contracts::dma::Port; + use stela_contracts::interrupt::InterruptLatch; // Independent permission tables in m1n1 PTE.access_fw/access_gpu, // OS=1, AP rows and (UXN << 1 | PXN) columns. 1=read, 2=write; // None is its uncertain firmware "-?" entry. diff --git a/crates/stela-runtime/src/platform/apple/aic.rs b/crates/stela-runtime/src/platform/apple/aic.rs index bf64af24e3..579b02ec4f 100644 --- a/crates/stela-runtime/src/platform/apple/aic.rs +++ b/crates/stela-runtime/src/platform/apple/aic.rs @@ -126,12 +126,17 @@ pub mod layout; pub use layout::Aic2Layout; use super::aic1::AIC1_MAX_IRQ; -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; -use super::interrupt::{AicInput, CpuIndex, Wire}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; +use { + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::CpuIndex, + stela_contracts::interrupt::Wire, +}; const NAME: &str = "aic2"; @@ -814,7 +819,7 @@ impl MmioDevice for Aic2 { mod tests { use super::layout::Aic2DieLayout; use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; const NR_IRQ: u16 = 0x3a0; const MAX_IRQ: u16 = 0x400; diff --git a/crates/stela-runtime/src/platform/apple/aic1.rs b/crates/stela-runtime/src/platform/apple/aic1.rs index 94e0fac671..fa002d12f8 100644 --- a/crates/stela-runtime/src/platform/apple/aic1.rs +++ b/crates/stela-runtime/src/platform/apple/aic1.rs @@ -28,10 +28,17 @@ //! is a permitted one). `CONFIG` (0x10), the per-CPU views from 0x5000 and //! `IPI_SEND` bit 31 have no public description, so they stop explicitly, as //! does any CPU mask naming a CPU the model does not serve. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; -use super::interrupt::{AicInput, CpuIndex, Wire}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; +use { + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::CpuIndex, + stela_contracts::interrupt::Wire, +}; const NAME: &str = "aic1"; @@ -406,7 +413,7 @@ impl MmioDevice for Aic1 { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; const NR_IRQ: u16 = 0x380; const SW_SET: u64 = 0x4000; diff --git a/crates/stela-runtime/src/platform/apple/amcc.rs b/crates/stela-runtime/src/platform/apple/amcc.rs index d23daeaf75..85c2b27a50 100644 --- a/crates/stela-runtime/src/platform/apple/amcc.rs +++ b/crates/stela-runtime/src/platform/apple/amcc.rs @@ -71,12 +71,16 @@ //! This uses the bus's reset/stop request boundary, never a host reset. //! Readback, nonzero encodings and other widths refuse without effects. //! Every other register of the aperture refuses. -use super::bus::{Access, Direction, MmioDevice, MmioError, Transition, Width, refuse}; use super::regfile::{self, Held, Span}; use alloc::rc::Rc; use alloc::vec::Vec; use core::cell::RefCell; use core::sync::atomic::{Ordering, fence}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, + stela_contracts::bus::Transition, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const NAME: &str = "amcc"; const DRAM_ACCESS: u64 = 0x410; @@ -756,7 +760,7 @@ impl MmioDevice for Amcc { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; const fn bit_register(offset: u64) -> Register { Register { diff --git a/crates/stela-runtime/src/platform/apple/ans.rs b/crates/stela-runtime/src/platform/apple/ans.rs index 970cbb44f0..835597954c 100644 --- a/crates/stela-runtime/src/platform/apple/ans.rs +++ b/crates/stela-runtime/src/platform/apple/ans.rs @@ -35,11 +35,6 @@ mod namespace; mod prp; mod tunables; -use super::{ - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - interrupt::{AicInput, Wire}, -}; -use crate::platform::{apple::sart::Sart, dma::Port}; use alloc::{ boxed::Box, collections::{BTreeMap, VecDeque}, @@ -54,6 +49,13 @@ pub use namespace::Description; use namespace::Medium; use prp::dma_error; use stela_drivers::block::BlockDevice; +use {crate::platform::apple::sart::Sart, stela_contracts::dma::Port}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire, +}; const NAME: &str = "ans2"; /// Historical default software tag slots; configured dies use QueueGeometry. @@ -1042,15 +1044,13 @@ impl MmioDevice for Ans { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{ - interrupt::InterruptLatch, - sart::{Bounds, Sart}, - }, - dma::{Memory, Physical, tests::Ram}, - }; use alloc::{vec, vec::Vec}; use stela_drivers::block::{BlockError, RamDisk}; + use { + crate::platform::apple::sart::Bounds, crate::platform::apple::sart::Sart, + stela_contracts::dma::Memory, stela_contracts::dma::Physical, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, + }; const RAM: u64 = 0x8_0000_0000; const SQ: u64 = RAM; const CQ: u64 = RAM + 0x1000; diff --git a/crates/stela-runtime/src/platform/apple/ans/commands.rs b/crates/stela-runtime/src/platform/apple/ans/commands.rs index eab7590824..5c6881787a 100644 --- a/crates/stela-runtime/src/platform/apple/ans/commands.rs +++ b/crates/stela-runtime/src/platform/apple/ans/commands.rs @@ -14,9 +14,9 @@ use super::{ prp::{MAX_TRANSFER, Prps, dma_error}, tunables, }; -use crate::platform::{apple::sart::Sart, dma::Port}; use alloc::{vec, vec::Vec}; use stela_drivers::block::{BlockError, Finished, Request}; +use {crate::platform::apple::sart::Sart, stela_contracts::dma::Port}; pub(super) const IDENTIFY_BYTES: usize = 4096; /// `AppleANS2NVMeController::AllocateTunnelBuffer` (0x3dbe83c) rounds every @@ -1137,20 +1137,17 @@ impl Ans { mod tests { use super::super::Description; use super::*; - use crate::platform::{ - apple::{ - bus::Access, - interrupt::InterruptLatch, - sart::{Bounds, Sart}, - }, - dma::{Physical, tests::Ram}, - }; use alloc::boxed::Box; use stela_drivers::block::{BlockDevice, RamDisk}; + use { + crate::platform::apple::sart::Bounds, crate::platform::apple::sart::Sart, + stela_contracts::bus::Access, stela_contracts::dma::Physical, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, + }; #[test] fn os_build_tunnel_stores_only_the_recovered_message_and_checks_extensions() { - use crate::platform::apple::bus::{MmioDevice, Width}; + use {stela_contracts::bus::MmioDevice, stela_contracts::bus::Width}; let mut ans = Ans::new( Box::new(RamDisk::new("", 4, 4096)), &[Description { @@ -1258,7 +1255,7 @@ mod tests { #[test] fn device_time_tunnel_records_the_recovery_request_and_unserved_types_refuse_by_name() { - use crate::platform::apple::bus::{MmioDevice, Width}; + use {stela_contracts::bus::MmioDevice, stela_contracts::bus::Width}; let mut ans = Ans::new( Box::new(RamDisk::new("", 4, 4096)), &[Description { @@ -1368,7 +1365,7 @@ mod tests { #[test] fn sanitize_counter_tunnel_fills_its_whole_output_with_zero_counters() { - use crate::platform::apple::bus::{MmioDevice, Width}; + use {stela_contracts::bus::MmioDevice, stela_contracts::bus::Width}; let mut ans = Ans::new( Box::new(RamDisk::new("", 4, 4096)), &[Description { @@ -1430,7 +1427,7 @@ mod tests { #[test] fn tunable_table_tunnel_records_its_buffer_and_refuses_other_shapes() { - use crate::platform::apple::bus::{MmioDevice, Width}; + use {stela_contracts::bus::MmioDevice, stela_contracts::bus::Width}; let mut ans = Ans::new( Box::new(RamDisk::new("", 4, 4096)), &[Description { diff --git a/crates/stela-runtime/src/platform/apple/ans/prp.rs b/crates/stela-runtime/src/platform/apple/ans/prp.rs index 045be614ce..76b1569f48 100644 --- a/crates/stela-runtime/src/platform/apple/ans/prp.rs +++ b/crates/stela-runtime/src/platform/apple/ans/prp.rs @@ -6,8 +6,8 @@ //! the next, page-aligned list page while more than one data page remains. //! Every list entry consumes data or chains to a whole list page, so the //! transfer limit bounds traversal even if a guest supplies a cyclic list. -use crate::platform::dma::{DmaError, Port}; use alloc::vec::Vec; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; pub(super) const MAX_TRANSFER: usize = 1024 * 1024; @@ -106,9 +106,9 @@ impl Prps { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{bus::Access, interrupt::InterruptLatch}, - dma::{Physical, tests::Ram}, + use { + stela_contracts::bus::Access, stela_contracts::dma::Physical, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, }; #[test] diff --git a/crates/stela-runtime/src/platform/apple/asc.rs b/crates/stela-runtime/src/platform/apple/asc.rs index 93f1bd6962..2bfd685450 100644 --- a/crates/stela-runtime/src/platform/apple/asc.rs +++ b/crates/stela-runtime/src/platform/apple/asc.rs @@ -43,17 +43,20 @@ //! must admit retained stop/resume explicitly; unsupported reset and //! power-loss flows still refuse. Mailbox controls, staged payload and //! queued responses survive a retained halt. -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Transition, Width, refuse, -}; -use super::interrupt::{AicInput, Wire}; -use crate::platform::dma::Port; use alloc::boxed::Box; use alloc::collections::{BTreeSet, VecDeque}; use alloc::string::String; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use core::any::Any; +use stela_contracts::dma::Port; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Transition, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; +use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire}; pub mod entry; pub use entry::{Auxiliary, EntryFetch, EntryHandoff}; @@ -605,7 +608,7 @@ impl MmioDevice for Asc { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn physical_retention_freezes_work_and_preserves_mailbox_irq_ownership() { @@ -1227,7 +1230,7 @@ mod tests { ) }) .collect(); - let rtkit = RtKit::new(endpoints, crate::builds::DEFAULT.rtkit_version).unwrap(); + let rtkit = RtKit::new(endpoints, stela_formats::builds::DEFAULT.rtkit_version).unwrap(); let mut asc = Asc::booted(Box::new(rtkit), Lines::from_interrupts(LINES)).unwrap(); let mut latch = InterruptLatch::new(); let mut access = Access::new(0, 0, &mut latch); @@ -1297,7 +1300,7 @@ mod tests { #[test] fn an_earlier_dma_notification_survives_a_later_transfer_fault() { - use crate::platform::dma::{Physical, tests::Ram}; + use {stela_contracts::dma::Physical, stela_contracts::dma::test_support::Ram}; let mut latch = InterruptLatch::new(); let mut access = Access::new(0, 0, &mut latch); let mut memory = Ram::new(0, 8); diff --git a/crates/stela-runtime/src/platform/apple/asc/entry.rs b/crates/stela-runtime/src/platform/apple/asc/entry.rs index ce64ce3e48..ba63403a57 100644 --- a/crates/stela-runtime/src/platform/apple/asc/entry.rs +++ b/crates/stela-runtime/src/platform/apple/asc/entry.rs @@ -15,9 +15,13 @@ //! All writes to a locked register refuse; no ignored hardware write is //! invented. Destructive lifecycle changes invalidate knowledge rather than //! fabricating a reset value. Native protocol firmware alone supplies no word. -use super::super::bus::{Access, Direction, LifecycleState, MmioDevice, MmioError, Width, refuse}; use alloc::rc::Rc; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const NAME: &str = "asc-iorvbar"; const LOCK: u64 = 1; @@ -271,10 +275,10 @@ impl MmioDevice for Auxiliary { mod tests { use super::*; use crate::platform::apple::asc::{Asc, Firmware, Lines, Message}; - use crate::platform::apple::bus::Lifecycle; - use crate::platform::apple::interrupt::{AicInput, InterruptLatch}; - use crate::platform::dma::{Memory, tests::Ram}; use alloc::{boxed::Box, vec::Vec}; + use stela_contracts::bus::Lifecycle; + use {stela_contracts::dma::Memory, stela_contracts::dma::test_support::Ram}; + use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch}; struct FetchOwner { ram: Ram, diff --git a/crates/stela-runtime/src/platform/apple/atc_phy.rs b/crates/stela-runtime/src/platform/apple/atc_phy.rs index 0cad739735..1cd4edce33 100644 --- a/crates/stela-runtime/src/platform/apple/atc_phy.rs +++ b/crates/stela-runtime/src/platform/apple/atc_phy.rs @@ -32,9 +32,10 @@ //! LOAD_CNT restarts the count. The model has no UTMI cycle clock, so the //! count reports one event once the clock has been active with EVT_EN set, //! not elapsed cycles. The block's other words refuse. -use super::{ - bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}, - regfile::Held, +use { + super::regfile::Held, stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, }; const NAME: &str = "Apple ATC PHY"; @@ -342,8 +343,8 @@ impl MmioDevice for AtcPhy { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{bus::Bus, interrupt::InterruptLatch}; use alloc::boxed::Box; + use {stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch}; fn wr(p: &mut AtcPhy, a: &mut Access<'_>, o: u64, v: u32) { p.write(o, Width::Word, v.into(), a).unwrap(); } diff --git a/crates/stela-runtime/src/platform/apple/bridge.rs b/crates/stela-runtime/src/platform/apple/bridge.rs index ed00c9d38b..2256566f65 100644 --- a/crates/stela-runtime/src/platform/apple/bridge.rs +++ b/crates/stela-runtime/src/platform/apple/bridge.rs @@ -33,12 +33,16 @@ //! //! Stela's existing T8112 model hands off zero idle/disabled configuration, without conditional iBoot //! tuning. Header flag variants, other layouts and unknown registers refuse. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use super::regfile::Held; use alloc::{ collections::{BTreeMap, BTreeSet}, vec::Vec, }; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; pub mod tunables; const NAME: &str = "fabric-bridge"; const CONFIG_BYTES: usize = 36; @@ -344,7 +348,7 @@ impl MmioDevice for Bridge { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn tuning_and_dt_selected_configuration_hold_without_claiming_command_readback() { let mut sink = InterruptLatch::new(); diff --git a/crates/stela-runtime/src/platform/apple/cluster.rs b/crates/stela-runtime/src/platform/apple/cluster.rs index 3b4e078427..b618a6cff1 100644 --- a/crates/stela-runtime/src/platform/apple/cluster.rs +++ b/crates/stela-runtime/src/platform/apple/cluster.rs @@ -46,9 +46,13 @@ //! Every other register refuses. pub mod t6000; -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use super::regfile::Held; use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "cpu-cluster"; const COUNTER_BASE: u64 = 0x20400; @@ -225,7 +229,7 @@ impl MmioDevice for Cluster { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn cpu_commands_complete_against_the_same_state_table_and_scratch_holds_copies() { diff --git a/crates/stela-runtime/src/platform/apple/cluster/t6000.rs b/crates/stela-runtime/src/platform/apple/cluster/t6000.rs index 1b39a6b391..a7a520817f 100644 --- a/crates/stela-runtime/src/platform/apple/cluster/t6000.rs +++ b/crates/stela-runtime/src/platform/apple/cluster/t6000.rs @@ -6,8 +6,12 @@ //! Native performance/APSC, DVMR, throttling and autonomous counter execution //! require their actual controller owner; neither zero nor a cleared BUSY is //! manufactured to satisfy the driver's polls. -use super::super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::{collections::BTreeMap, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "t6000-cpu-cluster"; pub const COMMAND: u64 = 0xe20020; @@ -323,7 +327,7 @@ impl MmioDevice for T6000 { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn all_three_banks_preserve_unknownness_actual_table_stride_and_disabled_samples() { let mut irq = InterruptLatch::new(); @@ -427,12 +431,12 @@ mod tests { #[cfg(all(test, feature = "std"))] mod original { use super::*; - use crate::{ - machine::adt::Node, - platform::apple::{bus::Bus, interrupt::InterruptLatch, pmgr::t6000::Layout}, - }; use alloc::boxed::Box; use sha2::{Digest, Sha256}; + use { + crate::platform::apple::pmgr::t6000::Layout, stela_contracts::adt::Node, + stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch, + }; fn original(variable: &str, digest: &str) -> Vec { let bytes = std::fs::read(std::env::var(variable).expect("pinned J314s original")).unwrap(); assert_eq!(hex::encode(Sha256::digest(&bytes)), digest); diff --git a/crates/stela-runtime/src/platform/apple/core_counters.rs b/crates/stela-runtime/src/platform/apple/core_counters.rs index 05b79a3d3b..5c9b7d7268 100644 --- a/crates/stela-runtime/src/platform/apple/core_counters.rs +++ b/crates/stela-runtime/src/platform/apple/core_counters.rs @@ -38,8 +38,12 @@ //! the memory-stall deltas to 48 bits itself, testing bit 47 for overflow, //! which a counter that never counts never sets. So each is held as 64 bits //! (inference). -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use stela_compiler::aarch64::system::registers::Encoding; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "cpu-impl-reg counters"; /// The core performance counters' slots: eight 0x10 apart, then the @@ -247,7 +251,7 @@ impl MmioDevice for CoreCounters { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; const AON_1: Encoding = Encoding::new(3, 7, 15, 2, 3); const AON_3: Encoding = Encoding::new(3, 7, 15, 6, 3); diff --git a/crates/stela-runtime/src/platform/apple/coresight.rs b/crates/stela-runtime/src/platform/apple/coresight.rs index 7896ebc5ef..f40a72cd72 100644 --- a/crates/stela-runtime/src/platform/apple/coresight.rs +++ b/crates/stela-runtime/src/platform/apple/coresight.rs @@ -12,7 +12,11 @@ //! `reg-private` and a 4 KiB component map within the DT's larger CoreSight //! region. Only the lock pair of that component is mapped here; other debug registers //! and accesses with undescribed widths or directions still refuse. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "coresight-software-lock"; /// Offset of the write-only external debug lock-access register. @@ -162,7 +166,7 @@ impl MmioDevice for PcSampler { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn pc_sampler_latches_only_on_word_read_and_keeps_per_pe_state() { let mut sink = InterruptLatch::new(); diff --git a/crates/stela-runtime/src/platform/apple/cpm.rs b/crates/stela-runtime/src/platform/apple/cpm.rs index 9ed76b3457..a65491b79c 100644 --- a/crates/stela-runtime/src/platform/apple/cpm.rs +++ b/crates/stela-runtime/src/platform/apple/cpm.rs @@ -9,9 +9,13 @@ //! at +40f8. The restore request completes immediately against the already //! retained configuration. Its completion is recorded; electrical effects and //! command readback are not proved. Other values and reads of it refuse. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use super::regfile::Held; use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "cpm-power"; const RESTORE: u64 = 0x40f8; const THROTTLERS: [u64; 4] = [0x250, 0x270, 0x8400, 0x8408]; @@ -85,7 +89,7 @@ impl MmioDevice for Cpm { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn throttlers_retain_configuration_and_restore_does_not_discard_it() { let mut sink = InterruptLatch::new(); diff --git a/crates/stela-runtime/src/platform/apple/cpustart.rs b/crates/stela-runtime/src/platform/apple/cpustart.rs index 410b7c7ffa..d9cad1b38c 100644 --- a/crates/stela-runtime/src/platform/apple/cpustart.rs +++ b/crates/stela-runtime/src/platform/apple/cpustart.rs @@ -20,8 +20,12 @@ //! core's release for the machine ([`CpuStart::take`]), and the start words //! read 0. Stopping a core is not modelled: a stop request refuses, as does //! every other register. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "cpu-start"; @@ -117,7 +121,7 @@ impl MmioDevice for CpuStart { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn start_bits_release_their_cores_and_stops_refuse() { diff --git a/crates/stela-runtime/src/platform/apple/dart.rs b/crates/stela-runtime/src/platform/apple/dart.rs index a405da62bb..0cb120616b 100644 --- a/crates/stela-runtime/src/platform/apple/dart.rs +++ b/crates/stela-runtime/src/platform/apple/dart.rs @@ -18,12 +18,15 @@ mod legacy_umms; pub mod smmu; mod t8110; -use super::bus::{Access, MmioDevice, MmioError, Width}; -use super::interrupt::AicInput; -use crate::platform::dma::{DmaError, Iommu, Memory}; use alloc::vec::Vec; pub use irq::SharedIrq; pub use smmu::SmmuBlock; +use stela_contracts::interrupt::AicInput; +use { + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, +}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, stela_contracts::dma::Memory}; /// Internal bus offsets of the independently placed APF and UMMS views, /// above the largest translation window any profile admits. pub const DAPF_OFFSET: u64 = TRANSLATION_WINDOW_LIMIT; @@ -443,11 +446,11 @@ impl MmioDevice for Dart { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::interrupt::{InterruptLatch, Wire}, - dma::{Port, tests::Ram}, - }; use alloc::vec; + use { + stela_contracts::dma::Port, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::InterruptLatch, stela_contracts::interrupt::Wire, + }; #[test] fn explicit_profiles_keep_the_shared_bus_master_type_and_actual_table_effects() { @@ -709,12 +712,12 @@ mod tests { } legacy.write(0x40, Width::Word, 1, &mut access).unwrap(); } - assert!(sink.is_asserted(crate::platform::apple::interrupt::Wire::Aic(input))); + assert!(sink.is_asserted(stela_contracts::interrupt::Wire::Aic(input))); { let mut access = Access::new(0, 0, &mut sink); modern.set_reset(true, &mut access); } - assert!(!sink.is_asserted(crate::platform::apple::interrupt::Wire::Aic(input))); + assert!(!sink.is_asserted(stela_contracts::interrupt::Wire::Aic(input))); assert!( legacy .bind_shared_irq(&SharedIrq::new(AicInput::new(0, 1))) diff --git a/crates/stela-runtime/src/platform/apple/dart/context_route.rs b/crates/stela-runtime/src/platform/apple/dart/context_route.rs index 939fff48c9..865f7bdaa9 100644 --- a/crates/stela-runtime/src/platform/apple/dart/context_route.rs +++ b/crates/stela-runtime/src/platform/apple/dart/context_route.rs @@ -12,9 +12,9 @@ //! assigned context must agree. A fault cannot identify its physical bank //! or incoming SID here and therefore refuses without latching metadata. use super::{Dart, Model}; -use crate::platform::{ - apple::bus::Access, - dma::{DmaError, Iommu, Memory}, +use { + stela_contracts::bus::Access, stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, + stela_contracts::dma::Memory, }; const USB_TRADS: usize = 2; @@ -145,15 +145,13 @@ impl Iommu for T6000ContextDma<'_> { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{ - bus::{MmioDevice, Width}, - dart::Profile, - interrupt::{AicInput, InterruptLatch, Wire}, - }, - dma::{Port, tests::Ram}, - }; use alloc::{vec, vec::Vec}; + use { + crate::platform::apple::dart::Profile, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, stela_contracts::dma::Port, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::AicInput, + stela_contracts::interrupt::InterruptLatch, stela_contracts::interrupt::Wire, + }; const ROOT: u64 = 0x8_0000_0000; const FRAME: u64 = ROOT + 4 * PAGE; diff --git a/crates/stela-runtime/src/platform/apple/dart/descriptor.rs b/crates/stela-runtime/src/platform/apple/dart/descriptor.rs index da7a9105b5..923aff6902 100644 --- a/crates/stela-runtime/src/platform/apple/dart/descriptor.rs +++ b/crates/stela-runtime/src/platform/apple/dart/descriptor.rs @@ -4,7 +4,7 @@ //! permissions, subpage bounds and valid bits. m1n1's dart8020.py names the //! wider address fields through bit39. A profile's smaller PA width must //! reject those high address bits rather than silently truncate them. -use crate::platform::dma::DmaError; +use stela_contracts::dma::DmaError; const VALID: u64 = 1; /// DART1: subpage protection disable. DART2: no-cache. Neither adds an diff --git a/crates/stela-runtime/src/platform/apple/dart/gen3/descriptor.rs b/crates/stela-runtime/src/platform/apple/dart/gen3/descriptor.rs index 7e57c5537b..3c82f25414 100644 --- a/crates/stela-runtime/src/platform/apple/dart/gen3/descriptor.rs +++ b/crates/stela-runtime/src/platform/apple/dart/gen3/descriptor.rs @@ -5,7 +5,7 @@ //! revision3.0. Its native TTBR write at158df8..158e00 still uses PA>>12. //! Choosing a software encoding does not qualify the native mode/revision, //! security, filter or context contracts needed for profile admission. -use crate::platform::{apple::dart::descriptor::Format, dma::DmaError}; +use {crate::platform::apple::dart::descriptor::Format, stela_contracts::dma::DmaError}; const COMPACT_ADDRESS: u64 = 0x0000_0003_ffff_ffc0; const ATTRIBUTES: u64 = 0xfff << 52 | 0xfff << 40 | 0xf; diff --git a/crates/stela-runtime/src/platform/apple/dart/gen3/fault.rs b/crates/stela-runtime/src/platform/apple/dart/gen3/fault.rs index 7d832769b2..23ed2f3c41 100644 --- a/crates/stela-runtime/src/platform/apple/dart/gen3/fault.rs +++ b/crates/stela-runtime/src/platform/apple/dart/gen3/fault.rs @@ -10,8 +10,12 @@ //! decoder. Other header fields, auxiliary AXI data and secondary-capture //! behavior remain unqualified. Observations retain every raw summary bit; //! failed DMA never fabricates a complete header from the known fields. -use crate::platform::apple::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::{vec, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const PENDING: u64 = 0x4000; const RECORDS: u64 = 0x8000; @@ -272,7 +276,7 @@ impl MmioDevice for Capture { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn original_fault_taxonomy_keeps_observed_direction_and_unmodeled_bits() { diff --git a/crates/stela-runtime/src/platform/apple/dart/gen3/streams.rs b/crates/stela-runtime/src/platform/apple/dart/gen3/streams.rs index cf2a060da9..40a66d199d 100644 --- a/crates/stela-runtime/src/platform/apple/dart/gen3/streams.rs +++ b/crates/stela-runtime/src/platform/apple/dart/gen3/streams.rs @@ -98,18 +98,15 @@ impl Snapshot { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{ - bus::Access, - dart::gen3::{ - context::Context, - fault::{Code, Record}, - handoff::Handoff, - tables::Tables, - }, - interrupt::InterruptLatch, - }, - dma::{DmaError, Iommu, Memory, Port, tests::Ram}, + use { + crate::platform::apple::dart::gen3::context::Context, + crate::platform::apple::dart::gen3::fault::Code, + crate::platform::apple::dart::gen3::fault::Record, + crate::platform::apple::dart::gen3::handoff::Handoff, + crate::platform::apple::dart::gen3::tables::Tables, stela_contracts::bus::Access, + stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::Port, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::InterruptLatch, }; const PAGE: u64 = 0x4000; diff --git a/crates/stela-runtime/src/platform/apple/dart/gen3/tables.rs b/crates/stela-runtime/src/platform/apple/dart/gen3/tables.rs index 5202779bd9..2ce1e3c7ca 100644 --- a/crates/stela-runtime/src/platform/apple/dart/gen3/tables.rs +++ b/crates/stela-runtime/src/platform/apple/dart/gen3/tables.rs @@ -10,11 +10,11 @@ use super::descriptor::Encoding; use super::fault::{Capture, Code, Level, Record}; use super::handoff::Handoff; use super::streams::{self, Command, Snapshot}; -use crate::platform::{ - apple::bus::Access, - dma::{DmaError, Iommu, Memory}, -}; use alloc::{vec, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, + stela_contracts::dma::Memory, +}; const PA_BITS: u32 = 42; const TRANSLATE: u32 = 1; @@ -337,9 +337,9 @@ impl Iommu for Tables { mod tests { use super::super::context::{BoundsPolicy, TableLevel}; use super::*; - use crate::platform::{ - apple::interrupt::InterruptLatch, - dma::{Port, tests::Ram}, + use { + stela_contracts::dma::Port, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::InterruptLatch, }; const ROOT: u64 = 0x8_0000_0000; diff --git a/crates/stela-runtime/src/platform/apple/dart/irq.rs b/crates/stela-runtime/src/platform/apple/dart/irq.rs index d143d3d3cc..07bc2aa764 100644 --- a/crates/stela-runtime/src/platform/apple/dart/irq.rs +++ b/crates/stela-runtime/src/platform/apple/dart/irq.rs @@ -2,9 +2,9 @@ //! //! Original J314s firmware and surface DART nodes both name AIC873. The //! grouping boundary is a software ownership boundary, not a wired-OR gate. -use super::super::interrupt::AicInput; use alloc::{rc::Rc, vec::Vec}; use core::cell::RefCell; +use stela_contracts::interrupt::AicInput; /// Retain one owner per physical input across every logical DART group on /// that input. Bind each translator before publishing its MMIO aperture. diff --git a/crates/stela-runtime/src/platform/apple/dart/legacy.rs b/crates/stela-runtime/src/platform/apple/dart/legacy.rs index 848f05f4a8..4cc2176a2e 100644 --- a/crates/stela-runtime/src/platform/apple/dart/legacy.rs +++ b/crates/stela-runtime/src/platform/apple/dart/legacy.rs @@ -20,12 +20,16 @@ //! fields and the different 64-SID USB4 interface refuse explicitly. //! This module does not qualify those board configurations by constructing a //! successful-looking superset. Translation is cacheless and DMA synchronous. -use super::super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; -use super::super::interrupt::{AicInput, Wire}; use super::{Profile, SMMU_BYTES, SMMU_OFFSET, descriptor::Format, legacy_umms}; -use crate::platform::dma::{DmaError, Iommu, Memory}; use alloc::{rc::Rc, vec, vec::Vec}; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, stela_contracts::dma::Memory}; +use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire}; const PARAMS1: u64 = 0; const PARAMS2: u64 = 4; @@ -673,9 +677,9 @@ impl MmioDevice for Dart { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::interrupt::InterruptLatch, - dma::{Port, tests::Ram}, + use { + stela_contracts::dma::Port, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::InterruptLatch, }; const ROOT: u64 = 0x8_0000_0000; diff --git a/crates/stela-runtime/src/platform/apple/dart/smmu.rs b/crates/stela-runtime/src/platform/apple/dart/smmu.rs index d2c6072cb0..761a089c0e 100644 --- a/crates/stela-runtime/src/platform/apple/dart/smmu.rs +++ b/crates/stela-runtime/src/platform/apple/dart/smmu.rs @@ -14,7 +14,11 @@ //! registers, writes to identification and non-word reads. Supporting cached //! generations requires a different coherent count, selector and payload //! implementation. See `docs/research/dart-iommu.md`. -use super::super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "dart-smmu"; const BUILD_PARAMS: u64 = 0; @@ -64,7 +68,7 @@ impl MmioDevice for SmmuBlock { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn capture_count_matches_the_absent_store_and_never_fabricates_a_dump() { diff --git a/crates/stela-runtime/src/platform/apple/dart/t8110.rs b/crates/stela-runtime/src/platform/apple/dart/t8110.rs index e79aeacdda..bbfeb5fc4f 100644 --- a/crates/stela-runtime/src/platform/apple/dart/t8110.rs +++ b/crates/stela-runtime/src/platform/apple/dart/t8110.rs @@ -159,16 +159,20 @@ //! Full family evidence, capability gates and qualification gaps are in //! `docs/research/dart-iommu.md`. The paired SMMU view exposes the capture //! count of this cacheless implementation, not a physical chip's dump. -use super::super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; -use super::super::interrupt::{AicInput, Wire}; use super::descriptor::Format; use super::gen3::fault::{Capture, Code, Level, Record}; use super::{DAPF_BYTES, DAPF_OFFSET, Fault, Profile, SMMU_BYTES, SMMU_OFFSET, SmmuBlock}; -use crate::platform::dma::{DmaError, Iommu, Memory}; #[cfg(not(feature = "std"))] use alloc::vec; use alloc::{rc::Rc, vec::Vec}; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, stela_contracts::dma::Memory}; +use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire}; const NAME: &str = "dart-t8110"; @@ -1151,7 +1155,7 @@ impl MmioDevice for Dart { mod tests { use super::super::super::interrupt::InterruptLatch; use super::*; - use crate::platform::dma::tests::Ram; + use stela_contracts::dma::test_support::Ram; const ROOT: u64 = 0x1_0000_0000; const LEAVES: u64 = ROOT + PAGE; @@ -1607,7 +1611,7 @@ mod tests { ); let mut a = Access::new(0, 0, &mut sink); let first = 0x200_8000 - 4; - let mut port = crate::platform::dma::Port { + let mut port = stela_contracts::dma::Port { iommu: &mut dart, stream: 1, memory: &mut ram, @@ -1796,10 +1800,10 @@ mod tests { ) .unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); - let root = crate::machine::adt::Node::root(&bytes).unwrap(); + let root = stela_contracts::adt::Node::root(&bytes).unwrap(); let node = root.child("arm-io").unwrap().child("dart-pmp").unwrap(); assert_eq!(node.first_u32("n-apfs-instance-0"), Some(16)); assert_eq!(node.first_u32("sid"), Some(0)); diff --git a/crates/stela-runtime/src/platform/apple/dcp.rs b/crates/stela-runtime/src/platform/apple/dcp.rs index 1e2c9ffa42..020bb99ea2 100644 --- a/crates/stela-runtime/src/platform/apple/dcp.rs +++ b/crates/stela-runtime/src/platform/apple/dcp.rs @@ -41,14 +41,14 @@ pub mod swap; use super::asc::{Firmware, Message, TransitionRequest}; use super::rtkit::{Endpoint, RtKit}; use super::scanout::{Scanout, Surface}; -use crate::builds::Build; -use crate::platform::dma::Port; use alloc::boxed::Box; use alloc::rc::Rc; use alloc::string::String; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use core::cell::RefCell; +use stela_contracts::dma::Port; +use stela_formats::builds::Build; /// The RTKit endpoint numbers the J473AP DCPEXT advertises to the AP. 0x37 is /// the IOMFB link service (DCPEXTEndpoint24); the AFK/EPIC endpoints are the @@ -504,8 +504,8 @@ impl Firmware for Coprocessor { mod tests { use super::super::scanout::PixelFormat; use super::*; - use crate::builds::DEFAULT; - use crate::platform::dma::{DmaError, tests::Ram}; + use stela_formats::builds::DEFAULT; + use {stela_contracts::dma::DmaError, stela_contracts::dma::test_support::Ram}; const RAM: u64 = 0x8_0000_0000; @@ -531,13 +531,13 @@ mod tests { } struct Identity; - impl crate::platform::dma::Iommu for Identity { + impl stela_contracts::dma::Iommu for Identity { fn page(&self) -> u64 { 0x4000 } fn translate( &mut self, - _: &mut dyn crate::platform::dma::Memory, + _: &mut dyn stela_contracts::dma::Memory, _: usize, iova: u64, _: u64, diff --git a/crates/stela-runtime/src/platform/apple/dcp/abi.rs b/crates/stela-runtime/src/platform/apple/dcp/abi.rs index 0693fcfb70..dabad75206 100644 --- a/crates/stela-runtime/src/platform/apple/dcp/abi.rs +++ b/crates/stela-runtime/src/platform/apple/dcp/abi.rs @@ -1,5 +1,5 @@ //! The method and callback ABI of the DCP IOMFB link (the 26A434 interface -//! version, [`crate::builds`]): which four-character tag names which method, +//! version, [`stela_formats::builds`]): which four-character tag names which method, //! the wire sizes of its input and output, and how a method's arguments are //! packed into those bytes. //! diff --git a/crates/stela-runtime/src/platform/apple/dcp/link.rs b/crates/stela-runtime/src/platform/apple/dcp/link.rs index 664721c167..238898401c 100644 --- a/crates/stela-runtime/src/platform/apple/dcp/link.rs +++ b/crates/stela-runtime/src/platform/apple/dcp/link.rs @@ -29,7 +29,7 @@ //! ## Bring-up //! //! The coprocessor says hello with its interface version (type 0, subtype -//! 0, the build's `dcp_link_version` from [`crate::builds`], checked by +//! 0, the build's `dcp_link_version` from [`stela_formats::builds`], checked by //! the AP's handler 0x3d7e47c when the //! `iomfb_version_check` boot-arg is set). The AP's `link_state_init` //! (0x3d7c7a0) writes the [`RegionHeader`] at the start of its region and @@ -106,7 +106,7 @@ const FIELD: u64 = 0xffff; /// the interface `version`'s four bytes, extended by the empty interface /// string the 26A434 AP hashes after them (handler 0x3d7e528). pub fn interface_crc(version: u32) -> u32 { - crate::payload::gpt::crc32(&version.to_le_bytes()) + stela_formats::payload::gpt::crc32(&version.to_le_bytes()) } /// Which side owns a stream. @@ -329,7 +329,9 @@ mod tests { #[test] fn the_interface_crc_is_the_26a434_value() { - let version = crate::builds::find("26A434").unwrap().dcp_link_version; + let version = stela_formats::builds::find("26A434") + .unwrap() + .dcp_link_version; assert_eq!(interface_crc(version), 0x15a5_c96b); } diff --git a/crates/stela-runtime/src/platform/apple/dcp/rpc.rs b/crates/stela-runtime/src/platform/apple/dcp/rpc.rs index 99de543df3..2632b127f8 100644 --- a/crates/stela-runtime/src/platform/apple/dcp/rpc.rs +++ b/crates/stela-runtime/src/platform/apple/dcp/rpc.rs @@ -627,7 +627,7 @@ mod tests { use alloc::string::String; const WINDOW: u64 = 0x8_0000_0000; - const VERSION: u32 = crate::builds::DEFAULT.dcp_link_version; + const VERSION: u32 = stela_formats::builds::DEFAULT.dcp_link_version; const REGION_DVA: u64 = 0x4000; const REGION: u64 = WINDOW + REGION_DVA; diff --git a/crates/stela-runtime/src/platform/apple/dcs/native.rs b/crates/stela-runtime/src/platform/apple/dcs/native.rs index 303e4021e4..d8b3256036 100644 --- a/crates/stela-runtime/src/platform/apple/dcs/native.rs +++ b/crates/stela-runtime/src/platform/apple/dcs/native.rs @@ -20,11 +20,13 @@ //! them; `_enablePerfCtrl` panics unless a clear bit reads clear within //! 20 us, and a clear completes at once. The counters at +4000 count DRAM //! events, which no producer supplies, so their reads refuse. -use crate::platform::apple::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; use alloc::{rc::Rc, vec::Vec}; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const NAME: &str = "dcs"; pub const CHANNEL_STRIDE: u64 = 0x400000; @@ -380,7 +382,7 @@ mod tests { }; let mut owner = Controller::initialized(alloc::vec![configuration; CHANNELS], live).unwrap(); - let mut latch = crate::platform::apple::interrupt::InterruptLatch::new(); + let mut latch = stela_contracts::interrupt::InterruptLatch::new(); let mut access = Access::new(0, 0, &mut latch); let base = 3 * CHANNEL_STRIDE; assert_eq!( diff --git a/crates/stela-runtime/src/platform/apple/display.rs b/crates/stela-runtime/src/platform/apple/display.rs index 13408c6399..8def3ddd01 100644 --- a/crates/stela-runtime/src/platform/apple/display.rs +++ b/crates/stela-runtime/src/platform/apple/display.rs @@ -12,8 +12,12 @@ //! doc, never a fabricated value. This is the spec-first boundary; the //! registers the restored_external boot actually touches are closed from its //! trace, not guessed here. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; /// A present-but-unmodeled register aperture: every access refuses, named. pub struct Region { @@ -99,7 +103,7 @@ impl MmioDevice for Region { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn every_display_register_access_refuses_by_name() { diff --git a/crates/stela-runtime/src/platform/apple/dpe.rs b/crates/stela-runtime/src/platform/apple/dpe.rs index e55438a181..0cb477ada6 100644 --- a/crates/stela-runtime/src/platform/apple/dpe.rs +++ b/crates/stela-runtime/src/platform/apple/dpe.rs @@ -17,11 +17,13 @@ //! hardware sampling/restoration effects and refuse before commit. Clock-stop //! MMIO availability is unqualified; quiesce permits nonmutating reads. This //! native-bank hook does not establish its implicit PMGR domain association. -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; use super::regfile::Held; use alloc::{collections::BTreeMap, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; const NAME: &str = "soc-dpe"; pub const ENGINES: [u64; 6] = [0x2400, 0x2800, 0x2c00, 0x3000, 0x3400, 0x3800]; pub const CONTROLS: [u64; 3] = [0, 0x200, 0x300]; @@ -173,7 +175,7 @@ impl MmioDevice for Dpe { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn restore_slots_and_dt_reporting_samples_are_independent_address_sources() { let mut sink = InterruptLatch::new(); @@ -316,8 +318,8 @@ mod tests { } #[test] fn mounted_saved_counter_aliases_keep_the_same_lifecycle_owner() { - use crate::platform::apple::bus::Bus; use alloc::boxed::Box; + use stela_contracts::bus::Bus; let mut bus = Bus::new(); let device = bus.add(Box::new(Dpe::new(&[]).unwrap())); bus.map(device, 0x10000, 8, 0x2708).unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/dwc3.rs b/crates/stela-runtime/src/platform/apple/dwc3.rs index b609d7242f..8205a12d96 100644 --- a/crates/stela-runtime/src/platform/apple/dwc3.rs +++ b/crates/stela-runtime/src/platform/apple/dwc3.rs @@ -35,17 +35,19 @@ mod apple; mod regs; pub mod xhci; -use super::{ - bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}, - interrupt::{AicInput, Wire}, - typec::Usb2Speed, -}; -use crate::platform::{ - dma::{DmaError, Port}, - usb::{BusPeer, Function, MAX_PACKET, Reply, Token}, -}; use alloc::{collections::VecDeque, string::String}; use regs::*; +use { + super::typec::Usb2Speed, stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, stela_contracts::interrupt::AicInput, + stela_contracts::interrupt::Wire, +}; +use { + crate::platform::usb::BusPeer, crate::platform::usb::Function, + crate::platform::usb::MAX_PACKET, crate::platform::usb::Reply, crate::platform::usb::Token, + stela_contracts::dma::DmaError, stela_contracts::dma::Port, +}; const NAME: &str = "dwc3-device"; pub const PLATFORM_WINDOW_BASE: u64 = 0x20000; @@ -1339,11 +1341,11 @@ impl MmioDevice for Dwc3 { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{dart::Dart, interrupt::InterruptLatch}, - dma::{Memory, tests::Ram}, - }; use alloc::vec; + use { + crate::platform::apple::dart::Dart, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, + }; const RAM: u64 = 0x1_0000_0000; const TRB: u64 = RAM + 0x1000; const PAYLOAD: u64 = RAM + 0x2000; diff --git a/crates/stela-runtime/src/platform/apple/dwc3/xhci.rs b/crates/stela-runtime/src/platform/apple/dwc3/xhci.rs index 3216f45ae5..4fcf4670c5 100644 --- a/crates/stela-runtime/src/platform/apple/dwc3/xhci.rs +++ b/crates/stela-runtime/src/platform/apple/dwc3/xhci.rs @@ -60,9 +60,9 @@ mod slot; use super::super::typec::Usb2Speed; -use crate::platform::{dma::Port, usb::Function}; use alloc::{boxed::Box, collections::VecDeque, format, string::String}; use slot::Slot; +use {crate::platform::usb::Function, stela_contracts::dma::Port}; /// Bytes of the core's address space the host registers occupy. pub const BYTES: u64 = 0x1000; @@ -1269,12 +1269,12 @@ impl Xhci { #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::platform::apple::{ - bus::{Access, MmioDevice, Width}, - dart::Dart, - interrupt::InterruptLatch, + use { + crate::platform::apple::dart::Dart, stela_contracts::bus::Access, + stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, + stela_contracts::interrupt::InterruptLatch, }; - use crate::platform::dma::{Memory, tests::Ram}; + use {stela_contracts::dma::Memory, stela_contracts::dma::test_support::Ram}; const STOPPED_CODE: u32 = 26; @@ -2096,17 +2096,6 @@ pub(crate) mod tests { /// buffers are host memory, which the model reaches through a `Memory` /// over the same addresses. pub(crate) mod host { - use crate::platform::{ - apple::{ - bus::{Access, MmioDevice, Width}, - dart::Dart, - dwc3::xhci::Xhci, - interrupt::InterruptLatch, - typec::Usb2Speed, - }, - dma::{Memory, Port}, - usb::Function, - }; use alloc::{boxed::Box, rc::Rc, string::String, vec::Vec}; use core::cell::RefCell; use stela_drivers::{ @@ -2114,6 +2103,13 @@ pub(crate) mod tests { bus::dma::RegionAllocator, usb::xhci::{Found, Registers, start}, }; + use { + crate::platform::apple::dart::Dart, crate::platform::apple::dwc3::xhci::Xhci, + crate::platform::apple::typec::Usb2Speed, crate::platform::usb::Function, + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, stela_contracts::dma::Memory, stela_contracts::dma::Port, + stela_contracts::interrupt::InterruptLatch, + }; /// Host memory the test owns, by address. struct Arena { diff --git a/crates/stela-runtime/src/platform/apple/dwc3/xhci/slot.rs b/crates/stela-runtime/src/platform/apple/dwc3/xhci/slot.rs index 307aef2ffa..656939583e 100644 --- a/crates/stela-runtime/src/platform/apple/dwc3/xhci/slot.rs +++ b/crates/stela-runtime/src/platform/apple/dwc3/xhci/slot.rs @@ -37,11 +37,11 @@ use super::{ CONTEXT_STATE_ERROR, CYCLE, Event, LINK, MAX_SLOTS, MICROFRAME, PARAMETER_ERROR, SLOT_NOT_ENABLED, SUCCESS, TOGGLE, TRANSACTION_ERROR, TRB_BYTES, TRB_ERROR, Xhci, }; -use crate::platform::{ - dma::Port, - usb::{self, Function, Reply, Token}, -}; use alloc::{boxed::Box, format, vec::Vec}; +use { + crate::platform::usb, crate::platform::usb::Function, crate::platform::usb::Reply, + crate::platform::usb::Token, stela_contracts::dma::Port, +}; pub(super) const ENDPOINTS: usize = 31; const CONTEXT: u64 = 32; diff --git a/crates/stela-runtime/src/platform/apple/energy.rs b/crates/stela-runtime/src/platform/apple/energy.rs index 79c3e1e4c9..d51a075f83 100644 --- a/crates/stela-runtime/src/platform/apple/energy.rs +++ b/crates/stela-runtime/src/platform/apple/energy.rs @@ -18,7 +18,11 @@ //! both counts zero: accumulators disabled, with no other field set, as a //! boot chain that programs none of them would. Configuration then holds //! full writes. iBoot's conditional programming is not reproduced. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "cpu-energy"; const SRAM: u64 = 8; @@ -103,7 +107,7 @@ impl MmioDevice for Energy { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn the_boot_stage_hands_off_disabled_energy_and_samples_hold_without_physical_activity() { diff --git a/crates/stela-runtime/src/platform/apple/fuse.rs b/crates/stela-runtime/src/platform/apple/fuse.rs index f8a4c16c7f..108c1ef816 100644 --- a/crates/stela-runtime/src/platform/apple/fuse.rs +++ b/crates/stela-runtime/src/platform/apple/fuse.rs @@ -23,7 +23,11 @@ //! ones. The registers' other bits are fields no reader of this kernel is //! known to take, so they read 0 as well, and every other register refuses. //! Fuses are read-only. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "aon-fuse"; @@ -75,7 +79,7 @@ impl MmioDevice for AonFuses { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn the_rail_leakage_and_gpu_power_fields_read_uncalibrated() { diff --git a/crates/stela-runtime/src/platform/apple/gpio.rs b/crates/stela-runtime/src/platform/apple/gpio.rs index 63d58343fa..ed3caa8a22 100644 --- a/crates/stela-runtime/src/platform/apple/gpio.rs +++ b/crates/stela-runtime/src/platform/apple/gpio.rs @@ -43,12 +43,14 @@ //! driver's separate enableWakeOnly/claimWakeEvents contract is not modeled, //! so a stopped clock cannot silently discard edge/wake ownership. Physical //! supply loss, pad retention and reset remain explicit refusals. -use super::{ - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - interrupt::{AicInput, Wire}, -}; use alloc::{rc::Rc, vec, vec::Vec}; use core::cell::Cell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire, +}; const NAME: &str = "Apple GPIO"; const DATA: u32 = 1; const MODE: u32 = 7 << 1; @@ -458,7 +460,7 @@ impl MmioDevice for Gpio { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; fn lines() -> Vec { (199..206).map(|irq| AicInput::new(0, irq)).collect() } @@ -708,9 +710,10 @@ mod tests { #[test] fn mounted_gpio_refusal_keeps_real_aic_delivery_owned() { - use crate::platform::apple::{ - aic::{AIC2_IRQ_CFG, AIC2_TIMESTAMPS, Aic2, Aic2Config}, - bus::Bus, + use { + crate::platform::apple::aic::AIC2_IRQ_CFG, + crate::platform::apple::aic::AIC2_TIMESTAMPS, crate::platform::apple::aic::Aic2, + crate::platform::apple::aic::Aic2Config, stela_contracts::bus::Bus, }; let net = Net::new(); let input = net.open_drain().unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/i2c.rs b/crates/stela-runtime/src/platform/apple/i2c.rs index 33c35c9526..df538704fa 100644 --- a/crates/stela-runtime/src/platform/apple/i2c.rs +++ b/crates/stela-runtime/src/platform/apple/i2c.rs @@ -17,11 +17,13 @@ //! matches the driver's bounded PIO command (0x2cc0f08). Unknown registers, //! fields and target operations refuse, including diagnostic XFSTA, whose //! encoding the available evidence does not establish. -use super::{ - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - interrupt::{AicInput, Wire}, -}; use alloc::{boxed::Box, collections::VecDeque, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire, +}; pub const BYTES: u64 = 0x4000; const NAME: &str = "Apple I2C"; @@ -445,7 +447,7 @@ impl MmioDevice for I2c { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; struct Echo { cursor: u8, } diff --git a/crates/stela-runtime/src/platform/apple/ipi.rs b/crates/stela-runtime/src/platform/apple/ipi.rs index 756a0ae5d0..76f568c402 100644 --- a/crates/stela-runtime/src/platform/apple/ipi.rs +++ b/crates/stela-runtime/src/platform/apple/ipi.rs @@ -22,10 +22,13 @@ //! //! These registers are EL1-accessible; the engine decides EL0 traps before //! calling [`FastIpi::access`]. -use super::interrupt::{CpuIndex, FiqSource, InterruptSink, Wire}; use crate::system::access::{AccessKind, Encoding}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; +use { + stela_contracts::interrupt::CpuIndex, stela_contracts::interrupt::FiqSource, + stela_contracts::interrupt::InterruptSink, stela_contracts::interrupt::Wire, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Register { @@ -201,7 +204,7 @@ impl FastIpi { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; /// T8112: four E-cores in cluster 0, four P-cores in cluster 1. fn t8112() -> FastIpi { diff --git a/crates/stela-runtime/src/platform/apple/lockdown.rs b/crates/stela-runtime/src/platform/apple/lockdown.rs index 6e60a4ecf5..79f92e9e46 100644 --- a/crates/stela-runtime/src/platform/apple/lockdown.rs +++ b/crates/stela-runtime/src/platform/apple/lockdown.rs @@ -55,7 +55,11 @@ //! with read-modify-write (sptm.t6020 file 0xbb0b8..0xbb0c4). The //! emulated core has no power throttling, so the word holds what software //! writes, 0 from reset (inference). -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; /// CONTROL and MASK. pub const BYTES: u64 = 16; @@ -229,7 +233,7 @@ impl MmioDevice for Lockdown { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn sptms_lockdown_sequence_completes_and_locks_the_pair() { diff --git a/crates/stela-runtime/src/platform/apple/mcc.rs b/crates/stela-runtime/src/platform/apple/mcc.rs index 5c4917c17d..1fac60f184 100644 --- a/crates/stela-runtime/src/platform/apple/mcc.rs +++ b/crates/stela-runtime/src/platform/apple/mcc.rs @@ -2,11 +2,13 @@ //! programs this bank directly; it does not use the T8112 PMP quota protocol. //! Explicit Stela initialization and retained physical observations are distinct. //! Committed inputs never become cache-power or quota completion by themselves. -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; use alloc::{collections::BTreeMap, rc::Rc, vec::Vec}; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; mod configuration; mod drain; @@ -563,7 +565,7 @@ impl MmioDevice for View { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; fn lifecycle() -> LifecycleState { LifecycleState { powered: true, diff --git a/crates/stela-runtime/src/platform/apple/mcc/configuration.rs b/crates/stela-runtime/src/platform/apple/mcc/configuration.rs index 7816bd7a9b..fe57643815 100644 --- a/crates/stela-runtime/src/platform/apple/mcc/configuration.rs +++ b/crates/stela-runtime/src/platform/apple/mcc/configuration.rs @@ -54,12 +54,15 @@ fn validate(apertures: usize, weights: &[u8; GROUPS as usize]) -> Result LifecycleState { LifecycleState { diff --git a/crates/stela-runtime/src/platform/apple/mcc/status.rs b/crates/stela-runtime/src/platform/apple/mcc/status.rs index 7a1f2c56ef..a5011fae02 100644 --- a/crates/stela-runtime/src/platform/apple/mcc/status.rs +++ b/crates/stela-runtime/src/platform/apple/mcc/status.rs @@ -19,12 +19,14 @@ pub(super) fn aliases() -> impl Iterator { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::{Access, Lifecycle, LifecycleState, MmioDevice, Width}, - interrupt::InterruptLatch, - mcc::{Configuration, Controller, Origin}, - }; use alloc::vec; + use { + crate::platform::apple::mcc::Configuration, crate::platform::apple::mcc::Controller, + crate::platform::apple::mcc::Origin, stela_contracts::bus::Access, + stela_contracts::bus::Lifecycle, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, + stela_contracts::interrupt::InterruptLatch, + }; fn running() -> LifecycleState { LifecycleState { diff --git a/crates/stela-runtime/src/platform/apple/mcc/t6020.rs b/crates/stela-runtime/src/platform/apple/mcc/t6020.rs index eeaa97a1d5..fb1f869e5a 100644 --- a/crates/stela-runtime/src/platform/apple/mcc/t6020.rs +++ b/crates/stela-runtime/src/platform/apple/mcc/t6020.rs @@ -7,11 +7,13 @@ //! DCS flush2ece46c selects200a40+channel*200000 and preserves high16. //! These are request/consumer facts, not evidence that a write powers a cache, //! programs DRAM or produces an event counter. Unknown effects stay pending. -use crate::platform::apple::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; use alloc::{collections::BTreeMap, rc::Rc, vec::Vec}; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; pub const APERTURE_BYTES: u64 = 0x1000000; pub const MAX_APERTURES: usize = 16; @@ -421,7 +423,7 @@ impl MmioDevice for View { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; fn running() -> LifecycleState { LifecycleState { powered: true, diff --git a/crates/stela-runtime/src/platform/apple/mxwrap.rs b/crates/stela-runtime/src/platform/apple/mxwrap.rs index 1d84643ce6..f1824f58af 100644 --- a/crates/stela-runtime/src/platform/apple/mxwrap.rs +++ b/crates/stela-runtime/src/platform/apple/mxwrap.rs @@ -19,11 +19,15 @@ //! repeats cold start or resets the mailboxes. CPU idle remains unsupported, //! never inferred from FIFO emptiness. use super::asc::{Firmware, Lines, Message}; -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; -use super::interrupt::Wire; -use crate::platform::dma::Port; use alloc::{boxed::Box, collections::VecDeque, vec::Vec}; use core::any::Any; +use stela_contracts::dma::Port; +use stela_contracts::interrupt::Wire; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "mxwrap"; /// Logical offset for ADT `reg[0]`, the AP mailbox view. @@ -316,7 +320,7 @@ impl MmioDevice for MxWrap { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::{AicInput, InterruptLatch}; + use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch}; #[derive(Default)] struct Peer { @@ -548,7 +552,8 @@ mod tests { #[test] fn shared_rtkit_management_runs_through_the_original_mailbox_framing() { use crate::platform::apple::rtkit::RtKit; - let firmware = RtKit::new(Vec::new(), crate::builds::DEFAULT.rtkit_version).unwrap(); + let firmware = + RtKit::new(Vec::new(), stela_formats::builds::DEFAULT.rtkit_version).unwrap(); let mut wrapper = MxWrap::booted(Box::new(firmware), Lines::default()).unwrap(); let mut latch = InterruptLatch::new(); let mut access = Access::new(0, 0, &mut latch); @@ -730,7 +735,7 @@ mod tests { #[test] fn native_dma_completes_through_ram_before_its_mailbox_reply_is_visible() { - use crate::platform::dma::{Physical, tests::Ram}; + use {stela_contracts::dma::Physical, stela_contracts::dma::test_support::Ram}; struct DmaPeer(bool); impl Firmware for DmaPeer { fn start(&mut self, _: &mut Vec) -> Result<(), &'static str> { @@ -801,7 +806,7 @@ mod tests { #[test] fn committed_dma_messages_survive_faults_masking_halt_and_wrapping_backlog() { - use crate::platform::dma::{Physical, tests::Ram}; + use {stela_contracts::dma::Physical, stela_contracts::dma::test_support::Ram}; #[derive(Default)] struct PartialDma { committed: bool, diff --git a/crates/stela-runtime/src/platform/apple/nhi.rs b/crates/stela-runtime/src/platform/apple/nhi.rs index deb4e5b28d..f54b382aac 100644 --- a/crates/stela-runtime/src/platform/apple/nhi.rs +++ b/crates/stela-runtime/src/platform/apple/nhi.rs @@ -8,12 +8,16 @@ //! capability template, CIO readiness or machine admission is supplied here. //! DMA completion is a separate retained phase so a fault cannot replay an //! already accepted frame. Payload and timestamp precede completion ownership. -use super::bus::{Access, Direction as AccessDirection, MmioDevice, MmioError, Width, refuse}; -use super::interrupt::{AicInput, Wire}; -use crate::platform::dma::{DmaError, Port}; use alloc::{boxed::Box, collections::BTreeSet, vec, vec::Vec}; pub use ring::Direction; use ring::{Descriptor, Ring, Transfer}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction as AccessDirection, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; +use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire}; pub mod control; mod ring; pub mod router; @@ -790,10 +794,13 @@ impl MmioDevice for Nhi { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; - use crate::platform::dma::{Iommu, Memory, tests::Ram}; use alloc::rc::Rc; use core::cell::RefCell; + use stela_contracts::interrupt::InterruptLatch; + use { + stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, + }; #[derive(Default)] struct State { diff --git a/crates/stela-runtime/src/platform/apple/nhi/ring.rs b/crates/stela-runtime/src/platform/apple/nhi/ring.rs index c2817f99a7..25e7336bda 100644 --- a/crates/stela-runtime/src/platform/apple/nhi/ring.rs +++ b/crates/stela-runtime/src/platform/apple/nhi/ring.rs @@ -1,7 +1,7 @@ //! NHI's sixteen-byte DMA descriptor and programmed ring state. use super::{Frame, Options}; -use crate::platform::dma::{DmaError, Port}; use alloc::vec::Vec; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; pub(super) const POSTED: u32 = 1 << 22; pub(super) const COMPLETED: u32 = 1 << 21; diff --git a/crates/stela-runtime/src/platform/apple/nhi/router.rs b/crates/stela-runtime/src/platform/apple/nhi/router.rs index 06b7915add..298b98ccc0 100644 --- a/crates/stela-runtime/src/platform/apple/nhi/router.rs +++ b/crates/stela-runtime/src/platform/apple/nhi/router.rs @@ -865,9 +865,16 @@ mod tests { #[test] fn programmed_control_dma_retains_queued_replies_and_effects_across_faults() { use super::super::{Error as NhiError, Layout, Nhi, Profile}; - use crate::platform::apple::bus::{Access, MmioDevice, Width}; - use crate::platform::apple::interrupt::{AicInput, InterruptLatch}; - use crate::platform::dma::{DmaError, Iommu, Memory, Port, tests::Ram}; + use { + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, + }; + use { + stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, + stela_contracts::dma::Memory, stela_contracts::dma::Port, + stela_contracts::dma::test_support::Ram, + }; + use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch}; struct Fault(Option); impl Iommu for Fault { fn page(&self) -> u64 { diff --git a/crates/stela-runtime/src/platform/apple/pcie.rs b/crates/stela-runtime/src/platform/apple/pcie.rs index 17086d2aca..727f9fc51f 100644 --- a/crates/stela-runtime/src/platform/apple/pcie.rs +++ b/crates/stela-runtime/src/platform/apple/pcie.rs @@ -5,11 +5,13 @@ //! configuration images. Downstream USB-A/Ethernet require real endpoint //! models and firmware protocols; adding a config header never creates one. //! See `docs/research/apple-pcie.md` for evidence and unsupported boundaries. -use super::super::dma::{DmaError, Port as DmaPort}; -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; use alloc::{boxed::Box, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port as DmaPort}; pub mod config; mod endpoint; pub mod port; @@ -666,9 +668,12 @@ mod tests { use super::config::{MemoryBar, Register}; use super::port::{APP_CLOCK, LTSSM, Layout, REF_CLOCK}; use super::*; - use crate::platform::dma::{Iommu, Memory, tests::Ram}; use alloc::rc::Rc; use core::cell::RefCell; + use { + stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, + }; struct NativeState { state: LifecycleState, diff --git a/crates/stela-runtime/src/platform/apple/pcie/config.rs b/crates/stela-runtime/src/platform/apple/pcie/config.rs index cea01c0a92..3c94b79fc5 100644 --- a/crates/stela-runtime/src/platform/apple/pcie/config.rs +++ b/crates/stela-runtime/src/platform/apple/pcie/config.rs @@ -3,8 +3,8 @@ //! Field encodings: Linux v6.17 `include/uapi/linux/pci_regs.h`. Device //! identities and capabilities must be supplied from the selected device's //! evidence; this module supplies no Apple or downstream-device identity. -use super::super::bus::Width; use alloc::vec::Vec; +use stela_contracts::bus::Width; pub const COMMAND: u16 = 0x04; pub const MEMORY_ENABLE: u16 = 1 << 1; diff --git a/crates/stela-runtime/src/platform/apple/pcie/endpoint.rs b/crates/stela-runtime/src/platform/apple/pcie/endpoint.rs index 8e8deaa67e..46fa09d1b7 100644 --- a/crates/stela-runtime/src/platform/apple/pcie/endpoint.rs +++ b/crates/stela-runtime/src/platform/apple/pcie/endpoint.rs @@ -1,8 +1,10 @@ //! Actual endpoint bank ownership. Configuration alone cannot back a peer. use super::{ConfigSpace, MmioDevice}; -use crate::platform::apple::bus::{Access, LifecycleState, Width}; use alloc::{boxed::Box, vec::Vec}; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::LifecycleState, stela_contracts::bus::Width, +}; /// Exact offset of a function's whole memory BAR within its actual device. /// Explicit overlapping offsets may describe aliases of the same real bank. diff --git a/crates/stela-runtime/src/platform/apple/pcie/port.rs b/crates/stela-runtime/src/platform/apple/pcie/port.rs index 04669da994..0595a1dbc4 100644 --- a/crates/stela-runtime/src/platform/apple/pcie/port.rs +++ b/crates/stela-runtime/src/platform/apple/pcie/port.rs @@ -2,11 +2,12 @@ //! Register facts: Linux v6.17 `drivers/pci/controller/pcie-apple.c`. //! Link readiness is derived from actual modeled supplies and a backed peer. //! Analog training, ASPM, tunnel-reset handshakes and AER recovery refuse. -use super::super::{ - bus::{Access, Direction, MmioError, Width, refuse}, - interrupt::{AicInput, Wire}, -}; use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::MmioError, + stela_contracts::bus::Width, stela_contracts::bus::refuse, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire, +}; pub const LTSSM: u64 = 0x80; pub const INT_STATUS: u64 = 0x100; diff --git a/crates/stela-runtime/src/platform/apple/perf.rs b/crates/stela-runtime/src/platform/apple/perf.rs index c61c2e0242..7c16943ba5 100644 --- a/crates/stela-runtime/src/platform/apple/perf.rs +++ b/crates/stela-runtime/src/platform/apple/perf.rs @@ -21,8 +21,12 @@ //! //! Only DT-selected counters exist; holes, other widths, layout versions, //! class-1 busy status and control fields without described effects refuse. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::{collections::BTreeMap, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "pmgr-perf"; pub const COUNTER_BASE: u64 = 0x100; @@ -182,7 +186,7 @@ impl MmioDevice for PerfCounters { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn the_boot_stage_hands_off_disabled_controls_and_empty_counts() { diff --git a/crates/stela-runtime/src/platform/apple/pmgr.rs b/crates/stela-runtime/src/platform/apple/pmgr.rs index 9341cfa22e..342fe10932 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr.rs @@ -26,10 +26,14 @@ pub mod install; pub mod sequencer; pub mod t6000; -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::collections::{BTreeMap, BTreeSet}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "pmgr"; @@ -309,7 +313,7 @@ impl MmioDevice for Pmgr { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; /// `t8112.dtsi` pmgr base and `t8112-pmgr.dtsi` `ps_uart0` / `ps_aic`. const PMGR: u64 = 0x2_3b70_0000; diff --git a/crates/stela-runtime/src/platform/apple/pmgr/dvfs.rs b/crates/stela-runtime/src/platform/apple/pmgr/dvfs.rs index 1de9152ff8..3181693902 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/dvfs.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/dvfs.rs @@ -19,7 +19,7 @@ use super::sequencer::PhysicalWrite; #[cfg(test)] use super::sequencer::poll::PhysicalRead; #[cfg(test)] -use crate::platform::apple::bus::Width; +use stela_contracts::bus::Width; /// Physical-controller ordinal in the original hardware table. Domain+0x9c /// selects this ordinal independently of PMGR power-domain IDs and names. @@ -309,7 +309,7 @@ mod tests { fn original_native_protocol_keeps_hardware_identity_and_request_settlement_distinct() { let bytes = std::fs::read(std::env::var("STELA_TEST_PMGR_PMP").unwrap()).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "b39ef494f808c6db0a2c4feab42497e466d270b0935b2e1e948dadf0b510716c" ); // Complete source methods/tables, including the separate issue and @@ -356,7 +356,10 @@ mod tests { "4befcac752d421c415db3cbde8ee00b8dc52e5e40eeba58a23b48aaba4cce5cd", ), ] { - assert_eq!(crate::sha256(&bytes[offset..offset + length]), expected); + assert_eq!( + stela_formats::sha256(&bytes[offset..offset + length]), + expected + ); } let word = |offset: usize| u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()); diff --git a/crates/stela-runtime/src/platform/apple/pmgr/install.rs b/crates/stela-runtime/src/platform/apple/pmgr/install.rs index 31424aa42f..cc0bbd23b9 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/install.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/install.rs @@ -8,8 +8,8 @@ //! route. Release controller/bus borrows before dispatch; never run two program //! installations concurrently against the same physical controller/SRAM. use super::sequencer::PhysicalWrite; -use crate::platform::apple::bus::Width; use alloc::{rc::Rc, vec::Vec}; +use stela_contracts::bus::Width; pub mod t6000; @@ -697,13 +697,14 @@ fn checked_write(steps: &mut Vec, address: u64, value: u32) { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::{Access, Bus, Direction, MmioDevice, MmioError}, - interrupt::InterruptLatch, - }; - use crate::platform::dma::{Memory, tests::Ram}; use alloc::{boxed::Box, collections::BTreeMap, vec}; use core::sync::atomic::{Ordering, fence}; + use { + stela_contracts::bus::Access, stela_contracts::bus::Bus, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, + stela_contracts::interrupt::InterruptLatch, + }; + use {stela_contracts::dma::Memory, stela_contracts::dma::test_support::Ram}; /// Test-only captured configuration bank, without any hardware execution or /// completion semantics. All SRAM data still traverses the actual RAM API. @@ -790,7 +791,7 @@ mod tests { fn install(kind: ProgramKind, stage: u32) -> Installation { Installation::new(inputs(kind, stage), images(kind)).unwrap() } - fn bus(installation: &Installation) -> (Bus, crate::platform::apple::bus::DeviceId) { + fn bus(installation: &Installation) -> (Bus, stela_contracts::bus::DeviceId) { let mut bank = Captured::default(); bank.words.insert(0x23d050008, 0); bank.words.insert(0x23d054008, 0); diff --git a/crates/stela-runtime/src/platform/apple/pmgr/install/t6000.rs b/crates/stela-runtime/src/platform/apple/pmgr/install/t6000.rs index afc00f3b83..d284ef0a90 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/install/t6000.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/install/t6000.rs @@ -6,8 +6,8 @@ //! configuration only; compilation's live AP reads/effects, later activation, //! request-to-PC selection and native execution/retirement are not performed. use super::{Error, History, Installation, NativeImage, Placement, Step, align, write}; -use crate::platform::apple::bus::Width; use alloc::{rc::Rc, vec::Vec}; +use stela_contracts::bus::Width; pub mod activation; @@ -286,19 +286,21 @@ fn bind(steps: &mut Vec, placement: Placement, code: u64, bound: &mut bool #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{ - bus::{Access, Bus, Direction, MmioDevice, MmioError}, - interrupt::InterruptLatch, - pmgr::install::{Action, Blockage, FinishError, Outcome}, - }, - dma::{Memory, tests::Ram}, - }; use alloc::{ boxed::Box, collections::{BTreeMap, BTreeSet}, vec, }; + use { + crate::platform::apple::pmgr::install::Action, + crate::platform::apple::pmgr::install::Blockage, + crate::platform::apple::pmgr::install::FinishError, + crate::platform::apple::pmgr::install::Outcome, stela_contracts::bus::Access, + stela_contracts::bus::Bus, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, + stela_contracts::dma::Memory, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::InterruptLatch, + }; const CAPTURED: u64 = 0xa5a55aa5; #[derive(Default)] @@ -365,7 +367,7 @@ mod tests { }) .collect() } - fn bus(installation: &Installation) -> (Bus, crate::platform::apple::bus::DeviceId) { + fn bus(installation: &Installation) -> (Bus, stela_contracts::bus::DeviceId) { let mut addresses = BTreeSet::new(); for step in &installation.steps { match step { diff --git a/crates/stela-runtime/src/platform/apple/pmgr/install/t6000/activation.rs b/crates/stela-runtime/src/platform/apple/pmgr/install/t6000/activation.rs index edefe19b1d..78d08c3873 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/install/t6000/activation.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/install/t6000/activation.rs @@ -6,8 +6,8 @@ //! are ordered controller inputs only. No native PC, request response, PS value //! or retirement follows merely because this transaction was published. use super::super::{Error, History, Installation, Step, write}; -use crate::platform::apple::bus::Width; use alloc::{rc::Rc, vec::Vec}; +use stela_contracts::bus::Width; pub use super::super::super::t6000::PRE_ACTIVATION_BASE; @@ -57,16 +57,20 @@ pub fn sequence(stage: u32, kind: u32) -> Result, Error> { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::{Access, Bus, LifecycleState, MmioError}, - interrupt::InterruptLatch, - pmgr::{ - install::{Action, FinishError, Outcome}, - sequencer::PhysicalWrite, - }, - power::t6000::{Bank, Controller, Instance, Observation, native}, - }; use alloc::{boxed::Box, vec}; + use { + crate::platform::apple::pmgr::install::Action, + crate::platform::apple::pmgr::install::FinishError, + crate::platform::apple::pmgr::install::Outcome, + crate::platform::apple::pmgr::sequencer::PhysicalWrite, + crate::platform::apple::power::t6000::Bank, + crate::platform::apple::power::t6000::Controller, + crate::platform::apple::power::t6000::Instance, + crate::platform::apple::power::t6000::Observation, + crate::platform::apple::power::t6000::native, stela_contracts::bus::Access, + stela_contracts::bus::Bus, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MmioError, stela_contracts::interrupt::InterruptLatch, + }; fn owner(unknown_rmw: bool) -> Controller { // Explicit supplied test handoff, not native Apple reset observations. diff --git a/crates/stela-runtime/src/platform/apple/pmgr/sequencer.rs b/crates/stela-runtime/src/platform/apple/pmgr/sequencer.rs index e041ce93c5..90aba39505 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/sequencer.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/sequencer.rs @@ -11,8 +11,8 @@ //! checked RAM/MMIO boundary, then finish with its typed effect outcome. Only a //! positively proven no-effect refusal permits retry. Uncertain or partial //! effects quarantine the cursor; earlier committed writes remain recorded. -use crate::platform::apple::bus::Width; use alloc::{rc::Rc, vec::Vec}; +use stela_contracts::bus::Width; pub mod control; pub mod copy; @@ -557,13 +557,16 @@ fn decode(sram: &Sram, pc: usize) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::bus::{Access, Bus, Direction, MmioDevice, MmioError}; - use crate::platform::apple::interrupt::InterruptLatch; use crate::platform::apple::pmgr::sequencer::control::{test_fields, test_initial}; use crate::platform::apple::pmgr::{ACTIVE, Pmgr, PowerState}; - use crate::platform::dma::{Memory, tests::Ram}; use alloc::boxed::Box; use core::cell::Cell; + use stela_contracts::interrupt::InterruptLatch; + use { + stela_contracts::bus::Access, stela_contracts::bus::Bus, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, + }; + use {stela_contracts::dma::Memory, stela_contracts::dma::test_support::Ram}; const SRAM: u64 = 0x23df05200; @@ -786,11 +789,11 @@ mod tests { if result { RouteOutcome::Committed } else { - RouteOutcome::NoEffect(crate::platform::dma::DmaError::Memory) + RouteOutcome::NoEffect(stela_contracts::dma::DmaError::Memory) } ), Err(FinishError::NoEffect( - crate::platform::dma::DmaError::Memory + stela_contracts::dma::DmaError::Memory )) ); assert_eq!(cursor.committed_writes(), 0); diff --git a/crates/stela-runtime/src/platform/apple/pmgr/sequencer/delay.rs b/crates/stela-runtime/src/platform/apple/pmgr/sequencer/delay.rs index df816e6c26..850192a9b3 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/sequencer/delay.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/sequencer/delay.rs @@ -91,10 +91,10 @@ impl PacketCursor { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::bus::Width; use crate::platform::apple::pmgr::sequencer::control::{test_fields, test_initial}; use crate::platform::apple::pmgr::sequencer::{AddressFormat, PhysicalWrite, RouteOutcome}; use alloc::vec::Vec; + use stela_contracts::bus::Width; fn cursor(words: &[u32]) -> PacketCursor { let mut cursor = PacketCursor::unknown(); cursor.bind_initial_control(test_initial()).unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/pmgr/sequencer/poll.rs b/crates/stela-runtime/src/platform/apple/pmgr/sequencer/poll.rs index 4b0fafa969..5d579b3c47 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/sequencer/poll.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/sequencer/poll.rs @@ -6,8 +6,8 @@ //! inferred. A nonmatching actual read retains the packet PC. Read effects can //! be partial too: an uncertain route result quarantines all future claims. use super::{Error, FlightKind, InFlight, PacketCursor, Sram, control}; -use crate::platform::apple::bus::Width; use alloc::rc::Rc; +use stela_contracts::bus::Width; const TAG: u32 = 2; const WIDE: u32 = 1 << 5; @@ -473,12 +473,14 @@ mod tests { } #[test] fn mounted_partial_read_error_preserves_actual_mmio_effect_and_cannot_be_replayed() { - use crate::platform::apple::{ - bus::{Access, Bus, Direction, MmioDevice, MmioError, refuse}, - interrupt::InterruptLatch, - }; use alloc::boxed::Box; use core::cell::Cell; + use { + stela_contracts::bus::Access, stela_contracts::bus::Bus, + stela_contracts::bus::Direction, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::refuse, + stela_contracts::interrupt::InterruptLatch, + }; struct ClearOnRead { value: Rc>, reads: Rc>, diff --git a/crates/stela-runtime/src/platform/apple/pmgr/sequencer/stride.rs b/crates/stela-runtime/src/platform/apple/pmgr/sequencer/stride.rs index 3d80cf19b1..db77b995ca 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/sequencer/stride.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/sequencer/stride.rs @@ -67,12 +67,15 @@ pub(super) fn decode(sram: &Sram, pc: usize) -> Result { mod tests { use super::*; use crate::platform::apple::pmgr::sequencer::control::{test_fields, test_initial}; - use crate::platform::apple::{ - bus::{Access, Bus, MmioDevice, MmioError}, - interrupt::InterruptLatch, - pmgr::sequencer::{FinishError, PacketCursor, PacketKind, RouteOutcome}, - }; use alloc::{boxed::Box, vec}; + use { + crate::platform::apple::pmgr::sequencer::FinishError, + crate::platform::apple::pmgr::sequencer::PacketCursor, + crate::platform::apple::pmgr::sequencer::PacketKind, + crate::platform::apple::pmgr::sequencer::RouteOutcome, stela_contracts::bus::Access, + stela_contracts::bus::Bus, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::interrupt::InterruptLatch, + }; fn cursor( base: u64, diff --git a/crates/stela-runtime/src/platform/apple/pmgr/t6000.rs b/crates/stela-runtime/src/platform/apple/pmgr/t6000.rs index 97d9a71bfe..4a8966a63c 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/t6000.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/t6000.rs @@ -298,9 +298,9 @@ mod tests { #[cfg(all(test, feature = "std"))] mod original { - use crate::machine::adt::Node; use alloc::vec::Vec; use sha2::{Digest, Sha256}; + use stela_contracts::adt::Node; fn original(variable: &str, digest: &str) -> Vec { let bytes = std::fs::read(std::env::var(variable).expect("pinned J314s input")).unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/pmgr/t6000/tunables.rs b/crates/stela-runtime/src/platform/apple/pmgr/t6000/tunables.rs index ef4862f697..092c597872 100644 --- a/crates/stela-runtime/src/platform/apple/pmgr/t6000/tunables.rs +++ b/crates/stela-runtime/src/platform/apple/pmgr/t6000/tunables.rs @@ -2330,14 +2330,11 @@ mod tests { #[cfg(all(test, feature = "std"))] mod original { use super::*; - use crate::{ - machine::adt::Node, - platform::apple::{ - bridge::Bridge, - bus::{MmioDevice, Width}, - }, - }; use sha2::{Digest, Sha256}; + use { + crate::platform::apple::bridge::Bridge, stela_contracts::adt::Node, + stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, + }; fn word(bytes: &[u8], offset: usize) -> u32 { u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) @@ -2688,8 +2685,8 @@ mod original { } // No metadata-driven default word can satisfy a native RMW. let mut model = model; - let mut irq = crate::platform::apple::interrupt::InterruptLatch::new(); - let mut access = crate::platform::apple::bus::Access::new(0, 0, &mut irq); + let mut irq = stela_contracts::interrupt::InterruptLatch::new(); + let mut access = stela_contracts::bus::Access::new(0, 0, &mut irq); for row in profile.program(id).unwrap() { assert!( model diff --git a/crates/stela-runtime/src/platform/apple/pmp/duties.rs b/crates/stela-runtime/src/platform/apple/pmp/duties.rs index 25c61995cc..e81030fdc9 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/duties.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/duties.rs @@ -18,11 +18,12 @@ //! //! Every other update, the memory cache's commands among them, only holds //! what the AP wrote. -use crate::platform::apple::{ - bus::{Access, MmioDevice, MmioError, Width}, - ptd::{Range, UPDATE_OFFSET, transport::Ptd}, -}; use core::cell::Cell; +use { + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::Ptd, stela_contracts::bus::Access, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, +}; const STATUS: &str = "PMP-STATUS"; const REQUESTS: &str = "SOC-DEV-PS-REQ"; @@ -106,8 +107,8 @@ fn publish(bank: &Ptd, entry: u32, value: u64, access: &mut Access<'_>) -> Resul #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{bus::LifecycleState, interrupt::InterruptLatch}; use alloc::{vec, vec::Vec}; + use {stela_contracts::bus::LifecycleState, stela_contracts::interrupt::InterruptLatch}; fn range(id: u32, start: u32, count: u32, name: &str) -> Range { Range { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native.rs b/crates/stela-runtime/src/platform/apple/pmp/native.rs index e90bc9ecbc..905a29219e 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native.rs @@ -2,12 +2,12 @@ //! Original t6000pmp file91b4..9f04, c750..ce68 and9f04..a50c order the //! effects below. Device-specific effects require actual owned resources; //! neither this coordinator nor the ping endpoint supplies their settlement. -use super::super::{ - bus::{Access, MmioError}, - ptd::{Range, transport::notifications::LocalNotifications}, -}; use alloc::{rc::Rc, vec::Vec}; use core::cell::Cell; +use { + super::super::ptd::Range, super::super::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, stela_contracts::bus::MmioError, +}; pub mod cache; pub mod counters; @@ -654,12 +654,12 @@ impl Drop for Owner { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::{Lifecycle, LifecycleState, MmioDevice, Width}, - interrupt::InterruptLatch, - ptd::Ptd, - }; use alloc::format; + use { + crate::platform::apple::ptd::Ptd, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, stela_contracts::interrupt::InterruptLatch, + }; const IDS: [u32; 15] = [1, 2, 3, 4, 5, 6, 7, 0, 0, 9, 10, 11, 12, 13, 0]; const PACKETS: Packets = Packets([ diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/cache/metrics.rs b/crates/stela-runtime/src/platform/apple/pmp/native/cache/metrics.rs index d9aa4676b4..4ee2fa55a2 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/cache/metrics.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/cache/metrics.rs @@ -11,12 +11,12 @@ use super::super::{ platform::owner::Completion, scheduler::{Invocation, Work}, }; -use crate::platform::apple::bus::Access; use alloc::{format, rc::Rc, string::String, vec::Vec}; use core::{ cell::Cell, sync::atomic::{Ordering, fence}, }; +use stela_contracts::bus::Access; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { @@ -881,7 +881,7 @@ impl Owner { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[derive(Clone)] struct Samples { geometry: Geometry, diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/cache/policy.rs b/crates/stela-runtime/src/platform/apple/pmp/native/cache/policy.rs index 2b0aafd9d8..0307975eea 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/cache/policy.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/cache/policy.rs @@ -927,8 +927,8 @@ mod tests { #[cfg(feature = "std")] #[ignore = "requires original T8112 PMP and J473 DT via STELA_TEST_PMP_T8112 and STELA_TEST_MCC_J473_DT"] fn original_t8112_cache_rows_seeds_defaults_and_allocator_match_source_windows() { - use crate::machine::adt::Node; use sha2::{Digest, Sha256}; + use stela_contracts::adt::Node; let pmp = std::fs::read(std::env::var("STELA_TEST_PMP_T8112").unwrap()).unwrap(); assert_eq!( hex::encode(Sha256::digest(&pmp)), diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/cache/publisher.rs b/crates/stela-runtime/src/platform/apple/pmp/native/cache/publisher.rs index 6e75c27c26..6d8e5577dc 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/cache/publisher.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/cache/publisher.rs @@ -4,11 +4,12 @@ //! group's hardware store. This component supplies neither command consumption //! nor event housekeeping/ACK, native startup, IRQ admission or cache capacity. use super::policy::{GROUPS, HardwareUpdate, Inputs, Policy}; -use crate::platform::apple::{ - bus::{Access, MmioDevice, Width}, - ptd::{Range, UPDATE_OFFSET, transport::notifications::LocalNotifications}, -}; use alloc::rc::Rc; +use { + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, +}; type Error = &'static str; diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/cache/service.rs b/crates/stela-runtime/src/platform/apple/pmp/native/cache/service.rs index 79fed9d386..bdbd0a67d3 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/cache/service.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/cache/service.rs @@ -15,15 +15,14 @@ use super::{ metrics, publisher::{Bank, Publisher}, }; -use crate::platform::apple::{ - bus::{Access, MmioDevice, Width}, - ptd::{ - Range, UPDATE_OFFSET, - transport::{Entry, notifications::LocalNotifications}, - }, -}; use alloc::{rc::Rc, vec::Vec}; use core::cell::Cell; +use { + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::Entry, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, +}; const GROUPS: usize = 24; const GROUP_BYTES: usize = 64; @@ -746,13 +745,15 @@ impl Owner { mod tests { use super::super::{policy, publisher}; use super::*; - use crate::{ - machine::apple::memory_resources::t8112::{Prepared, cache::EmptyResource}, - platform::apple::{interrupt::InterruptLatch, pmp::native, ptd::transport::Entry}, - }; use alloc::vec::Vec; use core::cell::RefCell; use owner::{Completion, EffectValue}; + use { + crate::machine::apple::memory_resources::t8112::Prepared, + crate::machine::apple::memory_resources::t8112::cache::EmptyResource, + crate::platform::apple::pmp::native, crate::platform::apple::ptd::transport::Entry, + stela_contracts::interrupt::InterruptLatch, + }; struct MissingResources; impl native::Resources for MissingResources { @@ -1528,7 +1529,7 @@ mod tests { } #[test] fn consumed_budget_payload_is_not_replayed_after_real_cache_pause_and_new_input() { - use crate::platform::apple::bus::{Lifecycle, LifecycleState}; + use {stela_contracts::bus::Lifecycle, stela_contracts::bus::LifecycleState}; let live = LifecycleState { powered: true, clocked: true, @@ -1729,7 +1730,7 @@ mod tests { fn original_t8112_mc_command_housekeeping_ack_and_initialized_geometry_match() { let b = std::fs::read(std::env::var("STELA_TEST_PMP_T8112").unwrap()).unwrap(); assert_eq!( - crate::sha256(&b), + stela_formats::sha256(&b), "b39ef494f808c6db0a2c4feab42497e466d270b0935b2e1e948dadf0b510716c" ); for (start, len, hash) in [ @@ -1749,7 +1750,7 @@ mod tests { "de72571fe3bba53a8c2ae3058a4b09b323ee2976026efb334ed10f04d03c05c3", ), ] { - assert_eq!(crate::sha256(&b[start..start + len]), hash); + assert_eq!(stela_formats::sha256(&b[start..start + len]), hash); } let w = |a: usize| u32::from_le_bytes(b[a - 0xfff000..a - 0xfff000 + 4].try_into().unwrap()); @@ -1808,10 +1809,10 @@ mod tests { assert_eq!([w(0x1034380), w(0x1034384)], [8, 2]); let dt = std::fs::read(std::env::var("STELA_TEST_MCC_J473_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&dt), + stela_formats::sha256(&dt), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); - let root = crate::machine::adt::Node::root(&dt).unwrap(); + let root = stela_contracts::adt::Node::root(&dt).unwrap(); let nub = root .child("arm-io") .unwrap() diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/counters.rs b/crates/stela-runtime/src/platform/apple/pmp/native/counters.rs index 241489c158..07481fc791 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/counters.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/counters.rs @@ -9,15 +9,13 @@ //! No hardware events, lifecycle eligibility, generic provider decode, arrival //! mask, IRQ admission, metrics completion or command ACK is supplied here. use super::power::DeviceTable; -use crate::platform::apple::{ - bus::Access, - ptd::{ - Range, - transport::{Entry, notifications::LocalNotifications}, - }, -}; use alloc::{rc::Rc, vec::Vec}; use core::cell::Cell; +use { + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::transport::Entry, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, +}; type Error = &'static str; const ENTRIES_PER_BLOCK: u32 = 8; @@ -670,12 +668,15 @@ fn next(value: u64) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::{Lifecycle, LifecycleState, MmioDevice, Width}, - interrupt::InterruptLatch, - ptd::{Geometry, Ptd, UPDATE_OFFSET, transport::notifications::NativeProfile}, - }; use alloc::vec; + use { + crate::platform::apple::ptd::Geometry, crate::platform::apple::ptd::Ptd, + crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::notifications::NativeProfile, + stela_contracts::bus::Lifecycle, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, + stela_contracts::interrupt::InterruptLatch, + }; const LIVE: LifecycleState = LifecycleState { powered: true, clocked: true, @@ -1359,15 +1360,15 @@ mod tests { #[cfg(feature = "std")] #[ignore = "requires original T8112 PMP and J473 DT via STELA_TEST_PMP_T8112 and STELA_TEST_MCC_J473_DT"] fn original_dynamic_slices_and_metadata_copy_match_actual_ptd_effects() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let pmp = std::fs::read(std::env::var("STELA_TEST_PMP_T8112").unwrap()).unwrap(); let dt = std::fs::read(std::env::var("STELA_TEST_MCC_J473_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&pmp), + stela_formats::sha256(&pmp), "b39ef494f808c6db0a2c4feab42497e466d270b0935b2e1e948dadf0b510716c" ); assert_eq!( - crate::sha256(&dt), + stela_formats::sha256(&dt), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); for (start, end, hash) in [ @@ -1402,7 +1403,7 @@ mod tests { "5ffb9090d6b2b23dcf29a50bca350fb6c57a73815f27d0ccab92c25f7a1e40aa", ), ] { - assert_eq!(crate::sha256(&pmp[start..end]), hash); + assert_eq!(stela_formats::sha256(&pmp[start..end]), hash); } let io = Node::root(&dt).unwrap().child("arm-io").unwrap(); let pmp_node = io.child("pmp").unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/dma/broker.rs b/crates/stela-runtime/src/platform/apple/pmp/native/dma/broker.rs index 6941417d0c..89b5c3b4cb 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/dma/broker.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/dma/broker.rs @@ -7,13 +7,13 @@ use super::{ mapping::{Client, ReportingMapping, TraceMapping}, service::Service, }; -use crate::platform::dma::{DmaError, TransferFault}; use alloc::{ collections::{BTreeMap, VecDeque}, rc::Rc, vec::Vec, }; use core::cell::RefCell; +use {stela_contracts::dma::DmaError, stela_contracts::dma::TransferFault}; /// Placement selected by the actual device dispatcher. Numeric topology does /// not authorize a substitute Port: Owners must name the same actual objects. diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/dma/mapping.rs b/crates/stela-runtime/src/platform/apple/pmp/native/dma/mapping.rs index f43a19f794..e76620642e 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/dma/mapping.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/dma/mapping.rs @@ -7,8 +7,8 @@ use super::{ broker::{Broker, Descriptor, Key, Life, Op, Output, Reply, convert, reason}, service::Effect, }; -use crate::platform::apple::bus::Access; use alloc::vec::Vec; +use stela_contracts::bus::Access; #[derive(Clone, PartialEq, Eq)] enum Action { @@ -380,12 +380,13 @@ impl trace::Mapping for TraceMapping { mod tests { use super::super::{Coherence, Configuration, Owners, Route, Service, ServiceRequest, pair}; use super::*; - use crate::platform::{ - apple::interrupt::InterruptLatch, - dma::{self, DmaError, Memory, Port, TransferFault}, - }; use alloc::{rc::Rc, vec}; use core::cell::Cell; + use { + stela_contracts::dma, stela_contracts::dma::DmaError, stela_contracts::dma::Memory, + stela_contracts::dma::Port, stela_contracts::dma::TransferFault, + stela_contracts::interrupt::InterruptLatch, + }; struct Ram { bytes: Vec, writes: Vec<(u64, usize)>, diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/dma/service.rs b/crates/stela-runtime/src/platform/apple/pmp/native/dma/service.rs index 5329482704..c9211401f7 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/dma/service.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/dma/service.rs @@ -6,9 +6,9 @@ use super::super::platform::owner::Completion; use super::broker::{ Descriptor, Grant, Job, Life, Op, Output, Owners, Reply, ServiceRequest, State, reason, }; -use crate::platform::dma::Port; use alloc::{rc::Rc, vec}; use core::cell::RefCell; +use stela_contracts::dma::Port; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Effect { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts.rs b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts.rs index 02101f5096..ecdeb07456 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts.rs @@ -11,9 +11,12 @@ pub mod device; mod owner; use super::platform::owner::Completion; -use crate::platform::apple::bus::{Access, MmioDevice, MmioError, Width}; pub use auxiliary::{AuxiliaryHandler, AuxiliaryReset, AuxiliaryTarget}; pub use owner::{Event, Handler, Owner, Registration, Signal, Signals, Snapshot}; +use { + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, +}; pub const SPECIAL: u32 = 0x0800_0000; @@ -166,9 +169,9 @@ pub(super) fn refused(error: Error) -> Completion { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::{boxed::Box, collections::VecDeque, rc::Rc, vec, vec::Vec}; use core::cell::RefCell; + use stela_contracts::interrupt::InterruptLatch; #[test] fn mapped_bounds_refuse_before_borrowing_the_supplied_actual_view() { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/auxiliary.rs b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/auxiliary.rs index 6319784705..49b366989c 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/auxiliary.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/auxiliary.rs @@ -6,9 +6,9 @@ use super::super::platform::{ owner::Completion, }; use super::{Error, Event, Handler, Signals}; -use crate::platform::apple::bus::Access; use alloc::rc::Rc; use core::cell::Cell; +use stela_contracts::bus::Access; /// Opaque live callback receipt, minted only from the actual Signals context /// after the same source disable and actual registration retired. Event data diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/device.rs b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/device.rs index 669373c37c..a6a5d764ec 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/device.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/device.rs @@ -11,12 +11,15 @@ //! All words and relocation are explicit. Real peripheral owners must retain //! their electrical input handles. No request, enable or ACK creates an input. use super::{Device, Error, Placement, Route}; -use crate::platform::apple::bus::{Access, Direction, MmioDevice, MmioError, Width}; use alloc::{ rc::{Rc, Weak}, vec::Vec, }; use core::{any::Any, cell::RefCell}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Arbitration { @@ -572,9 +575,9 @@ mod tests { Completion, Event, Handler, Outcome, Owner, Signals, SoftwareConfiguration, }; use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::{boxed::Box, vec}; use core::cell::Cell; + use stela_contracts::interrupt::InterruptLatch; // Authored NEW profile, deliberately not a production/reset default. fn configuration(count: u32) -> Configuration { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/owner.rs b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/owner.rs index add891e3ac..9e86571b03 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/owner.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/interrupts/owner.rs @@ -4,9 +4,9 @@ //! the current-source state with foreground signals. use super::super::platform::owner::Completion; use super::{Device, Error, Outcome, Placement, SPECIAL, SoftwareConfiguration, refused}; -use crate::platform::apple::bus::Access; use alloc::{boxed::Box, rc::Rc, vec::Vec}; use core::cell::Cell; +use stela_contracts::bus::Access; /// Actual handler invocation, pinned to the sole consumed hardware event. /// Cloning this value grants no right to create another dispatch operation. diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/memory.rs b/crates/stela-runtime/src/platform/apple/pmp/native/memory.rs index eda940b698..6dbc6433e1 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/memory.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/memory.rs @@ -3,9 +3,9 @@ //! A wire reply is not local mapping authority. The backend must retain the //! actual canonical RAM/DMA mapping and retire each real map/unmap operation. use super::{Progress, Step}; -use crate::platform::apple::bus::Access; use alloc::{rc::Rc, vec::Vec}; use core::cell::Cell; +use stela_contracts::bus::Access; mod regions; mod wire; @@ -445,8 +445,8 @@ impl Client { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::{collections::VecDeque, vec}; + use stela_contracts::interrupt::InterruptLatch; struct Mapped { geometry: MapRequest, bytes: Vec, diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/amcc.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/amcc.rs index 38e396e927..30a9435449 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/amcc.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/amcc.rs @@ -11,8 +11,8 @@ use super::super::counters::{CaptureIdentity, Captured, Copied, Frame, Frames, R use super::ingestion::{self, Backend, Pair, Statistics}; use super::owner::{CounterContext, EffectValue}; use super::{CounterReference, Descriptor}; -use crate::platform::apple::bus::Access; use alloc::rc::Rc; +use stela_contracts::bus::Access; pub use ingestion::{Error, Progress}; const TIME_MASK: u64 = (1 << 54) - 1; @@ -562,16 +562,16 @@ mod tests { use super::super::ingestion::{Call, Request, Value}; use super::super::owner::Completion; use super::*; - use crate::platform::apple::{ - bus::{LifecycleState, MmioDevice, Width}, - interrupt::InterruptLatch, - ptd::{ - Geometry, Ptd, Range, UPDATE_OFFSET, - transport::notifications::{LocalNotifications, NativeProfile}, - }, - }; use alloc::{rc::Rc, vec::Vec}; use core::cell::Cell; + use { + crate::platform::apple::ptd::Geometry, crate::platform::apple::ptd::Ptd, + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + crate::platform::apple::ptd::transport::notifications::NativeProfile, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, stela_contracts::interrupt::InterruptLatch, + }; struct NoProviders; impl Backend for NoProviders { @@ -1226,7 +1226,7 @@ mod tests { hex::encode(Sha256::digest(&dt)), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); - let root = crate::machine::adt::Node::root(&dt).unwrap(); + let root = stela_contracts::adt::Node::root(&dt).unwrap(); let nub = root .child("arm-io") .unwrap() diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/counter_cache.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/counter_cache.rs index d6a137cc5a..37e74c35ed 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/counter_cache.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/counter_cache.rs @@ -8,12 +8,13 @@ //! No firmware executes, hardware events, samples, eligibility or ACKs arise. use super::super::counters::{CaptureIdentity, Captured, Frame, Frames}; use super::{ingestion, owner::Completion}; -use crate::platform::apple::{ - bus::Access, - ptd::{Range, transport::notifications::LocalNotifications}, -}; use alloc::{rc::Rc, vec::Vec}; use core::cell::{Cell, RefCell}; +use { + crate::platform::apple::ptd::Range, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, +}; type Error = &'static str; /// Unique native PMP allocation claim. Dropping it never permits another cache diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion.rs index 8e357dc36e..a7d2fee978 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion.rs @@ -14,10 +14,10 @@ mod model; use super::super::counters::{Copied, Frame, Frames, Retained}; use super::owner::{Completion, CounterContext, EffectValue}; use super::{CounterReference, Descriptor, Ordinal}; -use crate::platform::apple::bus::Access; use alloc::{collections::VecDeque, rc::Rc, vec, vec::Vec}; pub use arithmetic::{Delta, Pair, Statistics}; pub use model::{Auxiliary, Configuration, Frequency}; +use stela_contracts::bus::Access; const TIME_MASK: u64 = (1 << 54) - 1; /// Pure original101b974 field arithmetic over supplied frame data; no copy, @@ -1151,15 +1151,15 @@ mod tests { use super::super::super::counters::{Claim, CopyStep}; use super::super::super::power::DeviceTable; use super::*; - use crate::platform::apple::{ - bus::{LifecycleState, MmioDevice, Width}, - interrupt::InterruptLatch, - ptd::{ - Geometry, Ptd, Range, UPDATE_OFFSET, - transport::notifications::{LocalNotifications, NativeProfile}, - }, - }; use core::cell::Cell; + use { + crate::platform::apple::ptd::Geometry, crate::platform::apple::ptd::Ptd, + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + crate::platform::apple::ptd::transport::notifications::NativeProfile, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, stela_contracts::interrupt::InterruptLatch, + }; struct TestBackend { calls: Vec<(Request, Call)>, busy: bool, diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control.rs index 3cb07ff2cb..f619b1ef00 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control.rs @@ -13,11 +13,11 @@ mod packed; use super::super::owner::Completion; use super::{Pair, Request}; -use crate::platform::apple::bus::Access; use crate::platform::apple::ptd::transport::notifications::LocalNotifications; use alloc::rc::Rc; pub use model::{Configuration, SlotImage, SoftwareImage}; pub use owner::{AuxiliaryBinding, Owner}; +use stela_contracts::bus::Access; /// Identity of the actual retained resource composition; no completion rights. #[derive(Clone)] diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/controller.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/controller.rs index b1d85e8920..d7208d4b36 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/controller.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/controller.rs @@ -7,8 +7,11 @@ //! a register read may consume, and this adapter must not replay it. use super::super::super::owner::Completion; use super::{FlagsMethod, Operation, ResourceRequest, ResourceValue}; -use crate::platform::apple::bus::{Access, MmioDevice, MmioError, Width}; use alloc::boxed::Box; +use { + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Mapping { @@ -243,9 +246,9 @@ impl Controller { mod tests { use super::super::Identity; use super::*; - use crate::platform::apple::{bus::Direction, interrupt::InterruptLatch}; use alloc::{rc::Rc, vec, vec::Vec}; use core::cell::RefCell; + use {stela_contracts::bus::Direction, stela_contracts::interrupt::InterruptLatch}; type AccessLog = Rc)>>>; #[derive(Clone)] struct Device(AccessLog, bool); diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/owner.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/owner.rs index 3cec1ecc7b..1812f326f1 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/owner.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/control/owner.rs @@ -11,10 +11,10 @@ use super::{ Caller, Configuration, FlagsMethod, Identity, Operation, ResourceRequest, ResourceValue, Resources, SoftwareImage, }; -use crate::platform::apple::bus::Access; use crate::platform::apple::ptd::transport::notifications::LocalNotifications; use alloc::{boxed::Box, collections::VecDeque, rc::Rc, vec::Vec}; use core::cell::Cell; +use stela_contracts::bus::Access; /// Retained identity of the actual101cff0 context allocation. Cloning carries /// that identity, not permission to mark registration complete or set flags. @@ -948,16 +948,16 @@ mod tests { }; use super::super::super::{Auxiliary, Pair}; use super::*; - use crate::platform::apple::{ - bus::{LifecycleState, MmioDevice, Width}, - interrupt::InterruptLatch, - ptd::{ - Geometry, Ptd, Range, UPDATE_OFFSET, - transport::notifications::{LocalNotifications, NativeProfile}, - }, - }; use alloc::{vec, vec::Vec}; use core::cell::Cell; + use { + crate::platform::apple::ptd::Geometry, crate::platform::apple::ptd::Ptd, + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + crate::platform::apple::ptd::transport::notifications::NativeProfile, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::Width, stela_contracts::interrupt::InterruptLatch, + }; fn descriptor(ordinal: usize) -> super::super::super::Descriptor { super::super::super::super::profile::tests::fixture().descriptors()[ordinal].clone() diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/model.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/model.rs index 5f9a7c82f8..9d7846ee11 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/model.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/ingestion/model.rs @@ -462,7 +462,7 @@ mod tests { hex::encode(Sha256::digest(&dt)), "a99fa2260f292236fbad210fcee380fc69f101e591125bce347819e84e68034c" ); - let root = crate::machine::adt::Node::root(&dt).unwrap(); + let root = stela_contracts::adt::Node::root(&dt).unwrap(); let nub = root .child("arm-io") .unwrap() diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner.rs index f85b79741a..0c5119ff95 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner.rs @@ -8,8 +8,8 @@ use super::super::{ power::policy::{ConstraintState, Resolution}, }; use super::{Descriptor, Evaluation, Hook, McSelection, Ordinal, Packed, Profile, Slice}; -use crate::platform::apple::bus::Access; use alloc::{collections::VecDeque, rc::Rc, vec::Vec}; +use stela_contracts::bus::Access; pub mod controllers; @@ -1420,8 +1420,8 @@ impl Owner { mod tests { use super::super::profile::tests::fixture; use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::vec; + use stela_contracts::interrupt::InterruptLatch; struct Snapshot(u128, u128); impl Pending for Snapshot { fn bits(&self, start: u32, count: u32) -> Result { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner/controllers.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner/controllers.rs index 03ed8e9df3..6bc98e24a4 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner/controllers.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/owner/controllers.rs @@ -11,8 +11,11 @@ use super::super::Ordinal; use super::super::counter_cache::{ManagerClaim, ReadMasks}; use super::{Completion, ManagerContext, ManagerEffect, Request}; -use crate::platform::apple::bus::{Access, MmioDevice, MmioError, Width}; use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, +}; type Error = &'static str; const CONTROL_MASK: u32 = 0xf << 16; @@ -430,12 +433,12 @@ mod tests { use super::super::super::super::Packets; use super::super::super::Evaluation; use super::*; - use crate::platform::apple::{ - bus::{Direction, refuse}, - interrupt::InterruptLatch, - }; use alloc::{rc::Rc, vec}; use core::cell::RefCell; + use { + stela_contracts::bus::Direction, stela_contracts::bus::refuse, + stela_contracts::interrupt::InterruptLatch, + }; #[derive(Default)] struct DeviceState { @@ -912,15 +915,14 @@ mod tests { Manager, ); fn cache_fixture() -> CacheHarness { - use crate::platform::apple::{ - bus::LifecycleState, - pmp::native, - ptd::{ - Geometry, PTD_BYTES, Ptd, Range, UPDATE_OFFSET, - transport::notifications::NativeProfile, - }, - }; use native::{counters::Frames, platform::counter_cache::Cache, power::DeviceTable}; + use { + crate::platform::apple::pmp::native, crate::platform::apple::ptd::Geometry, + crate::platform::apple::ptd::PTD_BYTES, crate::platform::apple::ptd::Ptd, + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::notifications::NativeProfile, + stela_contracts::bus::LifecycleState, + }; let ranges: Vec = [ (1, 0, 1), (2, 1, 1), @@ -995,7 +997,7 @@ mod tests { } #[test] fn provider_cache_uses_actual_before_capture_masks_and_preserves_newer_ptd_until_next_reset() { - use crate::platform::apple::{bus::MmioDevice, ptd::UPDATE_OFFSET}; + use {crate::platform::apple::ptd::UPDATE_OFFSET, stela_contracts::bus::MmioDevice}; let (native, mut frames, mut cache, mut manager) = cache_fixture(); let masks = manager.read_masks(); let mut irq = InterruptLatch::default(); diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/platform/profile.rs b/crates/stela-runtime/src/platform/apple/pmp/native/platform/profile.rs index 350e3e9333..815d32c989 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/platform/profile.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/platform/profile.rs @@ -659,8 +659,8 @@ pub(super) mod tests { #[cfg(feature = "std")] #[ignore = "requires original T8112 PMP and J473 DT via STELA_TEST_PMP_T8112 and STELA_TEST_MCC_J473_DT"] fn original_t8112_join_and_selection_match_every_native_counter_reference() { - use crate::machine::adt::Node; use sha2::{Digest, Sha256}; + use stela_contracts::adt::Node; let pmp = std::fs::read(std::env::var("STELA_TEST_PMP_T8112").unwrap()).unwrap(); assert_eq!( hex::encode(Sha256::digest(&pmp)), diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/power.rs b/crates/stela-runtime/src/platform/apple/pmp/native/power.rs index 222147d128..7af3892b7e 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/power.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/power.rs @@ -217,8 +217,8 @@ mod tests { #[cfg(feature = "std")] #[ignore = "requires original J473 DT and KC via STELA_TEST_MCC_J473_DT and STELA_TEST_MCC_J473_KERNELCACHE"] fn original_j473_power_vector_uses_source_ordinals_and_distinct_domain_ids() { - use crate::machine::adt::Node; use sha2::{Digest, Sha256}; + use stela_contracts::adt::Node; let data = std::fs::read(std::env::var("STELA_TEST_MCC_J473_DT").unwrap()).unwrap(); assert_eq!( hex::encode(Sha256::digest(&data)), diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/power/policy.rs b/crates/stela-runtime/src/platform/apple/pmp/native/power/policy.rs index 0a8aca4276..7adfc721d9 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/power/policy.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/power/policy.rs @@ -400,8 +400,8 @@ mod tests { #[cfg(feature = "std")] #[ignore = "requires original T8112 PMP and J473 DT via STELA_TEST_PMP_T8112 and STELA_TEST_MCC_J473_DT"] fn original_native_constructor_descriptors_and_request_policy_match_the_profile() { - use crate::machine::adt::Node; use sha2::{Digest, Sha256}; + use stela_contracts::adt::Node; let data = std::fs::read(std::env::var("STELA_TEST_PMP_T8112").unwrap()).unwrap(); assert_eq!( hex::encode(Sha256::digest(&data)), diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/publication.rs b/crates/stela-runtime/src/platform/apple/pmp/native/publication.rs index 976b3ebbf8..1c0ba22b34 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/publication.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/publication.rs @@ -1,11 +1,12 @@ //! A source update target retains actual bank identity and one startup lifetime. use super::{Error, transport}; -use crate::platform::apple::{ - bus::Access, - ptd::{Range, transport::notifications::LocalNotifications}, -}; use alloc::rc::Rc; use core::cell::Cell; +use { + crate::platform::apple::ptd::Range, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, +}; /// Bounded native publisher capability. A later startup creates a new epoch; /// an old cloned target cannot acquire the new lifetime via mutable context. diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/registry.rs b/crates/stela-runtime/src/platform/apple/pmp/native/registry.rs index 8ed9ecfa7e..52adf8a60e 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/registry.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/registry.rs @@ -1,10 +1,10 @@ //! Original native PMP registry producer and class4 callback. Allocations are //! actual class1 client objects; no numeric slot/DMA address grants ownership. use super::{Progress, Step, memory}; -use crate::platform::apple::bus::Access; use alloc::{boxed::Box, rc::Rc, vec::Vec}; use core::cell::Cell; use memory::Mapping; +use stela_contracts::bus::Access; mod operations; mod wire; use wire::Kind; @@ -709,12 +709,12 @@ where #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::{ collections::{BTreeMap, VecDeque}, vec, }; use core::cell::RefCell; + use stela_contracts::interrupt::InterruptLatch; struct Object { data: Vec, mapped: bool, diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/getter.rs b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/getter.rs index 95dfd95c00..cafe3948ca 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/getter.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/getter.rs @@ -1,8 +1,8 @@ //! Native callable representation retained out of band; never host pointers. use super::super::platform::owner::Completion; use super::{record::Layout, resources::Request}; -use crate::platform::apple::bus::Access; use alloc::boxed::Box; +use stela_contracts::bus::Access; pub trait Scalar { fn get(&mut self, request: &Request, access: &mut Access<'_>) -> Completion; diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/owner.rs b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/owner.rs index cdd4f50d18..c0306fef5e 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/owner.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/owner.rs @@ -8,9 +8,9 @@ use super::{ resources::{MapResult, Mapping, Request, Resources, WaitKey}, wire, }; -use crate::platform::apple::bus::Access; use alloc::{boxed::Box, collections::VecDeque, rc::Rc, vec::Vec}; use core::cell::RefCell; +use stela_contracts::bus::Access; pub const NO_DATABASE: u32 = 0x8000_0007; #[derive(Clone, Debug)] @@ -922,9 +922,9 @@ fn convert(value: Completion, f: impl FnOnce(T) -> U) -> Completion mod tests { use super::super::{getter, resources::Wake}; use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::vec; use core::cell::Cell; + use stela_contracts::interrupt::InterruptLatch; fn done(value: T) -> Completion { Completion::Retired { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/receive.rs b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/receive.rs index c33436ad23..fae6a27ecc 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/receive.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/receive.rs @@ -4,9 +4,9 @@ use super::{ resources::{WaitKey, Wake}, wire, }; -use crate::platform::apple::bus::Access; use alloc::rc::Rc; use core::cell::RefCell; +use stela_contracts::bus::Access; #[derive(Default)] pub(super) struct Inbox { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/resources.rs b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/resources.rs index 30045217c9..9b518e9d94 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/reporting/resources.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/reporting/resources.rs @@ -1,8 +1,8 @@ //! Actual owners required by the source endpoint. No successful defaults. use super::super::platform::owner::Completion; use super::wire::Buffer; -use crate::platform::apple::bus::Access; use alloc::rc::Rc; +use stela_contracts::bus::Access; #[derive(Clone, Debug)] pub struct Request { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/scheduler.rs b/crates/stela-runtime/src/platform/apple/pmp/native/scheduler.rs index 0d0f947ac0..8baa6233c0 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/scheduler.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/scheduler.rs @@ -12,7 +12,6 @@ //! bytes are retained configuration metadata, not a claim to execute the Apple //! stack ABI. Rc ownership restricts this resource to one cooperative executor. use super::platform::owner::Completion; -use crate::platform::apple::bus::Access; use alloc::{ boxed::Box, rc::{Rc, Weak}, @@ -23,6 +22,7 @@ use core::{ cell::{Cell, RefCell}, sync::atomic::{Ordering, fence}, }; +use stela_contracts::bus::Access; mod dispatch; mod waits; @@ -549,7 +549,7 @@ impl Runtime { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; struct Count(Rc>); impl Callback for Count { fn advance(&mut self, i: &Invocation, _: &mut Access<'_>) -> Completion { diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/dispatch.rs b/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/dispatch.rs index faaadc6a46..206b3fc1b7 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/dispatch.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/dispatch.rs @@ -319,7 +319,7 @@ impl Runtime { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; struct Order { name: &'static str, log: Rc>>, @@ -475,7 +475,7 @@ mod tests { #[cfg(test)] mod retained_tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; struct AbandonedLease { runtime: Runtime, queue: Queue, diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/waits.rs b/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/waits.rs index 3767464e9f..6e426e4fee 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/waits.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/scheduler/waits.rs @@ -298,7 +298,7 @@ impl Lease { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; fn done(value: u32) -> Completion { Completion::Retired { value, diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/services.rs b/crates/stela-runtime/src/platform/apple/pmp/native/services.rs index cd3b55dfb9..1aed53d897 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/services.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/services.rs @@ -5,15 +5,15 @@ //! executes. Mailboxes are actual paired RTKit slots; mappings retain the real //! DMA broker. Startup never supplies an AP allocation or echoes an AP message. use super::{dma, platform::owner::Completion, reporting, scheduler, trace}; -use crate::platform::apple::{ - bus::Access, - rtkit::{self, channel}, -}; use alloc::{ boxed::Box, rc::{Rc, Weak}, }; use core::cell::{Cell, RefCell}; +use { + crate::platform::apple::rtkit, crate::platform::apple::rtkit::channel, + stela_contracts::bus::Access, +}; mod clock; mod metrics_backend; @@ -265,8 +265,8 @@ impl Services { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::vec::Vec; + use stela_contracts::interrupt::InterruptLatch; fn ticks() -> u64 { 24_000_000 } diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/trace.rs b/crates/stela-runtime/src/platform/apple/pmp/native/trace.rs index 4a96b3684d..377c3bbd37 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/trace.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/trace.rs @@ -13,8 +13,8 @@ //! allocations. An actual no-buffer/disabled/filtered return is an Emitted //! outcome with its source code; it does not claim any record was published. use super::platform::owner::Completion; -use crate::platform::apple::bus::Access; use alloc::{collections::VecDeque, rc::Rc, vec, vec::Vec}; +use stela_contracts::bus::Access; mod protocol; use protocol::{Command, encode_body}; @@ -1011,9 +1011,9 @@ impl Owner { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::collections::VecDeque; use core::cell::RefCell; + use stela_contracts::interrupt::InterruptLatch; type WriteLog = Rc)>>>; #[derive(Clone)] diff --git a/crates/stela-runtime/src/platform/apple/pmp/native/transport.rs b/crates/stela-runtime/src/platform/apple/pmp/native/transport.rs index 3fc4555638..0947336689 100644 --- a/crates/stela-runtime/src/platform/apple/pmp/native/transport.rs +++ b/crates/stela-runtime/src/platform/apple/pmp/native/transport.rs @@ -1,10 +1,11 @@ //! Actual PTD effects, never service replies inferred from a resource request. use super::{Error, Operation, Packets, Value}; -use crate::platform::apple::{ - bus::{Access, MmioDevice, Width}, - ptd::{Range, UPDATE_OFFSET, transport::notifications::LocalNotifications}, -}; use alloc::vec::Vec; +use { + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::notifications::LocalNotifications, + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, +}; pub(super) fn publish( local: &LocalNotifications, diff --git a/crates/stela-runtime/src/platform/apple/pmu.rs b/crates/stela-runtime/src/platform/apple/pmu.rs index ec8816be9f..b202e3b7cd 100644 --- a/crates/stela-runtime/src/platform/apple/pmu.rs +++ b/crates/stela-runtime/src/platform/apple/pmu.rs @@ -1193,9 +1193,10 @@ mod tests { #[test] fn a_pmu_without_rtc_routes_an_actual_permanently_deasserted_output() { - use crate::platform::apple::{ - interrupt::AicInput, - spmi::{Configuration as Controller, Profile, Spmi}, + use { + crate::platform::apple::spmi::Configuration as Controller, + crate::platform::apple::spmi::Profile, crate::platform::apple::spmi::Spmi, + stela_contracts::interrupt::AicInput, }; // A Vale-shaped secondary: scratch, legacy scratch, no RTC. let windows = alloc::vec![ @@ -1527,7 +1528,7 @@ mod tests { fn original_primary_service_rtc_registers_alarm_and_edge_contract_are_source_pinned() { let data = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_KERNELCACHE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "5109fca5209bdbb89cec29e3241cc42a90418cb737d65e31962b059b9879af90" ); for (offset, bytes, digest) in [ @@ -1663,7 +1664,7 @@ mod tests { ), // identity-descriptor-retain ] { assert_eq!( - crate::sha256(&data[offset..offset + bytes]), + stela_formats::sha256(&data[offset..offset + bytes]), digest, "source span {offset:#x}" ); @@ -1699,10 +1700,10 @@ mod tests { #[test] #[ignore = "requires original J314s26A434 DT via STELA_TEST_SPMI_DT"] fn original_j314s_two_rtc_resources_have_one_primary_service_and_local_output() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let data = std::fs::read(std::env::var("STELA_TEST_SPMI_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/pmu/fault.rs b/crates/stela-runtime/src/platform/apple/pmu/fault.rs index ed2baf8ac6..8b7e1bcd32 100644 --- a/crates/stela-runtime/src/platform/apple/pmu/fault.rs +++ b/crates/stela-runtime/src/platform/apple/pmu/fault.rs @@ -532,13 +532,14 @@ mod tests { #[test] fn original_ten_byte_fault_sequence_retires_real_spmi_chunks_and_keeps_failed_tail_unconsumed() { - use crate::platform::apple::{ - bus::{Access, MmioDevice, MmioError, Width}, - interrupt::{AicInput, InterruptLatch}, - spmi::{self, Spmi}, - }; use alloc::{boxed::Box, rc::Rc}; use core::cell::RefCell; + use { + crate::platform::apple::spmi, crate::platform::apple::spmi::Spmi, + stela_contracts::bus::Access, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch, + }; struct ObservedPmu(Rc>); impl SpmiSlave for ObservedPmu { fn read(&mut self, address: u16, data: &mut [u8], now: u64) -> Result<(), SlaveError> { diff --git a/crates/stela-runtime/src/platform/apple/pmu/firmware.rs b/crates/stela-runtime/src/platform/apple/pmu/firmware.rs index bf9c4feae2..d5f990e609 100644 --- a/crates/stela-runtime/src/platform/apple/pmu/firmware.rs +++ b/crates/stela-runtime/src/platform/apple/pmu/firmware.rs @@ -597,13 +597,15 @@ mod tests { #[test] fn real_gen1_fifo_retires_each_sram_chunk_and_does_not_consume_failed_tail() { - use crate::platform::apple::{ - bus::{Access, Lifecycle, LifecycleState, MmioDevice, MmioError, Width}, - interrupt::{AicInput, InterruptLatch}, - spmi::{self, Spmi}, - }; use alloc::{boxed::Box, rc::Rc}; use core::cell::RefCell; + use { + crate::platform::apple::spmi, crate::platform::apple::spmi::Spmi, + stela_contracts::bus::Access, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch, + }; struct Observed(Rc>); impl SpmiSlave for Observed { fn read(&mut self, address: u16, data: &mut [u8], now: u64) -> Result<(), SlaveError> { @@ -789,7 +791,7 @@ mod tests { fn original_images_full_producers_and_ap_sram_read_write_contract_are_pinned() { let data = std::fs::read(std::env::var("STELA_TEST_CRAM_J314S_LLB").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "f45549025d8cb4aa5e1cdb6107a25f90999f6b96da0b31a2f3cfb90561653ae1" ); for (offset, bytes, digest) in [ @@ -859,7 +861,7 @@ mod tests { "68879f00e937ba85942f3912e3ba6f77d6bd367bd8f6caede2f81cf3d99255a7", ), // second-fw ] { - assert_eq!(crate::sha256(&data[offset..offset + bytes]), digest); + assert_eq!(stela_formats::sha256(&data[offset..offset + bytes]), digest); } // Positive original board records and the actual dispatch/container consumers. for (offset, bytes, digest) in [ @@ -894,7 +896,7 @@ mod tests { "4ed5798c0adf84593f1ef9acf6322fca8a391243bc9fa414130758dc88068353", ), // full-runtime-descriptor-accessors ] { - assert_eq!(crate::sha256(&data[offset..offset + bytes]), digest); + assert_eq!(stela_formats::sha256(&data[offset..offset + bytes]), digest); } let base = 0x1fc058000u64; let qword = |offset| u64::from_le_bytes(data[offset..offset + 8].try_into().unwrap()); @@ -917,11 +919,11 @@ mod tests { } let kc = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_KERNELCACHE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&kc), + stela_formats::sha256(&kc), "5109fca5209bdbb89cec29e3241cc42a90418cb737d65e31962b059b9879af90" ); assert_eq!( - crate::sha256(&kc[0x2d552f8..0x2d552f8 + 1216]), + stela_formats::sha256(&kc[0x2d552f8..0x2d552f8 + 1216]), "f6a80ac867c834d37f1e75c71a9f4b0d908ef3bac3193b1f0490019ae4c990fe" ); // These exact encoded entries retain image descriptor/upload functions. diff --git a/crates/stela-runtime/src/platform/apple/pmu/startup.rs b/crates/stela-runtime/src/platform/apple/pmu/startup.rs index b50ec804f3..573e6b9863 100644 --- a/crates/stela-runtime/src/platform/apple/pmu/startup.rs +++ b/crates/stela-runtime/src/platform/apple/pmu/startup.rs @@ -615,13 +615,15 @@ mod tests { #[test] fn real_master_retains_native_loader_ownership_and_failed_start_payload() { - use crate::platform::apple::{ - bus::{Access, Lifecycle, LifecycleState, MmioDevice, MmioError, Width}, - interrupt::{AicInput, InterruptLatch}, - spmi::{self, Spmi}, - }; use alloc::{boxed::Box, rc::Rc}; use core::cell::RefCell; + use { + crate::platform::apple::spmi, crate::platform::apple::spmi::Spmi, + stela_contracts::bus::Access, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch, + }; struct Owned(Rc>); impl SpmiSlave for Owned { fn read(&mut self, address: u16, bytes: &mut [u8], now: u64) -> Result<(), SlaveError> { @@ -762,13 +764,14 @@ mod tests { } #[test] fn paused_master_still_advances_the_same_native_pmic_clock_without_firmware_completion() { - use crate::platform::apple::{ - bus::{Access, Lifecycle, LifecycleState, MmioDevice}, - interrupt::{AicInput, InterruptLatch}, - spmi::{self, Spmi}, - }; use alloc::{boxed::Box, rc::Rc}; use core::cell::RefCell; + use { + crate::platform::apple::spmi, crate::platform::apple::spmi::Spmi, + stela_contracts::bus::Access, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch, + }; struct Owned(Rc>); impl SpmiSlave for Owned { fn read(&mut self, at: u16, bytes: &mut [u8], now: u64) -> Result<(), SlaveError> { @@ -930,7 +933,7 @@ mod tests { fn original_images_and_exact_protected_sequences_replay_without_completion_credit() { let source = std::fs::read(std::env::var("STELA_TEST_CRAM_J314S_LLB").unwrap()).unwrap(); assert_eq!( - crate::sha256(&source), + stela_formats::sha256(&source), "f45549025d8cb4aa5e1cdb6107a25f90999f6b96da0b31a2f3cfb90561653ae1" ); for (profile, start, len, metadata, configuration, version) in [ diff --git a/crates/stela-runtime/src/platform/apple/pmu/startup/clock.rs b/crates/stela-runtime/src/platform/apple/pmu/startup/clock.rs index bebe6cd786..f34f10f7df 100644 --- a/crates/stela-runtime/src/platform/apple/pmu/startup/clock.rs +++ b/crates/stela-runtime/src/platform/apple/pmu/startup/clock.rs @@ -261,7 +261,7 @@ mod tests { fn original_reload_branch_fields_and_first_arm_have_immutable_source_identity() { let llb = std::fs::read(std::env::var("STELA_TEST_CRAM_J314S_LLB").unwrap()).unwrap(); assert_eq!( - crate::sha256(&llb), + stela_formats::sha256(&llb), "f45549025d8cb4aa5e1cdb6107a25f90999f6b96da0b31a2f3cfb90561653ae1" ); for (range, hash) in [ @@ -282,7 +282,7 @@ mod tests { "cc9f198e19cd463c0697009f601f80ff9048b0c9c08002a36cd79fc673d9fc8f", ), ] { - assert_eq!(crate::sha256(&llb[range]), hash); + assert_eq!(stela_formats::sha256(&llb[range]), hash); } let image = &llb[0x1f9b20..0x1fbd90]; assert_eq!( diff --git a/crates/stela-runtime/src/platform/apple/pmu/startup/integrity.rs b/crates/stela-runtime/src/platform/apple/pmu/startup/integrity.rs index 57ec9615a2..6a4a7f9684 100644 --- a/crates/stela-runtime/src/platform/apple/pmu/startup/integrity.rs +++ b/crates/stela-runtime/src/platform/apple/pmu/startup/integrity.rs @@ -162,7 +162,7 @@ mod tests { fn original_maverick_tag_matches_all_1132_actual_covered_bytes() { let llb = std::fs::read(std::env::var("STELA_TEST_CRAM_J314S_LLB").unwrap()).unwrap(); assert_eq!( - crate::sha256(&llb), + stela_formats::sha256(&llb), "f45549025d8cb4aa5e1cdb6107a25f90999f6b96da0b31a2f3cfb90561653ae1" ); let bytes = &llb[0x1f9b20..0x1fbd90]; @@ -184,7 +184,7 @@ mod tests { "79c85be1994e8260bde5248ee0968858bb839a510ef27977c3e259c209e4072c", ), ] { - assert_eq!(crate::sha256(&bytes[range]), hash); + assert_eq!(stela_formats::sha256(&bytes[range]), hash); } } } diff --git a/crates/stela-runtime/src/platform/apple/power.rs b/crates/stela-runtime/src/platform/apple/power.rs index 568473f16b..cfd77bcad2 100644 --- a/crates/stela-runtime/src/platform/apple/power.rs +++ b/crates/stela-runtime/src/platform/apple/power.rs @@ -40,9 +40,13 @@ //! observations only, not native execution, functional ownership or PS values. pub mod t6000; -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::collections::BTreeMap; use alloc::vec::Vec; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "soc-power"; const STATUS: u64 = 0x24; @@ -474,8 +478,8 @@ fn nub_fields(offset: u64) -> (u32, bool) { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{bus::Bus, interrupt::InterruptLatch}; use alloc::boxed::Box; + use {stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch}; fn snapshot(kind: Kind, value: u32) -> Power { Power::from_snapshot( diff --git a/crates/stela-runtime/src/platform/apple/power/t6000.rs b/crates/stela-runtime/src/platform/apple/power/t6000.rs index ea04d3f347..f28caad560 100644 --- a/crates/stela-runtime/src/platform/apple/power/t6000.rs +++ b/crates/stela-runtime/src/platform/apple/power/t6000.rs @@ -15,11 +15,13 @@ //! micro-PC, cold state or unsupported native operation is manufactured. //! A retained pause preserves every input, observation and chronological prefix //! across all mapped views. -use super::super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; use alloc::{collections::BTreeMap, rc::Rc, vec::Vec}; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; pub mod clock; pub mod identity; @@ -522,8 +524,8 @@ impl MmioDevice for View { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{bus::Bus, interrupt::InterruptLatch}; use alloc::{boxed::Box, vec}; + use {stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch}; const LIVE: LifecycleState = LifecycleState { powered: true, diff --git a/crates/stela-runtime/src/platform/apple/power/t6000/clock.rs b/crates/stela-runtime/src/platform/apple/power/t6000/clock.rs index 4d062b073a..6852ab438d 100644 --- a/crates/stela-runtime/src/platform/apple/power/t6000/clock.rs +++ b/crates/stela-runtime/src/platform/apple/power/t6000/clock.rs @@ -5,8 +5,12 @@ //! 408a0. The five raw words and the native clock phase are separate inputs; //! no enable, lock, frequency, phase or physical reset value is invented. use super::identity::Authority; -use crate::platform::apple::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::{rc::Rc, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; pub(super) mod phase; pub use phase::{Phase, Snapshot}; @@ -263,8 +267,8 @@ impl MmioDevice for Image { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{bus::Bus, interrupt::InterruptLatch}; use alloc::{boxed::Box, vec}; + use {stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch}; pub(super) fn image(selection: u32, pll0: u32, pll1: u32, config0: u32, config1: u32) -> Image { let values = [pll0, config0, pll1, config1, selection]; diff --git a/crates/stela-runtime/src/platform/apple/power/t6000/identity.rs b/crates/stela-runtime/src/platform/apple/power/t6000/identity.rs index 11c7294247..eed47cb77e 100644 --- a/crates/stela-runtime/src/platform/apple/power/t6000/identity.rs +++ b/crates/stela-runtime/src/platform/apple/power/t6000/identity.rs @@ -7,8 +7,12 @@ //! This image owns no fuse programming, bit31 lock, PMGR supply, firmware RAM //! cache, native trigger or retirement. Those operations cannot mutate or //! replace it through this read interface. -use crate::platform::apple::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; use alloc::{rc::Rc, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "t6000-identity-inputs"; @@ -207,8 +211,8 @@ impl MmioDevice for Image { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{bus::Bus, interrupt::InterruptLatch}; use alloc::{boxed::Box, vec}; + use {stela_contracts::bus::Bus, stela_contracts::interrupt::InterruptLatch}; fn word(register: Register, value: u32) -> Observation { Observation { diff --git a/crates/stela-runtime/src/platform/apple/power/t6000/native.rs b/crates/stela-runtime/src/platform/apple/power/t6000/native.rs index 900f12dcf5..54f29dcb30 100644 --- a/crates/stela-runtime/src/platform/apple/power/t6000/native.rs +++ b/crates/stela-runtime/src/platform/apple/power/t6000/native.rs @@ -8,11 +8,17 @@ //! captured Apple microstate. Every view shares the parent controller's lifecycle, //! request prefix and actual byte storage; there is no parallel SRAM image. use super::{Controller, RequestKind}; -use crate::platform::apple::{ - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - pmgr::t6000::{CODE_BASE, PRE_ACTIVATION_BASE, SRAM_BASE, SRAM_LIMIT, TABLE_BASE}, -}; use alloc::{collections::BTreeMap, vec, vec::Vec}; +use { + crate::platform::apple::pmgr::t6000::CODE_BASE, + crate::platform::apple::pmgr::t6000::PRE_ACTIVATION_BASE, + crate::platform::apple::pmgr::t6000::SRAM_BASE, + crate::platform::apple::pmgr::t6000::SRAM_LIMIT, + crate::platform::apple::pmgr::t6000::TABLE_BASE, stela_contracts::bus::Access, + stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; pub mod effects; pub mod engine; @@ -555,7 +561,7 @@ impl Sram { native.write_bytes(offset, input) } } -impl crate::platform::dma::Memory for Sram { +impl stela_contracts::dma::Memory for Sram { fn read(&mut self, address: u64, output: &mut [u8]) -> bool { self.read_checked(address, output).is_ok() } @@ -670,15 +676,15 @@ mod tests { use super::super::{Bank, Instance, Observation as RequestObservation}; use super::*; use crate::platform::apple::pmgr::sequencer::control::{test_fields, test_initial}; - use crate::platform::{ - apple::{ - bus::{Bus, DeviceId}, - interrupt::InterruptLatch, - pmgr::install::{Action, NativeImage, Outcome, t6000}, - }, - dma::Memory, - }; use alloc::boxed::Box; + use { + crate::platform::apple::pmgr::install::Action, + crate::platform::apple::pmgr::install::NativeImage, + crate::platform::apple::pmgr::install::Outcome, + crate::platform::apple::pmgr::install::t6000, stela_contracts::bus::Bus, + stela_contracts::bus::DeviceId, stela_contracts::dma::Memory, + stela_contracts::interrupt::InterruptLatch, + }; const LIVE: LifecycleState = LifecycleState { powered: true, diff --git a/crates/stela-runtime/src/platform/apple/power/t6000/native/engine.rs b/crates/stela-runtime/src/platform/apple/power/t6000/native/engine.rs index 620df77d62..a753f56836 100644 --- a/crates/stela-runtime/src/platform/apple/power/t6000/native/engine.rs +++ b/crates/stela-runtime/src/platform/apple/power/t6000/native/engine.rs @@ -6,16 +6,21 @@ //! This engine executes supplied, finalized programs; it is not a capture of //! Apple's hidden micro-PC, cold state, or unimplemented control instructions. use super::{Controller, Entry, Error as NativeError, effects::Effects}; -use crate::platform::apple::{ - bus::Width, - pmgr::sequencer::{self, AddressFormat, PacketCursor, PacketKind, RouteOutcome, WriteClaim}, - power::t6000::{Bank, CIO, RequestKind}, -}; use alloc::{collections::BTreeMap, rc::Rc, vec, vec::Vec}; use core::{ cell::RefCell, ops::{Deref, DerefMut}, }; +use { + crate::platform::apple::pmgr::sequencer, + crate::platform::apple::pmgr::sequencer::AddressFormat, + crate::platform::apple::pmgr::sequencer::PacketCursor, + crate::platform::apple::pmgr::sequencer::PacketKind, + crate::platform::apple::pmgr::sequencer::RouteOutcome, + crate::platform::apple::pmgr::sequencer::WriteClaim, + crate::platform::apple::power::t6000::Bank, crate::platform::apple::power::t6000::CIO, + crate::platform::apple::power::t6000::RequestKind, stela_contracts::bus::Width, +}; const BINDING: u64 = 0x28e099068; const CIO_ADDRESS: u64 = 0x28e09a034; @@ -536,16 +541,22 @@ impl Engine { mod tests { use super::*; use crate::platform::apple::pmgr::sequencer::control::{test_fields, test_initial}; - use crate::platform::apple::{ - bus::{Access, Bus, DeviceId, Lifecycle, LifecycleState, MmioDevice, MmioError}, - interrupt::InterruptLatch, - pmgr::{ - install::{Action, NativeImage, Outcome, t6000}, - sequencer::{FinishError, copy, poll}, - }, - power::t6000::{Instance, Observation, clock}, - }; use alloc::boxed::Box; + use { + crate::platform::apple::pmgr::install::Action, + crate::platform::apple::pmgr::install::NativeImage, + crate::platform::apple::pmgr::install::Outcome, + crate::platform::apple::pmgr::install::t6000, + crate::platform::apple::pmgr::sequencer::FinishError, + crate::platform::apple::pmgr::sequencer::copy, + crate::platform::apple::pmgr::sequencer::poll, + crate::platform::apple::power::t6000::Instance, + crate::platform::apple::power::t6000::Observation, + crate::platform::apple::power::t6000::clock, stela_contracts::bus::Access, + stela_contracts::bus::Bus, stela_contracts::bus::DeviceId, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::interrupt::InterruptLatch, + }; const LIVE: LifecycleState = LifecycleState { powered: true, diff --git a/crates/stela-runtime/src/platform/apple/ptd/transport.rs b/crates/stela-runtime/src/platform/apple/ptd/transport.rs index 7566987517..678309b6c1 100644 --- a/crates/stela-runtime/src/platform/apple/ptd/transport.rs +++ b/crates/stela-runtime/src/platform/apple/ptd/transport.rs @@ -5,12 +5,14 @@ #[cfg(test)] use super::PTD_BYTES; use super::{MAX_ENTRIES, Range, UPDATE_OFFSET}; -use crate::platform::apple::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; -use crate::platform::apple::interrupt::Wire; use alloc::{collections::BTreeSet, rc::Rc, vec, vec::Vec}; use core::cell::RefCell; +use stela_contracts::interrupt::Wire; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; pub mod notifications; pub mod status; @@ -617,7 +619,7 @@ impl MmioDevice for Ptd { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::{AicInput, InterruptLatch}; + use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch}; fn lifecycle() -> LifecycleState { LifecycleState { diff --git a/crates/stela-runtime/src/platform/apple/ptd/transport/notifications.rs b/crates/stela-runtime/src/platform/apple/ptd/transport/notifications.rs index c6bcf503c7..9a5a3d3226 100644 --- a/crates/stela-runtime/src/platform/apple/ptd/transport/notifications.rs +++ b/crates/stela-runtime/src/platform/apple/ptd/transport/notifications.rs @@ -3,9 +3,9 @@ //! through RTKit-local IRQ 1+r, encoded in namespace 0x10000. These are not AP //! AIC numbers or ASC messages. See docs/research/apple-mcc.md. use super::{NotificationOwner, Ptd, ROUTES, Range}; -use crate::platform::apple::bus::LifecycleState; use crate::platform::apple::ptd::Geometry; use alloc::rc::Rc; +use stela_contracts::bus::LifecycleState; /// Original native descriptor geometry, independently cross-checked by the /// source DeviceTree's 0xc00-byte update alias. @@ -151,10 +151,11 @@ impl Ptd { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::{Access, Lifecycle, MmioDevice, MmioError, Width}, - interrupt::InterruptLatch, - ptd::{UPDATE_OFFSET, transport::Entry}, + use { + crate::platform::apple::ptd::UPDATE_OFFSET, crate::platform::apple::ptd::transport::Entry, + stela_contracts::bus::Access, stela_contracts::bus::Lifecycle, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, + stela_contracts::bus::Width, stela_contracts::interrupt::InterruptLatch, }; fn lifecycle() -> LifecycleState { diff --git a/crates/stela-runtime/src/platform/apple/ptd/transport/status.rs b/crates/stela-runtime/src/platform/apple/ptd/transport/status.rs index 804d5b2442..f581347900 100644 --- a/crates/stela-runtime/src/platform/apple/ptd/transport/status.rs +++ b/crates/stela-runtime/src/platform/apple/ptd/transport/status.rs @@ -129,12 +129,14 @@ impl State { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::{ - bus::{Access, Lifecycle, LifecycleState, MmioDevice, Width as BusWidth}, - interrupt::InterruptLatch, - ptd::{Range, UPDATE_OFFSET, transport::Observation}, - }; use alloc::vec::Vec; + use { + crate::platform::apple::ptd::Range, crate::platform::apple::ptd::UPDATE_OFFSET, + crate::platform::apple::ptd::transport::Observation, stela_contracts::bus::Access, + stela_contracts::bus::Lifecycle, stela_contracts::bus::LifecycleState, + stela_contracts::bus::MmioDevice, stela_contracts::bus::Width as BusWidth, + stela_contracts::interrupt::InterruptLatch, + }; const PATTERN: [u32; 12] = [ 0x01234567, 0x89abcdef, 0x13579bdf, 0x2468ace0, 0x55667788, 0x99aabbcc, 0xddeeff00, diff --git a/crates/stela-runtime/src/platform/apple/regfile.rs b/crates/stela-runtime/src/platform/apple/regfile.rs index b31d3a3596..65bc6655a1 100644 --- a/crates/stela-runtime/src/platform/apple/regfile.rs +++ b/crates/stela-runtime/src/platform/apple/regfile.rs @@ -2,8 +2,8 @@ //! share a width and a role the model gives meaning to. An offset no span //! covers, or an access of another width, has no described meaning and //! refuses. -use super::bus::Width; use alloc::collections::BTreeMap; +use stela_contracts::bus::Width; /// Registers `[start, end)` of `width`, one every `width` bytes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/stela-runtime/src/platform/apple/rtkit.rs b/crates/stela-runtime/src/platform/apple/rtkit.rs index 44fe8da12d..38c513300c 100644 --- a/crates/stela-runtime/src/platform/apple/rtkit.rs +++ b/crates/stela-runtime/src/platform/apple/rtkit.rs @@ -573,13 +573,13 @@ mod tests { use super::*; use alloc::vec; - const VERSION: u64 = crate::builds::DEFAULT.rtkit_version; + const VERSION: u64 = stela_formats::builds::DEFAULT.rtkit_version; #[test] fn a_physical_reset_clears_enumeration_without_reusing_boot_quiescence() { let mut kit = RtKit::new( vec![(0x20, Box::new(super::super::pmp::Pmp::default()))], - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap() .quiesced(); @@ -631,7 +631,7 @@ mod tests { (0x20, Box::new(Complement) as Box), (0x41, Box::new(Complement)), ], - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap(); let mut outbox = Vec::new(); @@ -642,7 +642,7 @@ mod tests { #[test] fn cold_system_binding_keeps_the_started_session_and_precedes_roll_call() { - let mut kit = RtKit::new(Vec::new(), crate::builds::DEFAULT.rtkit_version).unwrap(); + let mut kit = RtKit::new(Vec::new(), stela_formats::builds::DEFAULT.rtkit_version).unwrap(); let mut initial = Vec::new(); kit.start(&mut initial).unwrap(); kit.attach_cold_system_endpoints(SystemEndpoints { @@ -668,7 +668,7 @@ mod tests { #[test] fn late_or_duplicate_native_binding_refuses_before_changing_the_endpoint_map() { - let mut kit = RtKit::new(Vec::new(), crate::builds::DEFAULT.rtkit_version).unwrap(); + let mut kit = RtKit::new(Vec::new(), stela_formats::builds::DEFAULT.rtkit_version).unwrap(); let mut initial = Vec::new(); kit.start(&mut initial).unwrap(); mgmt(&mut kit, HELLO_REPLY, VERSION | VERSION << 16).unwrap(); @@ -686,7 +686,7 @@ mod tests { trace: Some(Box::new(Complement)), reporting: None, }, - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap(); assert!( @@ -707,7 +707,7 @@ mod tests { trace: Some(Box::new(Complement)), reporting: Some(Box::new(Complement)), }, - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap(); let mut output = Vec::new(); @@ -752,7 +752,7 @@ mod tests { assert!( RtKit::new( vec![(IOREPORTING, Box::new(Complement))], - crate::builds::DEFAULT.rtkit_version + stela_formats::builds::DEFAULT.rtkit_version ) .is_err() ); @@ -909,7 +909,7 @@ mod tests { // word: the AP waited 20 s for running after its last answer. let mut rtkit = RtKit::new( vec![(0x20, Box::new(Complement) as Box)], - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap(); let raw = |rtkit: &mut RtKit, payload| step(rtkit, 0, payload).unwrap(); @@ -951,7 +951,7 @@ mod tests { fn a_quiesced_coprocessor_waits_for_its_wake_and_acks_it_after_enumeration() { let mut rtkit = RtKit::new( vec![(0x20, Box::new(Complement) as Box)], - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap() .quiesced(); @@ -1007,7 +1007,7 @@ mod tests { fn enabled_endpoints_send_board_events_and_carry_transitions() { let mut rtkit = RtKit::new( vec![(0x20, Box::new(Board::default()) as Box)], - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap(); rtkit.start(&mut Vec::new()).unwrap(); @@ -1042,11 +1042,17 @@ mod tests { #[test] fn endpoints_are_application_endpoints_once_each() { let one = || Box::new(Complement) as Box; - assert!(RtKit::new(vec![(0x2, one())], crate::builds::DEFAULT.rtkit_version).is_err()); + assert!( + RtKit::new( + vec![(0x2, one())], + stela_formats::builds::DEFAULT.rtkit_version + ) + .is_err() + ); assert!( RtKit::new( vec![(0x20, one()), (0x20, one())], - crate::builds::DEFAULT.rtkit_version + stela_formats::builds::DEFAULT.rtkit_version ) .is_err() ); diff --git a/crates/stela-runtime/src/platform/apple/rtkit/channel.rs b/crates/stela-runtime/src/platform/apple/rtkit/channel.rs index 52e97b0cb4..cde9c0f6b1 100644 --- a/crates/stela-runtime/src/platform/apple/rtkit/channel.rs +++ b/crates/stela-runtime/src/platform/apple/rtkit/channel.rs @@ -191,7 +191,7 @@ mod tests { trace: None, reporting: Some(Box::new(endpoint)), }, - crate::builds::DEFAULT.rtkit_version, + stela_formats::builds::DEFAULT.rtkit_version, ) .unwrap(); let mut output = Vec::new(); diff --git a/crates/stela-runtime/src/platform/apple/sart.rs b/crates/stela-runtime/src/platform/apple/sart.rs index dd5ba8a1cd..a7badbaf9d 100644 --- a/crates/stela-runtime/src/platform/apple/sart.rs +++ b/crates/stela-runtime/src/platform/apple/sart.rs @@ -33,10 +33,12 @@ //! word still holds it when the count returns to 0 (0xfffffff0270d8c9c), so //! a lost write shows a power loss. Here the word is plain storage at //! [`CANARY`]; the SART refuses non-retained power loss. -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, }; -use crate::platform::dma::{DmaError, Iommu, Memory}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Iommu, stela_contracts::dma::Memory}; const NAME: &str = "sart"; /// The most entries a layout has, v4's. @@ -462,9 +464,9 @@ impl MmioDevice for Sart { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::interrupt::InterruptLatch, - dma::{Port, tests::Ram}, + use { + stela_contracts::dma::Port, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::InterruptLatch, }; #[test] @@ -721,7 +723,7 @@ mod tests { assert_eq!(sart.read(status, Width::Word, &mut access), Ok(0)); } sart.write(0x801c, Width::Word, 0, &mut access).unwrap(); - let mut memory = crate::platform::dma::tests::Ram::new(0, 0x1000); + let mut memory = stela_contracts::dma::test_support::Ram::new(0, 0x1000); assert!( sart.translate(&mut memory, 0, address, address, false, &mut access) .is_err() diff --git a/crates/stela-runtime/src/platform/apple/sep.rs b/crates/stela-runtime/src/platform/apple/sep.rs index b5ab5a97fd..0c0e845bd5 100644 --- a/crates/stela-runtime/src/platform/apple/sep.rs +++ b/crates/stela-runtime/src/platform/apple/sep.rs @@ -39,12 +39,14 @@ pub mod store; pub mod transaction; pub mod xart; -use super::{ - asc::{Asc, Lines}, - bus::{Access, Direction, Lifecycle, MmioDevice, MmioError, Width, refuse}, -}; -use crate::platform::dma::Port; use alloc::boxed::Box; +use stela_contracts::dma::Port; +use { + super::asc::Asc, super::asc::Lines, stela_contracts::bus::Access, + stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "sep"; const SEND_COMMIT: u64 = 0x8808; @@ -242,7 +244,10 @@ impl MmioDevice for Sep { mod tests { use super::message::{Frame, ROM}; use super::*; - use crate::platform::apple::interrupt::{AicInput, InterruptLatch, Wire}; + use { + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch, + stela_contracts::interrupt::Wire, + }; const PHYSICAL: u64 = 0x396400000; const ACTIVE: super::super::bus::LifecycleState = super::super::bus::LifecycleState { diff --git a/crates/stela-runtime/src/platform/apple/sep/der.rs b/crates/stela-runtime/src/platform/apple/sep/der.rs index 05829c58fc..7cd223279e 100644 --- a/crates/stela-runtime/src/platform/apple/sep/der.rs +++ b/crates/stela-runtime/src/platform/apple/sep/der.rs @@ -97,6 +97,7 @@ impl<'a> Cursor<'a> { } } +#[cfg(test)] pub(super) fn sequence(bytes: &[u8]) -> Result, &'static str> { let mut cursor = Cursor(bytes); let element = cursor.take(16)?; diff --git a/crates/stela-runtime/src/platform/apple/sep/firmware.rs b/crates/stela-runtime/src/platform/apple/sep/firmware.rs index 0c7dccdf5a..e0a64a0df8 100644 --- a/crates/stela-runtime/src/platform/apple/sep/firmware.rs +++ b/crates/stela-runtime/src/platform/apple/sep/firmware.rs @@ -21,8 +21,8 @@ use super::{ rom::Rom, state, xart, }; -use crate::platform::dma::{DmaError, Port}; use alloc::{boxed::Box, vec::Vec}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; /// `_bootAction` 0x2d72d68 accepts opcode 106 ("SEP accepted IMG4") and moves /// the AP BootStatus to 101. SEPROM replies with it once Stela's policy @@ -111,9 +111,9 @@ impl SepFirmware { /// Measure the container, bind its payload type to the request, and record /// any manifest signature as evidence. Structural or type errors refuse. fn measure(&self, snapshot: &image::Snapshot, parameter: u8) -> Result { - let parts = crate::img4::parse(snapshot.bytes()) + let parts = stela_formats::img4::parse(snapshot.bytes()) .map_err(|_| "SEP firmware Image4 structure is malformed")?; - let kind = crate::img4::payload_type(parts.payload) + let kind = stela_formats::img4::payload_type(parts.payload) .map_err(|_| "SEP firmware payload type is malformed")?; let expected = if parameter == FIRMWARE_SEPI { *b"sepi" @@ -126,7 +126,8 @@ impl SepFirmware { let manifest = parts .manifest .map(|m| signature::inspect(parts.payload, m)) - .transpose()?; + .transpose() + .map_err(|error| error.reason())?; Ok(Evidence { measurement: snapshot.measurement.clone(), manifest, @@ -242,9 +243,9 @@ impl Firmware for SepFirmware { mod tests { use super::super::observe; use super::*; - use crate::platform::{ - apple::{bus::Access, interrupt::InterruptLatch}, - dma::{Iommu, Memory, tests::Ram}, + use { + stela_contracts::bus::Access, stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, }; struct Identity { @@ -377,7 +378,7 @@ mod tests { state::Location::Volatile, ); booted(&mut fw); - let image = crate::img4::tests::im4p(b"sepi", b"stela-sepos"); + let image = stela_formats::img4::test_support::im4p(b"sepi", b"stela-sepos"); let acks = deliver(&mut fw, &image, false).unwrap(); assert_eq!(acks.len(), 1); assert_eq!(Frame::from_mailbox(acks[0]).unwrap().opcode, IMAGE_ACCEPTED); @@ -407,7 +408,12 @@ mod tests { state::Location::Volatile, ); booted(&mut fw); - deliver(&mut fw, &crate::img4::tests::im4p(b"sepi", b"x"), false).unwrap(); + deliver( + &mut fw, + &stela_formats::img4::test_support::im4p(b"sepi", b"x"), + false, + ) + .unwrap(); map_shared(&mut fw); // Unknown commands refuse before DMA; recognized keybag codecs must // validate their actual buffers before refusing unresolved semantics. @@ -446,7 +452,7 @@ mod tests { ); booted(&mut fw); let (payload, manifest) = signature::tests::inputs(); - let image = crate::img4::compose(&payload, &manifest); + let image = stela_formats::img4::compose(&payload, &manifest); let acks = deliver(&mut fw, &image, false).unwrap(); assert_eq!(acks.len(), 1); assert!(fw.evidence().unwrap().manifest.is_some()); @@ -454,8 +460,8 @@ mod tests { #[test] fn malformed_payloads_and_dma_faults_refuse_without_a_boot_ack() { - let rsep = crate::img4::tests::im4p(b"rsep", b"x"); - let sepi = crate::img4::tests::im4p(b"sepi", b"x"); + let rsep = stela_formats::img4::test_support::im4p(b"rsep", b"x"); + let sepi = stela_formats::img4::test_support::im4p(b"sepi", b"x"); for (image, fault, refusal) in [ ( b"\x30\x06\x16\x04IM4P".as_slice(), @@ -503,7 +509,7 @@ mod tests { state::Location::Volatile, ); booted(&mut fw); - let image = crate::img4::tests::im4p(b"sepi", b"native SEP fixture"); + let image = stela_formats::img4::test_support::im4p(b"sepi", b"native SEP fixture"); assert_eq!(deliver(&mut fw, &image, false), Err("entropy unavailable")); assert!(fw.dma_pending()); assert!(fw.evidence().is_none()); @@ -535,7 +541,7 @@ mod tests { booted(&mut fw); deliver( &mut fw, - &crate::img4::tests::im4p(b"sepi", b"native SEP fixture"), + &stela_formats::img4::test_support::im4p(b"sepi", b"native SEP fixture"), false, ) .unwrap(); @@ -597,7 +603,7 @@ mod tests { assert_eq!((rom.tag, rom.opcode, rom.data), (2, ROM_FAILURE, 0x30)); assert_eq!(reply(&mut fw, request(boot_policy::ID, 2, 0)), None); - let image = crate::img4::tests::im4p(b"sepi", b"stela-sepos"); + let image = stela_formats::img4::test_support::im4p(b"sepi", b"stela-sepos"); deliver(&mut fw, &image, false).unwrap(); map_shared(&mut fw); assert!(fw.booted()); diff --git a/crates/stela-runtime/src/platform/apple/sep/image.rs b/crates/stela-runtime/src/platform/apple/sep/image.rs index 23818dca77..b0e47cfb04 100644 --- a/crates/stela-runtime/src/platform/apple/sep/image.rs +++ b/crates/stela-runtime/src/platform/apple/sep/image.rs @@ -4,13 +4,11 @@ //! IOVA in 4-KiB units without a length. DER supplies the container extent; //! the caller supplies its permitted maximum. This is source-integrity //! evidence only: measurement never authenticates Image4 or boots sepOS. -use super::der; -pub(crate) mod rsa; pub mod signature; -use crate::platform::dma::{DmaError, Port}; use alloc::vec::Vec; use sha2::{Digest, Sha256}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; const SEQUENCE: u8 = 0x30; const IA5: u8 = 0x16; @@ -148,9 +146,9 @@ pub fn measure( #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{bus::Access, interrupt::InterruptLatch}, - dma::{Iommu, Memory, tests::Ram}, + use { + stela_contracts::bus::Access, stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, }; struct Mapping { diff --git a/crates/stela-runtime/src/platform/apple/sep/image/signature.rs b/crates/stela-runtime/src/platform/apple/sep/image/signature.rs index b1345400d7..5573a6407a 100644 --- a/crates/stela-runtime/src/platform/apple/sep/image/signature.rs +++ b/crates/stela-runtime/src/platform/apple/sep/image/signature.rs @@ -6,12 +6,127 @@ //! but grants NO trust: missing roots, certificate constraints, board/nonce //! policy and rollback remain the admission owner's obligations. In particular //! a key supplied by an untrusted manifest cannot authenticate itself as Apple. -use super::{ - der::{self, Cursor, Element}, - rsa::{Hash, Key}, -}; use alloc::vec::Vec; use sha2::{Digest, Sha384}; +use stela_formats::{ + der::{self, Cursor, Element}, + rsa::{self, Hash, Key}, +}; + +/// A structural or cryptographic failure, with its original parser cause. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SignatureError { + Der(der::Error), + Rsa(rsa::Error), + Payload(stela_formats::img4::Img4Error), + Violation(SignatureViolation), +} +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SignatureViolation { + AlgorithmParameters, + UnusedBits, + CertificateSignatureAlgorithm, + CertificateVersion, + CertificateSerial, + CertificateAlgorithmMismatch, + CertificateKeyAlgorithm, + CertificateOptionalField, + ManifestTag, + ManifestName, + ManifestProperties, + ManifestBody, + ObjectLimit, + DuplicateObject, + PropertyLimit, + DuplicateProperty, + DigestAlgorithm, + MissingPayload, + ManifestLimit, + PayloadType, + ManifestType, + ManifestVersion, + PayloadDigest, + CertificateLimit, + DuplicateCertificate, + MissingCertificate, + CertificateIssuer, +} +impl SignatureViolation { + pub const fn reason(self) -> &'static str { + match self { + Self::AlgorithmParameters => "SEP algorithm parameters are not NULL", + Self::UnusedBits => "SEP signature/key BIT STRING has unused bits", + Self::CertificateSignatureAlgorithm => { + "SEP certificate signature algorithm is unsupported" + } + Self::CertificateVersion => "SEP certificate version is unsupported", + Self::CertificateSerial => "SEP certificate version/serial is malformed", + Self::CertificateAlgorithmMismatch => "SEP certificate signature algorithms disagree", + Self::CertificateKeyAlgorithm => "SEP certificate key algorithm is unsupported", + Self::CertificateOptionalField => "SEP certificate optional field is unsupported", + Self::ManifestTag => "SEP manifest entry is not a private constructed tag", + Self::ManifestName => "SEP manifest entry name differs from its tag", + Self::ManifestProperties => "SEP manifest properties are not a SET", + Self::ManifestBody => "SEP manifest has no MANB", + Self::ObjectLimit => "SEP manifest object count exceeds the resource bound", + Self::DuplicateObject => "SEP manifest has duplicate objects", + Self::PropertyLimit => "SEP manifest property count exceeds the resource bound", + Self::DuplicateProperty => "SEP manifest has duplicate properties", + Self::DigestAlgorithm => "SEP manifest digest is not SHA-384", + Self::MissingPayload => "SEP manifest does not cover this payload type", + Self::ManifestLimit => "SEP manifest exceeds the resource bound", + Self::PayloadType => "SEP payload type is unsupported", + Self::ManifestType => "SEP firmware manifest is not an IM4M", + Self::ManifestVersion => "SEP manifest version is unsupported", + Self::PayloadDigest => "SEP manifest payload digest mismatch", + Self::CertificateLimit => "SEP certificate chain exceeds the resource bound", + Self::DuplicateCertificate => "SEP certificate chain contains a duplicate certificate", + Self::MissingCertificate => "SEP manifest has no signing certificate", + Self::CertificateIssuer => "SEP certificate issuer/subject mismatch", + } + } +} +impl SignatureError { + /// Description for the legacy ROM protocol's static refusal vocabulary. + pub const fn reason(self) -> &'static str { + match self { + Self::Der(_) => "SEP signature DER is malformed", + Self::Rsa(_) => "SEP RSA signature verification failed", + Self::Payload(_) => "SEP payload is not an IM4P", + Self::Violation(reason) => reason.reason(), + } + } +} +impl From for SignatureError { + fn from(error: der::Error) -> Self { + Self::Der(error) + } +} +impl From for SignatureError { + fn from(error: rsa::Error) -> Self { + Self::Rsa(error) + } +} +impl core::fmt::Display for SignatureError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Der(error) => write!(f, "SEP signature: {error}"), + Self::Rsa(error) => write!(f, "SEP signature: {error}"), + Self::Payload(error) => write!(f, "SEP payload: {error}"), + Self::Violation(reason) => f.write_str(reason.reason()), + } + } +} +impl core::error::Error for SignatureError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Der(error) => Some(error), + Self::Rsa(error) => Some(error), + Self::Payload(error) => Some(error), + Self::Violation(_) => None, + } + } +} const RSA_ENCRYPTION: &[u8] = b"\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01"; const RSA_SHA256: &[u8] = b"\x2a\x86\x48\x86\xf7\x0d\x01\x01\x0b"; @@ -37,11 +152,13 @@ pub struct Evidence { pub payload_sha384: [u8; 48], } -fn algorithm(encoded: &[u8]) -> Result<&[u8], &'static str> { +fn algorithm(encoded: &[u8]) -> Result<&[u8], SignatureError> { let mut fields = der::sequence(encoded)?; let oid = fields.take(6)?.value; if !fields.0.is_empty() && !fields.take(5)?.value.is_empty() { - return Err("SEP algorithm parameters are not NULL"); + return Err(SignatureError::Violation( + SignatureViolation::AlgorithmParameters, + )); } fields.end()?; Ok(oid) @@ -57,54 +174,68 @@ struct Certificate<'a> { key: Key, } -fn bit_string(value: &[u8]) -> Result<&[u8], &'static str> { +fn bit_string(value: &[u8]) -> Result<&[u8], SignatureError> { if value.first() != Some(&0) { - return Err("SEP signature/key BIT STRING has unused bits"); + return Err(SignatureError::Violation(SignatureViolation::UnusedBits)); } Ok(&value[1..]) } -fn certificate(encoded: &[u8]) -> Result, &'static str> { +fn certificate(encoded: &[u8]) -> Result, SignatureError> { let mut outer = der::sequence(encoded)?; let tbs = outer.take(16)?; let alg = outer.take(16)?; let hash = match algorithm(alg.encoded)? { RSA_SHA256 => Hash::Sha256, RSA_SHA384 => Hash::Sha384, - _ => return Err("SEP certificate signature algorithm is unsupported"), + _ => { + return Err(SignatureError::Violation( + SignatureViolation::CertificateSignatureAlgorithm, + )); + } }; let signature = bit_string(outer.take(3)?.value)?; outer.end()?; let mut fields = Cursor(tbs.value); - let first = fields.next()?; + let first = fields.next_element()?; if first.class == 2 && first.tag == 0 && first.constructed { if first.value != b"\x02\x01\x02" { - return Err("SEP certificate version is unsupported"); + return Err(SignatureError::Violation( + SignatureViolation::CertificateVersion, + )); } der::unsigned(fields.take(2)?.value)?; } else if first.class == 0 && first.tag == 2 && !first.constructed { der::unsigned(first.value)?; // X.509 v1 omits the DEFAULT version. } else { - return Err("SEP certificate version/serial is malformed"); + return Err(SignatureError::Violation( + SignatureViolation::CertificateSerial, + )); } if fields.take(16)?.encoded != alg.encoded { - return Err("SEP certificate signature algorithms disagree"); + return Err(SignatureError::Violation( + SignatureViolation::CertificateAlgorithmMismatch, + )); } let issuer = fields.take(16)?.encoded; fields.take(16)?; // Validity is preserved in tbs, not evaluated as trust here. let subject = fields.take(16)?.encoded; let mut spki = Cursor(fields.take(16)?.value); if algorithm(spki.take(16)?.encoded)? != RSA_ENCRYPTION { - return Err("SEP certificate key algorithm is unsupported"); + return Err(SignatureError::Violation( + SignatureViolation::CertificateKeyAlgorithm, + )); } let key = Key::parse(bit_string(spki.take(3)?.value)?)?; spki.end()?; // Only the optional X.509 v3 extensions field is supported; never claim // extension/role/time validation merely because a signature verified. if !fields.0.is_empty() { - let extensions = fields.next()?; + let extensions = fields.next_element()?; if extensions.class != 2 || extensions.tag != 3 || !extensions.constructed { - return Err("SEP certificate optional field is unsupported"); + return Err(SignatureError::Violation( + SignatureViolation::CertificateOptionalField, + )); } der::sequence(extensions.value)?; } @@ -120,32 +251,34 @@ fn certificate(encoded: &[u8]) -> Result, &'static str> { }) } -fn named(element: Element<'_>) -> Result<([u8; 4], Element<'_>), &'static str> { +fn named(element: Element<'_>) -> Result<([u8; 4], Element<'_>), SignatureError> { if element.class != 3 || !element.constructed { - return Err("SEP manifest entry is not a private constructed tag"); + return Err(SignatureError::Violation(SignatureViolation::ManifestTag)); } let name = element.tag.to_be_bytes(); let mut fields = der::sequence(element.value)?; if fields.take(22)?.value != name { - return Err("SEP manifest entry name differs from its tag"); + return Err(SignatureError::Violation(SignatureViolation::ManifestName)); } - let value = fields.next()?; + let value = fields.next_element()?; fields.end()?; Ok((name, value)) } -fn set(element: Element<'_>) -> Result, &'static str> { +fn set(element: Element<'_>) -> Result, SignatureError> { if element.class != 0 || element.tag != 17 || !element.constructed { - return Err("SEP manifest properties are not a SET"); + return Err(SignatureError::Violation( + SignatureViolation::ManifestProperties, + )); } Ok(Cursor(element.value)) } -fn digest_for(body: Element<'_>, payload_type: [u8; 4]) -> Result<&[u8], &'static str> { +fn digest_for(body: Element<'_>, payload_type: [u8; 4]) -> Result<&[u8], SignatureError> { let mut body = set(body)?; - let (name, entries) = named(body.next()?)?; + let (name, entries) = named(body.next_element()?)?; if name != *b"MANB" { - return Err("SEP manifest has no MANB"); + return Err(SignatureError::Violation(SignatureViolation::ManifestBody)); } body.end()?; let mut entries = set(entries)?; @@ -153,22 +286,26 @@ fn digest_for(body: Element<'_>, payload_type: [u8; 4]) -> Result<&[u8], &'stati let mut digest = None; while !entries.0.is_empty() { if names.len() == MAX_ENTRIES { - return Err("SEP manifest object count exceeds the resource bound"); + return Err(SignatureError::Violation(SignatureViolation::ObjectLimit)); } - let (name, properties) = named(entries.next()?)?; + let (name, properties) = named(entries.next_element()?)?; if names.contains(&name) { - return Err("SEP manifest has duplicate objects"); + return Err(SignatureError::Violation( + SignatureViolation::DuplicateObject, + )); } names.push(name); let mut properties = set(properties)?; let mut property_names = Vec::new(); while !properties.0.is_empty() { if property_names.len() == MAX_ENTRIES { - return Err("SEP manifest property count exceeds the resource bound"); + return Err(SignatureError::Violation(SignatureViolation::PropertyLimit)); } - let (property_name, value) = named(properties.next()?)?; + let (property_name, value) = named(properties.next_element()?)?; if property_names.contains(&property_name) { - return Err("SEP manifest has duplicate properties"); + return Err(SignatureError::Violation( + SignatureViolation::DuplicateProperty, + )); } property_names.push(property_name); if name == payload_type && property_name == *b"DGST" { @@ -177,38 +314,44 @@ fn digest_for(body: Element<'_>, payload_type: [u8; 4]) -> Result<&[u8], &'stati || value.constructed || value.value.len() != 48 { - return Err("SEP manifest digest is not SHA-384"); + return Err(SignatureError::Violation( + SignatureViolation::DigestAlgorithm, + )); } digest = Some(value.value); } } } - digest.ok_or("SEP manifest does not cover this payload type") + digest.ok_or(SignatureError::Violation( + SignatureViolation::MissingPayload, + )) } /// Verify signatures and IM4P digest binding using the supplied certificates. /// The returned evidence deliberately has no `trusted`/`booted` flag. -pub fn inspect(payload: &[u8], manifest: &[u8]) -> Result { +pub fn inspect(payload: &[u8], manifest: &[u8]) -> Result { if manifest.len() > MAX_MANIFEST_BYTES { - return Err("SEP manifest exceeds the resource bound"); + return Err(SignatureError::Violation(SignatureViolation::ManifestLimit)); } let payload_type = - crate::img4::payload_type(payload).map_err(|_| "SEP payload is not an IM4P")?; + stela_formats::img4::payload_type(payload).map_err(SignatureError::Payload)?; if ![*b"sepi", *b"rsep"].contains(&payload_type) { - return Err("SEP payload type is unsupported"); + return Err(SignatureError::Violation(SignatureViolation::PayloadType)); } let mut fields = der::sequence(manifest)?; if fields.take(22)?.value != b"IM4M" { - return Err("SEP firmware manifest is not an IM4M"); + return Err(SignatureError::Violation(SignatureViolation::ManifestType)); } if fields.take(2)?.value != [0] { - return Err("SEP manifest version is unsupported"); + return Err(SignatureError::Violation( + SignatureViolation::ManifestVersion, + )); } let body = fields.take(17)?; let digest = digest_for(body, payload_type)?; let payload_sha384: [u8; 48] = Sha384::digest(payload).into(); if digest != payload_sha384 { - return Err("SEP manifest payload digest mismatch"); + return Err(SignatureError::Violation(SignatureViolation::PayloadDigest)); } // Parse the remaining fields here too, so no trailing or duplicate // envelope is ignored before the signature check. @@ -223,16 +366,18 @@ pub fn inspect(payload: &[u8], manifest: &[u8]) -> Result Result { +pub fn verify_manifest(manifest: &[u8]) -> Result { if manifest.len() > MAX_MANIFEST_BYTES { - return Err("SEP manifest exceeds the resource bound"); + return Err(SignatureError::Violation(SignatureViolation::ManifestLimit)); } let mut fields = der::sequence(manifest)?; if fields.take(22)?.value != b"IM4M" { - return Err("SEP firmware manifest is not an IM4M"); + return Err(SignatureError::Violation(SignatureViolation::ManifestType)); } if fields.take(2)?.value != [0] { - return Err("SEP manifest version is unsupported"); + return Err(SignatureError::Violation( + SignatureViolation::ManifestVersion, + )); } let body = fields.take(17)?; let signature = fields.take(4)?.value; @@ -241,24 +386,30 @@ pub fn verify_manifest(manifest: &[u8]) -> Result> = Vec::new(); while !chain.0.is_empty() { if certificates.len() == MAX_CERTIFICATES { - return Err("SEP certificate chain exceeds the resource bound"); + return Err(SignatureError::Violation( + SignatureViolation::CertificateLimit, + )); } let encoded = chain.take(16)?.encoded; if certificates.iter().any(|c| c.encoded == encoded) { - return Err("SEP certificate chain contains a duplicate certificate"); + return Err(SignatureError::Violation( + SignatureViolation::DuplicateCertificate, + )); } certificates.push(certificate(encoded)?); } - let leaf = certificates - .first() - .ok_or("SEP manifest has no signing certificate")?; + let leaf = certificates.first().ok_or(SignatureError::Violation( + SignatureViolation::MissingCertificate, + ))?; leaf.key.verify(body.encoded, signature, Hash::Sha384)?; for pair in certificates.windows(2) { let [child, issuer] = pair else { unreachable!() }; if child.issuer != issuer.subject { - return Err("SEP certificate issuer/subject mismatch"); + return Err(SignatureError::Violation( + SignatureViolation::CertificateIssuer, + )); } issuer.key.verify(child.tbs, child.signature, child.hash)?; } @@ -292,7 +443,7 @@ pub(crate) mod tests { *altered.last_mut().unwrap() ^= 1; assert_eq!( inspect(&altered, &manifest), - Err("SEP manifest payload digest mismatch") + Err(SignatureError::Violation(SignatureViolation::PayloadDigest)) ); for length in 0..manifest.len() { assert!(inspect(&payload, &manifest[..length]).is_err()); @@ -307,7 +458,7 @@ pub(crate) mod tests { modified[offset] ^= 1; assert_eq!( inspect(&payload, &modified), - Err("SEP RSA PKCS1 signature verification failed") + Err(SignatureError::Rsa(rsa::Error::SignatureMismatch)) ); let mut excess = manifest.clone(); excess.push(0); @@ -319,11 +470,15 @@ pub(crate) mod tests { let mut fields = der::sequence(&manifest).unwrap(); let mut prefix = Vec::new(); for _ in 0..4 { - prefix.extend_from_slice(fields.next().unwrap().encoded); + prefix.extend_from_slice(fields.next_element().unwrap().encoded); } - let chain_manifest = crate::img4::tests::der( + let chain_manifest = stela_formats::img4::test_support::der( 0x30, - &[prefix.clone(), crate::img4::tests::der(0x30, &chain)].concat(), + &[ + prefix.clone(), + stela_formats::img4::test_support::der(0x30, &chain), + ] + .concat(), ); assert_eq!( inspect(&payload, &chain_manifest) @@ -334,29 +489,35 @@ pub(crate) mod tests { ); let mut c = Cursor(&chain); let child = c.take(16).unwrap().encoded; - let duplicate = crate::img4::tests::der( + let duplicate = stela_formats::img4::test_support::der( 0x30, &[ prefix.clone(), - crate::img4::tests::der(0x30, &[child, child].concat()), + stela_formats::img4::test_support::der(0x30, &[child, child].concat()), ] .concat(), ); assert_eq!( inspect(&payload, &duplicate), - Err("SEP certificate chain contains a duplicate certificate") + Err(SignatureError::Violation( + SignatureViolation::DuplicateCertificate + )) ); let mut broken = chain.clone(); // Last byte of the child is its signature; the manifest's key/body // remain intact, so this exercises issuer verification specifically. broken[child.len() - 1] ^= 1; - let broken = crate::img4::tests::der( + let broken = stela_formats::img4::test_support::der( 0x30, - &[prefix, crate::img4::tests::der(0x30, &broken)].concat(), + &[ + prefix, + stela_formats::img4::test_support::der(0x30, &broken), + ] + .concat(), ); assert_eq!( inspect(&payload, &broken), - Err("SEP RSA PKCS1 signature verification failed") + Err(SignatureError::Rsa(rsa::Error::SignatureMismatch)) ); } } diff --git a/crates/stela-runtime/src/platform/apple/sep/ool.rs b/crates/stela-runtime/src/platform/apple/sep/ool.rs index 4dfed84f00..f108bfa549 100644 --- a/crates/stela-runtime/src/platform/apple/sep/ool.rs +++ b/crates/stela-runtime/src/platform/apple/sep/ool.rs @@ -12,7 +12,7 @@ use super::{ message::{self, Frame}, shared::Region, }; -use crate::platform::dma::{DmaError, Port}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; const SET_INPUT_ADDRESS: u8 = 2; const SET_OUTPUT_ADDRESS: u8 = 3; @@ -144,9 +144,9 @@ impl Buffers { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{bus::Access, interrupt::InterruptLatch}, - dma::{Iommu, Memory, tests::Ram}, + use { + stela_contracts::bus::Access, stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, }; fn frame(opcode: u8, data: u32) -> Frame { Frame { diff --git a/crates/stela-runtime/src/platform/apple/sep/os.rs b/crates/stela-runtime/src/platform/apple/sep/os.rs index 9035a5caee..8cbfb7bb1b 100644 --- a/crates/stela-runtime/src/platform/apple/sep/os.rs +++ b/crates/stela-runtime/src/platform/apple/sep/os.rs @@ -45,8 +45,8 @@ use super::{ transaction::{Payload, Refusal}, xart::{self, Xart}, }; -use crate::platform::dma::{DmaError, Port}; use alloc::{boxed::Box, collections::VecDeque, format, string::String, vec::Vec}; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; /// The SEP's power state as the control endpoint drives it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -621,7 +621,7 @@ mod tests { fn map_shared(os: &mut SepOs, frame: Frame) -> Result, &'static str> { let region = Region::from_message(frame.mailbox())?; assert!(reply(os, frame)?.is_empty()); - let mut ram = crate::platform::dma::tests::Ram::new(region.address, 0x4000); + let mut ram = stela_contracts::dma::test_support::Ram::new(region.address, 0x4000); ram.bytes[..4].copy_from_slice(&u32::from_be_bytes(*b"null").to_le_bytes()); dma(os, &mut ram) } @@ -722,18 +722,18 @@ mod tests { } struct Identity; - impl crate::platform::dma::Iommu for Identity { + impl stela_contracts::dma::Iommu for Identity { fn page(&self) -> u64 { 0x4000 } fn translate( &mut self, - _: &mut dyn crate::platform::dma::Memory, + _: &mut dyn stela_contracts::dma::Memory, _: usize, iova: u64, _: u64, _: bool, - _: &mut crate::platform::apple::bus::Access<'_>, + _: &mut stela_contracts::bus::Access<'_>, ) -> Result { Ok(iova) } @@ -743,10 +743,10 @@ mod tests { /// step may also have. fn dma_step( os: &mut SepOs, - ram: &mut crate::platform::dma::tests::Ram, + ram: &mut stela_contracts::dma::test_support::Ram, ) -> (Result<(), &'static str>, Vec) { - let mut latch = crate::platform::apple::interrupt::InterruptLatch::new(); - let mut access = crate::platform::apple::bus::Access::new(0, 0, &mut latch); + let mut latch = stela_contracts::interrupt::InterruptLatch::new(); + let mut access = stela_contracts::bus::Access::new(0, 0, &mut latch); let mut port = Port { iommu: &mut Identity, stream: 0, @@ -771,7 +771,7 @@ mod tests { fn dma( os: &mut SepOs, - ram: &mut crate::platform::dma::tests::Ram, + ram: &mut stela_contracts::dma::test_support::Ram, ) -> Result, &'static str> { let (result, frames) = dma_step(os, ram); result.map(|()| frames) @@ -812,7 +812,7 @@ mod tests { // Without registered buffers the request is queued, then refuses. assert!(reply(&mut os, request).unwrap().is_empty()); assert!(os.dma_pending()); - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x10000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x10000); assert!(dma(&mut os, &mut ram).is_err()); // The AP registers one 0x8000-byte buffer each way, then sends. for (tag, opcode, data) in [ @@ -904,7 +904,7 @@ mod tests { assert!(reply(&mut os, control(3, control::SLEEP, 0, 0)).is_err()); assert_eq!(os.power(), Power::Awake); assert!(reply(&mut os, shm(0x8000, 4)).is_err()); - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x8000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x8000); ram.bytes[..16].fill(0x5a); let first = dma(&mut os, &mut ram).unwrap(); assert_eq!(first.len(), 1); @@ -937,7 +937,7 @@ mod tests { } .frame(); reply(&mut os, commit_hash).unwrap(); - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x1000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x1000); assert_eq!( dma_step(&mut os, &mut ram), ( @@ -954,7 +954,7 @@ mod tests { assert!(reply(&mut os, shm(0x8000, 4)).unwrap().is_empty()); assert_eq!(os.region(), Some(previous.region)); assert!(reply(&mut os, control(1, control::NOP, 0, 0)).is_err()); - let mut ram = crate::platform::dma::tests::Ram::new(0x8000, 0x4000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x8000, 0x4000); // A zero-filled directory has no null terminator and must not // replace the known layout, even after OS-active was published. assert!(dma(&mut os, &mut ram).is_err()); @@ -985,7 +985,7 @@ mod tests { parameter: 0, data: (request.len() as u32) << 16, }; - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x10000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x10000); ram.bytes[..request.len()].copy_from_slice(&request); assert!(reply(&mut os, frame).unwrap().is_empty()); let answer = dma(&mut os, &mut ram).unwrap(); @@ -1015,7 +1015,7 @@ mod tests { parameter: 0, data: (request.len() as u32) << 16, }; - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x10000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x10000); ram.bytes[..request.len()].copy_from_slice(&request); assert!(reply(&mut os, frame).unwrap().is_empty()); assert_eq!( @@ -1046,7 +1046,7 @@ mod tests { parameter: 0, data: (request.len() as u32) << 16, }; - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x10000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x10000); ram.bytes[..request.len()].copy_from_slice(&request); assert!(reply(&mut os, frame).unwrap().is_empty()); let (result, outbox) = dma_step(&mut os, &mut ram); @@ -1066,7 +1066,7 @@ mod tests { let mut os = SepOs::new(None).with_services(store(), false).unwrap(); map_shared(&mut os, shm(0x1234_4000, 0x20)).unwrap(); register(&mut os, boot_policy::ID, 0x1c000, 0x14000); - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x30000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x30000); let mut proposed = Vec::new(); for (command, length, expected) in [ (8u32, 0x124, 32), @@ -1193,7 +1193,7 @@ mod tests { parameter: 0, data: 32, }; - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x30000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x30000); ram.bytes[..4].copy_from_slice(b"hcPB"); ram.bytes[4] = 0x3e; // Recorded, then answered with the not-supported reply header. @@ -1229,7 +1229,7 @@ mod tests { ] { assert!(reply(&mut os, frame).unwrap().is_empty()); } - let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x1000); + let mut ram = stela_contracts::dma::test_support::Ram::new(0x10_0000, 0x1000); // Each DMA step consumes one request. The keystore refusal is // answered with its failure status; scrd is not answered at all. let (result, answer) = dma_step(&mut os, &mut ram); diff --git a/crates/stela-runtime/src/platform/apple/sep/shared.rs b/crates/stela-runtime/src/platform/apple/sep/shared.rs index 38359e124a..b40d6926bd 100644 --- a/crates/stela-runtime/src/platform/apple/sep/shared.rs +++ b/crates/stela-runtime/src/platform/apple/sep/shared.rs @@ -11,8 +11,8 @@ use super::{ super::asc::Message, message::{self, Frame}, }; -use crate::platform::dma::{DmaError, Port}; use alloc::vec::Vec; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; const ENTRY_BYTES: u64 = 16; const NULL: u32 = u32::from_be_bytes(*b"null"); @@ -175,9 +175,9 @@ pub fn raw_timebase(message: Message) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{bus::Access, interrupt::InterruptLatch}, - dma::{Iommu, Memory, tests::Ram}, + use { + stela_contracts::bus::Access, stela_contracts::dma::Iommu, stela_contracts::dma::Memory, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, }; struct Mapper { diff --git a/crates/stela-runtime/src/platform/apple/sio_dma.rs b/crates/stela-runtime/src/platform/apple/sio_dma.rs index ee7f26c1e0..226b398e37 100644 --- a/crates/stela-runtime/src/platform/apple/sio_dma.rs +++ b/crates/stela-runtime/src/platform/apple/sio_dma.rs @@ -16,10 +16,10 @@ //! Consequently this boundary is not yet registered as complete PMGR coverage. pub mod setup; -use super::bus::LifecycleState; -use crate::platform::dma::{DmaError, Port}; use alloc::collections::VecDeque; use alloc::vec::Vec; +use stela_contracts::bus::LifecycleState; +use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; const SLOT_BYTES: u64 = 12; /// The original 26A434 controller allocates 0x7ff8 bytes and sends 0xaaa slots. @@ -494,9 +494,9 @@ impl Channel { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::interrupt::InterruptLatch, - dma::{Physical, tests::Ram}, + use { + stela_contracts::dma::Physical, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::InterruptLatch, }; const RAM: u64 = 0x8000; @@ -830,9 +830,9 @@ mod tests { #[test] fn actual_dart_clock_and_stream_faults_cannot_be_substituted_for_dma_success() { - use crate::platform::apple::{ - bus::{Access, MmioDevice, Width}, - dart::Dart, + use { + crate::platform::apple::dart::Dart, stela_contracts::bus::Access, + stela_contracts::bus::MmioDevice, stela_contracts::bus::Width, }; let mut ram = Ram::new(RAM, 0x8000); ram.bytes[0x2000..0x2004].copy_from_slice(b"real"); diff --git a/crates/stela-runtime/src/platform/apple/sio_dma/setup.rs b/crates/stela-runtime/src/platform/apple/sio_dma/setup.rs index 1ebf4904c9..ae541833c1 100644 --- a/crates/stela-runtime/src/platform/apple/sio_dma/setup.rs +++ b/crates/stela-runtime/src/platform/apple/sio_dma/setup.rs @@ -8,8 +8,8 @@ pub mod control; use super::Error; -use crate::platform::{apple::bus::Width, dma::Port}; use alloc::vec::Vec; +use {stela_contracts::bus::Width, stela_contracts::dma::Port}; const ROW_BYTES: usize = 24; /// Native resource bound, not a hardware table-length claim. Larger tables @@ -232,15 +232,15 @@ impl TunableProgram { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{ - bus::{Access, Bus, Direction, MmioDevice, MmioError, refuse}, - gpio::Gpio, - interrupt::{AicInput, InterruptLatch}, - }, - dma::{Physical, tests::Ram}, - }; use alloc::{boxed::Box, vec}; + use { + crate::platform::apple::gpio::Gpio, stela_contracts::bus::Access, + stela_contracts::bus::Bus, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, + stela_contracts::bus::refuse, stela_contracts::dma::Physical, + stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::AicInput, + stela_contracts::interrupt::InterruptLatch, + }; const TABLE: u64 = 0x8000; const BANK: u64 = 0x238300000; diff --git a/crates/stela-runtime/src/platform/apple/sio_dma/setup/control.rs b/crates/stela-runtime/src/platform/apple/sio_dma/setup/control.rs index 887fdb27ba..6de587148f 100644 --- a/crates/stela-runtime/src/platform/apple/sio_dma/setup/control.rs +++ b/crates/stela-runtime/src/platform/apple/sio_dma/setup/control.rs @@ -2,7 +2,7 @@ //! This is a setup component, not a complete SIO firmware or version handshake. use super::{Effect, EffectResult, FinishError, Request, TunableProgram}; use crate::platform::apple::sio_dma::Error; -use crate::platform::dma::Port; +use stela_contracts::dma::Port; /// A physical map range qualified by the actual owner. Geometry alone does /// not qualify its registers; requests still use checked machine MMIO. @@ -227,15 +227,13 @@ impl TunableControl { #[cfg(test)] mod tests { use super::*; - use crate::platform::{ - apple::{ - bus::{Access, Bus, MmioError, Width}, - gpio::Gpio, - interrupt::{AicInput, InterruptLatch}, - }, - dma::{Physical, tests::Ram}, - }; use alloc::{boxed::Box, vec}; + use { + crate::platform::apple::gpio::Gpio, stela_contracts::bus::Access, + stela_contracts::bus::Bus, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::dma::Physical, stela_contracts::dma::test_support::Ram, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::InterruptLatch, + }; const TABLE: u64 = 0x8000; const BASE: u64 = 0x238300000; diff --git a/crates/stela-runtime/src/platform/apple/smc.rs b/crates/stela-runtime/src/platform/apple/smc.rs index 918720ce33..7611b3a89d 100644 --- a/crates/stela-runtime/src/platform/apple/smc.rs +++ b/crates/stela-runtime/src/platform/apple/smc.rs @@ -151,7 +151,6 @@ use rtc::RtcBinding; pub use rtc::RtcKeyProfile; use super::asc::TransitionRequest; -use super::bus::{Access, Direction, MmioDevice, MmioError, Transition, Width, refuse}; use super::rtkit::Endpoint; use alloc::{ collections::{BTreeMap, VecDeque}, @@ -160,6 +159,11 @@ use alloc::{ vec::Vec, }; use core::cell::RefCell; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, + stela_contracts::bus::Transition, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; pub const ENDPOINT: u8 = 0x20; /// The shared page: one 16 KiB kernel page at the start of the region. diff --git a/crates/stela-runtime/src/platform/apple/smc/rtc.rs b/crates/stela-runtime/src/platform/apple/smc/rtc.rs index ac26d60349..3d4780100f 100644 --- a/crates/stela-runtime/src/platform/apple/smc/rtc.rs +++ b/crates/stela-runtime/src/platform/apple/smc/rtc.rs @@ -49,11 +49,11 @@ mod tests { #[test] #[ignore = "requires original26A434 KC and J314s DT via STELA_TEST_PMGR_M1_KERNELCACHE/STELA_TEST_SPMI_DT"] fn original_rtc_helper_uses_raw_keyr_with_actual_interface_dispatch() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let bytes = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_KERNELCACHE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "5109fca5209bdbb89cec29e3241cc42a90418cb737d65e31962b059b9879af90" ); for (offset, size, hash) in [ @@ -129,7 +129,7 @@ mod tests { ), // rtc-tick-units ] { assert_eq!( - crate::sha256(&bytes[offset..offset + size]), + stela_formats::sha256(&bytes[offset..offset + size]), hash, "source span {offset:#x}" ); @@ -144,7 +144,7 @@ mod tests { } let data = std::fs::read(std::env::var("STELA_TEST_SPMI_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/spi.rs b/crates/stela-runtime/src/platform/apple/spi.rs index b6cb17c404..d907d520d4 100644 --- a/crates/stela-runtime/src/platform/apple/spi.rs +++ b/crates/stela-runtime/src/platform/apple/spi.rs @@ -20,12 +20,14 @@ //! guarantees, so their words are retained. Only OVERRIDE_CS may change in //! SHIFTCFG, and only while an external GPIO drives the chip select, since //! the internal CS output is then disconnected from the attached device. -use super::{ - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - interrupt::{AicInput, Wire}, - nor::{Image, Nor}, -}; use alloc::{collections::VecDeque, vec::Vec}; +use { + super::nor::Image, super::nor::Nor, stela_contracts::bus::Access, + stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire, +}; pub const BYTES: u64 = 0x4000; const NAME: &str = "Apple SPI v1"; @@ -480,7 +482,7 @@ impl MmioDevice for Spi { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; fn write(spi: &mut Spi, offset: u64, value: u32, access: &mut Access<'_>) { spi.write(offset, Width::Word, u64::from(value), access) .unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/spmi.rs b/crates/stela-runtime/src/platform/apple/spmi.rs index ded421db68..ebf2d703d1 100644 --- a/crates/stela-runtime/src/platform/apple/spmi.rs +++ b/crates/stela-runtime/src/platform/apple/spmi.rs @@ -71,11 +71,13 @@ mod config; pub use config::{Configuration, Profile}; -use super::{ - bus::{Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse}, - interrupt::{AicInput, Wire}, -}; use alloc::{boxed::Box, collections::VecDeque, vec::Vec}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, + stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire, +}; pub const BANK_BYTES: u64 = 0x4000; /// Bank B's device offset; the placement maps `reg[1]` here. @@ -678,7 +680,7 @@ impl MmioDevice for Spmi { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; // The Gen1 and Gen2 offsets and status bits. const STATUS: u64 = 0x00; @@ -1322,7 +1324,7 @@ mod tests { ); c.attach_with_interrupt(15, 2, Box::new(model)).unwrap(); struct Sink(alloc::rc::Rc>, Wire); - impl crate::platform::apple::interrupt::InterruptSink for Sink { + impl stela_contracts::interrupt::InterruptSink for Sink { fn set_level(&mut self, wire: Wire, asserted: bool) { assert_eq!(wire, self.1); self.0.set(asserted); @@ -1542,7 +1544,7 @@ mod tests { } #[test] fn mounted_spmi_aliases_share_one_checked_controller_capability() { - use crate::platform::apple::bus::Bus; + use stela_contracts::bus::Bus; let mut bus = Bus::new(); let device = bus.add(Box::new(controller())); bus.map(device, 0x10000, BANK_BYTES, 0).unwrap(); @@ -1769,10 +1771,10 @@ mod tests { #[test] #[ignore = "requires original26A434 J314s DT through STELA_TEST_SPMI_DT"] fn original_j314s_all_seven_gen1_resource_views_match_the_qualified_contract() { - use crate::machine::adt::Node; + use stela_contracts::adt::Node; let data = std::fs::read(std::env::var("STELA_TEST_SPMI_DT").unwrap()).unwrap(); assert_eq!( - crate::sha256(&data), + stela_formats::sha256(&data), "44fa41bfd0fe0027fd862b8615ae956885614636625d44a59cab226d682558ad" ); let root = Node::root(&data).unwrap(); @@ -1863,7 +1865,7 @@ mod tests { let bytes = std::fs::read(std::env::var("STELA_TEST_PMGR_M1_KERNELCACHE").unwrap()).unwrap(); assert_eq!( - crate::sha256(&bytes), + stela_formats::sha256(&bytes), "5109fca5209bdbb89cec29e3241cc42a90418cb737d65e31962b059b9879af90" ); let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); diff --git a/crates/stela-runtime/src/platform/apple/uart.rs b/crates/stela-runtime/src/platform/apple/uart.rs index 859c8ddb90..af9bc783ad 100644 --- a/crates/stela-runtime/src/platform/apple/uart.rs +++ b/crates/stela-runtime/src/platform/apple/uart.rs @@ -18,11 +18,13 @@ //! state is the 8N1, FIFO-enabled, polled console left by the boot firmware. //! Transmitted bytes go to the host [`ConsoleSink`] immediately; bytes it cannot //! take stay in the 16-byte TX FIFO and are reported as FIFO occupancy. -use super::bus::{ - Access, Direction, Lifecycle, LifecycleState, MmioDevice, MmioError, Width, refuse, -}; -use super::interrupt::{AicInput, Wire}; use alloc::collections::VecDeque; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, stela_contracts::bus::Lifecycle, + stela_contracts::bus::LifecycleState, stela_contracts::bus::MmioDevice, + stela_contracts::bus::MmioError, stela_contracts::bus::Width, stela_contracts::bus::refuse, +}; +use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire}; const NAME: &str = "s5l-uart"; const FIFO_BYTES: usize = 16; @@ -471,8 +473,8 @@ impl MmioDevice for S5lUart { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; use alloc::vec::Vec; + use stela_contracts::interrupt::InterruptLatch; #[derive(Default)] struct Console { diff --git a/crates/stela-runtime/src/platform/apple/wake.rs b/crates/stela-runtime/src/platform/apple/wake.rs index bffd4b3aa4..f07454ba71 100644 --- a/crates/stela-runtime/src/platform/apple/wake.rs +++ b/crates/stela-runtime/src/platform/apple/wake.rs @@ -16,7 +16,11 @@ //! no status words are claimed. AOP/NUB/SMC/ATC physical wake generators are //! not emulated; this model supplies mask state for a supported generator to //! query, and does not invent a wake event when a mask is written. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; const NAME: &str = "aop-wake-masks"; pub const WORDS: usize = 8; @@ -88,7 +92,7 @@ impl MmioDevice for WakeMasks { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; #[test] fn active_low_masks_hold_writes_and_exclude_reserved_sources() { diff --git a/crates/stela-runtime/src/platform/apple/wdt.rs b/crates/stela-runtime/src/platform/apple/wdt.rs index 1c70b18c5d..09a98a2bb8 100644 --- a/crates/stela-runtime/src/platform/apple/wdt.rs +++ b/crates/stela-runtime/src/platform/apple/wdt.rs @@ -43,8 +43,12 @@ //! which the driver sets to its value under the record's mask on CPU start //! events (`writeCoreTriggerConfigurationStateChange`, 0x1ca5cf8). Bits //! outside the mask refuse; like the configuration, it acts only on expiry. -use super::bus::{Access, Direction, MmioDevice, MmioError, Width, refuse}; -use super::interrupt::{AicInput, Wire}; +use { + stela_contracts::bus::Access, stela_contracts::bus::Direction, + stela_contracts::bus::MmioDevice, stela_contracts::bus::MmioError, stela_contracts::bus::Width, + stela_contracts::bus::refuse, +}; +use {stela_contracts::interrupt::AicInput, stela_contracts::interrupt::Wire}; const NAME: &str = "apple-wdt"; @@ -366,7 +370,7 @@ impl MmioDevice for CoreTrigger { #[cfg(test)] mod tests { use super::*; - use crate::platform::apple::interrupt::InterruptLatch; + use stela_contracts::interrupt::InterruptLatch; const WD1: u64 = STRIDE; const IRQ: AicInput = AicInput::new(0, 379); diff --git a/crates/stela-runtime/src/platform/pc/boot_log.rs b/crates/stela-runtime/src/platform/pc/boot_log.rs index 7f8c83cef2..a7d26c5301 100644 --- a/crates/stela-runtime/src/platform/pc/boot_log.rs +++ b/crates/stela-runtime/src/platform/pc/boot_log.rs @@ -1176,7 +1176,7 @@ mod tests { #[test] fn a_file_gives_the_block_runs_of_its_clusters_that_hold_the_layout() { - use crate::payload::pieces::Extent; + use stela_formats::payload::pieces::Extent; let file = |extents: &[(u64, u64)]| fat32::File { bytes: extents.iter().map(|e| e.1).sum(), extents: extents diff --git a/crates/stela-runtime/src/platform/pc/fat32.rs b/crates/stela-runtime/src/platform/pc/fat32.rs index 82d2512487..afbba44268 100644 --- a/crates/stela-runtime/src/platform/pc/fat32.rs +++ b/crates/stela-runtime/src/platform/pc/fat32.rs @@ -8,9 +8,9 @@ //! short entries, which every FAT driver writes beside a long name. A file //! comes back as the device extents of its cluster chain, cut to its size. //! Nothing is written, and a malformed volume or chain is refused. -use crate::payload::{ReadAt, pieces::Extent}; use alloc::{format, string::String, vec, vec::Vec}; use core::fmt; +use {stela_formats::payload::ReadAt, stela_formats::payload::pieces::Extent}; const BOOT_SIGNATURE: u16 = 0xaa55; /// The fewest clusters a FAT32 volume has. diff --git a/crates/stela-runtime/src/platform/pc/fdr_store.rs b/crates/stela-runtime/src/platform/pc/fdr_store.rs index ddf29fa8f8..1887c294ac 100644 --- a/crates/stela-runtime/src/platform/pc/fdr_store.rs +++ b/crates/stela-runtime/src/platform/pc/fdr_store.rs @@ -598,12 +598,9 @@ mod tests { #[test] fn the_engine_finds_the_state_file_by_its_short_name_and_reads_its_runs() { - use crate::{ - payload::ReadAt, - platform::pc::{ - boot_log, - fat32::{Fat32, tests::Volume}, - }, + use { + crate::platform::pc::boot_log, crate::platform::pc::fat32::Fat32, + crate::platform::pc::fat32::tests::Volume, stela_formats::payload::ReadAt, }; let image = initial_image(b"seed").unwrap(); let mut volume = Volume::new(); diff --git a/crates/stela-runtime/src/platform/pc/storage.rs b/crates/stela-runtime/src/platform/pc/storage.rs index 030af1e334..6bf11be6ac 100644 --- a/crates/stela-runtime/src/platform/pc/storage.rs +++ b/crates/stela-runtime/src/platform/pc/storage.rs @@ -279,7 +279,7 @@ pub fn check(device: &mut dyn BlockDevice, bytes: usize) -> Result return Err(error.into()), } - Ok(crate::sha256(&read)) + Ok(stela_formats::sha256(&read)) } #[cfg(test)] @@ -334,7 +334,7 @@ mod tests { assert_eq!(device.identity().blocks, 100); let hash = check(&mut device, 4096).unwrap(); let expected: Vec = (0..4096).map(pattern).collect(); - assert_eq!(hash, crate::sha256(&expected)); + assert_eq!(hash, stela_formats::sha256(&expected)); let mut devices = disks(); assert_eq!( diff --git a/crates/stela-runtime/src/platform/usb/storage.rs b/crates/stela-runtime/src/platform/usb/storage.rs index 1c0032b4c4..0048519109 100644 --- a/crates/stela-runtime/src/platform/usb/storage.rs +++ b/crates/stela-runtime/src/platform/usb/storage.rs @@ -272,7 +272,7 @@ impl MassStorage { /// identity across boots, and its model in INQUIRY. pub fn of(device: Box) -> Result { let identity = device.identity(); - let digest = crate::hash::sha256( + let digest = stela_formats::sha256( alloc::format!("{}\0{}", identity.serial, identity.location).as_bytes(), ); let serial = digest[..24].to_ascii_uppercase(); diff --git a/crates/stela-runtime/src/restore/answers.rs b/crates/stela-runtime/src/restore/answers.rs index 801fce16f5..cdb1b61561 100644 --- a/crates/stela-runtime/src/restore/answers.rs +++ b/crates/stela-runtime/src/restore/answers.rs @@ -9,7 +9,6 @@ use super::{ ticket::Ticket, tss, }; -use crate::payload::{ReadAt, safe_path}; use alloc::{ boxed::Box, collections::BTreeMap, @@ -18,6 +17,7 @@ use alloc::{ vec::Vec, }; use sha2::{Digest, Sha384}; +use {stela_formats::payload::ReadAt, stela_formats::payload::safe_path}; const MAX_STAGED_ANSWERS: usize = 128; const MAX_STAGED_BYTES: usize = 16 * 1024 * 1024; const MAX_REPLY_BYTES: usize = 8 * 1024 * 1024; @@ -78,7 +78,7 @@ impl Staged { { return Err(Error::Limit("staged answers")); } - if crate::sha256(response_bytes) != sha256 { + if stela_formats::sha256(response_bytes) != sha256 { return Err(Error::Invalid("staged response digest")); } validate_http_args(kind, args)?; @@ -111,7 +111,7 @@ impl Staged { /// SHA-256 of the staged `URLAsset` reply for a recipient key PEM, for the /// inventory to record so the restore host serves the identical answer. pub fn staged_system_image_key_digest(pem: &str) -> Result { - Ok(crate::sha256(&plist::encode_binary( + Ok(stela_formats::sha256(&plist::encode_binary( &url_asset_reply(pem), Limits::default(), )?)) @@ -127,7 +127,10 @@ fn url_asset_reply(pem: &str) -> Value { ]) } fn fingerprint(v: &Value) -> Result { - Ok(crate::sha256(&plist::encode_binary(v, Limits::default())?)) + Ok(stela_formats::sha256(&plist::encode_binary( + v, + Limits::default(), + )?)) } fn validate_http_args(kind: &str, args: &Value) -> Result<()> { let method = args.required("RequestMethod")?.string()?; @@ -274,7 +277,7 @@ impl Answers { ("RequestURL", Value::from(key.url.as_str())), ]); let bytes = plist::encode_binary(&url_asset_reply(&key.key_pem), Limits::default())?; - let digest = crate::sha256(&bytes); + let digest = stela_formats::sha256(&bytes); if key.url_asset_sha256.as_deref().is_some_and(|s| s != digest) { return Err(Error::Invalid("staged key does not match its member")); } @@ -834,13 +837,13 @@ impl Answers { let path = identity.path(component)?.to_string(); let mut bytes = self.member_bytes(&path)?; let digest = identity.component(component)?.required("Digest")?.data()?; - let parts = crate::img4::parse(&bytes) + let parts = stela_formats::img4::parse(&bytes) .map_err(|_| Error::Invalid("SEP firmware is not an IM4P"))?; if parts.manifest.is_some() { return Err(Error::Invalid("SEP firmware is not a bare IM4P")); } if let Some(kind) = kind { - crate::img4::set_payload_type(&mut bytes, kind) + stela_formats::img4::set_payload_type(&mut bytes, kind) .map_err(|_| Error::Invalid("SEP firmware type cannot be set"))?; } if Sha384::digest(&bytes).as_slice() != digest { @@ -848,7 +851,7 @@ impl Answers { "SEP firmware differs from its BuildManifest digest", )); } - let image = crate::img4::container(&bytes); + let image = stela_formats::img4::container(&bytes); total += image.len(); if total > MAX_REPLY_BYTES { return Err(Error::Limit("NOR response bytes")); @@ -1181,7 +1184,7 @@ fn bare_type(prefix: &[u8], bytes: u64) -> Result<([u8; 4], usize)> { if length + header as u64 != bytes || prefix.get(header..header + 6) != Some(b"\x16\x04IM4P") { return Err(Error::Invalid("source must be exactly one bare IM4P")); } - let tag = crate::img4::peek_payload_type(prefix) + let tag = stela_formats::img4::peek_payload_type(prefix) .map_err(|_| Error::Invalid("IM4P streaming type"))?; // `IA5String "IM4P"` is followed by the four-character type's IA5String. let at = header + 8; @@ -1315,7 +1318,7 @@ mod tests { .unwrap() .data() .unwrap(), - crate::img4::container(&sep) + stela_formats::img4::container(&sep) ); let mut bare = Answers::new(super::super::store::tests::fixture(b"x", false)); assert!(bare.sep_firmware(&request).is_err()); @@ -1351,7 +1354,7 @@ mod tests { .unwrap() .data() .unwrap(), - crate::img4::container(&rsep) + stela_formats::img4::container(&rsep) ); // A digest of the file as stored does not cover the retyped image. let store = super::super::store::tests::with_components(b"x", false, &components); @@ -1545,7 +1548,7 @@ mod tests { /// refuses by member. #[test] fn the_system_image_key_answers_the_fcs_key_url_get_offline() { - use crate::payload::AeaKey; + use stela_formats::payload::AeaKey; let pem = "-----BEGIN PRIVATE KEY-----\nMIGHA==\n-----END PRIVATE KEY-----\n"; let url = "https://wkms-public.apple.com/fcs-keys/mIR-wHh7FG0="; let key = AeaKey { @@ -1553,8 +1556,8 @@ mod tests { header_sha256: "a".repeat(64), url: url.into(), key_pem: pem.into(), - key_sha256: crate::sha256(pem.as_bytes()), - url_asset_sha256: Some(crate::sha256( + key_sha256: stela_formats::sha256(pem.as_bytes()), + url_asset_sha256: Some(stela_formats::sha256( &plist::encode_binary(&url_asset_reply(pem), Limits::default()).unwrap(), )), }; @@ -1590,7 +1593,7 @@ mod tests { header_sha256: "a".repeat(64), url: url.into(), key_pem: other.into(), - key_sha256: crate::sha256(other.as_bytes()), + key_sha256: stela_formats::sha256(other.as_bytes()), url_asset_sha256: Some("0".repeat(64)), }], ); @@ -1617,7 +1620,7 @@ mod tests { .is_err() ); staged - .insert("URLAsset", &args, &bytes, &crate::sha256(&bytes)) + .insert("URLAsset", &args, &bytes, &stela_formats::sha256(&bytes)) .unwrap(); assert_eq!(staged.get("URLAsset", &args).unwrap(), response); let mut changed = args.clone(); diff --git a/crates/stela-runtime/src/restore/asr.rs b/crates/stela-runtime/src/restore/asr.rs index 9210d06101..a2cd754bb8 100644 --- a/crates/stela-runtime/src/restore/asr.rs +++ b/crates/stela-runtime/src/restore/asr.rs @@ -7,10 +7,10 @@ use super::{ store::Store, stream::{ByteStream, Output, XmlStream}, }; -use crate::payload::ReadAt; use alloc::{collections::VecDeque, string::String, vec::Vec}; use core::task::Poll; use sha1::{Digest, Sha1}; +use stela_formats::payload::ReadAt; pub const PORT: u16 = 12345; pub const CHUNK_BYTES: usize = 128 * 1024; const SHA1_BYTES: usize = 20; diff --git a/crates/stela-runtime/src/restore/driver.rs b/crates/stela-runtime/src/restore/driver.rs index 28c7834dca..a5be8df8a1 100644 --- a/crates/stela-runtime/src/restore/driver.rs +++ b/crates/stela-runtime/src/restore/driver.rs @@ -10,9 +10,9 @@ use super::{ session::{Action, Job, PORT, Phase, Session}, stream::{ByteStream, Endian, Framed}, }; -use crate::payload::ReadAt; use alloc::{boxed::Box, format, vec::Vec}; use core::task::Poll; +use stela_formats::payload::ReadAt; /// Handles identify owned streams, including ones still connecting. A Pending /// open must not allocate a stream. A successful close releases the handle. @@ -374,7 +374,10 @@ mod tests { s.input.extend((body.len() as u32).to_be_bytes()); s.input.extend(body); } - fn setup() -> (Driver, Harness) { + fn setup() -> ( + Driver, + Harness, + ) { let d = Driver::new( Answers::new(fixture(b"payload", false)), Route::StelaFirmwareStudy, @@ -411,7 +414,10 @@ mod tests { ); (d, h) } - fn restoring(d: &mut Driver, h: &mut Harness) { + fn restoring( + d: &mut Driver, + h: &mut Harness, + ) { for _ in 0..100 { assert!(d.poll(h).is_pending()); } diff --git a/crates/stela-runtime/src/restore/session.rs b/crates/stela-runtime/src/restore/session.rs index 9d041fc242..7a151f2b96 100644 --- a/crates/stela-runtime/src/restore/session.rs +++ b/crates/stela-runtime/src/restore/session.rs @@ -10,9 +10,9 @@ use super::{ store::{MAX_READ_BYTES, Store}, stream::{ByteStream, Endian, Framed, Output}, }; -use crate::payload::ReadAt; use alloc::{boxed::Box, collections::BTreeMap, format, string::String, vec::Vec}; use core::task::Poll; +use stela_formats::payload::ReadAt; pub const PORT: u16 = 62078; pub const PROTOCOL: u64 = 15; const MAX_JOBS: usize = 16; @@ -656,19 +656,32 @@ mod tests { stream::tests::{Memory, receive}, }; use super::*; - fn ready() -> (Session, Answers) { + fn ready() -> ( + Session, + Answers, + ) { let (session, answers, _) = ready_with(fixture(b"payload", false)); (session, answers) } - type Fixture = super::super::store::Store; + type Fixture = super::super::store::Store; /// A session past StartRestore, and the StartRestore request it sent. - fn ready_with(store: Fixture) -> (Session, Answers, Value) { + fn ready_with( + store: Fixture, + ) -> ( + Session, + Answers, + Value, + ) { ready_with_fdr(store, None) } fn ready_with_fdr( store: Fixture, diagnostic: Option, - ) -> (Session, Answers, Value) { + ) -> ( + Session, + Answers, + Value, + ) { let mut s = Session::new(); let mut a = Answers::new(store); a.fdr_diagnostic = diagnostic; diff --git a/crates/stela-runtime/src/restore/source.rs b/crates/stela-runtime/src/restore/source.rs index 9859699f9c..fad3baed54 100644 --- a/crates/stela-runtime/src/restore/source.rs +++ b/crates/stela-runtime/src/restore/source.rs @@ -1,8 +1,8 @@ //! Exact archive extent within read-only host storage. Partition padding is //! excluded from ZIP end-record searches; no read can escape the extent. use super::{Error, Result}; -use crate::payload::ReadAt; use alloc::{format, string::String}; +use stela_formats::payload::ReadAt; pub struct Extent { reader: R, bytes: u64, diff --git a/crates/stela-runtime/src/restore/store.rs b/crates/stela-runtime/src/restore/store.rs index fafdf00663..16e253453d 100644 --- a/crates/stela-runtime/src/restore/store.rs +++ b/crates/stela-runtime/src/restore/store.rs @@ -22,10 +22,6 @@ use super::{ Error, Result, plist::{self, Limits, Value}, }; -use crate::payload::{ - MemberRead, PayloadManifest, Purpose, ReadAt, - zip::{Archive, Entry}, -}; use alloc::{ collections::BTreeMap, format, @@ -33,8 +29,13 @@ use alloc::{ vec::Vec, }; use sha2::{Digest, Sha256, Sha384}; +use { + stela_formats::payload::MemberRead, stela_formats::payload::PayloadManifest, + stela_formats::payload::Purpose, stela_formats::payload::ReadAt, + stela_formats::payload::zip::Archive, stela_formats::payload::zip::Entry, +}; -pub const BLOCK_BYTES: usize = crate::payload::HASH_BLOCK_BYTES as usize; +pub const BLOCK_BYTES: usize = stela_formats::payload::HASH_BLOCK_BYTES as usize; pub const MAX_READ_BYTES: usize = 1024 * 1024; const MAX_BLOCKS: usize = 1 << 20; const MAX_BUILD_MANIFEST_BYTES: usize = 64 * 1024 * 1024; @@ -107,7 +108,7 @@ pub struct Store { /// The most recently read member and its resumable inflate position, so /// reading a deflate member block by block inflates it once rather than /// replaying it from the start each block. - cursor: Option<(String, crate::payload::zip::Progress)>, + cursor: Option<(String, stela_formats::payload::zip::Progress)>, } fn payload(e: impl core::fmt::Display) -> Error { Error::Payload(e.to_string()) @@ -136,7 +137,7 @@ impl Store { archive .read_member_at(&mut reader, entry, 0, &mut bytes) .map_err(payload)?; - if crate::sha256(&bytes) != manifest.source.build_manifest_sha256 { + if stela_formats::sha256(&bytes) != manifest.source.build_manifest_sha256 { return Err(Error::Invalid("BuildManifest SHA-256")); } // A universal BuildManifest names every board. Only this board's @@ -270,7 +271,7 @@ impl Store { .block_hashes .as_ref() .ok_or(Error::Invalid("the payload names no block hashes"))?; - if crate::sha256(file) != blocks.sha256 { + if stela_formats::sha256(file) != blocks.sha256 { return Err(Error::Payload(format!( "{}: SHA-256 differs from the payload manifest", blocks.file @@ -540,16 +541,20 @@ impl Store { #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::payload::{ - IdentitySet, Member, - tests::{Memory, manifest}, - zip::tests::archive, + use { + stela_formats::payload::IdentitySet, stela_formats::payload::Member, + stela_formats::payload::test_support::Memory, + stela_formats::payload::test_support::manifest, + stela_formats::payload::zip::test_support::archive, }; pub(crate) fn fixture(data: &[u8], deflate: bool) -> Store { with_components(data, deflate, &[]) } /// Give a store's manifest AEA keys, for the staged-answer tests. - pub(crate) fn set_aea_keys(store: &mut Store, keys: Vec) { + pub(crate) fn set_aea_keys( + store: &mut Store, + keys: Vec, + ) { store.manifest.aea_keys = keys; } /// Set one Info field on the selected fixture identity. @@ -682,7 +687,7 @@ pub(crate) mod tests { .unwrap(); let (mut m, _) = manifest(); m.device_class = "testap".into(); - m.source.build_manifest_sha256 = crate::sha256(&build); + m.source.build_manifest_sha256 = stela_formats::sha256(&build); m.global_manifests.clear(); m.aea_keys.clear(); let mut files: Vec<(&str, &[u8])> = vec![("os.dmg", data)]; @@ -696,7 +701,7 @@ pub(crate) mod tests { .map(|(name, bytes)| Member { name: (*name).into(), bytes: bytes.len() as u64, - sha256: Some(crate::sha256(bytes)), + sha256: Some(stela_formats::sha256(bytes)), sha384: None, }) .collect(); @@ -719,10 +724,10 @@ pub(crate) mod tests { .flat_map(|block| Sha256::digest(block).to_vec()) .collect(); s.manifest.members[0].sha384 = Some(hex::encode(Sha384::digest(data))); - s.manifest.block_hashes = Some(crate::payload::BlockHashes { - file: crate::payload::BLOCK_HASHES_FILE.into(), - block_bytes: crate::payload::HASH_BLOCK_BYTES, - sha256: crate::sha256(&file), + s.manifest.block_hashes = Some(stela_formats::payload::BlockHashes { + file: stela_formats::payload::BLOCK_HASHES_FILE.into(), + block_bytes: stela_formats::payload::HASH_BLOCK_BYTES, + sha256: stela_formats::sha256(&file), }); s.manifest.validate().unwrap(); file @@ -743,7 +748,7 @@ pub(crate) mod tests { let mut s = fixture(&data, true); let mut file = precomputed(&mut s, &data); file[64] ^= 1; - s.manifest.block_hashes.as_mut().unwrap().sha256 = crate::sha256(&file); + s.manifest.block_hashes.as_mut().unwrap().sha256 = stela_formats::sha256(&file); s.adopt_block_hashes(&file).unwrap(); let error = s.prepare().unwrap_err().to_string(); assert!( @@ -793,7 +798,7 @@ pub(crate) mod tests { let mut s = fixture(&data, true); let mut file = precomputed(&mut s, &data); file[32] ^= 1; - s.manifest.block_hashes.as_mut().unwrap().sha256 = crate::sha256(&file); + s.manifest.block_hashes.as_mut().unwrap().sha256 = stela_formats::sha256(&file); s.set_verify(Verify::OnRead); s.adopt_block_hashes(&file).unwrap(); s.prepare().unwrap(); @@ -885,7 +890,7 @@ pub(crate) mod tests { fn a_remote_images_device_verified_member_passes_through_unhashed() { let data = b"bytes the device verifies"; let mut s = fixture(data, true); - s.manifest.layout = crate::payload::Layout::Remote { + s.manifest.layout = stela_formats::payload::Layout::Remote { url: "http://updates-http.cdn-apple.com/a.ipsw".into(), etag: "\"e\"".into(), }; diff --git a/crates/stela-runtime/src/restore/ticket.rs b/crates/stela-runtime/src/restore/ticket.rs index e7ad24c0c3..99e15cbc76 100644 --- a/crates/stela-runtime/src/restore/ticket.rs +++ b/crates/stela-runtime/src/restore/ticket.rs @@ -309,30 +309,30 @@ impl Ticket { if Sha384::digest(&*im4p).as_slice() == digest { return Ok(()); } - let original = - crate::img4::payload_type(im4p).map_err(|_| Error::Invalid("IM4P payload type"))?; + let original = stela_formats::img4::payload_type(im4p) + .map_err(|_| Error::Invalid("IM4P payload type"))?; for tag in self.tags_with(digest) { - crate::img4::set_payload_type(im4p, tag) + stela_formats::img4::set_payload_type(im4p, tag) .map_err(|_| Error::Invalid("IM4P payload type"))?; if Sha384::digest(&*im4p).as_slice() == digest { return Ok(()); } } - crate::img4::set_payload_type(im4p, original) + stela_formats::img4::set_payload_type(im4p, original) .map_err(|_| Error::Invalid("IM4P payload type"))?; Err(Error::Invalid( "the ticket does not cover the exact component digest", )) } pub fn wrap(&self, source: &[u8], manifest_digest: &[u8]) -> Result> { - let parts = crate::img4::parse(source) + let parts = stela_formats::img4::parse(source) .map_err(|_| Error::Invalid("personalized object needs original IM4P"))?; if parts.manifest.is_some() || parts.restore_info.is_some() { return Err(Error::Invalid( "refuse replacing existing IMG4 manifest/restore info", )); } - let tag = crate::img4::payload_type(parts.payload) + let tag = stela_formats::img4::payload_type(parts.payload) .map_err(|_| Error::Invalid("IM4P payload type"))?; let digest = Sha384::digest(parts.payload); if digest.as_slice() != manifest_digest || !self.covers(tag, manifest_digest) { @@ -492,7 +492,7 @@ pub(crate) mod tests { let g = Ticket::global(manifest(&p), store.identity()).unwrap(); let hash = Sha384::digest(&p); let wrapped = g.wrap(&p, &hash).unwrap(); - let parts = crate::img4::parse(&wrapped).unwrap(); + let parts = stela_formats::img4::parse(&wrapped).unwrap(); assert_eq!(parts.payload, p); assert_eq!(parts.manifest, Some(g.bytes())); assert!(g.wrap(&p, &[0; 48]).is_err()); @@ -517,14 +517,14 @@ pub(crate) mod tests { .concat(), ); let mut rdtr = file.clone(); - crate::img4::set_payload_type(&mut rdtr, *b"rdtr").unwrap(); + stela_formats::img4::set_payload_type(&mut rdtr, *b"rdtr").unwrap(); let digest = Sha384::digest(&rdtr); let g = Ticket::global(ticket_for(b"rdtr", &rdtr, None), store.identity()).unwrap(); assert_eq!(g.tags_with(&digest), [*b"rdtr"]); let mut image = file.clone(); g.retype_covered(&mut image, &digest).unwrap(); assert_eq!(image, rdtr); - let parts = crate::img4::parse(&g.wrap(&image, &digest).unwrap()) + let parts = stela_formats::img4::parse(&g.wrap(&image, &digest).unwrap()) .unwrap() .payload .to_vec(); diff --git a/crates/stela-runtime/src/restore/tss.rs b/crates/stela-runtime/src/restore/tss.rs index b697e2b42f..f3dba6d40c 100644 --- a/crates/stela-runtime/src/restore/tss.rs +++ b/crates/stela-runtime/src/restore/tss.rs @@ -763,7 +763,7 @@ mod tests { panic!() }; let policy = reply.required("Ap,LocalPolicy").unwrap().data().unwrap(); - let parts = crate::img4::parse(policy).unwrap(); + let parts = stela_formats::img4::parse(policy).unwrap(); assert_eq!(parts.payload, LOCAL_POLICY); assert!(parts.manifest.is_some()); answers.signer = Some(Signer { diff --git a/crates/stela-runtime/src/scalable/block.rs b/crates/stela-runtime/src/scalable/block.rs index 0b8e8b053b..8c8fd2a0f2 100644 --- a/crates/stela-runtime/src/scalable/block.rs +++ b/crates/stela-runtime/src/scalable/block.rs @@ -6,7 +6,6 @@ use alloc::rc::Rc; use alloc::{boxed::Box, string::String}; use core::marker::PhantomData; -use crate::sha256; use anyhow::{Context, Result, ensure}; use stela_compiler::{ GuestAddress, Options, TargetCpu, @@ -14,6 +13,7 @@ use stela_compiler::{ context::ExecutionContext, scalable_context::CONTEXT_WRAPPER_BYTES, }; +use stela_formats::sha256; pub use crate::floating::scalable::CompletionError; use crate::{ diff --git a/crates/stela-runtime/src/scalable/leaf.rs b/crates/stela-runtime/src/scalable/leaf.rs index d884582508..5ff433731e 100644 --- a/crates/stela-runtime/src/scalable/leaf.rs +++ b/crates/stela-runtime/src/scalable/leaf.rs @@ -4,7 +4,6 @@ use alloc::rc::Rc; use alloc::{boxed::Box, string::String}; use core::marker::PhantomData; -use crate::sha256; use anyhow::{Context, Result, ensure}; use stela_compiler::{ GuestAddress, GuestState, Options, TargetCpu, @@ -21,6 +20,7 @@ use stela_compiler::{ }, scalable_context::ScalableProfile, }; +use stela_formats::sha256; use super::{ScalableState, context::ContextLoan}; use crate::{ diff --git a/crates/stela-runtime/src/system/identification_snapshot.rs b/crates/stela-runtime/src/system/identification_snapshot.rs index 618adbf79e..eda171a7fa 100644 --- a/crates/stela-runtime/src/system/identification_snapshot.rs +++ b/crates/stela-runtime/src/system/identification_snapshot.rs @@ -190,7 +190,7 @@ impl Snapshot { input.extend(value.to_le_bytes()); } } - let input_sha256 = crate::sha256(&input); + let input_sha256 = stela_formats::sha256(&input); Ok(Self { values, provenance: Provenance { @@ -234,7 +234,7 @@ impl Snapshot { u64::from_le_bytes(input[offset..end].try_into().expect("checked u64 readback")); insert(&mut values, register, value)?; } - let input_sha256 = crate::sha256(&input); + let input_sha256 = stela_formats::sha256(&input); Ok(Self { values, provenance: Provenance { @@ -425,7 +425,10 @@ mod tests { assert_eq!(snapshot.read(Register::IdAa64Isar2El1), Ok(u64::MAX)); assert_eq!(snapshot.provenance().origin(), Origin::CapturedHardware); assert_eq!(snapshot.provenance().input(), input.as_ref()); - assert_eq!(snapshot.provenance().input_sha256(), crate::sha256(&input)); + assert_eq!( + snapshot.provenance().input_sha256(), + stela_formats::sha256(&input) + ); assert_eq!(snapshot.provenance().captured_fields(), fields); assert!(Arc::ptr_eq(&input, &snapshot.provenance.input)); assert!(matches!( diff --git a/crates/stela-runtime/src/translations/pack.rs b/crates/stela-runtime/src/translations/pack.rs index 0216dd10fc..f1f64e52e0 100644 --- a/crates/stela-runtime/src/translations/pack.rs +++ b/crates/stela-runtime/src/translations/pack.rs @@ -279,7 +279,7 @@ const TRANSFER_BYTES: usize = 1 << 20; #[cfg(target_arch = "x86_64")] pub fn write_in_place( device: &mut dyn stela_drivers::block::BlockDevice, - extents: &[crate::payload::pieces::Extent], + extents: &[stela_formats::payload::pieces::Extent], layout: &Layout, ) -> Result<(), WriteError> { let block = u64::from(device.identity().block_size); @@ -808,8 +808,8 @@ mod tests { #[test] fn a_pack_is_written_over_its_files_extents_and_never_past_them() { - use crate::payload::pieces::Extent; use stela_drivers::block::RamDisk; + use stela_formats::payload::pieces::Extent; const BLOCK: u32 = 512; let translator = Digest::of(b"translator"); let records: Vec<(Digest, Piece)> = (0u8..40) diff --git a/crates/stela-runtime/tests/context_block_abi_refusal.rs b/crates/stela-runtime/tests/context_block_abi_refusal.rs index 4ea0a36d09..e227819d01 100644 --- a/crates/stela-runtime/tests/context_block_abi_refusal.rs +++ b/crates/stela-runtime/tests/context_block_abi_refusal.rs @@ -11,7 +11,7 @@ use stela_runtime::{ dispatch::LeafDispatcher, prepare_block_for_target, prepare_leaf_for_target, }; -use stela_runtime::{sha256, write_json}; +use {stela_formats::sha256, stela_runtime::write_json}; const BASE: GuestAddress = GuestAddress(0x1000); const NOP: u32 = 0xd503_201f; diff --git a/crates/stela-runtime/tests/pmgr_handoff_source.rs b/crates/stela-runtime/tests/pmgr_handoff_source.rs index 4c4a854b6b..5accd79e6d 100644 --- a/crates/stela-runtime/tests/pmgr_handoff_source.rs +++ b/crates/stela-runtime/tests/pmgr_handoff_source.rs @@ -38,7 +38,7 @@ fn original_physical_ps() -> std::collections::BTreeSet { // The restore DT's /chosen chip-id is unprovisioned (zero), so do not // patch it or mount a fabricated board to inspect its original records. // Replay the pinned v1 placement fields only, using the public ADT reader. - let root = stela_runtime::machine::adt::Node::root(&adt).unwrap(); + let root = stela_contracts::adt::Node::root(&adt).unwrap(); let io = root.child("arm-io").unwrap(); let pmgr = io.child("pmgr").unwrap(); assert!(pmgr.property("ps-groups").is_none()); diff --git a/crates/stela-runtime/tests/pmgr_llb_execution.rs b/crates/stela-runtime/tests/pmgr_llb_execution.rs index d4cf49897d..b9b29273f8 100644 --- a/crates/stela-runtime/tests/pmgr_llb_execution.rs +++ b/crates/stela-runtime/tests/pmgr_llb_execution.rs @@ -5,16 +5,17 @@ use sha2::{Digest, Sha256}; use std::{cell::RefCell, collections::VecDeque, io::Write as _, rc::Rc}; use stela_compiler::{GuestState, TargetCpu, aarch64::system::registers::Encoding}; -use stela_runtime::{ - hosted::host::NativeRunner, - machine::{ - Chip, Cpu, CpuProfile, DeviceError, Devices, FaultCause, Host, InstallError, Lines, - Machine, NativeCode, NativeExit, Regime, Stop, - exception::Pstate, - identification::{self, Speculation}, - mmu, - registers::encodings::MPIDR_EL1, - }, +use { + stela_contracts::Chip, stela_runtime::hosted::host::NativeRunner, stela_runtime::machine::Cpu, + stela_runtime::machine::CpuProfile, stela_runtime::machine::DeviceError, + stela_runtime::machine::Devices, stela_runtime::machine::FaultCause, + stela_runtime::machine::Host, stela_runtime::machine::InstallError, + stela_runtime::machine::Lines, stela_runtime::machine::Machine, + stela_runtime::machine::NativeCode, stela_runtime::machine::NativeExit, + stela_runtime::machine::Regime, stela_runtime::machine::Stop, + stela_runtime::machine::exception::Pstate, stela_runtime::machine::identification, + stela_runtime::machine::identification::Speculation, stela_runtime::machine::mmu, + stela_runtime::machine::registers::encodings::MPIDR_EL1, }; const BASE: u64 = 0x1fc050000; diff --git a/crates/stela-runtime/tests/pmgr_m1_handoff_source.rs b/crates/stela-runtime/tests/pmgr_m1_handoff_source.rs index 174209bb3a..b06955128c 100644 --- a/crates/stela-runtime/tests/pmgr_m1_handoff_source.rs +++ b/crates/stela-runtime/tests/pmgr_m1_handoff_source.rs @@ -4,7 +4,7 @@ use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; -use stela_runtime::machine::adt::Node; +use stela_contracts::adt::Node; fn original(variable: &str, digest: &str) -> Vec { let bytes = diff --git a/crates/stela-runtime/tests/pointer_authentication/memory.rs b/crates/stela-runtime/tests/pointer_authentication/memory.rs index af6c689ac8..17c214e897 100644 --- a/crates/stela-runtime/tests/pointer_authentication/memory.rs +++ b/crates/stela-runtime/tests/pointer_authentication/memory.rs @@ -12,15 +12,18 @@ use stela_compiler::{ block::{BlockProfile, Features}, context::memory::MemoryStatus, }; -use stela_runtime::{ - blocks::{BlockRuntime, StopReason, ThreadState}, - memory::{ - backing::{AccessPermissions, MemoryBacking, MemoryView}, - domain::{MappingAttributes, MemoryDomain, MemorySystem}, - policy::{LowerAddressProfile, MemoryControls, TagCheckFaultMode}, - tags::{AllocationTag, TAG_GRANULE_BYTES}, - }, - pauth::{Context, Key, Keys, Version}, +use { + stela_contracts::pauth::Key, stela_runtime::blocks::BlockRuntime, + stela_runtime::blocks::StopReason, stela_runtime::blocks::ThreadState, + stela_runtime::memory::backing::AccessPermissions, + stela_runtime::memory::backing::MemoryBacking, stela_runtime::memory::backing::MemoryView, + stela_runtime::memory::domain::MappingAttributes, stela_runtime::memory::domain::MemoryDomain, + stela_runtime::memory::domain::MemorySystem, + stela_runtime::memory::policy::LowerAddressProfile, + stela_runtime::memory::policy::MemoryControls, + stela_runtime::memory::policy::TagCheckFaultMode, stela_runtime::memory::tags::AllocationTag, + stela_runtime::memory::tags::TAG_GRANULE_BYTES, stela_runtime::pauth::Context, + stela_runtime::pauth::Keys, stela_runtime::pauth::Version, }; const ADDRESS_SPACE: u64 = 73; diff --git a/crates/stela-runtime/tests/pointer_authentication/modern.rs b/crates/stela-runtime/tests/pointer_authentication/modern.rs index 5d2a5cbab7..ce5e4de48f 100644 --- a/crates/stela-runtime/tests/pointer_authentication/modern.rs +++ b/crates/stela-runtime/tests/pointer_authentication/modern.rs @@ -6,9 +6,10 @@ use stela_compiler::{ GuestAddress, GuestState, block::{BlockProfile, Features}, }; -use stela_runtime::{ - blocks::{BlockRuntime, StopReason, ThreadState}, - pauth::{Context, Key, Keys, Version}, +use { + stela_contracts::pauth::Key, stela_runtime::blocks::BlockRuntime, + stela_runtime::blocks::StopReason, stela_runtime::blocks::ThreadState, + stela_runtime::pauth::Context, stela_runtime::pauth::Keys, stela_runtime::pauth::Version, }; const ADDRESS_SPACE: u64 = 73; diff --git a/crates/stela-runtime/tests/synchronous_traps.rs b/crates/stela-runtime/tests/synchronous_traps.rs index fe94d60c88..5ba7e46285 100644 --- a/crates/stela-runtime/tests/synchronous_traps.rs +++ b/crates/stela-runtime/tests/synchronous_traps.rs @@ -149,7 +149,7 @@ fn traps_report_the_same_record_through_cold_hot_and_disk_aot_paths() -> Result< assert_eq!(manifest.source_map.len(), 2); assert_eq!( manifest.identity.source_sha256, - stela_runtime::sha256(&words(&program[..2])) + stela_formats::sha256(&words(&program[..2])) ); } drop(first); diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 15df2d9ab9..2578474cd4 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -6,6 +6,8 @@ license.workspace = true publish = false [dependencies] +stela-contracts = { path = "../crates/stela-contracts", default-features = false } +stela-formats = { path = "../crates/stela-formats", default-features = false } anyhow.workspace = true clap.workspace = true serde.workspace = true diff --git a/xtask/src/bench.rs b/xtask/src/bench.rs index f7bfbbf51c..b6c025993c 100644 --- a/xtask/src/bench.rs +++ b/xtask/src/bench.rs @@ -321,7 +321,7 @@ impl Bench { "symbol": workload.symbol, "origin": origin, "code": hex(&code), - "code_sha256": stela_runtime::sha256(&code), + "code_sha256": stela_formats::sha256(&code), })); } let path = work.join("fixtures.json"); diff --git a/xtask/src/bench/engines.rs b/xtask/src/bench/engines.rs index c4f8b9b139..e19228549c 100644 --- a/xtask/src/bench/engines.rs +++ b/xtask/src/bench/engines.rs @@ -16,7 +16,10 @@ use stela_runtime::blocks::{BlockRuntime, StopReason, ThreadState}; #[cfg(all(target_os = "macos", target_arch = "x86_64"))] use stela_runtime::hosted::{hardware::Hardware, host::ProcessHost, pe, tables::Tables}; #[cfg(all(target_os = "macos", target_arch = "x86_64"))] -use stela_runtime::machine::{Chip, Machine, NoDevices, Stop}; +use { + stela_contracts::Chip, stela_runtime::machine::Machine, stela_runtime::machine::NoDevices, + stela_runtime::machine::Stop, +}; /// One prepared function in one engine. pub(super) trait Runner { @@ -116,11 +119,11 @@ fn refused(error: impl core::fmt::Debug) -> anyhow::Error { pub(super) fn digest(blocks: &[NativeBlock]) -> (usize, String) { let digests: String = blocks .iter() - .map(|block| stela_runtime::sha256(&block.code)) + .map(|block| stela_formats::sha256(&block.code)) .collect(); ( blocks.iter().map(|block| block.code.len()).sum(), - stela_runtime::sha256(digests.as_bytes()), + stela_formats::sha256(digests.as_bytes()), ) } @@ -259,7 +262,7 @@ impl Runner for Blocks { .collect(); Some(( manifests.iter().map(|manifest| manifest.native_bytes).sum(), - stela_runtime::sha256(digests.as_bytes()), + stela_formats::sha256(digests.as_bytes()), )) } } diff --git a/xtask/src/bench/fixtures.rs b/xtask/src/bench/fixtures.rs index e29f762d4b..df15c6598d 100644 --- a/xtask/src/bench/fixtures.rs +++ b/xtask/src/bench/fixtures.rs @@ -421,5 +421,5 @@ pub(super) fn state_digest(state: &GuestState) -> String { bytes.extend(value.to_le_bytes()); } bytes.extend(state.nzcv.to_le_bytes()); - stela_runtime::sha256(&bytes) + stela_formats::sha256(&bytes) } diff --git a/xtask/src/bench/hosted.rs b/xtask/src/bench/hosted.rs index 0d0fa744c5..b778c2ec0f 100644 --- a/xtask/src/bench/hosted.rs +++ b/xtask/src/bench/hosted.rs @@ -350,11 +350,11 @@ impl HostedBench { "stela": stelas.iter().map(|(build, path)| json!({ "build": build, "path": path, - "sha256": std::fs::read(path).map(|bytes| stela_runtime::sha256(&bytes)).ok(), + "sha256": std::fs::read(path).map(|bytes| stela_formats::sha256(&bytes)).ok(), })).collect::>(), "programs": programs.iter().map(|program| json!({ "name": program.name, - "source_sha256": stela_runtime::sha256(program.source.as_bytes()), + "source_sha256": stela_formats::sha256(program.source.as_bytes()), })).collect::>(), "checksums": checksums, "summary": summary, @@ -403,8 +403,8 @@ impl HostedBench { &work.join("command.json"), &json!({ "command": format!("{command:?}"), "binary": binary, - "binary_sha256": stela_runtime::sha256(&std::fs::read(binary)?), - "stela_sha256": variant.stela.as_ref().map(std::fs::read).transpose()?.map(|bytes| stela_runtime::sha256(&bytes)), + "binary_sha256": stela_formats::sha256(&std::fs::read(binary)?), + "stela_sha256": variant.stela.as_ref().map(std::fs::read).transpose()?.map(|bytes| stela_formats::sha256(&bytes)), }), )?; let start = Instant::now(); @@ -420,8 +420,8 @@ impl HostedBench { "status": status.as_ref().map(ToString::to_string), "success": status.as_ref().is_some_and(std::process::ExitStatus::success), "timeout": status.is_none(), "wall_seconds": wall, - "stdout_sha256": stela_runtime::sha256(output.as_bytes()), - "stderr_sha256": stela_runtime::sha256(&std::fs::read(&stderr)?), + "stdout_sha256": stela_formats::sha256(output.as_bytes()), + "stderr_sha256": stela_formats::sha256(&std::fs::read(&stderr)?), }), )?; let Some(status) = status else { @@ -548,9 +548,9 @@ fn build_program( &directory.join(format!("build-{}.json", variant.arch)), &json!({ "command": format!("{command:?}"), "status": status.to_string(), - "source_sha256": stela_runtime::sha256(program.source.as_bytes()), - "header_sha256": stela_runtime::sha256(HEADER.1.as_bytes()), - "binary_sha256": if status.success() { Some(stela_runtime::sha256(&std::fs::read(&binary)?)) } else { None }, + "source_sha256": stela_formats::sha256(program.source.as_bytes()), + "header_sha256": stela_formats::sha256(HEADER.1.as_bytes()), + "binary_sha256": if status.success() { Some(stela_formats::sha256(&std::fs::read(&binary)?)) } else { None }, }), )?; ensure!( diff --git a/xtask/src/boot.rs b/xtask/src/boot.rs index 8476bbba08..e9492147a1 100644 --- a/xtask/src/boot.rs +++ b/xtask/src/boot.rs @@ -31,8 +31,10 @@ use std::{ process::{Command as Process, ExitCode, Stdio}, time::{Duration, Instant}, }; -use stela_runtime::payload::{ - PayloadError, PayloadSource, ReadAt, copy_verified, gpt, staging::StagedSource, +use { + stela_formats::payload::PayloadError, stela_formats::payload::PayloadSource, + stela_formats::payload::ReadAt, stela_formats::payload::copy_verified, + stela_formats::payload::gpt, stela_formats::payload::staging::StagedSource, }; mod audio_check; diff --git a/xtask/src/boot/audio_check.rs b/xtask/src/boot/audio_check.rs index e36dc696bd..e16c8c4b7d 100644 --- a/xtask/src/boot/audio_check.rs +++ b/xtask/src/boot/audio_check.rs @@ -11,7 +11,7 @@ use std::{ thread, time::{Duration, Instant}, }; -use stela_runtime::sha256; +use stela_formats::sha256; const RING_BYTES: usize = 16_384; const MIN_WRAPS: u64 = 5; diff --git a/xtask/src/boot/disks.rs b/xtask/src/boot/disks.rs index c519ba7ed4..950ac03f69 100644 --- a/xtask/src/boot/disks.rs +++ b/xtask/src/boot/disks.rs @@ -9,12 +9,9 @@ use std::{ path::{Path, PathBuf}, process::Command, }; -use stela_runtime::{ - pc::{ - gpt::{self, Guid, Partition}, - storage::pattern, - }, - sha256, +use { + stela_formats::sha256, stela_runtime::pc::gpt, stela_runtime::pc::gpt::Guid, + stela_runtime::pc::gpt::Partition, stela_runtime::pc::storage::pattern, }; const BLOCK: u64 = 512; diff --git a/xtask/src/boot/host_firmware.rs b/xtask/src/boot/host_firmware.rs index 3f1ff90486..9c9d9341cd 100644 --- a/xtask/src/boot/host_firmware.rs +++ b/xtask/src/boot/host_firmware.rs @@ -18,7 +18,7 @@ fn expected(data: &[u8]) -> Result> { for phase in ["before-ebs", "after-ebs"] { records.push(json!({"kind":"manifest", "phase":phase, "images":manifest.images.len(), "bytes":manifest.total_bytes(), - "sha256":stela_runtime::sha256(data)})); + "sha256":stela_formats::sha256(data)})); for (index, image) in manifest.images.iter().enumerate() { let target = &image.target; let source = &image.provenance; diff --git a/xtask/src/boot/network_check.rs b/xtask/src/boot/network_check.rs index 65c4e1b3c4..a23e4c74ff 100644 --- a/xtask/src/boot/network_check.rs +++ b/xtask/src/boot/network_check.rs @@ -26,7 +26,7 @@ impl Fixture { let body: Vec = (0..BODY_BYTES) .map(|index| index.wrapping_mul(73).wrapping_add(index >> 8) as u8) .collect(); - let sha256 = stela_runtime::sha256(&body); + let sha256 = stela_formats::sha256(&body); thread::spawn(move || { let result = server .accept() @@ -154,7 +154,7 @@ mod tests { assert!(headers.contains(&format!("\r\nContent-Length: {BODY_BYTES}\r\n"))); let body = &response[split..]; assert_eq!(body.len(), BODY_BYTES); - assert_eq!(stela_runtime::sha256(body), fixture.sha256); + assert_eq!(stela_formats::sha256(body), fixture.sha256); assert_eq!( fixture.sha256, "1f1747c499dd2b60e4aad488fd4cb9ba0d4df3f9be8f91827f2d6bb90f94384e" diff --git a/xtask/src/boot/preboot.rs b/xtask/src/boot/preboot.rs index e5b194975f..4eeffdb238 100644 --- a/xtask/src/boot/preboot.rs +++ b/xtask/src/boot/preboot.rs @@ -17,9 +17,9 @@ use stela_loader::{ boot_bundle::{Manifest, Options}, installed, }; -use stela_runtime::{ - apfs::{self, Container}, - payload::{ReadAt, gpt}, +use { + stela_formats::apfs, stela_formats::apfs::Container, stela_formats::payload::ReadAt, + stela_formats::payload::gpt, }; /// The serial the NVMe disk reports, which `stela.cfg` names. diff --git a/xtask/src/boot/storage.rs b/xtask/src/boot/storage.rs index 48ec413daa..ca316cca3b 100755 --- a/xtask/src/boot/storage.rs +++ b/xtask/src/boot/storage.rs @@ -157,7 +157,7 @@ pub(super) fn write_volume( .with_context(|| format!("restore manifest {}", manifest.display()))?; // The block hashes the manifest names go beside it, so the // restore host needs no scan of the payload. - let parsed = stela_runtime::payload::PayloadManifest::parse(&fs::read(manifest)?) + let parsed = stela_formats::payload::PayloadManifest::parse(&fs::read(manifest)?) .map_err(|error| anyhow::anyhow!("{}: {error}", manifest.display()))?; if let Some(blocks) = &parsed.block_hashes { let from = manifest.with_file_name(&blocks.file); diff --git a/xtask/src/gpu/macos/library_test.rs b/xtask/src/gpu/macos/library_test.rs index c0463b59e0..87390cffd0 100644 --- a/xtask/src/gpu/macos/library_test.rs +++ b/xtask/src/gpu/macos/library_test.rs @@ -21,7 +21,7 @@ use std::{ process::{Command, Stdio}, time::Duration, }; -use stela_runtime::sha256; +use stela_formats::sha256; #[derive(Debug)] struct Inconclusive(String); diff --git a/xtask/src/gpu/mesa.rs b/xtask/src/gpu/mesa.rs index 44731c71c0..2513067df3 100644 --- a/xtask/src/gpu/mesa.rs +++ b/xtask/src/gpu/mesa.rs @@ -670,7 +670,7 @@ mod tests { assert_eq!(fs::read(snapshot).unwrap(), bytes); assert_eq!( records[0]["snapshot"]["sha256"], - stela_runtime::sha256(bytes) + stela_formats::sha256(bytes) ); assert!( snapshot_air_inputs(std::slice::from_ref(&input), temp.path(), "air-input").is_err() diff --git a/xtask/src/restore_dry_run.rs b/xtask/src/restore_dry_run.rs index 85cf4d1a13..f5a609ae85 100644 --- a/xtask/src/restore_dry_run.rs +++ b/xtask/src/restore_dry_run.rs @@ -25,17 +25,13 @@ use std::{ task::Poll, time::{Instant, SystemTime, UNIX_EPOCH}, }; -use stela_runtime::{ - payload::{PayloadManifest, Purpose, ReadAt}, - restore::{ - Error, - answers::Answers, - driver::Driver, - route::Route, - source::Extent, - store::{Store, Verify}, - tss::Signer, - }, +use { + stela_formats::payload::PayloadManifest, stela_formats::payload::Purpose, + stela_formats::payload::ReadAt, stela_runtime::restore::Error, + stela_runtime::restore::answers::Answers, stela_runtime::restore::driver::Driver, + stela_runtime::restore::route::Route, stela_runtime::restore::source::Extent, + stela_runtime::restore::store::Store, stela_runtime::restore::store::Verify, + stela_runtime::restore::tss::Signer, }; mod context; diff --git a/xtask/src/restore_dry_run/context.rs b/xtask/src/restore_dry_run/context.rs index 7aa65ff366..bc83473df7 100644 --- a/xtask/src/restore_dry_run/context.rs +++ b/xtask/src/restore_dry_run/context.rs @@ -15,7 +15,7 @@ use std::{ rc::Rc, }; use stela_cli::restore::archive; -use stela_runtime::{payload::PayloadManifest, restore::tss::Nonces}; +use {stela_formats::payload::PayloadManifest, stela_runtime::restore::tss::Nonces}; /// Members read whole for comparison; larger ones are only streamed. pub const SMALL: u64 = 96 << 20; diff --git a/xtask/src/restore_dry_run/image4.rs b/xtask/src/restore_dry_run/image4.rs index 68370bfa96..b920d55dbe 100644 --- a/xtask/src/restore_dry_run/image4.rs +++ b/xtask/src/restore_dry_run/image4.rs @@ -1,5 +1,5 @@ //! Image4 as restored and the guest's Image4 validator read it, written -//! independently of `stela_runtime::img4` and `restore::ticket` so the dry +//! independently of `stela_formats::img4` and `restore::ticket` so the dry //! run does not check the host with the host's own parser. //! //! An `IMG4` is `SEQUENCE { IA5String "IMG4", IM4P, [0] IM4M, [1] IM4R? }`. diff --git a/xtask/src/sysregs.rs b/xtask/src/sysregs.rs index f160967982..601c8464ac 100644 --- a/xtask/src/sysregs.rs +++ b/xtask/src/sysregs.rs @@ -616,6 +616,14 @@ impl Sysregs { .status()?; ensure!(status.success(), "rustfmt failed on {}", access::GENERATED); println!("wrote {}", access::GENERATED); + let features = root().join(access::FEATURES); + fs::write(&features, access::generate_features(&profiles)?)?; + let status = Command::new("rustfmt") + .args(["--edition", "2024"]) + .arg(&features) + .status()?; + ensure!(status.success(), "rustfmt failed on {}", access::FEATURES); + println!("wrote {}", access::FEATURES); Ok(()) } } @@ -630,7 +638,7 @@ fn extract( ) -> Result<()> { let data = fs::read(archive).with_context(|| format!("cannot read {}", archive.display()))?; ensure!( - data.len() == bytes && stela_runtime::sha256(&data) == sha256, + data.len() == bytes && stela_formats::sha256(&data) == sha256, "{} is not the pinned {RELEASE} download ({uri})", archive.display() ); diff --git a/xtask/src/sysregs/access.rs b/xtask/src/sysregs/access.rs index 5b71e48d1d..1d08d261e7 100644 --- a/xtask/src/sysregs/access.rs +++ b/xtask/src/sysregs/access.rs @@ -17,6 +17,7 @@ use std::{ }; pub const GENERATED: &str = "crates/stela-runtime/src/machine/system/generated.rs"; +pub const FEATURES: &str = "crates/stela-contracts/src/cpu_features.rs"; /// A register of the profile: instances and, per chip, the bits that are /// RES0 or RES1 in every layout the chip allows. @@ -561,7 +562,7 @@ pub fn generate( //! {}).\n\ //! Regenerate with `cargo xtask sysregs --aarchmrs DIR`, `DIR` holding both\n\ //! downloads. Do not edit.\n\ - #![allow(\n clippy::all,\n clippy::pedantic,\n unused_parens,\n unused_variables,\n unreachable_code,\n non_camel_case_types\n)]\n\ + #![allow(\n clippy::all,\n clippy::pedantic,\n unused_parens,\n unused_variables,\n unreachable_code,\n non_camel_case_types,\n reason = \"Arm-derived output preserves vendor names, folded branches and helper shapes\"\n)]\n\ use super::{{\n Accessor, Broadcast, CacheOp, CacheScope, CacheType, Chip, Context, Effect, ErrorRecord, Limit, Operation,\n \ Pstate, Regime, Restrict, Stage, AtAccess, Tlbi, TlbiAttr, TlbiKind, TlbiLevel, WithheldLayout, helpers::*,\n}};\n", @@ -656,7 +657,7 @@ pub fn generate( )?; } writeln!(out, "];\n")?; - write_features(&mut out, profiles)?; + writeln!(out, "use stela_contracts::Feature;\n")?; writeln!( out, "pub static ACCESSORS: [Accessor; {}] = [", @@ -697,6 +698,15 @@ fn chip_variant(name: &str) -> String { .collect() } +/// Canonical CPU metadata, independent of the engine and generated accessors. +pub fn generate_features(profiles: &Profiles) -> Result { + let mut out = String::from( + "//! Generated Apple CPU feature profiles from Arm AARCHMRS 2026-06.\n//! Arm data: BSD-3-Clause, Copyright (c) 2010-2026 Arm Limited\n//! or its affiliates.\n//! Regenerate with `cargo xtask sysregs --aarchmrs DIR`.\n#![allow(non_camel_case_types, reason = \"feature names follow Arm AARCHMRS\")]\nuse crate::Chip;\n\n", + ); + write_features(&mut out, profiles)?; + Ok(out) +} + /// The chips in generation order, and the features only some of them have, /// each with the chips whose profile has it. fn write_features(out: &mut String, profiles: &Profiles) -> Result<()> { diff --git a/xtask/src/tools.rs b/xtask/src/tools.rs index ecb404b48e..8e6eca4fb0 100644 --- a/xtask/src/tools.rs +++ b/xtask/src/tools.rs @@ -10,7 +10,7 @@ use std::{ thread, time::{Duration, Instant}, }; -use stela_runtime::sha256; +use stela_formats::sha256; pub fn root() -> &'static Path { Path::new(env!("CARGO_MANIFEST_DIR"))