diff --git a/crates/stela-cli/src/run.rs b/crates/stela-cli/src/run.rs index 2bbbfaa0d6..f5ab21b828 100644 --- a/crates/stela-cli/src/run.rs +++ b/crates/stela-cli/src/run.rs @@ -374,6 +374,10 @@ impl Run { eprintln!("stela: {count:>8} {name}"); } eprintln!("stela: {:>8} shared-region pages slid", report.slid_pages); + hosted::translations::finish(); + for line in hosted::translations::summary(&report.engine) { + eprintln!("stela: {line}"); + } } report.termination.end_host_process() } diff --git a/crates/stela-compiler/src/block.rs b/crates/stela-compiler/src/block.rs index f4742c1722..d08b8dbea2 100644 --- a/crates/stela-compiler/src/block.rs +++ b/crates/stela-compiler/src/block.rs @@ -343,7 +343,7 @@ pub struct BlockExit { pub kind: u64, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct CompiledBlock { pub native: NativeBlock, /// Exact consumed prefix, including the terminator when present. diff --git a/crates/stela-compiler/src/lib.rs b/crates/stela-compiler/src/lib.rs index 0cd51cc614..4d3e02b833 100644 --- a/crates/stela-compiler/src/lib.rs +++ b/crates/stela-compiler/src/lib.rs @@ -67,7 +67,7 @@ pub trait Lifter { } /// Each native range keeps its guest address for faults and debugging. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct NativeBlock { pub x86_64_code: Vec, pub source_map: Vec<(GuestAddress, usize)>, diff --git a/crates/stela-runtime/Cargo.toml b/crates/stela-runtime/Cargo.toml index fe4192e09f..f6cf41a23e 100644 --- a/crates/stela-runtime/Cargo.toml +++ b/crates/stela-runtime/Cargo.toml @@ -32,6 +32,9 @@ hex = { version = "0.4", default-features = false, features = ["alloc"] } miniz_oxide = { version = "0.9", default-features = false, features = ["with-alloc"] } stela-compiler = { path = "../stela-compiler", default-features = false } +[build-dependencies] +sha2.workspace = true + [dev-dependencies] # The reference LZFSE encoder the no_std decoder is checked against. lzfse_rust = "0.2" diff --git a/crates/stela-runtime/build.rs b/crates/stela-runtime/build.rs new file mode 100644 index 0000000000..b523453c67 --- /dev/null +++ b/crates/stela-runtime/build.rs @@ -0,0 +1,50 @@ +//! Fingerprint the engine's compile-driver sources: with the compiler's own +//! fingerprint they make the persistent translation store's translator id +//! (`translations::translator_id`). +use sha2::{Digest, Sha256}; +use std::{ + fs, + path::{Path, PathBuf}, +}; + +/// What decides the input the engine gives the compiler for a block: the +/// dispatch loop's fetch and compile, the chip's admission and checks, and +/// the store format itself. +const INPUTS: &[&str] = &[ + "src/machine/engine.rs", + "src/machine/engine", + "src/machine/chip.rs", + "src/machine/chip", + "src/translations.rs", +]; + +fn collect(path: &Path, files: &mut Vec) { + if path.is_dir() { + for entry in fs::read_dir(path).expect("readable source directory") { + collect(&entry.expect("source entry").path(), files); + } + } else { + files.push(path.to_owned()); + } +} + +fn main() { + let mut files = Vec::new(); + for input in INPUTS { + println!("cargo:rerun-if-changed={input}"); + collect(Path::new(input), &mut files); + } + files.sort(); + let mut hasher = Sha256::new(); + for file in files { + hasher.update(file.to_string_lossy().as_bytes()); + hasher.update([0]); + hasher.update(fs::read(&file).expect("readable source file")); + } + let digest: String = hasher + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + println!("cargo:rustc-env=STELA_ENGINE_SOURCE_SHA256={digest}"); +} diff --git a/crates/stela-runtime/src/hosted.rs b/crates/stela-runtime/src/hosted.rs index 42f93e7828..966d29c95e 100644 --- a/crates/stela-runtime/src/hosted.rs +++ b/crates/stela-runtime/src/hosted.rs @@ -33,6 +33,7 @@ pub mod requirements; pub mod shared_region; pub mod tables; mod threads; +pub mod translations; pub mod unsupported; pub use kernel::{Executable, Signature}; @@ -52,6 +53,7 @@ impl Termination { /// End the host process as the guest process ended, so that its /// parent's `wait` sees the same status. pub fn end_host_process(self) -> ! { + translations::finish(); match self { Self::Exited(status) => std::process::exit(status & 0xff), Self::Signaled(signal) => { @@ -133,6 +135,8 @@ pub struct Launch { #[derive(Debug, Clone)] pub struct Report { pub termination: Termination, + /// The engine statistics of the threads that ended before the report. + pub engine: crate::machine::Statistics, pub calls: BTreeMap<&'static str, u64>, pub slid_pages: u64, } @@ -188,6 +192,7 @@ fn commpage_time() -> Result { /// Run the process to its exit. pub fn run(launch: Launch) -> Result { check_host_timebase()?; + translations::configure(translations::Config::from_environment()); // SIGPIPE as exec left it, which the host runtime's own start-up // changed to ignored. core::hint::black_box(&RECORD_SIGPIPE_AT_EXEC); @@ -343,6 +348,7 @@ pub fn run(launch: Launch) -> Result { }; Ok(Report { termination, + engine: *threads::lock(&process.runtime.statistics), calls: threads::lock(&process.counts).clone(), slid_pages: process.slid_pages(), }) diff --git a/crates/stela-runtime/src/hosted/host.rs b/crates/stela-runtime/src/hosted/host.rs index 3fc868e699..06e1d4f98b 100644 --- a/crates/stela-runtime/src/hosted/host.rs +++ b/crates/stela-runtime/src/hosted/host.rs @@ -418,6 +418,8 @@ pub struct ProcessHost { tables: std::sync::Arc, deadline: Option, runner: NativeRunner, + /// The process's translation store, if it has one. + translations: Option, } impl ProcessHost { @@ -446,6 +448,7 @@ impl ProcessHost { deadline: None, // Installed blocks, chained ones and thunks lie in the arena. runner: NativeRunner::new(vec![(start, start + ARENA_BYTES as u64)]), + translations: super::translations::Store::open(), }) } @@ -542,6 +545,12 @@ impl Host for ProcessHost { fn invalidate_translations(&mut self) {} + fn translations(&mut self) -> Option<&mut dyn crate::machine::Translations> { + self.translations + .as_mut() + .map(|store| store as &mut dyn crate::machine::Translations) + } + fn counter(&mut self) -> u64 { counter_at(host_nanoseconds()) } diff --git a/crates/stela-runtime/src/hosted/kernel/bsd/process.rs b/crates/stela-runtime/src/hosted/kernel/bsd/process.rs index 65bb9284eb..2c2b8aabed 100644 --- a/crates/stela-runtime/src/hosted/kernel/bsd/process.rs +++ b/crates/stela-runtime/src/hosted/kernel/bsd/process.rs @@ -363,6 +363,8 @@ fn execve(kernel: &mut Kernel, call: &Call, label: u64) -> Result { host.display() ); } + // The image ends here: its proven translations are written first. + crate::hosted::translations::finish(); // The new image keeps the descriptor table with no descriptor // mid-flag change. let _gate = kernel.process.files.gate(); diff --git a/crates/stela-runtime/src/hosted/threads.rs b/crates/stela-runtime/src/hosted/threads.rs index 6a0ec65316..d84dc2acf5 100644 --- a/crates/stela-runtime/src/hosted/threads.rs +++ b/crates/stela-runtime/src/hosted/threads.rs @@ -330,6 +330,7 @@ impl Lifetime { match outcome { Ok(termination) => termination.end_host_process(), Err(error) => { + super::translations::finish(); eprintln!("error: {error:#}"); std::process::exit(1) } @@ -359,6 +360,8 @@ pub(super) struct Runtime { pub(super) execution: ExecutionLock, pub(super) registry: Registry, pub(super) lifetime: Lifetime, + /// The engine statistics of every thread that ended. + pub(super) statistics: Mutex, } /// Take `mutex` if no other thread holds it. @@ -561,7 +564,9 @@ fn enter( } }; drop(sender); - let outcome = run(&mut kernel, pe, &member); + let mut pe = pe; + let outcome = run(&mut kernel, &mut pe, &member); + *lock(&process.runtime.statistics) += pe.statistics; process.exception_ports.thread_ended(port); // A thread ending the process records the end while it is still a // member, so that no thread the end wakes counts itself the last. @@ -631,38 +636,38 @@ impl Drop for EndsControl<'_> { /// At each return to guest code the thread's control parks it while it is /// suspended or held (`thread_suspend`, `thread_get_state`); a thread the /// process's end wakes there ends. -fn run(kernel: &mut Kernel, mut pe: Box, member: &Member) -> Result> { +fn run(kernel: &mut Kernel, pe: &mut Box, member: &Member) -> Result> { let process = kernel.process.clone(); let thread = kernel.thread; let execution = &process.runtime.execution; let control = member.control.clone(); let _ends = EndsControl(&control); - if let Some(end) = kernel.begin(&mut pe)? { + if let Some(end) = kernel.begin(pe)? { return Ok(ended(end)); } control.set_thread_pointer(pe.cpu.read(Register::TPIDRRO_EL0)); // `PTHREAD_START_SUSPENDED` parks before the first instruction. - if !control.leave(&mut pe) { + if !control.leave(pe) { return Ok(None); } - resume(&process, thread, member, &mut pe); + resume(&process, thread, member, pe); loop { match pe.run(pe.statistics.blocks + SLICE_BLOCKS) { Stop::Breakpoint(pe::LOWER_SYNCHRONOUS) => { execution.release(thread); - control.enter_kernel(&pe); + control.enter_kernel(pe); kernel.blocked(true); - kernel.synchronous(&mut pe)?; + kernel.synchronous(pe)?; kernel.blocked(false); match kernel.end.take() { Some(End::Process(termination)) => return Ok(Some(termination)), Some(End::Thread) => return Ok(None), None => {} } - if !control.leave(&mut pe) { + if !control.leave(pe) { return Ok(None); } - resume(&process, thread, member, &mut pe); + resume(&process, thread, member, pe); pe.return_from_exception(); } // XNU defers an AST taken inside the commpage's @@ -677,35 +682,35 @@ fn run(kernel: &mut Kernel, mut pe: Box, member: &Member) -> Result { execution.release(thread); - if !control.leave(&mut pe) { + if !control.leave(pe) { return Ok(None); } std::thread::yield_now(); - if let Some(end) = deliver(kernel, &mut pe)? { + if let Some(end) = deliver(kernel, pe)? { return Ok(ended(end)); } - resume(&process, thread, member, &mut pe); + resume(&process, thread, member, pe); } // An instruction the runtime does not implement: as an Apple // CPU's UNDEFINED encoding, EXC_BAD_INSTRUCTION at its pc. @@ -726,11 +731,11 @@ fn run(kernel: &mut Kernel, mut pe: Box, member: &Member) -> Result { execution.release(thread); diff --git a/crates/stela-runtime/src/hosted/translations.rs b/crates/stela-runtime/src/hosted/translations.rs new file mode 100644 index 0000000000..9b93e206a4 --- /dev/null +++ b/crates/stela-runtime/src/hosted/translations.rs @@ -0,0 +1,626 @@ +//! The hosted directory store of block translations +//! (`docs/design/runtime.md#persistent-translation-store`), shared by every +//! hosted process and run of the same translator. +//! +//! Engines look records up as they fetch a page's first block and offer +//! the blocks they compile. Worker threads compile each offered block again +//! at the two probe addresses, keep the entries [`translations::prove`] +//! accepts and write their records off the guest's path; the process's end +//! (and an `execve`) waits a bounded time for them and writes what they +//! proved. A record is replaced whole through a sibling file and `rename`, +//! merged with the entries already there, so concurrent processes never +//! publish a partial record. +//! +//! A fork child starts its own store state: the parent's workers and +//! unwritten entries stay the parent's. +use crate::machine::{Offer, Translations, compile_input}; +use crate::translations::{self, Digest, Record}; +use std::{ + collections::{BTreeMap, VecDeque}, + io::{Read as _, Write as _}, + path::{Path, PathBuf}, + sync::{ + Arc, Condvar, Mutex, MutexGuard, OnceLock, + atomic::{AtomicPtr, AtomicU64, Ordering}, + }, + time::{Duration, Instant, SystemTime}, +}; + +/// The environment variable naming the store's home, or `off`. +pub const HOME_VARIABLE: &str = "STELA_TRANSLATION_CACHE"; +/// The environment variable bounding the home's size in bytes. +pub const BOUND_VARIABLE: &str = "STELA_TRANSLATION_CACHE_BYTES"; +const DEFAULT_HOME: &str = "Library/Caches/stela/translations"; +const DEFAULT_BOUND: u64 = 4 << 30; +/// The home's layout version directory. +const LAYOUT: &str = "v1"; +const RECORD_EXTENSION: &str = "stlt"; +const USAGE_FILE: &str = "usage"; +const TRANSLATOR_FILE: &str = "translator.txt"; +/// Threads proving offered blocks. +const WORKERS: usize = 2; +/// Proven pages a worker lets gather before it writes them. +const WRITE_BATCH: usize = 256; +/// The longest the process's end waits for the workers. +const FINISH_WAIT: Duration = Duration::from_secs(2); +/// How stale a hit record's modification time may become before a hit +/// refreshes it for eviction. +const REFRESH_AGE: Duration = Duration::from_secs(24 * 60 * 60); +/// Eviction removes records until the home is this fraction of its bound. +const EVICT_TO_PERCENT: u64 = 90; +/// No record is larger: a page's 4 KiB of code in every context. +const MAX_RECORD_BYTES: u64 = 64 << 20; + +/// What the store did, for `--statistics`. +#[derive(Debug, Default)] +pub struct Counters { + pub records_loaded: AtomicU64, + pub records_absent: AtomicU64, + pub records_invalid: AtomicU64, + pub proven: AtomicU64, + pub unprovable: AtomicU64, + pub dropped: AtomicU64, + pub records_written: AtomicU64, + pub bytes_written: AtomicU64, + pub evicted: AtomicU64, +} + +pub static COUNTERS: Counters = Counters { + records_loaded: AtomicU64::new(0), + records_absent: AtomicU64::new(0), + records_invalid: AtomicU64::new(0), + proven: AtomicU64::new(0), + unprovable: AtomicU64::new(0), + dropped: AtomicU64::new(0), + records_written: AtomicU64::new(0), + bytes_written: AtomicU64::new(0), + evicted: AtomicU64::new(0), +}; + +/// Where the store lives and how large it may grow. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Config { + pub home: PathBuf, + pub bound: u64, +} + +impl Config { + /// The store the environment names: `None` when it is `off` or no home + /// can be found. + pub fn from_environment() -> Option { + Self::from_values( + std::env::var_os(HOME_VARIABLE), + std::env::var(BOUND_VARIABLE).ok(), + std::env::var_os("HOME"), + ) + } + + fn from_values( + home: Option, + bound: Option, + user_home: Option, + ) -> Option { + let home = match home { + Some(value) if value == "off" => return None, + Some(value) if !value.is_empty() => PathBuf::from(value), + _ => PathBuf::from(user_home?).join(DEFAULT_HOME), + }; + let bound = bound + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_BOUND); + Some(Self { home, bound }) + } +} + +struct State { + /// Records looked up, `None` for those absent or invalid. + loaded: BTreeMap>>, + queue: VecDeque, + /// Offers a worker is proving. + busy: usize, + /// Proven entries not yet written, by page. + unwritten: BTreeMap, + workers: usize, + closed: bool, +} + +/// One process's store. +struct Shared { + config: Config, + translator: Digest, + /// `HOME/v1/TRANSLATOR`. + namespace: PathBuf, + pid: u32, + state: Mutex, + /// Signals work for the workers and their progress to the finish. + changed: Condvar, + written_bytes: AtomicU64, +} + +fn lock(state: &Mutex) -> MutexGuard<'_, State> { + state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +static CONFIG: OnceLock> = OnceLock::new(); +/// This process's store, recreated in a fork child. +static CURRENT: AtomicPtr = AtomicPtr::new(core::ptr::null_mut()); + +/// Use the store `config` names for this process. +pub fn configure(config: Option) { + let _ = CONFIG.set(config); +} + +/// The calling process's store, created on first use and again in a fork +/// child, whose parent's state (its locks included) it never touches. +fn shared() -> Option<&'static Shared> { + let config = CONFIG.get()?.as_ref()?; + let pid = std::process::id(); + let current = CURRENT.load(Ordering::Acquire); + // SAFETY: stores are leaked, never freed. + if let Some(shared) = unsafe { current.as_ref() } + && shared.pid == pid + { + return Some(shared); + } + let translator = translations::translator_id(); + let shared = Box::leak(Box::new(Shared { + namespace: config.home.join(LAYOUT).join(translator.hex()), + config: config.clone(), + translator, + pid, + state: Mutex::new(State { + loaded: BTreeMap::new(), + queue: VecDeque::new(), + busy: 0, + unwritten: BTreeMap::new(), + workers: 0, + closed: false, + }), + changed: Condvar::new(), + written_bytes: AtomicU64::new(0), + })); + CURRENT.store(shared, Ordering::Release); + Some(shared) +} + +/// The engine's view of this process's store. +#[derive(Debug, Default)] +pub struct Store; + +impl Store { + /// A handle, if the process has a store. + pub fn open() -> Option { + shared().map(|_| Self) + } +} + +impl Translations for Store { + fn record(&mut self, key: &Digest) -> Option> { + let shared = shared()?; + if let Some(loaded) = lock(&shared.state).loaded.get(key) { + return loaded.clone(); + } + let record = shared.load(key).map(Arc::new); + lock(&shared.state).loaded.insert(*key, record.clone()); + record + } + + fn offer(&mut self, offer: Offer) { + let Some(shared) = shared() else { + return; + }; + let mut state = lock(&shared.state); + if state.closed { + return; + } + state.queue.push_back(offer); + if state.workers < WORKERS { + state.workers += 1; + drop(state); + let spawned = std::thread::Builder::new() + .name("stela-translations".into()) + .spawn(move || shared.work()); + if spawned.is_err() { + lock(&shared.state).workers -= 1; + } + return; + } + drop(state); + shared.changed.notify_one(); + } +} + +impl Shared { + fn path(&self, key: &Digest) -> PathBuf { + let hex = key.hex(); + self.namespace + .join(&hex[..2]) + .join(format!("{hex}.{RECORD_EXTENSION}")) + } + + /// The valid record of page `key` on disk. + fn load(&self, key: &Digest) -> Option { + let path = self.path(key); + let Some(bytes) = read_bounded(&path) else { + COUNTERS.records_absent.fetch_add(1, Ordering::Relaxed); + return None; + }; + match Record::decode(&bytes, &self.translator, key) { + Ok(record) => { + COUNTERS.records_loaded.fetch_add(1, Ordering::Relaxed); + refresh(&path); + Some(record) + } + Err(_) => { + COUNTERS.records_invalid.fetch_add(1, Ordering::Relaxed); + None + } + } + } + + /// Prove offers until the store closes and the queue is empty. + fn work(&self) { + loop { + let mut state = lock(&self.state); + let offer = loop { + if let Some(offer) = state.queue.pop_front() { + break offer; + } + if state.closed { + state.workers -= 1; + drop(state); + self.changed.notify_all(); + return; + } + state = self + .changed + .wait(state) + .unwrap_or_else(std::sync::PoisonError::into_inner); + }; + state.busy += 1; + drop(state); + let entry = prove(&offer); + let mut state = lock(&self.state); + state.busy -= 1; + match entry { + Some(entry) => { + COUNTERS.proven.fetch_add(1, Ordering::Relaxed); + let translator = self.translator; + state + .unwritten + .entry(offer.key) + .or_insert_with(|| Record::new(translator, offer.key)) + .insert(entry); + } + None => { + COUNTERS.unprovable.fetch_add(1, Ordering::Relaxed); + } + } + let batch = (state.unwritten.len() >= WRITE_BATCH) + .then(|| std::mem::take(&mut state.unwritten)); + drop(state); + self.changed.notify_all(); + if let Some(batch) = batch { + self.write(batch); + } + } + } + + /// Write each record merged with the one on disk. + fn write(&self, records: BTreeMap) { + for (key, mut record) in records { + let path = self.path(&key); + let previous = read_bounded(&path); + if let Some(stored) = previous + .as_deref() + .and_then(|bytes| Record::decode(bytes, &self.translator, &key).ok()) + { + record.merge(stored); + } + let bytes = record.encode(); + if write_replacing(&path, &bytes).is_ok() { + COUNTERS.records_written.fetch_add(1, Ordering::Relaxed); + COUNTERS + .bytes_written + .fetch_add(bytes.len() as u64, Ordering::Relaxed); + let grown = (bytes.len() as u64) + .saturating_sub(previous.map_or(0, |previous| previous.len() as u64)); + self.written_bytes.fetch_add(grown, Ordering::Relaxed); + } + } + } + + /// Stop taking offers, wait for the workers until `deadline`, drop what + /// they did not reach and write what they proved. + fn finish(&self, deadline: Instant) { + let mut state = lock(&self.state); + state.closed = true; + self.changed.notify_all(); + while (state.busy != 0 || !state.queue.is_empty()) && state.workers != 0 { + let now = Instant::now(); + if now >= deadline { + break; + } + state = self + .changed + .wait_timeout(state, deadline - now) + .unwrap_or_else(std::sync::PoisonError::into_inner) + .0; + } + COUNTERS + .dropped + .fetch_add(state.queue.len() as u64, Ordering::Relaxed); + state.queue.clear(); + let unwritten = std::mem::take(&mut state.unwritten); + drop(state); + if unwritten.is_empty() { + return; + } + let _ = std::fs::create_dir_all(&self.namespace); + let described = self.namespace.join(TRANSLATOR_FILE); + if !described.exists() { + let text = format!( + "stela {}\ncompiler {}\nengine {}\nschema {}\n", + env!("CARGO_PKG_VERSION"), + stela_compiler::SOURCE_SHA256, + translations::ENGINE_SOURCE_SHA256, + translations::SCHEMA, + ); + let _ = write_replacing(&described, text.as_bytes()); + } + self.write(unwritten); + self.account(); + } + + /// Add this process's growth to the home's usage and evict past the + /// bound. + fn account(&self) { + let grown = self.written_bytes.swap(0, Ordering::Relaxed); + let root = self.config.home.join(LAYOUT); + let Ok(mut file) = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(root.join(USAGE_FILE)) + else { + return; + }; + let descriptor = std::os::fd::AsRawFd::as_raw_fd(&file); + // SAFETY: an open descriptor; the lock ends when the file closes. + if unsafe { libc::flock(descriptor, libc::LOCK_EX) } != 0 { + return; + } + let mut text = String::new(); + let _ = file.read_to_string(&mut text); + let mut usage = text.trim().parse::().unwrap_or(0) + grown; + if usage > self.config.bound { + usage = evict(&root, self.config.bound * EVICT_TO_PERCENT / 100); + } + let _ = file.set_len(0); + let _ = std::io::Seek::rewind(&mut file); + let _ = file.write_all(usage.to_string().as_bytes()); + } +} + +/// Compile the offered block at both probe addresses and prove its entry. +fn prove(offer: &Offer) -> Option { + let displacements = translations::probe_displacements(offer.page); + let probes = displacements.map(|displacement| { + compile_input( + &offer.input, + offer.pc.wrapping_add(displacement), + offer.target, + offer.checks, + offer.system, + ) + .ok() + }); + let [Some(first), Some(second)] = &probes else { + return None; + }; + translations::prove( + &offer.block, + offer.page, + offer.pc, + offer.context, + [first, second], + ) +} + +/// The process ends or replaces its image: write what the workers proved. +pub fn finish() { + let pid = std::process::id(); + // SAFETY: stores are leaked, never freed. + if let Some(shared) = unsafe { CURRENT.load(Ordering::Acquire).as_ref() } + && shared.pid == pid + { + shared.finish(Instant::now() + FINISH_WAIT); + } +} + +/// The engine's and the store's counts, one line each, for `--statistics`. +pub fn summary(engine: &crate::machine::Statistics) -> Vec { + let ticks_per_millisecond = super::host::COUNTER_HZ / 1000; + let counter = |value: &AtomicU64| value.load(Ordering::Relaxed); + let mut lines = vec![ + format!( + "engine: {} blocks run, {} chained, {} lookup hits, {} exits", + engine.blocks, + engine.chained, + engine.lookup_hits, + engine.exit_kinds.iter().sum::() + ), + format!( + "engine: {} blocks compiled in {} ms, {} from the store, {} offered to it", + engine.compiled, + engine.compile_ticks / ticks_per_millisecond, + engine.stored, + engine.offered + ), + format!("engine: exits by kind {:?}", engine.exit_kinds), + ]; + if CONFIG.get().is_some_and(Option::is_some) { + lines.push(format!( + "store: {} records loaded, {} absent, {} invalid; {} blocks proven, {} unprovable, \ + {} dropped; {} records written ({} bytes), {} evicted", + counter(&COUNTERS.records_loaded), + counter(&COUNTERS.records_absent), + counter(&COUNTERS.records_invalid), + counter(&COUNTERS.proven), + counter(&COUNTERS.unprovable), + counter(&COUNTERS.dropped), + counter(&COUNTERS.records_written), + counter(&COUNTERS.bytes_written), + counter(&COUNTERS.evicted), + )); + } else { + lines.push("store: off".into()); + } + lines +} + +fn read_bounded(path: &Path) -> Option> { + let mut file = std::fs::File::open(path).ok()?; + let length = file.metadata().ok()?.len(); + if length > MAX_RECORD_BYTES { + return None; + } + let mut bytes = Vec::with_capacity(length as usize); + file.read_to_end(&mut bytes).ok()?; + Some(bytes) +} + +/// Keep a record in use from eviction: its modification time ages a day +/// at most. +fn refresh(path: &Path) { + let Ok(file) = std::fs::File::options().write(true).open(path) else { + return; + }; + let stale = file + .metadata() + .and_then(|metadata| metadata.modified()) + .ok() + .and_then(|modified| SystemTime::now().duration_since(modified).ok()) + .is_some_and(|age| age > REFRESH_AGE); + if stale { + let _ = file.set_modified(SystemTime::now()); + } +} + +/// Replace `path` with `bytes` through a sibling file, creating its +/// directory. +fn write_replacing(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let directory = path.parent().expect("a record path has a directory"); + std::fs::create_dir_all(directory)?; + let sibling = directory.join(format!( + ".{}.{}.{}", + path.file_name() + .expect("a record path has a name") + .to_string_lossy(), + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let written = std::fs::write(&sibling, bytes).and_then(|()| std::fs::rename(&sibling, path)); + if written.is_err() { + let _ = std::fs::remove_file(&sibling); + } + written +} + +/// Remove the least recently modified records under `root` until its +/// records take `target` bytes at most; the bytes left. +fn evict(root: &Path, target: u64) -> u64 { + let mut records = Vec::new(); + let mut total = 0; + for namespace in read_directory(root) { + for shard in read_directory(&namespace) { + for path in read_directory(&shard) { + if path + .extension() + .is_some_and(|extension| extension == RECORD_EXTENSION) + && let Ok(metadata) = std::fs::metadata(&path) + { + total += metadata.len(); + let modified = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH); + records.push((modified, metadata.len(), path)); + } + } + } + } + records.sort(); + for (_, bytes, path) in records { + if total <= target { + break; + } + if std::fs::remove_file(&path).is_ok() { + total -= bytes; + COUNTERS.evicted.fetch_add(1, Ordering::Relaxed); + } + } + total +} + +fn read_directory(path: &Path) -> Vec { + std::fs::read_dir(path) + .map(|entries| { + entries + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| path.is_dir() || path.is_file()) + .collect() + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_replace_through_a_sibling_and_eviction_removes_the_oldest_first() { + let home = tempfile::tempdir().unwrap(); + let root = home.path().join(LAYOUT); + let shard = root.join("namespace").join("ab"); + let paths: Vec<_> = (0..3) + .map(|index| shard.join(format!("{index}.{RECORD_EXTENSION}"))) + .collect(); + for (age, path) in paths.iter().enumerate() { + write_replacing(path, &[age as u8; 100]).unwrap(); + let file = std::fs::File::options().write(true).open(path).unwrap(); + file.set_modified(SystemTime::now() - Duration::from_secs(1000 * (3 - age as u64))) + .unwrap(); + } + write_replacing(&paths[2], &[9; 100]).unwrap(); + assert_eq!(std::fs::read(&paths[2]).unwrap(), [9; 100]); + assert_eq!(read_directory(&shard).len(), 3, "no sibling is left"); + assert_eq!(evict(&root, 150), 100); + assert!(!paths[0].exists() && !paths[1].exists() && paths[2].exists()); + } + + #[test] + fn the_environment_names_the_home_and_bound_or_turns_the_store_off() { + let user = Some("/Users/u".into()); + assert_eq!( + Config::from_values(Some("off".into()), None, user.clone()), + None + ); + assert_eq!( + Config::from_values(None, None, user.clone()), + Some(Config { + home: PathBuf::from("/Users/u").join(DEFAULT_HOME), + bound: DEFAULT_BOUND, + }) + ); + assert_eq!( + Config::from_values(Some("/c".into()), Some("12".into()), None), + Some(Config { + home: PathBuf::from("/c"), + bound: 12, + }) + ); + assert_eq!(Config::from_values(None, None, None), None); + } +} diff --git a/crates/stela-runtime/src/lib.rs b/crates/stela-runtime/src/lib.rs index 8581ea23ba..57a9514f22 100644 --- a/crates/stela-runtime/src/lib.rs +++ b/crates/stela-runtime/src/lib.rs @@ -51,6 +51,7 @@ pub mod process; pub mod scalable; pub mod system; pub mod thread; +pub mod translations; #[cfg(feature = "std")] use anyhow::ensure; use anyhow::{Context, Result}; diff --git a/crates/stela-runtime/src/machine.rs b/crates/stela-runtime/src/machine.rs index 08e6b48ee6..a788e12862 100644 --- a/crates/stela-runtime/src/machine.rs +++ b/crates/stela-runtime/src/machine.rs @@ -33,7 +33,7 @@ pub(crate) use chip::test_chip; pub use cpu::{Cpu, Exception}; pub use engine::{ DeviceError, Devices, Event, FaultCause, Host, InstallError, Machine, NativeCode, NativeExit, - NativeFault, NoDevices, PeerState, Regime, Requirement, RequirementKind, Reset, StaleCode, - Statistics, Stop, Transition, + NativeFault, NoDevices, Offer, PeerState, Regime, Requirement, RequirementKind, Reset, + StaleCode, Statistics, Stop, Transition, Translations, compile_input, }; pub use registers::{CpuProfile, Identity, Lines}; diff --git a/crates/stela-runtime/src/machine/engine.rs b/crates/stela-runtime/src/machine/engine.rs index cabd9f1709..b74d02822a 100644 --- a/crates/stela-runtime/src/machine/engine.rs +++ b/crates/stela-runtime/src/machine/engine.rs @@ -7,6 +7,7 @@ mod hosted; mod pointer; mod processors; mod scalable; +mod stored; mod system; mod tags; mod unprivileged; @@ -68,6 +69,7 @@ use stela_compiler::{ pointer as x86_64_pointer, register_read, zero_block, }, }; +pub use stored::{Offer, Translations}; const PROFILE: BlockProfile = BlockProfile::SystemModeV1; const INSTRUCTION: u64 = 4; @@ -350,6 +352,11 @@ pub trait Host { fn wait_for_interrupt(&mut self); /// Progress events for the diagnostic log. fn report(&mut self, _event: &Event) {} + /// The persistent translation store blocks are taken from and offered + /// to, if the host keeps one ([`Translations`]). + fn translations(&mut self) -> Option<&mut dyn Translations> { + None + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -730,6 +737,12 @@ pub struct Statistics { /// ThreadRegister, FloatingPoint, ScalableNumerical, System, AMX). pub exit_kinds: [u64; 13], pub compiled: u64, + /// Counter ticks spent analyzing and compiling `compiled`. + pub compile_ticks: u64, + /// Blocks taken from the persistent translation store instead of + /// compiled, and compiled blocks offered to it. + pub stored: u64, + pub offered: u64, pub exceptions: u64, pub interrupts: u64, pub system_exits: u64, @@ -753,6 +766,65 @@ pub struct Statistics { pub prediction_isolations: u64, } +impl core::ops::AddAssign for Statistics { + fn add_assign(&mut self, other: Self) { + let Self { + blocks, + chained, + links, + lookups, + lookup_hits, + exit_kinds, + compiled, + compile_ticks, + stored, + offered, + exceptions, + interrupts, + system_exits, + device_accesses, + code_discards, + code_invalidations, + waits, + switches, + translation_changes, + tlb_maintenance, + scoped_maintenance, + table_base_changes, + prediction_isolations, + } = other; + for (total, count) in self.exit_kinds.iter_mut().zip(exit_kinds) { + *total += count; + } + for (total, count) in [ + (&mut self.blocks, blocks), + (&mut self.chained, chained), + (&mut self.links, links), + (&mut self.lookups, lookups), + (&mut self.lookup_hits, lookup_hits), + (&mut self.compiled, compiled), + (&mut self.compile_ticks, compile_ticks), + (&mut self.stored, stored), + (&mut self.offered, offered), + (&mut self.exceptions, exceptions), + (&mut self.interrupts, interrupts), + (&mut self.system_exits, system_exits), + (&mut self.device_accesses, device_accesses), + (&mut self.code_discards, code_discards), + (&mut self.code_invalidations, code_invalidations), + (&mut self.waits, waits), + (&mut self.switches, switches), + (&mut self.translation_changes, translation_changes), + (&mut self.tlb_maintenance, tlb_maintenance), + (&mut self.scoped_maintenance, scoped_maintenance), + (&mut self.table_base_changes, table_base_changes), + (&mut self.prediction_isolations, prediction_isolations), + ] { + *total += count; + } + } +} + struct Block { pc: u64, physical: u64, @@ -936,6 +1008,11 @@ pub struct Machine { index: BTreeMap<(u64, u64, Variant), usize>, /// The `index` keys of the blocks compiled from each physical page. code_pages: BTreeMap>, + /// The fetch pages read for the translation store, by physical page, + /// until their code is invalidated ([`stored`]). + pages: BTreeMap, + /// Entry contexts by variant and address class. + stored_contexts: BTreeMap<(Variant, u64), crate::translations::Digest>, fetch: Vec>, jump: Vec>, /// Advances when cached fetch translations become stale. @@ -1053,6 +1130,24 @@ pub struct Machine { tags_checked_at: Option, } +/// Compile the admitted words `input` at `pc` as the engine compiles a +/// block: the system-mode profile for `target`, with `checks` and the +/// System instructions `system` completes natively. A pure function of its +/// arguments, which the translation store's probes rely on. +pub fn compile_input( + input: &[u8], + pc: u64, + target: TargetCpu, + checks: MemoryChecks, + system: NativeSystem, +) -> Result { + CompilationPlan::new(input, GuestAddress(pc), PROFILE, target) + .and_then(|plan| plan.with_memory_checks(checks)) + .and_then(|plan| plan.with_zero_block(system.zero_block)) + .and_then(|plan| plan.with_cache_clean(system.cache_clean)) + .and_then(CompilationPlan::compile) +} + /// Breakpoints that can match and an enabled software step make every /// block a single instruction checked before it runs. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1091,6 +1186,8 @@ impl Machine { fault_recovery: BTreeMap::new(), index: BTreeMap::new(), code_pages: BTreeMap::new(), + pages: BTreeMap::new(), + stored_contexts: BTreeMap::new(), fetch: vec![None; FETCH_CACHE], jump: vec![None; JUMP_CACHE], translation_generation: 1, @@ -1480,6 +1577,7 @@ impl Machine { /// IC IVAU made stale: a later fetch compiles the page again. Their code /// stays installed until the next full discard. fn invalidate_code_page(&mut self, physical: u64) { + self.pages.remove(&(physical & !(FETCH_PAGE - 1))); let Some(keys) = self.code_pages.remove(&(physical & !(FETCH_PAGE - 1))) else { return; }; @@ -1498,6 +1596,7 @@ impl Machine { self.fault_recovery.clear(); self.index.clear(); self.code_pages.clear(); + self.pages.clear(); self.scalable_leaves.clear(); self.code_generation += 1; self.statistics.code_discards += 1; @@ -2546,14 +2645,34 @@ impl Machine { } else { (FETCH_PAGE - (pc & (FETCH_PAGE - 1))).min(MAX_BLOCK_BYTES) }; + let page = pc & !(FETCH_PAGE - 1); + let offset = (pc - page) as usize; let mut source = vec![0u8; available as usize]; if !self.host.read_ram(physical, &mut source) { return Err(self.unsupported(RequirementKind::Fetch { physical })); } + let stored = match single { + true => None, + false => self + .stored_page(pc, physical, &source) + .map(|stored| (stored.key, stored.record.clone())), + }; // A form the chip lacks compiles as the UDF or NOP it executes as. for bytes in source.as_chunks_mut::<4>().0 { *bytes = self.admit(u32::from_le_bytes(*bytes)).to_le_bytes(); } + let context = stored + .is_some() + .then(|| self.stored_context(variant, target, page)); + if let (Some((_, Some(record))), Some(context)) = (&stored, &context) + && let Some(compiled) = record + .find(offset as u16, context) + .and_then(|entry| entry.rebase(page)) + { + self.statistics.stored += 1; + return self.install(pc, physical, variant, &source, compiled); + } + let started = self.host.counter(); let chip = self.profile.chip; let mut length = source.len(); // No block runs into a host breakpoint or trace point: one ends @@ -2622,7 +2741,40 @@ impl Machine { } Err(error) => return Err(self.unsupported_word(&source, pc, pc, error.detail)), }; - let compiled = self.compile_prefix(&source[..consumed], pc, target, checks, system)?; + let (compiled, input) = + self.compile_prefix(&source[..consumed], pc, target, checks, system)?; + self.statistics.compiled += 1; + self.statistics.compile_ticks += self.host.counter().wrapping_sub(started); + if let (Some((key, _)), Some(context)) = (stored, context) + && let Some(translations) = self.host.translations() + { + translations.offer(Offer { + key, + page, + pc, + context, + input: source[..input].to_vec(), + target, + checks, + system, + block: compiled.clone(), + }); + self.statistics.offered += 1; + } + self.install(pc, physical, variant, &source, compiled) + } + + /// Install `compiled`, the block at `pc` of `variant` compiled from the + /// admitted `source`, and its thunks, and index it. + fn install( + &mut self, + pc: u64, + physical: u64, + variant: Variant, + source: &[u8], + compiled: stela_compiler::block::CompiledBlock, + ) -> Result { + let Variant { checks, single, .. } = variant; let last = compiled.source_bytes - INSTRUCTION as usize; let terminal = u32::from_le_bytes(source[last..last + 4].try_into().expect("a word")); let code = match self.host.install(&compiled.native.x86_64_code) { @@ -2636,7 +2788,6 @@ impl Machine { })? } }; - self.statistics.compiled += 1; let terminal_pc = pc + compiled.source_bytes as u64 - INSTRUCTION; let mut successors: Vec = compiled .direct_exits @@ -2781,7 +2932,8 @@ impl Machine { self.target.data_independent_timing_target() } - /// Compile the longest prefix `target` can emit. + /// Compile the longest prefix `target` can emit, and the bytes of + /// `source` the compiler was given for it. fn compile_prefix( &self, source: &[u8], @@ -2789,16 +2941,10 @@ impl Machine { target: TargetCpu, checks: MemoryChecks, system: NativeSystem, - ) -> Result { - let attempt = |bytes: &[u8]| { - CompilationPlan::new(bytes, GuestAddress(pc), PROFILE, target) - .and_then(|plan| plan.with_memory_checks(checks)) - .and_then(|plan| plan.with_zero_block(system.zero_block)) - .and_then(|plan| plan.with_cache_clean(system.cache_clean)) - .and_then(CompilationPlan::compile) - }; + ) -> Result<(stela_compiler::block::CompiledBlock, usize), Stop> { + let attempt = |bytes: &[u8]| compile_input(bytes, pc, target, checks, system); match attempt(source) { - Ok(compiled) => Ok(compiled), + Ok(compiled) => Ok((compiled, source.len())), Err(error) => { // A host-capability refusal names no PC; find the longest // prefix that compiles and report the first refused word. @@ -2816,6 +2962,7 @@ impl Machine { return Err(self.unsupported_word(source, pc, pc, error.0)); } attempt(&source[..good * 4]) + .map(|compiled| (compiled, good * 4)) .map_err(|error| self.unsupported_word(source, pc, pc, error.0)) } } @@ -4879,7 +5026,7 @@ mod tests { /// Calls of [`Host::isolate_predictions`]. pub(super) isolations: usize, reaches: Vec, - installed: Vec>, + pub(super) installed: Vec>, /// Executable copies of the context leaves the engine called. executables: Vec, patches: Vec<(usize, Vec)>, @@ -4888,6 +5035,8 @@ mod tests { /// What the next native blocks return, in order: unit tests do not /// run native code. pub(super) exits: Vec, + /// A translation store, for the tests that give the host one. + pub(super) store: Option, } impl Host for FakeHost { @@ -4967,6 +5116,11 @@ mod tests { fn wait_for_interrupt(&mut self) { self.now += 1000; } + fn translations(&mut self) -> Option<&mut dyn Translations> { + self.store + .as_mut() + .map(|store| store as &mut dyn Translations) + } } pub(super) const BASE: u64 = 0x8_0000_0000; @@ -5053,6 +5207,7 @@ mod tests { patches: Vec::new(), chained: None, exits: Vec::new(), + store: None, }; let profile = CpuProfile { name: "test", diff --git a/crates/stela-runtime/src/machine/engine/stored.rs b/crates/stela-runtime/src/machine/engine/stored.rs new file mode 100644 index 0000000000..3ed00c0a93 --- /dev/null +++ b/crates/stela-runtime/src/machine/engine/stored.rs @@ -0,0 +1,261 @@ +//! Block translations from and to the persistent translation store +//! (`crate::translations`): a fetch page is read and hashed once, its +//! record looked up once, and each block of it compiled in a context the +//! record has is rebased instead of compiled. A block compiled anew is +//! offered back, with what the host needs to compile it again at the probe +//! addresses (`translations::prove`). +use super::{Devices, FETCH_PAGE, Host, Machine, Variant}; +use crate::translations::{self, Digest, PAGE_BYTES, Record}; +use alloc::{boxed::Box, format, sync::Arc, vec::Vec}; +use stela_compiler::{ + TargetCpu, + block::CompiledBlock, + x86_64::{MemoryChecks, NativeSystem}, +}; + +/// The store a host keeps for the engine. +pub trait Translations { + /// The record of the page whose bytes hash to `key`, if the store has + /// a valid one. + fn record(&mut self, key: &Digest) -> Option>; + /// A block the engine compiled from a page the store had no entry for. + fn offer(&mut self, offer: Offer); +} + +/// A block compiled anew, and how it was compiled. +#[derive(Debug, Clone)] +pub struct Offer { + pub key: Digest, + /// The guest address of its fetch page. + pub page: u64, + pub pc: u64, + pub context: Digest, + /// The admitted words the compiler was given. + pub input: Vec, + pub target: TargetCpu, + pub checks: MemoryChecks, + pub system: NativeSystem, + pub block: CompiledBlock, +} + +/// A fetch page's bytes, as read for its first block, and its record. +pub(super) struct StoredPage { + pub(super) key: Digest, + pub(super) bytes: Box<[u8; PAGE_BYTES]>, + pub(super) record: Option>, +} + +impl Machine { + /// The stored page holding `pc` at `physical`, read and looked up on + /// its first block; `None` without a store, when the page cannot be + /// read whole or when a host breakpoint or trace point lies in it, + /// which shortens blocks in ways no context names. + /// + /// `source` is the block's window as just read: a page whose kept + /// bytes differ from it (guest memory written without the IC + /// maintenance that invalidates the page) is read and hashed again, so + /// a stored or offered block always has the bytes the guest holds now. + pub(super) fn stored_page( + &mut self, + pc: u64, + physical: u64, + source: &[u8], + ) -> Option<&StoredPage> { + let frame = physical & !(FETCH_PAGE - 1); + let offset = (physical - frame) as usize; + if self + .pages + .get(&frame) + .is_some_and(|stored| stored.bytes.get(offset..offset + source.len()) != Some(source)) + { + self.pages.remove(&frame); + } + if !self.pages.contains_key(&frame) { + self.host.translations()?; + let page = pc & !(FETCH_PAGE - 1); + if self + .breakpoints + .iter() + .chain(&self.traces) + .any(|&stop| stop & !(FETCH_PAGE - 1) == page) + { + return None; + } + let mut bytes = Box::new([0u8; PAGE_BYTES]); + if !self.host.read_ram(frame, bytes.as_mut_slice()) { + return None; + } + let key = Digest::of(bytes.as_slice()); + let record = self.host.translations()?.record(&key); + self.pages.insert(frame, StoredPage { key, bytes, record }); + } + self.pages.get(&frame) + } + + /// The entry context of blocks compiled for `variant` with `target` in + /// the page at `page`: everything besides their bytes and offset that + /// shapes their compilation. + pub(super) fn stored_context( + &mut self, + variant: Variant, + target: TargetCpu, + page: u64, + ) -> Digest { + let class = translations::address_class(page); + if let Some(context) = self.stored_contexts.get(&(variant, class)) { + return *context; + } + let Variant { + fp, + checks, + single, + scalable, + system, + guarded_page: _, + timing: _, + } = variant; + let described = format!( + "chip {:?} target {target:?} fp {fp} checks {checks:?} single {single} scalable \ + {scalable:?} system {system:?} class {class:#x}", + self.profile.chip + ); + let context = Digest::of(described.as_bytes()); + self.stored_contexts.insert((variant, class), context); + context + } +} + +#[cfg(test)] +pub(super) mod tests { + use super::super::{Fetched, tests::BASE, tests::machine}; + use super::*; + use alloc::collections::BTreeMap; + + /// A store in memory: records by key, and the blocks offered to it. + #[derive(Default)] + pub(crate) struct MemoryStore { + pub(crate) records: BTreeMap>, + pub(crate) offers: Vec, + } + + impl Translations for MemoryStore { + fn record(&mut self, key: &Digest) -> Option> { + self.records.get(key).cloned() + } + fn offer(&mut self, offer: Offer) { + self.offers.push(offer); + } + } + + /// What the hosted store's workers do with an offer. + fn proven(offer: &Offer) -> translations::Entry { + let [first, second] = translations::probe_displacements(offer.page).map(|displacement| { + super::super::compile_input( + &offer.input, + offer.pc.wrapping_add(displacement), + offer.target, + offer.checks, + offer.system, + ) + .unwrap() + }); + translations::prove( + &offer.block, + offer.page, + offer.pc, + offer.context, + [&first, &second], + ) + .unwrap() + } + + #[test] + fn a_stored_block_of_the_same_page_bytes_is_installed_without_compiling() { + // adr x0, #8; add x0, x0, #1; svc #0 + let words = [0x1000_0040, 0x9100_0400, 0xd400_0001]; + let mut first = machine(&words); + first.host.store = Some(MemoryStore::default()); + let Ok(Fetched::Block(compiled)) = first.fetch_block(BASE + 4, false) else { + panic!("block") + }; + assert_eq!( + (first.statistics.compiled, first.statistics.offered), + (1, 1) + ); + let offer = first.host.store.as_mut().unwrap().offers.pop().unwrap(); + assert_eq!((offer.page, offer.pc), (BASE, BASE + 4)); + let mut record = Record::new(translations::translator_id(), offer.key); + record.insert(proven(&offer)); + let mut store = MemoryStore::default(); + store.records.insert(offer.key, Arc::new(record)); + let mut second = machine(&words); + second.host.store = Some(store); + let Ok(Fetched::Block(stored)) = second.fetch_block(BASE + 4, false) else { + panic!("stored block") + }; + assert_eq!( + (second.statistics.compiled, second.statistics.stored), + (0, 1) + ); + let installed = |machine: &super::super::Machine< + super::super::tests::FakeHost, + crate::machine::NoDevices, + >, + index: usize| { + let block = &machine.blocks[index]; + ( + machine.host.installed[block.code.0 - 1].clone(), + block.source_map.clone(), + block.terminal, + block.successors.len(), + ) + }; + assert_eq!(installed(&first, compiled), installed(&second, stored)); + // Another entry PC, or the same page with other bytes, is compiled. + assert!(matches!( + second.fetch_block(BASE, false), + Ok(Fetched::Block(_)) + )); + assert_eq!(second.statistics.compiled, 1); + let mut changed = machine(&[0x1000_0040, 0x9100_0800, 0xd400_0001]); + changed.host.store = second.host.store.take(); + assert!(matches!( + changed.fetch_block(BASE + 4, false), + Ok(Fetched::Block(_)) + )); + assert_eq!( + (changed.statistics.compiled, changed.statistics.stored), + (1, 0) + ); + } + + #[test] + fn a_page_written_without_invalidation_is_read_and_hashed_again() { + // add x0, x0, #1; svc #0; add x0, x0, #2; svc #0 + let mut machine = machine(&[0x9100_0400, 0xd400_0001, 0x9100_0800, 0xd400_0001]); + machine.host.store = Some(MemoryStore::default()); + assert!(machine.fetch_block(BASE, false).is_ok()); + let key = machine.pages[&BASE].key; + // The guest rewrites the second block (add x0, x0, #3) with no IC + // IVAU: it is compiled from, and offered with, the new bytes. + machine.host.ram[8..12].copy_from_slice(&0x9100_0c00u32.to_le_bytes()); + assert!(machine.fetch_block(BASE + 8, false).is_ok()); + let offer = machine.host.store.as_mut().unwrap().offers.pop().unwrap(); + assert_ne!(offer.key, key); + assert_eq!(offer.key, machine.pages[&BASE].key); + assert_eq!(offer.input[..4], 0x9100_0c00u32.to_le_bytes()); + } + + #[test] + fn an_invalidated_page_is_read_and_looked_up_again() { + let mut machine = machine(&[0x9100_0400, 0xd400_0001]); + machine.host.store = Some(MemoryStore::default()); + assert!(machine.fetch_block(BASE, false).is_ok()); + let key = machine.pages[&BASE].key; + machine.host.ram[0] ^= 1; + machine.invalidate_code_page(BASE); + assert!(machine.pages.is_empty()); + assert!(machine.fetch_block(BASE, false).is_ok()); + assert_ne!(machine.pages[&BASE].key, key); + } +} diff --git a/crates/stela-runtime/src/translations.rs b/crates/stela-runtime/src/translations.rs new file mode 100644 index 0000000000..61a52276b1 --- /dev/null +++ b/crates/stela-runtime/src/translations.rs @@ -0,0 +1,664 @@ +//! The persistent translation store's format +//! (`docs/design/runtime.md#persistent-translation-store`): page records of +//! block translations keyed by the SHA-256 of their guest fetch page, with +//! guest addresses in the native code stored relative to the page, and the +//! proof that a block's code depends on its address only through them. +//! +//! The format is the same in every container: the hosted directory store +//! (`crate::hosted::translations`) and the pack `stela.efi` keeps. +use alloc::{string::String, vec::Vec}; +use sha2::{Digest as _, Sha256}; +use stela_compiler::{ + GuestAddress, NativeBlock, + block::{CompiledBlock, ExitKind, FaultRecovery}, + x86_64::chain::DirectExit, +}; + +/// The bytes of the fetch page a record covers: no block leaves it. +pub const PAGE_BYTES: usize = 4096; +pub const SCHEMA: u32 = 1; +const RECORD_MAGIC: [u8; 8] = *b"STLTPAGE"; +const HEADER_BYTES: usize = 88; +const TRAILER_BYTES: usize = 32; +/// A relocated field: a little-endian u64 in the native code. +const FIELD_BYTES: usize = 8; +/// The bits of a page's address its translations are bound to (the +/// address class): probes and rebasing never change them. +const CLASS_SHIFT: u32 = 47; +/// The probe displacements: 16 KiB multiples (every slide is one, so page +/// offsets are kept) with bits set in every 16-bit lane below the class +/// bits, in complementary patterns, so that a guest address the compiler +/// narrowed or partly overwrote moves by other than the displacement. +const PROBES: [u64; 2] = [0x2aaa_aaaa_c000, 0x1555_5555_4000]; + +/// A SHA-256 digest: a translator id, a page key or an entry context. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct Digest(pub [u8; 32]); + +impl Digest { + pub fn of(bytes: &[u8]) -> Self { + Self(Sha256::digest(bytes).into()) + } + + pub fn hex(&self) -> String { + hex::encode(self.0) + } +} + +/// The translator id: what decides the code a translation input produces. +pub fn translator_id() -> Digest { + let mut hasher = Sha256::new(); + hasher.update(RECORD_MAGIC); + hasher.update(SCHEMA.to_le_bytes()); + for part in [ + stela_compiler::block::SYSTEM_MODE_BLOCK_ABI, + stela_compiler::SOURCE_SHA256, + ENGINE_SOURCE_SHA256, + ] { + hasher.update(part.as_bytes()); + hasher.update([0]); + } + Digest(hasher.finalize().into()) +} + +/// The engine's compile-driver sources (`build.rs`). +pub const ENGINE_SOURCE_SHA256: &str = env!("STELA_ENGINE_SOURCE_SHA256"); + +/// The address class of a page: bits 47..63 of its address. +pub fn address_class(page: u64) -> u64 { + page >> CLASS_SHIFT +} + +/// One direct exit, its target relative to the page. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Exit { + pub offset: u32, + pub target: u64, + pub kind: u8, +} + +/// One stored block translation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + pub context: Digest, + /// The page offset of its entry PC. + pub offset: u16, + pub source_bytes: u16, + /// Native code, each relocation field holding `value - page`. + pub code: Vec, + /// Code offsets of the relocation fields, ascending. + pub relocations: Vec, + /// Page offset of each guest instruction and its native offset. + pub source_map: Vec<(u16, u32)>, + pub exits: Vec, + pub recovery: Vec, +} + +impl Entry { + /// The block as compiled at the page whose address is `page`. + pub fn rebase(&self, page: u64) -> Option { + let mut code = self.code.clone(); + for &at in &self.relocations { + let field = code.get_mut(at as usize..at as usize + FIELD_BYTES)?; + let value = u64::from_le_bytes(field.try_into().ok()?).wrapping_add(page); + field.copy_from_slice(&value.to_le_bytes()); + } + let direct_exits = self + .exits + .iter() + .map(|exit| { + Some(DirectExit { + offset: exit.offset as usize, + target: GuestAddress(exit.target.wrapping_add(page)), + kind: ExitKind::try_from(u64::from(exit.kind)).ok()?, + }) + }) + .collect::>()?; + Some(CompiledBlock { + native: NativeBlock { + x86_64_code: code, + source_map: self + .source_map + .iter() + .map(|&(guest, native)| { + (GuestAddress(page + u64::from(guest)), native as usize) + }) + .collect(), + }, + source_bytes: usize::from(self.source_bytes), + direct_exits, + fault_recovery: self.recovery.clone(), + }) + } + + /// Check what decoding cannot: offsets inside the code and the page, + /// ascending source map and relocations, and fields that do not overlap. + fn consistent(&self) -> bool { + let code = self.code.len(); + let in_code = |offset: u32, bytes: usize| (offset as usize).saturating_add(bytes) <= code; + usize::from(self.offset) + usize::from(self.source_bytes) <= PAGE_BYTES + && self.source_bytes != 0 + && self + .relocations + .windows(2) + .all(|pair| pair[0] + FIELD_BYTES as u32 <= pair[1]) + && self + .relocations + .iter() + .all(|&offset| in_code(offset, FIELD_BYTES)) + && self.source_map.windows(2).all(|pair| pair[0] < pair[1]) + && self + .source_map + .iter() + .all(|&(guest, native)| usize::from(guest) < PAGE_BYTES && in_code(native, 0)) + && self.exits.iter().all(|exit| { + in_code(exit.offset, 0) && ExitKind::try_from(u64::from(exit.kind)).is_ok() + }) + && self.recovery.iter().all(|range| { + range.start <= range.end + && range.end <= code + && range + .registers + .iter() + .all(|&(guest, host)| guest <= 31 && host < 16) + }) + } +} + +/// Why a stored record is not used. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FormatError { + Truncated, + Magic, + Schema, + Translator, + Key, + Checksum, + Entry, +} + +/// The translations of one page content. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Record { + pub translator: Digest, + pub key: Digest, + pub entries: Vec, +} + +impl Record { + pub fn new(translator: Digest, key: Digest) -> Self { + Self { + translator, + key, + entries: Vec::new(), + } + } + + pub fn find(&self, offset: u16, context: &Digest) -> Option<&Entry> { + self.entries + .iter() + .find(|entry| entry.offset == offset && entry.context == *context) + } + + /// Add `entry`, replacing one for the same entry PC and context. + pub fn insert(&mut self, entry: Entry) { + match self + .entries + .iter_mut() + .find(|other| other.offset == entry.offset && other.context == entry.context) + { + Some(other) => *other = entry, + None => self.entries.push(entry), + } + } + + /// Add the entries of `other` this record lacks. + pub fn merge(&mut self, other: Self) { + for entry in other.entries { + if self.find(entry.offset, &entry.context).is_none() { + self.entries.push(entry); + } + } + } + + pub fn encode(&self) -> Vec { + let mut out = Vec::with_capacity( + HEADER_BYTES + + TRAILER_BYTES + + self + .entries + .iter() + .map(|entry| 64 + entry.code.len() + entry.source_map.len() * 6) + .sum::(), + ); + out.extend(RECORD_MAGIC); + out.extend(SCHEMA.to_le_bytes()); + out.extend((self.entries.len() as u32).to_le_bytes()); + out.extend(self.translator.0); + out.extend(self.key.0); + out.extend(0u64.to_le_bytes()); + for entry in &self.entries { + out.extend(entry.context.0); + out.extend(entry.offset.to_le_bytes()); + out.extend(entry.source_bytes.to_le_bytes()); + out.extend((entry.code.len() as u32).to_le_bytes()); + out.extend((entry.relocations.len() as u32).to_le_bytes()); + for offset in &entry.relocations { + out.extend(offset.to_le_bytes()); + } + out.extend((entry.source_map.len() as u32).to_le_bytes()); + for (guest, native) in &entry.source_map { + out.extend(guest.to_le_bytes()); + out.extend(native.to_le_bytes()); + } + out.extend((entry.exits.len() as u32).to_le_bytes()); + for exit in &entry.exits { + out.extend(exit.offset.to_le_bytes()); + out.extend(exit.target.to_le_bytes()); + out.push(exit.kind); + } + out.extend((entry.recovery.len() as u32).to_le_bytes()); + for range in &entry.recovery { + out.extend((range.start as u32).to_le_bytes()); + out.extend((range.end as u32).to_le_bytes()); + out.extend((range.registers.len() as u32).to_le_bytes()); + for &(guest, host) in &range.registers { + out.extend([guest, host]); + } + } + out.extend(&entry.code); + } + let total = (out.len() + TRAILER_BYTES) as u64; + out[80..88].copy_from_slice(&total.to_le_bytes()); + let checksum = Sha256::digest(&out); + out.extend(checksum); + out + } + + /// Decode a record for `translator` and page `key`, checking it whole. + pub fn decode(bytes: &[u8], translator: &Digest, key: &Digest) -> Result { + if bytes.len() < HEADER_BYTES + TRAILER_BYTES { + return Err(FormatError::Truncated); + } + let (body, trailer) = bytes.split_at(bytes.len() - TRAILER_BYTES); + let mut reader = Reader(body); + if reader.take(8)? != RECORD_MAGIC { + return Err(FormatError::Magic); + } + if reader.u32()? != SCHEMA { + return Err(FormatError::Schema); + } + let count = reader.u32()?; + if reader.digest()? != *translator { + return Err(FormatError::Translator); + } + if reader.digest()? != *key { + return Err(FormatError::Key); + } + if reader.u64()? != bytes.len() as u64 { + return Err(FormatError::Truncated); + } + if Sha256::digest(body).as_slice() != trailer { + return Err(FormatError::Checksum); + } + let mut entries = Vec::new(); + for _ in 0..count { + let entry = reader.entry()?; + if !entry.consistent() { + return Err(FormatError::Entry); + } + entries.push(entry); + } + if !reader.0.is_empty() { + return Err(FormatError::Entry); + } + Ok(Self { + translator: *translator, + key: *key, + entries, + }) + } +} + +/// Bounded little-endian reads; every count is checked against the bytes +/// left before anything is allocated. +struct Reader<'a>(&'a [u8]); + +impl<'a> Reader<'a> { + fn take(&mut self, bytes: usize) -> Result<&'a [u8], FormatError> { + if self.0.len() < bytes { + return Err(FormatError::Truncated); + } + let (taken, rest) = self.0.split_at(bytes); + self.0 = rest; + Ok(taken) + } + + fn array(&mut self) -> Result<[u8; N], FormatError> { + Ok(self.take(N)?.try_into().expect("N bytes")) + } + + fn u8(&mut self) -> Result { + Ok(self.array::<1>()?[0]) + } + + fn u16(&mut self) -> Result { + Ok(u16::from_le_bytes(self.array()?)) + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.array()?)) + } + + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.array()?)) + } + + fn digest(&mut self) -> Result { + Ok(Digest(self.array()?)) + } + + /// A count of items of at least `item` bytes each. + fn count(&mut self, item: usize) -> Result { + let count = self.u32()? as usize; + if count.saturating_mul(item) > self.0.len() { + return Err(FormatError::Truncated); + } + Ok(count) + } + + fn entry(&mut self) -> Result { + let context = self.digest()?; + let offset = self.u16()?; + let source_bytes = self.u16()?; + let code_bytes = self.u32()? as usize; + let relocations = (0..self.count(4)?) + .map(|_| self.u32()) + .collect::>()?; + let source_map = (0..self.count(6)?) + .map(|_| Ok((self.u16()?, self.u32()?))) + .collect::>()?; + let exits = (0..self.count(13)?) + .map(|_| { + Ok(Exit { + offset: self.u32()?, + target: self.u64()?, + kind: self.u8()?, + }) + }) + .collect::>()?; + let recovery = (0..self.count(12)?) + .map(|_| { + let start = self.u32()? as usize; + let end = self.u32()? as usize; + let registers = (0..self.count(2)?) + .map(|_| Ok((self.u8()?, self.u8()?))) + .collect::>()?; + Ok(FaultRecovery { + start, + end, + registers, + }) + }) + .collect::>()?; + let code = self.take(code_bytes)?.to_vec(); + Ok(Entry { + context, + offset, + source_bytes, + code, + relocations, + source_map, + exits, + recovery, + }) + } +} + +/// The two probe displacements for a page at `page`: each moves it within +/// its address class, up when that stays in the class and down otherwise. +pub fn probe_displacements(page: u64) -> [u64; 2] { + PROBES.map(|probe| { + let up = page.wrapping_add(probe); + if address_class(up) == address_class(page) && up > page { + probe + } else { + probe.wrapping_neg() + } + }) +} + +/// The stored form of `block`, compiled at `pc` in the page at `page`, given +/// the same source compiled at the two [`probe_displacements`] of the page: +/// `None` unless the three differ only in 8-byte fields, each by exactly +/// its probe's displacement, and in their exit targets and source maps by +/// the same. +pub fn prove( + block: &CompiledBlock, + page: u64, + pc: u64, + context: Digest, + probes: [&CompiledBlock; 2], +) -> Option { + let displacements = probe_displacements(page); + let code = &block.native.x86_64_code; + let same_shape = |probe: &CompiledBlock, displacement: u64| { + probe.source_bytes == block.source_bytes + && probe.native.x86_64_code.len() == code.len() + && probe.fault_recovery == block.fault_recovery + && probe.native.source_map.len() == block.native.source_map.len() + && probe + .native + .source_map + .iter() + .zip(&block.native.source_map) + .all(|(moved, original)| { + moved.1 == original.1 && moved.0.0.wrapping_sub(original.0.0) == displacement + }) + && probe.direct_exits.len() == block.direct_exits.len() + && probe + .direct_exits + .iter() + .zip(&block.direct_exits) + .all(|(moved, original)| { + moved.offset == original.offset + && moved.kind == original.kind + && moved.target.0.wrapping_sub(original.target.0) == displacement + }) + }; + if !probes + .iter() + .zip(displacements) + .all(|(probe, displacement)| same_shape(probe, displacement)) + { + return None; + } + let field = |bytes: &[u8], at: usize| { + u64::from_le_bytes(bytes[at..at + FIELD_BYTES].try_into().expect("8 bytes")) + }; + let moves = |at: usize| { + at + FIELD_BYTES <= code.len() + && probes + .iter() + .zip(displacements) + .all(|(probe, displacement)| { + field(&probe.native.x86_64_code, at).wrapping_sub(field(code, at)) + == displacement + }) + }; + let mut relocations = Vec::new(); + let mut at = 0; + while at < code.len() { + if probes + .iter() + .all(|probe| probe.native.x86_64_code[at] == code[at]) + { + at += 1; + continue; + } + // The field holding the first differing byte starts at most 7 + // bytes before it, and after the previous field. + let floor = relocations + .last() + .map_or(0, |&last: &u32| last as usize + FIELD_BYTES); + let start = + (at.saturating_sub(FIELD_BYTES - 1).max(floor)..=at).find(|&start| moves(start))?; + relocations.push(start as u32); + at = start + FIELD_BYTES; + } + let mut stored = code.clone(); + for &start in &relocations { + let start = start as usize; + let value = field(code, start).wrapping_sub(page); + stored[start..start + FIELD_BYTES].copy_from_slice(&value.to_le_bytes()); + } + let page_offset = |guest: u64| { + u16::try_from(guest.wrapping_sub(page)) + .ok() + .filter(|&offset| usize::from(offset) < PAGE_BYTES) + }; + let entry = Entry { + context, + offset: page_offset(pc)?, + source_bytes: u16::try_from(block.source_bytes).ok()?, + code: stored, + relocations, + source_map: block + .native + .source_map + .iter() + .map(|&(guest, native)| Some((page_offset(guest.0)?, u32::try_from(native).ok()?))) + .collect::>()?, + exits: block + .direct_exits + .iter() + .map(|exit| { + Some(Exit { + offset: u32::try_from(exit.offset).ok()?, + target: exit.target.0.wrapping_sub(page), + kind: exit.kind as u8, + }) + }) + .collect::>()?, + recovery: block.fault_recovery.clone(), + }; + entry.consistent().then_some(entry) +} + +#[cfg(test)] +mod tests { + use super::*; + use stela_compiler::{ + TargetCpu, + block::{BlockProfile, CompilationPlan}, + x86_64::MemoryChecks, + }; + + const PAGE: u64 = 0x1_0000_4000; + + fn words(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() + } + + fn compile(source: &[u8], pc: u64) -> CompiledBlock { + CompilationPlan::new( + source, + GuestAddress(pc), + BlockProfile::SystemModeV1, + TargetCpu::Baseline, + ) + .and_then(|plan| plan.with_memory_checks(MemoryChecks::system(true, false, true, true))) + .and_then(CompilationPlan::compile) + .unwrap() + } + + fn proved(source: &[u8], offset: u64) -> Option { + let pc = PAGE + offset; + let block = compile(source, pc); + let [first, second] = probe_displacements(PAGE); + let probes = [ + compile(source, pc.wrapping_add(first)), + compile(source, pc.wrapping_add(second)), + ]; + prove( + &block, + PAGE, + pc, + Digest::of(b"context"), + [&probes[0], &probes[1]], + ) + } + + #[test] + fn address_dependent_blocks_rebase_to_what_the_compiler_emits_at_another_page() { + // adrp x0, 1; add x0, x0, #8; ldr x1, #16; bl +8 + let source = words(&[0x9000_0020, 0x9100_2000, 0x5800_0081, 0x9400_0002]); + let entry = proved(&source, 0x40).expect("relocatable"); + assert!(entry.relocations.len() >= 3, "{:?}", entry.relocations); + for other in [0x2_3456_8000u64, 0x4000, 0x7fff_0000_0000] { + let expected = compile(&source, other + 0x40); + let rebased = entry.rebase(other).unwrap(); + assert_eq!( + rebased.native.x86_64_code, expected.native.x86_64_code, + "page {other:#x}" + ); + assert_eq!(rebased.native.source_map, expected.native.source_map); + assert_eq!(rebased.direct_exits, expected.direct_exits); + assert_eq!(rebased.fault_recovery, expected.fault_recovery); + assert_eq!(rebased.source_bytes, expected.source_bytes); + } + } + + #[test] + fn a_narrowed_page_address_is_not_relocatable() { + // adrp x8, 0; add w9, w8, #0x20 (a 32-bit result of the address); ret + let source = words(&[0x9000_0008, 0x1100_8109, 0xd65f_03c0]); + assert_eq!(proved(&source, 0), None); + } + + #[test] + fn records_round_trip_and_refuse_every_damaged_byte_of_their_header_and_trailer() { + let source = words(&[0x9000_0020, 0x9400_0002]); + let entry = proved(&source, 0x10).unwrap(); + let (translator, key) = (translator_id(), Digest::of(&[7; PAGE_BYTES])); + let mut record = Record::new(translator, key); + record.insert(entry.clone()); + record.insert(entry); + assert_eq!(record.entries.len(), 1); + let bytes = record.encode(); + assert_eq!( + Record::decode(&bytes, &translator, &key), + Ok(record.clone()) + ); + assert_eq!( + Record::decode(&bytes, &Digest::default(), &key), + Err(FormatError::Translator) + ); + assert_eq!( + Record::decode(&bytes, &translator, &Digest::default()), + Err(FormatError::Key) + ); + for at in (0..bytes.len()).step_by(7) { + let mut damaged = bytes.clone(); + damaged[at] ^= 0x40; + assert!( + Record::decode(&damaged, &translator, &key).is_err(), + "byte {at}" + ); + } + for length in [0, HEADER_BYTES, bytes.len() - 1] { + assert!(Record::decode(&bytes[..length], &translator, &key).is_err()); + } + } + + #[test] + fn probes_stay_in_the_address_class_of_their_page() { + for page in [0u64, 0x1_8000_0000, 0x7fff_ffff_c000, 0xffff_fe00_0700_4000] { + for displacement in probe_displacements(page) { + let moved = page.wrapping_add(displacement); + assert_eq!(address_class(moved), address_class(page), "{page:#x}"); + assert_eq!(moved & 0x3fff, page & 0x3fff); + } + } + } +}