diff --git a/crates/stela-loader/tests/fixtures/bound-image-arm64.S b/crates/stela-loader/tests/fixtures/bound-image-arm64.S deleted file mode 100644 index 9ff41a6a3f..0000000000 --- a/crates/stela-loader/tests/fixtures/bound-image-arm64.S +++ /dev/null @@ -1,33 +0,0 @@ -// Own genuine dynamically linked entry fixture. DATA_CONST imports a function -// and data pointer from the companion dylib; the entry calls the resolved guest -// function with BLR and writes its result to a separate zero-tail BSS mapping. -.text -.p2align 2 -.globl _bound_entry -_bound_entry: - stp x29, x30, [sp, #-16]! - mov x29, sp - adrp x9, _bound_imports@PAGE - add x9, x9, _bound_imports@PAGEOFF - ldp x12, x13, [x9] - ldr x1, [x13] - add x0, x0, x1 - blr x12 - adrp x14, _bound_output@PAGE - add x14, x14, _bound_output@PAGEOFF - str x0, [x14] - ldp x29, x30, [sp], #16 - ret - -.section __DATA_CONST,__const -.p2align 3 -_bound_imports: - .quad _bound_function - .quad _bound_seed - -.data -.p2align 3 -_bound_data_marker: - .quad 0x123456789abcdef0 -.zerofill __DATA,__bss,_bound_padding,16384,3 -.zerofill __DATA,__bss,_bound_output,16384,3 diff --git a/crates/stela-loader/tests/fixtures/bound-library-arm64.S b/crates/stela-loader/tests/fixtures/bound-library-arm64.S deleted file mode 100644 index f9a16c0c68..0000000000 --- a/crates/stela-loader/tests/fixtures/bound-library-arm64.S +++ /dev/null @@ -1,27 +0,0 @@ -// Companion genuine MH_DYLIB. Only _bound_function and _bound_seed are exported. -// A chained rebase points at the dylib's own BSS; no imported symbols are used. -.text -.p2align 2 -.globl _bound_function -_bound_function: - adrp x9, _library_pointers@PAGE - add x9, x9, _library_pointers@PAGEOFF - ldr x10, [x9] - ldr x4, [x10] - str x0, [x10] - add x0, x0, #11 - str x0, [x10, #8] - ret - -.section __DATA_CONST,__const -.p2align 3 -_library_pointers: - .quad _library_output - -.data -.p2align 3 -.globl _bound_seed -_bound_seed: - .quad 0x9e3779b97f4a7c15 -.zerofill __DATA,__bss,_library_padding,16384,3 -.zerofill __DATA,__bss,_library_output,16384,3 diff --git a/crates/stela-loader/tests/fixtures/chained-image-arm64.S b/crates/stela-loader/tests/fixtures/chained-image-arm64.S deleted file mode 100644 index 6e20f5c91c..0000000000 --- a/crates/stela-loader/tests/fixtures/chained-image-arm64.S +++ /dev/null @@ -1,43 +0,0 @@ -// Own unchanged linker executable with three genuine chained rebases. -// X0 supplies an integer input; X30 supplies a dispatcher return boundary. -// The entry dereferences relocated data/BSS/function pointers and calls BLR. -// A normal FP/LR frame uses owned stack RAM; no imports, PAC or system calls. -.text -.p2align 2 -.globl _chained_entry -_chained_entry: - stp x29, x30, [sp, #-16]! - mov x29, sp - adrp x9, _chained_pointers@PAGE - add x9, x9, _chained_pointers@PAGEOFF - ldp x10, x11, [x9] - ldr x12, [x9, #16] - ldr x1, [x10] - ldr x4, [x11] - add x0, x0, x1 - blr x12 - ldp x29, x30, [sp], #16 - ret - -.p2align 2 -_chained_callee: - str x0, [x11] - add x0, x0, #7 - str x0, [x11, #8] - ret - -.section __DATA_CONST,__const -.p2align 3 -.globl _chained_pointers -_chained_pointers: - .quad _chained_seed - .quad _chained_output - .quad _chained_callee - -.data -.p2align 3 -.globl _chained_seed -_chained_seed: - .quad 0x9e3779b97f4a7c15 -.zerofill __DATA,__bss,_chained_padding,16384,3 -.zerofill __DATA,__bss,_chained_output,16384,3 diff --git a/crates/stela-loader/tests/fixtures/dependency-leaf-arm64.S b/crates/stela-loader/tests/fixtures/dependency-leaf-arm64.S deleted file mode 100644 index 6ae506b170..0000000000 --- a/crates/stela-loader/tests/fixtures/dependency-leaf-arm64.S +++ /dev/null @@ -1,25 +0,0 @@ -// Genuine leaf dylib with its own data/BSS mapping and chained rebase. -.text -.p2align 2 -.globl _leaf_function -_leaf_function: - adrp x9, _leaf_pointers@PAGE - add x9, x9, _leaf_pointers@PAGEOFF - ldr x10, [x9] - ldr x4, [x10] - str x0, [x10] - add x0, x0, #11 - str x0, [x10, #8] - ret - -.section __DATA_CONST,__const -.p2align 3 -_leaf_pointers: - .quad _leaf_output - -.data -.p2align 3 -_leaf_marker: - .quad 0x3141592653589793 -.zerofill __DATA,__bss,_leaf_padding,16384,3 -.zerofill __DATA,__bss,_leaf_output,16384,3 diff --git a/crates/stela-loader/tests/fixtures/dependency-middle-arm64.S b/crates/stela-loader/tests/fixtures/dependency-middle-arm64.S deleted file mode 100644 index 769ecb4275..0000000000 --- a/crates/stela-loader/tests/fixtures/dependency-middle-arm64.S +++ /dev/null @@ -1,32 +0,0 @@ -// Genuine middle dylib: main imports _bound_function/_bound_seed from this image. -// The function calls a leaf import through BLR, then stores the result and an -// adjusted result through a pointer rebased into its own zero-tail BSS. -.text -.p2align 2 -.globl _bound_function -_bound_function: - stp x29, x30, [sp, #-16]! - mov x29, sp - adrp x15, _middle_pointers@PAGE - add x15, x15, _middle_pointers@PAGEOFF - ldp x16, x17, [x15] - blr x16 - str x0, [x17] - add x0, x0, #13 - str x0, [x17, #8] - ldp x29, x30, [sp], #16 - ret - -.section __DATA_CONST,__const -.p2align 3 -_middle_pointers: - .quad _leaf_function - .quad _middle_output - -.data -.p2align 3 -.globl _bound_seed -_bound_seed: - .quad 0x9e3779b97f4a7c15 -.zerofill __DATA,__bss,_middle_padding,16384,3 -.zerofill __DATA,__bss,_middle_output,16384,3 diff --git a/crates/stela-loader/tests/fixtures/mapped-image-arm64.S b/crates/stela-loader/tests/fixtures/mapped-image-arm64.S deleted file mode 100644 index b5e1cabeee..0000000000 --- a/crates/stela-loader/tests/fixtures/mapped-image-arm64.S +++ /dev/null @@ -1,41 +0,0 @@ -// Own freestanding Mach-O entry fixture; this is not a macOS process ABI. -// X0 is a supplied input, X30 is a supplied dispatcher stop address. No -// imports, fixups or pointer authentication. A normal FP/LR frame uses owned -// guest stack RAM. Dirty GPRs and NZCV remain -// observable. ADR and ADRP use linked guest addresses without sliding. -.text -.p2align 2 -.globl _mapped_entry -_mapped_entry: - stp x29, x30, [sp, #-16]! - mov x29, sp - adr x8, Lcurrent -Lcurrent: - adrp x9, _mapped_seed@PAGE - add x9, x9, _mapped_seed@PAGEOFF - ldr x1, [x9] - add x0, x0, x1 - bl _mapped_callee - ldp x29, x30, [sp], #16 - ret - -.p2align 2 -_mapped_callee: - adrp x10, _mapped_output@PAGE - add x10, x10, _mapped_output@PAGEOFF - ldr x4, [x10] - str x0, [x10] - add x0, x0, #7 - str x0, [x10, #8] - ret - -.data -.p2align 3 -.globl _mapped_seed -_mapped_seed: - .quad 0x9e3779b97f4a7c15 -// Large zero-fill forces a segment tail beyond file-backed page padding. -// Put the observed output beyond the file-backed segment page, so LDR/STR -// actually exercise owned zero-fill RAM rather than zero padding in the file. -.zerofill __DATA,__bss,_mapped_padding,16384,3 -.zerofill __DATA,__bss,_mapped_output,16384,3 diff --git a/crates/stela-loader/tests/images.rs b/crates/stela-loader/tests/images.rs deleted file mode 100644 index ea21843115..0000000000 --- a/crates/stela-loader/tests/images.rs +++ /dev/null @@ -1,393 +0,0 @@ -//! Apple-linked fixture images load, bind and run through the loader. -//! -//! Each fixture is assembled and linked with the host's Apple toolchain, then -//! executed natively from an explicit entry ABI: X0 is an input and X30 a stop -//! address. Results are checked against each fixture's own arithmetic. -#![cfg(target_os = "macos")] - -use anyhow::{Context, Result, ensure}; -use object::{Object, ObjectSegment, ObjectSymbol}; -use std::{ - fs, - path::{Path, PathBuf}, - process::Command, -}; -use stela_compiler::{GuestAddress, GuestState}; -use stela_loader::{ - dependency_graph::{DiscoveryOptions, discover}, - linked_images::{ImageInput, LinkedImages}, - mapped_image::{MappedImage, StackSpec}, -}; -use stela_runtime::blocks::ThreadState; - -const SEED: u64 = 0x9e37_79b9_7f4a_7c15; -const INPUT: u64 = 0x0123_4567_89ab_cdef; -const STOP: u64 = 0xffff_0000; -const BLOCK_BUDGET: usize = 64; -const STACK_BYTES: u64 = 0x1_0000; -/// Tests share one process, so each loads its images in its own range. -const RANGE: u64 = 0x100_0000_0000; -const LIBRARY_STRIDE: u64 = 0x10_0000_0000; -const STACK_OFFSET: u64 = 0x80_0000_0000; -/// Each callee adds its own constant to the value it returns. -const CALLEE_ADDEND: u64 = 7; -const LIBRARY_ADDEND: u64 = 11; -const MIDDLE_ADDEND: u64 = 13; - -/// Assembles and links fixtures in a private directory. -struct Toolchain { - clang: PathBuf, - linker: PathBuf, - sdk: String, - work: tempfile::TempDir, -} - -fn xcrun(arguments: &[&str]) -> Result { - let output = Command::new("xcrun").args(arguments).output()?; - ensure!(output.status.success(), "xcrun {arguments:?} failed"); - Ok(String::from_utf8(output.stdout)?.trim().to_owned()) -} - -fn run(command: &mut Command) -> Result<()> { - let output = command.output()?; - ensure!( - output.status.success(), - "{command:?} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - Ok(()) -} - -impl Toolchain { - fn new() -> Result { - Ok(Self { - clang: xcrun(&["--find", "clang"])?.into(), - linker: xcrun(&["--find", "ld"])?.into(), - sdk: xcrun(&["--show-sdk-path"])?, - work: tempfile::tempdir()?, - }) - } - - fn path(&self, name: &str) -> PathBuf { - self.work.path().join(name) - } - - fn assemble(&self, fixture: &str) -> Result { - let source = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/fixtures") - .join(fixture); - let object = self.path(fixture).with_extension("o"); - run(Command::new(&self.clang) - .args(["-target", "arm64-apple-macos14", "-c"]) - .arg(source) - .arg("-o") - .arg(&object))?; - Ok(object) - } - - /// Link `inputs` into `output` with `options`, against libSystem. - fn link(&self, output: &Path, inputs: &[PathBuf], options: &[&str]) -> Result> { - if let Some(parent) = output.parent() { - fs::create_dir_all(parent)?; - } - run(Command::new(&self.linker) - .args([ - "-arch", - "arm64", - "-platform_version", - "macos", - "14.0", - "14.0", - ]) - .args(options) - .arg("-o") - .arg(output) - .args(inputs) - .args(["-syslibroot", &self.sdk, "-lSystem", "-no_adhoc_codesign"]))?; - Ok(fs::read(output)?) - } - - fn exports(&self, name: &str, symbols: &[&str]) -> Result { - let path = self.path(name); - fs::write(&path, symbols.join("\n") + "\n")?; - Ok(path.display().to_string()) - } -} - -/// The linked address of `name`, slid from the image's preferred base. -fn symbol(image: &[u8], name: &str, slide: u64) -> Result { - let file = object::File::parse(image)?; - let address = file - .symbols() - .find(|symbol| symbol.name() == Ok(name)) - .with_context(|| format!("missing symbol {name}"))? - .address(); - Ok(address.wrapping_add(slide)) -} - -/// The linked `__TEXT` address, from which a load base slides the image. -fn preferred_base(image: &[u8]) -> Result { - let file = object::File::parse(image)?; - let text = file - .segments() - .find(|segment| segment.name() == Ok(Some("__TEXT"))) - .context("missing __TEXT")?; - Ok(text.address()) -} - -/// The first image base of test `index`; libraries and the stack follow it. -fn base(index: u64) -> u64 { - (4 + index) * RANGE -} - -fn stack(index: u64) -> StackSpec { - StackSpec { - base: base(index) + STACK_OFFSET, - bytes: STACK_BYTES, - } -} - -fn entry_state(entry: u64, sp: u64) -> ThreadState { - let mut registers = GuestState { - sp, - ..GuestState::default() - }; - registers.x[0] = INPUT; - registers.x[30] = STOP; - ThreadState { - registers, - pc: GuestAddress(entry), - } -} - -fn quads(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<8>() - .0 - .iter() - .map(|quad| u64::from_le_bytes(*quad)) - .collect() -} - -fn input(data: Vec, load_base: u64) -> ImageInput { - ImageInput { - container_sha256: stela_formats::sha256(&data), - data, - slice_offset: 0, - load_base: Some(load_base), - } -} - -#[test] -fn mapped_image_runs_from_its_own_data_and_zero_fill() -> Result<()> { - let tools = Toolchain::new()?; - let object = tools.assemble("mapped-image-arm64.S")?; - let text = format!("{:#x}", base(0)); - let data = format!("{:#x}", base(0) + 0x4000); - let options = [ - "-e", - "_mapped_entry", - "-segaddr", - "__TEXT", - &text, - "-segaddr", - "__DATA", - &data, - "-no_uuid", - ]; - let image = tools.link(&tools.path("mapped"), &[object], &options)?; - let mut mapped = MappedImage::load(&image, tools.path("cache"), Some(stack(0)), None)?; - let sp = mapped.stack().context("stack")?.initial_sp; - let mut thread = entry_state(mapped.mapped_entry(), sp); - // SAFETY: the trusted fixture touches only its own mappings and stack. - unsafe { mapped.run(&mut thread, Some(GuestAddress(STOP)), BLOCK_BUDGET)? }; - let result = INPUT.wrapping_add(SEED); - assert_eq!(thread.pc, GuestAddress(STOP)); - assert_eq!(thread.registers.x[0], result + CALLEE_ADDEND); - assert_eq!(thread.registers.x[1], SEED); - assert_eq!(thread.registers.sp, sp); - let output = symbol(&image, "_mapped_output", 0)?; - assert_eq!( - quads(&mapped.read_snapshot(output, 16)?), - [result, result + CALLEE_ADDEND] - ); - Ok(()) -} - -#[test] -fn chained_rebases_follow_the_load_base() -> Result<()> { - let tools = Toolchain::new()?; - let object = tools.assemble("chained-image-arm64.S")?; - let image = tools.link( - &tools.path("chained"), - &[object], - &["-e", "_chained_entry", "-no_uuid"], - )?; - for index in [1, 2] { - let load_base = base(index); - let slide = load_base.wrapping_sub(preferred_base(&image)?); - let cache = tools.path(&format!("cache-{index}")); - let mut mapped = MappedImage::load(&image, cache, Some(stack(index)), Some(load_base))?; - let sp = mapped.stack().context("stack")?.initial_sp; - let mut thread = entry_state(mapped.mapped_entry(), sp); - // SAFETY: the trusted fixture touches only its own mappings and stack. - unsafe { mapped.run(&mut thread, Some(GuestAddress(STOP)), BLOCK_BUDGET)? }; - let pointers = symbol(&image, "_chained_pointers", slide)?; - let targets = ["_chained_seed", "_chained_output", "_chained_callee"] - .map(|name| symbol(&image, name, slide)); - let targets: Vec = targets.into_iter().collect::>()?; - assert_eq!(quads(&mapped.read_snapshot(pointers, 24)?), targets); - let result = INPUT.wrapping_add(SEED); - assert_eq!(thread.registers.x[0], result + CALLEE_ADDEND); - assert_eq!( - quads(&mapped.read_snapshot(targets[1], 16)?), - [result, result + CALLEE_ADDEND] - ); - } - Ok(()) -} - -#[test] -fn bound_imports_call_into_the_companion_dylib() -> Result<()> { - let tools = Toolchain::new()?; - let main_object = tools.assemble("bound-image-arm64.S")?; - let library_object = tools.assemble("bound-library-arm64.S")?; - let exports = tools.exports("exports.txt", &["_bound_function", "_bound_seed"])?; - let library_path = tools.path("libstela-fixture.dylib"); - let library = tools.link( - &library_path, - &[library_object], - &[ - "-dylib", - "-install_name", - "@rpath/libstela-fixture.dylib", - "-exported_symbols_list", - &exports, - ], - )?; - let main = tools.link( - &tools.path("bound-main"), - &[main_object, library_path], - &["-e", "_bound_entry", "-no_uuid"], - )?; - let main_base = base(3); - let library_base = main_base + LIBRARY_STRIDE; - let library_slide = library_base.wrapping_sub(preferred_base(&library)?); - let main_slide = main_base.wrapping_sub(preferred_base(&main)?); - let inputs = vec![ - input(main.clone(), main_base), - input(library.clone(), library_base), - ]; - let mut images = LinkedImages::load(inputs, tools.path("cache"), stack(3))?; - let mut thread = entry_state(images.entry(), images.stack().initial_sp); - // SAFETY: the trusted fixtures touch only their own mappings and stack. - unsafe { images.run(&mut thread, Some(GuestAddress(STOP)), BLOCK_BUDGET) }.context("run")?; - let result = INPUT.wrapping_add(SEED); - let returned = result + LIBRARY_ADDEND; - assert_eq!(thread.registers.x[0], returned); - let library_output = symbol(&library, "_library_output", library_slide)?; - assert_eq!( - quads(&images.read_snapshot(library_output, 16)?), - [result, returned] - ); - let main_output = symbol(&main, "_bound_output", main_slide)?; - assert_eq!(quads(&images.read_snapshot(main_output, 8)?), [returned]); - Ok(()) -} - -#[test] -fn rpath_dependencies_resolve_inside_the_guest_root() -> Result<()> { - let tools = Toolchain::new()?; - let guest = tools.path("guest"); - let main_path = guest.join("app/bin/main"); - let middle_path = guest.join("app/Frameworks/libmiddle-fixture.dylib"); - let leaf_path = guest.join("app/Frameworks/private/libleaf-fixture.dylib"); - let objects = [ - "bound-image-arm64.S", - "dependency-middle-arm64.S", - "dependency-leaf-arm64.S", - ] - .map(|fixture| tools.assemble(fixture)); - let [main_object, middle_object, leaf_object] = objects; - let leaf_exports = tools.exports("leaf-exports.txt", &["_leaf_function"])?; - let middle_exports = - tools.exports("middle-exports.txt", &["_bound_function", "_bound_seed"])?; - let leaf = tools.link( - &leaf_path, - &[leaf_object?], - &[ - "-dylib", - "-install_name", - "@rpath/libleaf-fixture.dylib", - "-exported_symbols_list", - &leaf_exports, - ], - )?; - tools.link( - &middle_path, - &[middle_object?, leaf_path], - &[ - "-dylib", - "-install_name", - "@rpath/libmiddle-fixture.dylib", - "-exported_symbols_list", - &middle_exports, - "-rpath", - "@loader_path/private", - ], - )?; - tools.link( - &main_path, - &[main_object?, middle_path], - &[ - "-e", - "_bound_entry", - "-rpath", - "@executable_path/../Frameworks", - "-no_uuid", - ], - )?; - let discovery = discover( - &main_path, - DiscoveryOptions { - guest_root: guest, - guest_path: Some("/app/bin/main".into()), - architecture: Some("arm64".into()), - image_base: Some(base(4)), - library_base: base(4) + LIBRARY_STRIDE, - library_stride: LIBRARY_STRIDE, - }, - )?; - // Only libSystem, absent from the guest root, stays unresolved. - ensure!( - discovery.inputs.len() == 3, - "fixture images were not all discovered" - ); - let leaf_index = discovery - .inputs - .iter() - .position(|image| image.data == leaf) - .context("leaf image was not discovered")?; - let leaf_base = discovery.inputs[leaf_index] - .load_base - .context("leaf base")?; - let leaf_slide = leaf_base.wrapping_sub(preferred_base(&leaf)?); - let mut images = LinkedImages::load_discovered( - discovery.inputs, - tools.path("cache"), - stack(4), - &discovery.links, - )?; - let mut thread = entry_state(images.entry(), images.stack().initial_sp); - // SAFETY: the trusted fixtures touch only their own mappings and stack. - unsafe { images.run(&mut thread, Some(GuestAddress(STOP)), BLOCK_BUDGET) }.context("run")?; - let result = INPUT.wrapping_add(SEED); - let from_leaf = result + LIBRARY_ADDEND; - assert_eq!(thread.registers.x[0], from_leaf + MIDDLE_ADDEND); - let leaf_output = symbol(&leaf, "_leaf_output", leaf_slide)?; - assert_eq!( - quads(&images.read_snapshot(leaf_output, 16)?), - [result, from_leaf] - ); - Ok(()) -} diff --git a/crates/stela-runtime/examples/restore_replay.rs b/crates/stela-runtime/examples/restore_replay.rs index 0572e3ec05..cefa44f794 100644 --- a/crates/stela-runtime/examples/restore_replay.rs +++ b/crates/stela-runtime/examples/restore_replay.rs @@ -1,4 +1,4 @@ -//! Hosted harness for the native restore client. No sockets or Apple servers. +//! Host-side harness for the native restore client. No sockets or Apple servers. //! See docs/research/restore-client.md for transcript layout and provenance. use anyhow::{Context, Result, bail, ensure}; use std::{ diff --git a/crates/stela-runtime/src/machine/engine.rs b/crates/stela-runtime/src/machine/engine.rs index 9619f86a8c..19a0c421af 100644 --- a/crates/stela-runtime/src/machine/engine.rs +++ b/crates/stela-runtime/src/machine/engine.rs @@ -2425,6 +2425,21 @@ impl Machine { } } + /// Resume a stopped architectural exception after a validation fixture has + /// repaired its backing. Apply the retained ELR/SPSR and synchronize all + /// native controls, without retiring a guest instruction or supplying OS + /// services. Production guest kernels return through their own ERET. + #[cfg(feature = "test-support")] + pub fn resume_exception( + &mut self, + ) -> Result<(), stela_compiler::context::memory::MemoryStatus> { + let target = self.cpu.exception_link(); + self.cpu.exception_return(target)?; + self.pacm_written = true; + self.sync_regime(); + Ok(()) + } + /// The architectural system count and each generic timer's `(CTL, CVAL)` /// in [`timer::CHANNELS`] order, sampled at that count, of the bank that /// counts it: the Apple generic timer's from the M3 on, where the kernel diff --git a/crates/stela-runtime/tests/store_continuation.rs b/crates/stela-runtime/tests/store_continuation.rs index 53021d5f5c..b88e081b08 100644 --- a/crates/stela-runtime/tests/store_continuation.rs +++ b/crates/stela-runtime/tests/store_continuation.rs @@ -1,12 +1,16 @@ //! Native ordinary-memory sequences preserve cached inputs over every split. -#![cfg(all(target_arch = "x86_64", target_os = "macos"))] +#![cfg(all( + feature = "test-support", + feature = "std", + target_arch = "x86_64", + target_os = "linux" +))] use anyhow::Result; -use std::sync::Arc; use stela_compiler::{GuestState, TargetCpu}; -use stela_runtime::{ - hosted::{hardware, host::ProcessHost, memory, pe, tables::Tables}, - machine::{Machine, NoDevices, Stop, system::Register}, -}; +use stela_runtime::machine::{Stop, system::Register}; +#[path = "support/store_host.rs"] +mod store_host; +use store_host::{Mapping, machine}; const HOST_PAGE: u64 = 4096; const MAPPING_BYTES: u64 = 4 * HOST_PAGE; @@ -14,57 +18,6 @@ const PREFIX: u32 = 0x9100_04a5; // add x5,x5,#1 const SUFFIX: u32 = 0x9100_04c6; // add x6,x6,#1 const VECTOR: [u64; 2] = [0xfedc_ba98_7654_3210, 0x0123_4567_89ab_cdef]; -struct Mapping(u64); -impl Mapping { - fn new() -> Result { - Ok(Self(memory::allocate( - 0, - MAPPING_BYTES, - true, - memory::Protection::READ_WRITE, - )?)) - } -} -impl Drop for Mapping { - fn drop(&mut self) { - memory::deallocate(self.0, MAPPING_BYTES).unwrap(); - } -} - -fn machine( - code: &Mapping, - words: &[u32], - target: TargetCpu, -) -> Result> { - assert!(memory::write( - code.0, - &words - .iter() - .flat_map(|word| word.to_le_bytes()) - .collect::>() - )); - let tables = Arc::new(Tables::new()?); - let hardware = hardware::Hardware::of_model(hardware::DEFAULT_MODEL, 8 << 30)?; - let cpu = pe::user_thread( - hardware.chip, - code.0, - &tables, - &pe::Keys::random()?, - pe::UserJop::Disabled, - ); - let mut machine = Machine::new( - cpu, - ProcessHost::new(tables)?, - NoDevices, - pe::profile(&hardware, target)?, - target, - ); - let mut points = pe::vectors().to_vec(); - points.push(code.0 + words.len() as u64 * 4); - machine.set_breakpoints(&points); - Ok(machine) -} - /// First transfer and a later transfer that reuses the same input. Pairs /// exercise both XMM sources; scalar cases control the byte-prefix path. fn cases() -> Vec<(&'static str, Vec, Vec, u64)> { @@ -153,7 +106,7 @@ fn assert_memory(data: &Mapping, writes: &[(u64, &[u8])], context: &str) { expected[start..start + bytes.len()].copy_from_slice(bytes); } assert_eq!( - memory::read(data.0, MAPPING_BYTES as usize).unwrap(), + data.read(data.0, MAPPING_BYTES as usize).unwrap(), expected, "{context}" ); @@ -166,13 +119,13 @@ fn every_store_split_preserves_sources_and_later_in_block_effects() -> Result<() for target in [TargetCpu::Baseline, TargetCpu::detect()] { for (name, stores, first, writeback) in cases() { let words = [vec![PREFIX], stores, vec![SUFFIX]].concat(); - let mut machine = machine(&code, &words, target)?; + let mut machine = machine(&code, &data, &words, target)?; let mut compiled = None; for split in 0..first.len() { // Split 0 is aligned; every other value is the accessible // prefix before a 4 KiB boundary, with both pages writable. let address = data.0 + HOST_PAGE - split as u64; - assert!(memory::write(data.0, &vec![0xa5; MAPPING_BYTES as usize])); + assert!(data.write(data.0, &vec![0xa5; MAPPING_BYTES as usize])); let initial = initial_state(address, data.0 + 2 * HOST_PAGE + 64, name); machine.cpu.state = initial.clone(); machine.cpu.pc = code.0; @@ -193,7 +146,7 @@ fn every_store_split_preserves_sources_and_later_in_block_effects() -> Result<() "{name} split {split}" ); assert_eq!( - memory::read(address, first.len()).unwrap(), + data.read(address, first.len()).unwrap(), first, "first {name} split {split}" ); @@ -211,7 +164,7 @@ fn every_store_split_preserves_sources_and_later_in_block_effects() -> Result<() first.clone() }; assert_eq!( - memory::read(later, output.len()).unwrap(), + data.read(later, output.len()).unwrap(), output, "later {name} split {split}" ); @@ -234,27 +187,23 @@ fn fault_prefix_and_repaired_continuation_keep_exact_pc_and_writeback() -> Resul for target in [TargetCpu::Baseline, TargetCpu::detect()] { for (name, stores, first, writeback) in cases() { let words = [vec![PREFIX], stores, vec![SUFFIX]].concat(); - let mut machine = machine(&code, &words, target)?; + let mut machine = machine(&code, &data, &words, target)?; let mut compiled = None; for split in 1..first.len() { let address = data.0 + HOST_PAGE - split as u64; - assert!(memory::write(data.0, &vec![0xa5; MAPPING_BYTES as usize])); + assert!(data.write(data.0, &vec![0xa5; MAPPING_BYTES as usize])); let initial = initial_state(address, data.0 + 2 * HOST_PAGE + 64, name); machine.cpu.state = initial.clone(); machine.cpu.pc = code.0; let retired = machine.cpu.retired; - memory::protect(data.0 + HOST_PAGE, HOST_PAGE, memory::Protection::NONE)?; + data.protect(HOST_PAGE as usize, HOST_PAGE as usize, false)?; let stopped = machine.run(machine.statistics.blocks + 64); // Restore permissions before any assertion can unwind and // before observing the page's exact untouched suffix. - memory::protect( - data.0 + HOST_PAGE, - HOST_PAGE, - memory::Protection::READ_WRITE, - )?; + data.protect(HOST_PAGE as usize, HOST_PAGE as usize, true)?; assert_eq!( stopped, - Stop::Breakpoint(pe::LOWER_SYNCHRONOUS), + Stop::Breakpoint(machine.host.lower_synchronous()), "{name} split {split}" ); assert_eq!( @@ -281,12 +230,15 @@ fn fault_prefix_and_repaired_continuation_keep_exact_pc_and_writeback() -> Resul let mut partial = vec![0xa5; first.len()]; partial[..split].copy_from_slice(&first[..split]); assert_eq!( - memory::read(address, first.len()).unwrap(), + data.read(address, first.len()).unwrap(), partial, "fault prefix {name} split {split}" ); assert_memory(&data, &[(address, &first[..split])], name); - machine.return_from_exception().unwrap(); + // Repair changes only this fixture's backing. Resume through + // the shared CPU ELR/SPSR primitive without adding a guest + // handler instruction to the sequence under test. + machine.resume_exception().unwrap(); assert_eq!(machine.cpu.pc, code.0 + 4); assert_eq!( machine.run(machine.statistics.blocks + 64), @@ -307,7 +259,7 @@ fn fault_prefix_and_repaired_continuation_keep_exact_pc_and_writeback() -> Resul "resumed retirement {name} split {split}" ); assert_eq!( - memory::read(address, first.len()).unwrap(), + data.read(address, first.len()).unwrap(), first, "resumed {name} split {split}" ); @@ -325,7 +277,7 @@ fn fault_prefix_and_repaired_continuation_keep_exact_pc_and_writeback() -> Resul first.clone() }; assert_eq!( - memory::read(later, output.len()).unwrap(), + data.read(later, output.len()).unwrap(), output, "resumed later {name} split {split}" ); diff --git a/crates/stela-runtime/tests/support/store_host.rs b/crates/stela-runtime/tests/support/store_host.rs new file mode 100644 index 0000000000..a3d5565902 --- /dev/null +++ b/crates/stela-runtime/tests/support/store_host.rs @@ -0,0 +1,426 @@ +//! Bounded native test host: only explicitly owned code/data/table pages. +use anyhow::{Result, ensure}; +use std::{cell::Cell, collections::BTreeMap, rc::Rc}; +use stela_compiler::{GuestState, TargetCpu}; +use stela_contracts::Chip; +use stela_runtime::{ + execution::reference::NativeRunner, + machine::{ + Cpu, CpuProfile, FaultCause, Host, InstallError, Machine, NativeCode, NativeExit, + NoDevices, Regime, exception::Pstate, identification, mmu, registers::encodings, + system::Register, + }, +}; +const PAGE: usize = 4096; +const PAGES: usize = 4; +const BYTES: usize = PAGE * PAGES; + +struct Region { + address: u64, + readable: [Cell; PAGES], +} +impl Drop for Region { + fn drop(&mut self) { + // SAFETY: this owner allocated the complete OS mapping and all clones + // retaining its address have dropped before this final Rc owner. + assert_eq!(unsafe { libc::munmap(self.address as *mut _, BYTES) }, 0); + } +} +impl Region { + fn offset(&self, address: u64, bytes: usize) -> Option { + let offset = usize::try_from(address.checked_sub(self.address)?).ok()?; + let end = offset.checked_add(bytes)?; + if end > BYTES { + return None; + } + if bytes != 0 && (offset / PAGE..=(end - 1) / PAGE).any(|page| !self.readable[page].get()) { + return None; + } + Some(offset) + } + fn read(&self, address: u64, out: &mut [u8]) -> bool { + if self.offset(address, out.len()).is_none() { + return false; + } + // SAFETY: the retained OS mapping and every touched page are readable; + // this distinct Rust output does not alias the externally mapped RAM. + unsafe { + core::ptr::copy_nonoverlapping(address as *const u8, out.as_mut_ptr(), out.len()) + }; + true + } + fn write(&self, address: u64, bytes: &[u8]) -> bool { + if self.offset(address, bytes.len()).is_none() { + return false; + } + // SAFETY: this bounded private RW mapping is idle outside a native run; + // no Rust data reference covers it and the source is separate storage. + unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), address as *mut u8, bytes.len()) }; + true + } +} +pub struct Mapping(pub u64, Rc); +impl Mapping { + pub fn new() -> Result { + // SAFETY: a fresh private RW mapping, never a fixed-address overwrite. + let pointer = unsafe { + libc::mmap( + core::ptr::null_mut(), + BYTES, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANON, + -1, + 0, + ) + }; + ensure!( + pointer != libc::MAP_FAILED, + "map test RAM: {}", + std::io::Error::last_os_error() + ); + let address = pointer as u64; + let mapping = Self( + address, + Rc::new(Region { + address, + readable: std::array::from_fn(|_| Cell::new(true)), + }), + ); + ensure!( + address != 0 && address < (1 << 47), + "test mapping exceeds declared 47bit guest range" + ); + Ok(mapping) + } + + pub fn write(&self, address: u64, bytes: &[u8]) -> bool { + self.1.write(address, bytes) + } + pub fn read(&self, address: u64, bytes: usize) -> Option> { + let mut out = vec![0; bytes]; + self.1.read(address, &mut out).then_some(out) + } + pub fn protect(&self, offset: usize, bytes: usize, readable: bool) -> Result<()> { + ensure!( + offset.is_multiple_of(PAGE) + && bytes.is_multiple_of(PAGE) + && offset.checked_add(bytes).is_some_and(|end| end <= BYTES), + "protection range" + ); + let flags = if readable { + libc::PROT_READ | libc::PROT_WRITE + } else { + libc::PROT_NONE + }; + // SAFETY: a page-aligned extent of this retained mapping; tests call + // only after native return and restore rights before reading RAM. + ensure!( + unsafe { libc::mprotect((self.0 + offset as u64) as *mut _, bytes, flags) } == 0, + "protect test RAM: {}", + std::io::Error::last_os_error() + ); + for page in offset / PAGE..(offset + bytes) / PAGE { + self.1.readable[page].set(readable); + } + Ok(()) + } +} + +#[repr(C, align(4096))] +struct Table([u64; 512]); +struct Tables { + root: u64, + pages: BTreeMap>, +} +impl Tables { + fn new(regions: &[Rc], vector: u64) -> Self { + let mut tables = Self { + root: 0, + pages: BTreeMap::new(), + }; + tables.root = tables.allocate(); + for region in regions { + for offset in (0..BYTES).step_by(PAGE) { + let address = region.address + offset as u64; + let mut current = tables.root; + for shift in [39, 30, 21] { + let index = ((address >> shift) & 511) as usize; + let mut entry = tables.pages[¤t].0[index]; + if entry == 0 { + entry = tables.allocate() | 3; + tables.pages.get_mut(¤t).unwrap().0[index] = entry; + } + current = entry & !0xfff; + } + // AF, inner-shareable Normal-WB attribute0. Code/data are + // EL0 RW. The ERET vector is privileged-only and EL0 XN; + // architectural EL1 execution excludes EL0-writable pages. + tables.pages.get_mut(¤t).unwrap().0[((address >> 12) & 511) as usize] = + address + | 3 + | (if region.address == vector { + 1 << 54 + } else { + 1 << 6 + }) + | (3 << 8) + | (1 << 10); + } + } + tables + } + fn allocate(&mut self) -> u64 { + let page = Box::new(Table([0; 512])); + let address = (&raw const *page) as u64; + self.pages.insert(address, page); + address + } + fn read(&self, address: u64, out: &mut [u8]) -> bool { + let Some(page) = self.pages.get(&(address & !0xfff)) else { + return false; + }; + let offset = (address & 0xfff) as usize; + if offset.checked_add(out.len()).is_none_or(|end| end > PAGE) { + return false; + } + // SAFETY: initialized immutable table bytes, retained through the run, + // copied to a disjoint caller buffer within this one page. + unsafe { + core::ptr::copy_nonoverlapping( + (&raw const **page).cast::().add(offset), + out.as_mut_ptr(), + out.len(), + ) + }; + true + } +} + +struct Executable { + address: u64, + bytes: usize, +} +impl Drop for Executable { + fn drop(&mut self) { + // SAFETY: uniquely owns this complete page-rounded executable mapping. + assert_eq!( + unsafe { libc::munmap(self.address as *mut _, self.bytes) }, + 0 + ); + } +} +pub struct NativeHost { + regions: Vec>, + tables: Tables, + code: Vec, + runner: NativeRunner, + vector: u64, +} +impl NativeHost { + pub fn lower_synchronous(&self) -> u64 { + self.vector + 0x400 + } +} +impl Host for NativeHost { + fn read_ram(&mut self, address: u64, out: &mut [u8]) -> bool { + self.tables.read(address, out) + || self.regions.iter().any(|region| region.read(address, out)) + } + fn write_ram(&mut self, address: u64, bytes: &[u8]) -> bool { + self.regions + .iter() + .any(|region| region.write(address, bytes)) + } + fn install(&mut self, bytes: &[u8]) -> Result { + let length = bytes.len().div_ceil(PAGE) * PAGE; + // SAFETY: requests a new private RW mapping for this immutable install. + let pointer = unsafe { + libc::mmap( + core::ptr::null_mut(), + length, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANON, + -1, + 0, + ) + }; + if pointer == libc::MAP_FAILED { + return Err(InstallError::Full); + } + let mapping = Executable { + address: pointer as u64, + bytes: length, + }; + if pointer.is_null() { + return Err(InstallError::Full); + } + // SAFETY: fresh RW mapping is disjoint from compiler output; no entry + // escapes before its initialized bytes become RX. + unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), pointer.cast(), bytes.len()) }; + // SAFETY: complete retained OS extent, idle and fully initialized. + if unsafe { libc::mprotect(pointer, length, libc::PROT_READ | libc::PROT_EXEC) } != 0 { + return Err(InstallError::Full); + } + self.code.push(mapping); + self.runner.set_ranges( + self.code + .iter() + .map(|code| (code.address, code.address + code.bytes as u64)) + .collect(), + ); + Ok(NativeCode(pointer as usize)) + } + fn patch(&mut self, native: NativeCode, bytes: &[u8]) { + let mapping = self + .code + .iter() + .find(|code| { + native.0 as u64 >= code.address + && (native.0 as u64) + .checked_add(bytes.len() as u64) + .is_some_and(|end| end <= code.address + code.bytes as u64) + }) + .unwrap(); + // SAFETY: the retained mapping is idle; Machine patches only outside + // invocation. No executable or byte reference escapes this owner. + unsafe { + assert_eq!( + libc::mprotect( + mapping.address as *mut _, + mapping.bytes, + libc::PROT_READ | libc::PROT_WRITE + ), + 0 + ); + core::ptr::copy_nonoverlapping(bytes.as_ptr(), native.0 as *mut u8, bytes.len()); + assert_eq!( + libc::mprotect( + mapping.address as *mut _, + mapping.bytes, + libc::PROT_READ | libc::PROT_EXEC + ), + 0 + ); + } + } + fn discard_code(&mut self) { + self.runner.set_ranges(vec![]); + self.code.clear(); + } + unsafe fn execute(&mut self, native: NativeCode, state: &mut GuestState) -> NativeExit { + // SAFETY: Machine retains this installed block and its block ABI, all + // reachable mappings and the distinct GuestState for the whole call. + match unsafe { self.runner.run(native.0, state) } { + Ok(exit) => NativeExit::Exit { + next_pc: exit.next_pc, + kind: exit.kind, + }, + Err(fault) => { + let cause = fault.check_cause().unwrap_or_else(|| { + let permission = self.regions.iter().any(|region| { + fault.address >= region.address + && fault.address < region.address + BYTES as u64 + }); + FaultCause::Guest(mmu::Fault { + kind: if permission { + mmu::FaultKind::Permission + } else { + mmu::FaultKind::Translation + }, + level: 3, + second_stage: None, + }) + }); + NativeExit::Fault( + fault.native(fault.rip.wrapping_sub(native.0 as u64) as usize, cause), + ) + } + } + } + fn report(&mut self, event: &stela_runtime::machine::Event) { + if let stela_runtime::machine::Event::Exception { from_el, .. } = event { + assert_eq!(*from_el, 0, "unexpected test-kernel exception: {event:?}"); + } + } + fn set_regime(&mut self, _: &Regime) {} + fn invalidate_translations(&mut self) {} + fn counter(&mut self) -> u64 { + 0 + } + fn arm_timer(&mut self, _: Option) {} + fn wait_for_interrupt(&mut self) { + panic!("store validation never waits") + } +} + +pub fn machine( + code: &Mapping, + data: &Mapping, + words: &[u32], + target: TargetCpu, +) -> Result> { + ensure!( + code.write( + code.0, + &words + .iter() + .flat_map(|word| word.to_le_bytes()) + .collect::>() + ), + "write code" + ); + let vector = Mapping::new()?; + ensure!( + vector.write(vector.0 + 0x400, &0xd69f_03e0u32.to_le_bytes()), + "write ERET vector" + ); + let regions = vec![Rc::clone(&code.1), Rc::clone(&data.1), Rc::clone(&vector.1)]; + let tables = Tables::new(®ions, vector.0); + let chip = Chip::AppleM2; + let mut cpu = Cpu::of( + chip, + code.0, + Pstate { + el: 0, + sp: false, + daif: 0, + ..Pstate::reset(0) + }, + ); + for (register, value) in [ + (Register::SCTLR_EL1, 1 | (1 << 2) | (1 << 12)), + ( + Register::TCR_EL1, + 17 | (1 << 8) | (1 << 10) | (3 << 12) | (1 << 23) | (5 << 32), + ), + (Register::MAIR_EL1, 0xff), + (Register::TTBR0_EL1, tables.root), + (Register::CPACR_EL1, 3 << 20), + (Register::VBAR_EL1, vector.0), + (Register::HCR_EL2, 1 << 31 | 1 << 40 | 1 << 41), + ] { + cpu.registers.set_raw(register, 0, value); + } + let mut fixed = identification::derive(chip, target, true, identification::Speculation::NONE); + fixed.push((encodings::MIDR_EL1, 0x611f_0320)); + let profile = CpuProfile { + name: "bounded native store validation", + chip, + counter_frequency: 24_000_000, + fixed, + processors: vec![], + }; + let host = NativeHost { + regions, + tables, + code: vec![], + runner: NativeRunner::new(vec![])?, + vector: vector.0, + }; + let mut machine = Machine::new(cpu, host, NoDevices, profile, target); + machine.set_breakpoints(&[ + machine.host.lower_synchronous(), + code.0 + words.len() as u64 * 4, + ]); + Ok(machine) +}