diff --git a/Cargo.lock b/Cargo.lock index ae3aff84d83..47908e1d40d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -657,6 +657,7 @@ name = "celox-heap" version = "0.11.0" dependencies = [ "fxhash", + "serde", ] [[package]] diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml index 477e1d8a232..0ab148bba27 100644 --- a/crates/celox-heap/Cargo.toml +++ b/crates/celox-heap/Cargo.toml @@ -10,6 +10,7 @@ edition.workspace = true rust-version.workspace = true [dependencies] +serde = { workspace = true, features = ["rc"] } fxhash = { workspace = true } [lints] diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index 9d708fe87c1..e280424d429 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -35,7 +35,7 @@ pub const EMPTY_STRING: Handle = 0; const MIN_COLLECTION_INTERVAL: usize = 1024; /// What a handle refers to. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum HandleKind { String, Object, @@ -65,7 +65,7 @@ impl Root { } /// Dynamic strings and class objects referenced by [`Handle`]. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct Heap { strings: HashMap>, lookup: HashMap, Handle>, diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index 2683ca747b9..097a345e198 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -11,7 +11,7 @@ use crate::{Handle, HandleKind, Heap}; /// The handle of `null`, the value of zero-initialized memory. pub const NULL: Handle = 0; -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(crate) struct Object { class: u32, random_state: u64, @@ -24,7 +24,7 @@ pub(crate) struct Object { pub(crate) handles: Vec<(u32, HandleKind)>, } -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] struct RandomModes { overrides: fxhash::FxHashMap, /// Non-rand properties temporarily made random by an argument list. @@ -47,7 +47,7 @@ impl Object { /// An error that compiled code made in a heap operation, which the runtime /// reports once control returns to it. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Fault { /// A property access or method call through `null` or a handle of no /// live object (IEEE 1800-2023 8.4). diff --git a/crates/celox-runtime/src/file_io.rs b/crates/celox-runtime/src/file_io.rs index 43829b1e38d..24c6b95517c 100644 --- a/crates/celox-runtime/src/file_io.rs +++ b/crates/celox-runtime/src/file_io.rs @@ -1,10 +1,12 @@ //! SystemVerilog file descriptors and multichannel descriptors (IEEE 1800-2023 21.3). //! //! A manager belongs to one simulation. No process-global descriptor table is used. +use crate::file_io_backend::{FileMode, FileSystem, HostFileSystem}; use std::collections::BTreeMap; -use std::fs::{File, OpenOptions}; +use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::Path; +use std::sync::{Arc, Mutex}; use celox_testbench::{DisplayFormatArg, FieldSpec, format_sv_display_arg}; @@ -12,7 +14,8 @@ const FD_FLAG: u32 = 0x8000_0000; #[derive(Debug)] pub struct FileIo { - channels: BTreeMap, + backend: Arc>>, + channels: BTreeMap, descriptors: BTreeMap, stdin_input: InputState, stdin_open: bool, @@ -20,7 +23,7 @@ pub struct FileIo { stderr_open: bool, } -#[derive(Debug, Default)] +#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] struct InputState { eof: bool, pushed: Option, @@ -28,14 +31,21 @@ struct InputState { #[derive(Debug)] struct InputFile { - file: File, + file: BackendFile, readable: bool, input: InputState, } impl Default for FileIo { fn default() -> Self { + Self::new(Box::::default()) + } +} + +impl FileIo { + pub fn new(backend: Box) -> Self { Self { + backend: Arc::new(Mutex::new(backend)), channels: BTreeMap::new(), descriptors: BTreeMap::new(), stdin_input: InputState::default(), @@ -44,34 +54,105 @@ impl Default for FileIo { stderr_open: true, } } -} -impl FileIo { + /// Capture Celox's bookkeeping and the backend's opaque state. Unsupported + /// backend capture is retained as a restore error, allowing inspection. + pub fn snapshot(&self) -> FileIoSnapshot { + let backend = self.backend.lock().unwrap(); + let state = backend + .snapshot() + .and_then(|bytes| { + if backend.snapshot_format().is_empty() { + return Err(io::Error::other( + "snapshot backend must declare a format identity", + )); + } + Ok((backend.snapshot_format().to_owned(), bytes)) + }) + .map_err(|error| error.to_string()); + FileIoSnapshot { + state, + channels: self + .channels + .iter() + .map(|(&key, file)| (key, file.id)) + .collect(), + descriptors: self + .descriptors + .iter() + .map(|(&key, file)| (key, file.file.id, file.readable, file.input.clone())) + .collect(), + stdin_input: self.stdin_input.clone(), + standard_open: [self.stdin_open, self.stdout_open, self.stderr_open], + } + } + + /// Capture a resumable handler state, reporting backend capture failures. + /// System-level checkpoint writers use this rather than publishing a + /// diagnostic snapshot containing an error. + pub fn try_snapshot(&self) -> io::Result { + let snapshot = self.snapshot(); + snapshot + .state + .as_ref() + .map_err(|error| io::Error::other(error.clone()))?; + Ok(snapshot) + } + + /// Prepare a replacement without changing this manager or its backend. + pub fn prepare_restore(&self, snapshot: &FileIoSnapshot) -> io::Result { + let (format, bytes) = snapshot + .state + .as_ref() + .map_err(|error| io::Error::other(error.clone()))?; + let backend = self.backend.lock().unwrap(); + if backend.snapshot_format() != format { + return Err(io::Error::other( + "file I/O snapshot backend format mismatch", + )); + } + let restored = backend.restore(bytes)?; + if restored.snapshot_format() != format { + return Err(io::Error::other( + "restored file I/O backend format mismatch", + )); + } + let mut manager = Self::new(restored); + for &(key, id) in &snapshot.channels { + manager.channels.insert( + key, + BackendFile { + id, + closed: false, + backend: manager.backend.clone(), + }, + ); + } + for (key, id, readable, input) in &snapshot.descriptors { + manager.descriptors.insert( + *key, + InputFile { + file: BackendFile { + id: *id, + closed: false, + backend: manager.backend.clone(), + }, + readable: *readable, + input: input.clone(), + }, + ); + } + manager.stdin_input = snapshot.stdin_input.clone(); + [manager.stdin_open, manager.stdout_open, manager.stderr_open] = snapshot.standard_open; + Ok(manager) + } + /// Open an MCD when mode is absent, otherwise an FD. Failure returns zero, /// as specified by 21.3.1. Closed channel numbers are reused. pub fn open(&mut self, path: impl AsRef, mode: Option<&str>) -> u32 { - let mut options = OpenOptions::new(); - match mode.unwrap_or("w") { - "r" | "rb" => { - options.read(true); - } - "w" | "wb" => { - options.write(true).create(true).truncate(true); - } - "a" | "ab" => { - options.append(true).create(true); - } - "r+" | "r+b" | "rb+" => { - options.read(true).write(true); - } - "w+" | "w+b" | "wb+" => { - options.read(true).write(true).create(true).truncate(true); - } - "a+" | "a+b" | "ab+" => { - options.read(true).append(true).create(true); - } - _ => return 0, - } + let Some(options) = FileMode::parse(mode.unwrap_or("w")) else { + return 0; + }; let key = if mode.is_some() { let Some(key) = (3..FD_FLAG).find(|key| !self.descriptors.contains_key(key)) else { return 0; @@ -86,9 +167,14 @@ impl FileIo { }; key }; - let Ok(mut file) = options.open(path) else { + let Ok(id) = self.backend.lock().unwrap().open(path.as_ref(), options) else { return 0; }; + let mut file = BackendFile { + id, + closed: false, + backend: self.backend.clone(), + }; if let Some(mode) = mode { // Table 21-6 places the initial position at EOF for append modes, // including the read position of update streams (a+). @@ -131,10 +217,10 @@ impl FileIo { Err(invalid_descriptor()) }; } - let Some(mut file) = self.descriptors.remove(&key) else { + let Some(file) = self.descriptors.remove(&key) else { return Err(invalid_descriptor()); }; - return file.file.flush(); + return file.file.close(); } let mut error = None; if descriptor & 1 != 0 && !std::mem::replace(&mut self.stdout_open, false) { @@ -144,8 +230,8 @@ impl FileIo { let key = 1u32 << bit; if descriptor & key != 0 { match self.channels.remove(&key) { - Some(mut file) => { - if let Err(err) = file.flush() { + Some(file) => { + if let Err(err) = file.close() { error = Some(err); } } @@ -171,7 +257,7 @@ impl FileIo { )), 1 if self.stdout_open => Ok(true), 2 if self.stderr_open => { - io::stderr().lock().write_all(bytes)?; + self.backend.lock().unwrap().write_stderr(bytes)?; Ok(false) } key => { @@ -217,7 +303,7 @@ impl FileIo { /// a pushed-back byte is returned before the underlying file is read. pub fn read_byte(&mut self, descriptor: u32) -> io::Result> { if descriptor == FD_FLAG && self.stdin_open { - return read_input_byte(&mut io::stdin().lock(), &mut self.stdin_input); + return read_input_byte(&mut BackendStdin(&self.backend), &mut self.stdin_input); } let file = self.readable_file(descriptor)?; read_input_byte(&mut file.file, &mut file.input) @@ -316,8 +402,8 @@ impl FileIo { if descriptor & FD_FLAG != 0 { return match descriptor & !FD_FLAG { 0 if self.stdin_open => Ok(()), - 1 if self.stdout_open => io::stdout().lock().flush(), - 2 if self.stderr_open => io::stderr().lock().flush(), + 1 if self.stdout_open => self.backend.lock().unwrap().flush_stdout(), + 2 if self.stderr_open => self.backend.lock().unwrap().flush_stderr(), _ => self.positioned_file(descriptor)?.file.flush(), }; } @@ -330,13 +416,13 @@ impl FileIo { }; if descriptor.is_none() || descriptor.is_some_and(|bits| bits & 1 != 0) { if self.stdout_open { - attempt(io::stdout().lock().flush()); + attempt(self.backend.lock().unwrap().flush_stdout()); } else if descriptor.is_some() { attempt(Err(invalid_descriptor())); } } if descriptor.is_none() && self.stderr_open { - attempt(io::stderr().lock().flush()); + attempt(self.backend.lock().unwrap().flush_stderr()); } for bit in 1..31 { let key = 1u32 << bit; @@ -376,6 +462,27 @@ impl FileIo { Ok(file) } + /// Write memory through the injected backend, including its snapshot policy. + pub fn write_memory_with_backend<'a>( + &mut self, + path: impl AsRef, + binary: bool, + words: impl IntoIterator>, + ) -> io::Result<()> { + let id = self + .backend + .lock() + .unwrap() + .open(path.as_ref(), FileMode::parse("w").unwrap())?; + let mut file = BackendFile { + id, + closed: false, + backend: self.backend.clone(), + }; + write_memory_words(&mut file, binary, words)?; + file.close() + } + /// Write a static unpacked memory snapshot, without address specifiers /// (21.5.3). The caller supplies elements in the requested address order. pub fn write_memory<'a>( @@ -384,15 +491,83 @@ impl FileIo { words: impl IntoIterator>, ) -> io::Result<()> { let mut file = File::create(path)?; - for word in words { - file.write_all(&format_sv_display_arg( - &word, - if binary { 'b' } else { 'h' }, - FieldSpec::default(), - ))?; - file.write_all(b"\n")?; + write_memory_words(&mut file, binary, words) + } +} + +fn write_memory_words<'a>( + file: &mut impl Write, + binary: bool, + words: impl IntoIterator>, +) -> io::Result<()> { + for word in words { + file.write_all(&format_sv_display_arg( + &word, + if binary { 'b' } else { 'h' }, + FieldSpec::default(), + ))?; + file.write_all(b"\n")?; + } + file.flush() +} + +/// Host-owned I/O snapshot, separate from core checkpoints. Backend bytes are opaque; descriptor +/// bookkeeping cannot be edited independently of them. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct FileIoSnapshot { + state: Result<(String, Vec), String>, + channels: Vec<(u32, u64)>, + descriptors: Vec<(u32, u64, bool, InputState)>, + stdin_input: InputState, + standard_open: [bool; 3], +} + +#[derive(Debug)] +struct BackendFile { + id: u64, + closed: bool, + backend: Arc>>, +} +impl BackendFile { + fn close(mut self) -> io::Result<()> { + self.closed = true; + self.backend.lock().unwrap().close(self.id) + } +} +impl Read for BackendFile { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.backend.lock().unwrap().read(self.id, buffer) + } +} +impl Write for BackendFile { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.backend.lock().unwrap().write(self.id, buffer) + } + fn flush(&mut self) -> io::Result<()> { + self.backend.lock().unwrap().flush(self.id) + } +} +impl Seek for BackendFile { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.backend.lock().unwrap().seek(self.id, position) + } +} +impl Drop for BackendFile { + fn drop(&mut self) { + if self.closed { + return; } - file.flush() + let _ = self + .backend + .lock() + .unwrap_or_else(|e| e.into_inner()) + .close(self.id); + } +} +struct BackendStdin<'a>(&'a Arc>>); +impl Read for BackendStdin<'_> { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.0.lock().unwrap().read_stdin(buffer) } } diff --git a/crates/celox-runtime/src/file_io_backend.rs b/crates/celox-runtime/src/file_io_backend.rs new file mode 100644 index 00000000000..4e1c44ec5aa --- /dev/null +++ b/crates/celox-runtime/src/file_io_backend.rs @@ -0,0 +1,188 @@ +//! Host-supplied file I/O. Handles here are private to a backend; HDL descriptor +//! allocation and input bookkeeping remain in `FileIo`. +use std::{ + collections::BTreeMap, + fmt::Debug, + fs::{File, OpenOptions}, + io::{self, Read, Seek, SeekFrom, Write}, + path::Path, + sync::Arc, +}; + +/// Validated access mode passed to a host filesystem. +#[derive(Debug, Clone, Copy)] +pub struct FileMode { + pub read: bool, + pub write: bool, + pub append: bool, + pub create: bool, + pub truncate: bool, +} + +impl FileMode { + pub(crate) fn parse(mode: &str) -> Option { + let (read, write, append, create, truncate) = match mode { + "r" | "rb" => (true, false, false, false, false), + "w" | "wb" => (false, true, false, true, true), + "a" | "ab" => (false, true, true, true, false), + "r+" | "r+b" | "rb+" => (true, true, false, false, false), + "w+" | "w+b" | "wb+" => (true, true, false, true, true), + "a+" | "a+b" | "ab+" => (true, true, true, true, false), + _ => return None, + }; + Some(Self { + read, + write, + append, + create, + truncate, + }) + } +} + +/// I/O boundary implemented by an embedding host. +/// +/// Each instance owns its handle namespace. `snapshot` records all backend +/// state needed to resume, including open handles, positions and shared-file +/// relationships. The host defines how contents and external effects are +/// retained (for example by versioning, recording, or filesystem snapshots). +/// Celox neither selects nor assumes a storage strategy. +/// +/// `restore` must prepare an independent instance without changing the current +/// instance or externally visible state, including on failure. Returned handles +/// must have the same identities as in the snapshot. Dropping/closing the old +/// instance must not invalidate the new one. This permits Celox to validate and +/// prepare every resource before committing the restored simulation state. +/// Hosts may leave the snapshot methods at their defaults. This places no +/// restriction on core checkpoints: only a request to snapshot this handler +/// itself requires these methods. +/// Stdout bytes remain Celox runtime events; they are not withdrawn on restore. +pub trait FileSystem: Debug + Send { + fn open(&mut self, path: &Path, mode: FileMode) -> io::Result; + /// Flush and release a handle, including when flushing reports an error. + fn close(&mut self, handle: u64) -> io::Result<()>; + fn read(&mut self, handle: u64, buffer: &mut [u8]) -> io::Result; + fn write(&mut self, handle: u64, buffer: &[u8]) -> io::Result; + fn seek(&mut self, handle: u64, position: SeekFrom) -> io::Result; + fn flush(&mut self, handle: u64) -> io::Result<()>; + fn read_stdin(&mut self, _buffer: &mut [u8]) -> io::Result { + Err(unsupported()) + } + fn write_stderr(&mut self, _buffer: &[u8]) -> io::Result<()> { + Err(unsupported()) + } + fn flush_stdout(&mut self) -> io::Result<()> { + Ok(()) + } + fn flush_stderr(&mut self) -> io::Result<()> { + Ok(()) + } + /// Stable, host-defined format identity, including a version. A restore + /// rejects a different identity before calling the backend. + fn snapshot_format(&self) -> &str { + "" + } + /// Capture without consuming input, advancing positions or changing contents. + fn snapshot(&self) -> io::Result> { + Err(unsupported()) + } + fn restore(&self, _state: &[u8]) -> io::Result> { + Err(unsupported()) + } +} + +fn unsupported() -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + "file I/O backend does not support this operation", + ) +} + +/// Creates a fresh I/O namespace for each simulator, including compiler-created +/// shadow instances. Factories must not share mutable stream positions. +#[derive(Clone)] +pub struct FileSystemFactory(Arc Box + Send + Sync>); +impl FileSystemFactory { + pub fn new(factory: impl Fn() -> Box + Send + Sync + 'static) -> Self { + Self(Arc::new(factory)) + } + pub fn create(&self) -> Box { + (self.0)() + } +} +impl Default for FileSystemFactory { + fn default() -> Self { + Self::new(|| Box::::default()) + } +} +impl std::fmt::Debug for FileSystemFactory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("FileSystemFactory(..)") + } +} + +/// Default host OS implementation. It deliberately cannot promise rollback of +/// arbitrary files, pipes or standard input and does not implement snapshots. +#[derive(Debug, Default)] +pub struct HostFileSystem { + files: BTreeMap, + next: u64, +} +impl HostFileSystem { + fn file(&mut self, handle: u64) -> io::Result<&mut File> { + self.files.get_mut(&handle).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "unknown backend file handle") + }) + } +} +impl FileSystem for HostFileSystem { + fn open(&mut self, path: &Path, mode: FileMode) -> io::Result { + let file = OpenOptions::new() + .read(mode.read) + .write(mode.write) + .append(mode.append) + .create(mode.create) + .truncate(mode.truncate) + .open(path)?; + let next = self + .next + .checked_add(1) + .ok_or_else(|| io::Error::other("file handle space exhausted"))?; + let id = self.next; + self.next = next; + self.files.insert(id, file); + Ok(id) + } + fn close(&mut self, handle: u64) -> io::Result<()> { + self.files + .remove(&handle) + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "unknown backend file handle") + })? + .flush() + } + fn read(&mut self, handle: u64, buffer: &mut [u8]) -> io::Result { + self.file(handle)?.read(buffer) + } + fn write(&mut self, handle: u64, buffer: &[u8]) -> io::Result { + self.file(handle)?.write(buffer) + } + fn seek(&mut self, handle: u64, position: SeekFrom) -> io::Result { + self.file(handle)?.seek(position) + } + fn flush(&mut self, handle: u64) -> io::Result<()> { + self.file(handle)?.flush() + } + fn read_stdin(&mut self, buffer: &mut [u8]) -> io::Result { + io::stdin().lock().read(buffer) + } + fn write_stderr(&mut self, buffer: &[u8]) -> io::Result<()> { + io::stderr().lock().write_all(buffer) + } + fn flush_stdout(&mut self) -> io::Result<()> { + io::stdout().lock().flush() + } + fn flush_stderr(&mut self) -> io::Result<()> { + io::stderr().lock().flush() + } +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 2a07d54399b..850afa15f01 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -7,6 +7,7 @@ mod edge; mod error; mod event_buffer; pub mod file_io; +pub mod file_io_backend; pub mod parallel; pub mod plusargs; mod reflection; @@ -35,9 +36,9 @@ pub use reflection::{ }; pub use schedule::{ResolvedSchedule, host_watch}; pub use simulation::{ - CompiledSlots, EventInfo, HostBoundary, KernelSchedule, ScheduleKey, ScheduleParts, - SchedulerMode, SchedulerStats, SimulationExecutor, SimulationSnapshot, SimulationState, - StepObserver, UnitExecutor, + CompiledSlots, EventInfo, HostBoundary, KernelSchedule, PersistedSimulationSnapshot, + ScheduleKey, ScheduleParts, SchedulerMode, SchedulerStats, SimulationExecutor, + SimulationSnapshot, SimulationState, StepObserver, UnitExecutor, }; pub use state_file::{ BaselineRecord, NbaRecord, ProcessRecord, ScheduleRecord, ScheduledEvent, StateDifference, diff --git a/crates/celox-runtime/src/scheduler.rs b/crates/celox-runtime/src/scheduler.rs index c328336c445..da0cd6409ca 100644 --- a/crates/celox-runtime/src/scheduler.rs +++ b/crates/celox-runtime/src/scheduler.rs @@ -4,7 +4,7 @@ use crate::{ }; use std::collections::BinaryHeap; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ClockDef { pub period: u64, } diff --git a/crates/celox-runtime/src/simulation/activation.rs b/crates/celox-runtime/src/simulation/activation.rs index dcdcaeea1b7..036144465e9 100644 --- a/crates/celox-runtime/src/simulation/activation.rs +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -8,7 +8,7 @@ use crate::{ }; use celox_design::ForkJoin; -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Activation { pub kernel: usize, pub parent: Option, diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 0a57c8a08b0..af8b78fa4c3 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -24,7 +24,7 @@ use celox_design::CounterKind; pub(crate) use batch::{edge_level, event_level}; pub use host::{CompiledSlots, HostBoundary, HostWatch, SimulationExecutor, UnitExecutor}; pub use nba::NbaUpdate; -pub use persist::{ScheduleKey, ScheduleParts, SimulationSnapshot}; +pub use persist::{PersistedSimulationSnapshot, ScheduleKey, ScheduleParts, SimulationSnapshot}; pub use stats::{KernelSchedule, SchedulerMode, SchedulerStats}; pub use wait::{Baseline, Waiter, Waiters}; diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index 00b493f1180..42ab82d7f11 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -279,7 +279,7 @@ pub(super) fn restore_working_image(backend: &mut B, image: &[u8] } /// A nonblocking assignment waiting for the NBA region. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NbaUpdate { pub target: SignalRef, /// Bit position of the assigned range in the target. diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index 5da0c2a960b..813a2bfb652 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -341,3 +341,100 @@ pub struct ScheduleKey { pub stopped: bool, pub suspended: bool, } + +/// Pointer-free encoding of a checkpoint's scheduler. Unlike a portable state +/// file this includes live fork activations and lexical cells. Its schema is +/// private to the checkpoint container version. +#[doc(hidden)] +#[derive(serde::Serialize, serde::Deserialize)] +pub struct PersistedSimulationSnapshot { + time: u64, + clocks: Vec>, + events: Vec<(u64, usize, crate::SignalRef, u8, bool)>, + high: Vec, + unknown: Vec, + wakeups: Vec, + processes: ProcessState, + declarations_pending: bool, + host_pending: bool, + finished: bool, + finalizing: Option, +} + +impl SimulationSnapshot { + #[doc(hidden)] + pub fn persisted(&self) -> PersistedSimulationSnapshot { + PersistedSimulationSnapshot { + time: self.time, + clocks: self.clocks.clone(), + events: self + .event_queue + .iter() + .map(|event| { + ( + event.time, + event.event_ref.id(), + event.signal, + event.next_val, + event.periodic, + ) + }) + .collect(), + high: self.last_clock_values.iter().collect(), + unknown: self.last_clock_unknown.iter().collect(), + wakeups: self.process_wakeups.iter().copied().collect(), + processes: self.process_state.clone(), + declarations_pending: self.declarations_pending, + host_pending: self.host_pending, + finished: self.finished, + finalizing: self.finalizing, + } + } +} + +impl PersistedSimulationSnapshot { + /// Bind event IDs to the receiving compiled instance; machine-code addresses + /// never occur in the file. + /// + /// # Safety + /// This record must have been produced from a valid snapshot for the same + /// design. Its process state contains raw state-memory offsets. + #[doc(hidden)] + pub unsafe fn bind(self, events: &[B::Event]) -> Option> { + if self.clocks.len() > events.len() + || self + .high + .iter() + .chain(&self.unknown) + .any(|&id| id >= events.len()) + { + return None; + } + let event_queue = self + .events + .into_iter() + .map(|(time, id, signal, next_val, periodic)| { + Some(SimEvent { + time, + event_ref: *events.get(id)?, + signal, + next_val, + periodic, + }) + }) + .collect::>()?; + Some(SimulationSnapshot { + time: self.time, + clocks: self.clocks, + event_queue, + last_clock_values: self.high.into_iter().collect(), + last_clock_unknown: self.unknown.into_iter().collect(), + process_wakeups: self.wakeups.into_iter().collect(), + process_state: self.processes, + declarations_pending: self.declarations_pending, + host_pending: self.host_pending, + finished: self.finished, + finalizing: self.finalizing, + }) + } +} diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index 7c23f974f2e..8d5058d2b0f 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -311,7 +311,7 @@ pub(super) fn wake_in_region( } /// What one term of a waiting process compares against. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Baseline { /// The counter's value when the wait began, and the signal's value at /// the last check. Only kernels and combinational process units count a @@ -330,7 +330,7 @@ pub enum Baseline { } /// A process suspended at a wait. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Waiter { pub site: usize, pub baselines: Vec, @@ -338,7 +338,7 @@ pub struct Waiter { /// The processes suspended at a wait, by process index. A slot keeps its /// storage while its process runs, so suspending again reuses it. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Waiters { slots: Vec, waiting: Vec, diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 63478460d29..ecc042d1f8c 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -330,7 +330,7 @@ pub fn planes_occur(kind: CounterKind, old: &[u8], new: &[u8], width: usize) -> /// Mutable process scheduling state beyond the delay queue: who waits for /// what, the inactive and post-NBA queues, and the queued nonblocking /// assignments. All of it is empty in a design without process kernels. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ProcessState { pub activations: Vec, pub cells: Vec, diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index c830e6a18ce..b2d98151a65 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -389,6 +389,17 @@ pub struct VpiSession { } impl VpiSession { + /// Capture the last evaluated HDL values without dispatching callbacks. + /// + /// VPI callbacks, pending writes, forces and plugin memory are not saved. + /// The returned file is for inspection/diff or HDL-only initialization; + /// it cannot resume a VPI session. Call between dispatch runs or from a + /// read-only synchronization callback for settled values. Other callback + /// phases capture exactly the values currently visible to VPI reads. + pub fn save_state(&self) -> Result { + capture_host_state(&self.host) + } + // The C loader has no Rust caller to retain a guard. Transfer its lifetime // to the explicit celox_vpi_clear_runtime/clear_runtime boundary instead. fn detach(mut self) { @@ -657,6 +668,45 @@ fn install(runtime: Runtime) -> Result { }) } +fn capture_host_state(host: &VpiHost) -> Result { + let runtime = host + .runtime + .try_borrow() + .map_err(|_| "VPI runtime is executing; capture at a callback boundary")?; + runtime + .as_ref() + .ok_or("VPI runtime is unavailable")? + .save_state() + .map_err(|error| error.to_string()) +} + +/// Write a diagnostic HDL state file for the active VPI session. +/// +/// Returns 1 on success, 0 for an unavailable/busy runtime, invalid UTF-8 path, +/// unsupported state value, or I/O failure. Uses the capture contract of +/// [`VpiSession::save_state`]. Existing files at `path` are overwritten. +/// +/// # Safety +/// `path` must be null or point to a readable NUL-terminated UTF-8 string +/// for the duration of this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn celox_vpi_save_state(path: *const c_char) -> i32 { + if path.is_null() { + return 0; + } + // Safety: the caller supplies a readable C string. + let Ok(path) = unsafe { CStr::from_ptr(path) }.to_str() else { + return 0; + }; + let Ok(state) = with_host(capture_host_state) else { + return 0; + }; + let Ok(file) = std::fs::File::create(path) else { + return 0; + }; + i32::from(state.write_to(file).is_ok()) +} + /// Unregister the current thread's host. During callback dispatch this requests /// finish and defers unregistration until the callback run returns. pub fn clear_runtime() { diff --git a/crates/celox-vpi/src/state.rs b/crates/celox-vpi/src/state.rs index 76248f8cb2b..e0d02f2d2e2 100644 --- a/crates/celox-vpi/src/state.rs +++ b/crates/celox-vpi/src/state.rs @@ -29,6 +29,8 @@ pub(crate) trait VpiState { self.image().signal_identity(id) } + fn save_state(&self) -> Result; + /// The stored value, without settling the design. fn get_four_state(&self, signal: SignalRef) -> (BigUint, BigUint); @@ -46,6 +48,10 @@ pub(crate) trait VpiState { } impl VpiState for NativeProgramInstance { + fn save_state(&self) -> Result { + NativeProgramInstance::save_state(self).map_err(|error| error.to_string()) + } + fn image(&self) -> &NativeProgramImage { self.program_image() } @@ -77,6 +83,7 @@ impl VpiState for NativeProgramInstance { /// entry points that its slot observer's callbacks call reach the state /// through `slot`, which the observer sets for the duration of a dispatch. pub(crate) struct TimedRuntime { + schema: std::sync::Arc, image: NativeProgramImage, pub(crate) simulation: Option>, slot: Option<*mut SlotIo<'static, NativeBackend>>, @@ -87,6 +94,7 @@ pub(crate) struct TimedRuntime { impl TimedRuntime { pub(crate) fn new(image: NativeProgramImage, simulation: Simulation) -> Self { Self { + schema: simulation.state_schema(), image, simulation: Some(simulation), slot: None, @@ -141,6 +149,19 @@ impl TimedRuntime { } impl VpiState for TimedRuntime { + fn save_state(&self) -> Result { + if let Some(slot) = self.slot() { + slot.capture_state(&self.schema) + .map_err(|error| error.to_string()) + } else if let Some(simulation) = &self.simulation { + simulation + .capture_state() + .map_err(|error| error.to_string()) + } else { + Err("VPI runtime is executing; capture at a callback boundary".into()) + } + } + fn image(&self) -> &NativeProgramImage { &self.image } @@ -201,6 +222,10 @@ pub(crate) enum Runtime { } impl Runtime { + pub(crate) fn save_state(&self) -> Result { + self.state().save_state() + } + pub(crate) fn state(&self) -> &dyn VpiState { match self { Runtime::Untimed(instance) => instance, diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 151bb450beb..8f2971e3266 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -157,6 +157,55 @@ fn trusted_instance(image: celox::NativeProgramImage) -> NativeProgramInstance { unsafe { NativeProgramInstance::from_image(image) }.unwrap() } +#[test] +fn vpi_state_capture_matches_simulator_and_preserves_visible_values() { + let _serial = lock_vpi(); + let mut simulator = Simulator::builder(DESIGN, "Top") + .four_state(true) + .build() + .unwrap(); + let expected = simulator.save_state().unwrap(); + let instance = trusted_instance(simulator.shared_code().program_image().clone()); + assert_eq!(instance.save_state().unwrap(), expected); + let session = install_runtime(instance).unwrap(); + let before = session.save_state().unwrap(); + unsafe { + let a = vpi_handle_by_name(c"Top.a".as_ptr(), ptr::null_mut()); + assert!(!a.is_null()); + let value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 42 }, + }; + vpi_put_value(a, &value, ptr::null(), VPI_NO_DELAY); + let saved = session.save_state().unwrap(); + assert_ne!(saved, before); + assert!(saved.schedule.is_none()); + let a = saved + .objects + .iter() + .find(|object| object.path == "a") + .unwrap(); + assert_eq!(a.value, [42]); + let mut bytes = Vec::new(); + saved.write_to(&mut bytes).unwrap(); + assert_eq!( + celox::StateFile::read_from(bytes.as_slice()).unwrap(), + saved + ); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("vpi.state"); + let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap(); + assert_eq!(celox_vpi_save_state(c_path.as_ptr()), 1); + assert_eq!( + celox::StateFile::read_from(std::fs::File::open(path).unwrap()).unwrap(), + saved + ); + assert_eq!(celox_vpi_save_state(ptr::null()), 0); + // Capturing neither consumes events nor changes HDL values. + assert_eq!(session.save_state().unwrap(), saved); + } +} + const DESIGN: &str = r#" module Child ( i: input logic<8>, @@ -3899,3 +3948,76 @@ fn a_plain_input_settle_reports_fatal_errors() { let error = settle_plain_data_input("$fatal(1, \"fallback failure\");").unwrap_err(); assert!(error.contains("fallback failure"), "{error}"); } + +#[cfg(feature = "systemverilog")] +static TIMED_CAPTURE_STATUS: AtomicI32 = AtomicI32::new(0); + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn capture_timed_read_only(data: *mut VpiCbData) -> i32 { + // Safety: the test keeps its CString alive until callback dispatch returns. + let result = unsafe { celox_vpi_save_state((*data).user_data) }; + TIMED_CAPTURE_STATUS.store(result, Ordering::SeqCst); + 0 +} + +#[cfg(feature = "systemverilog")] +#[test] +fn timed_vpi_capture_reads_the_active_slot_without_advancing_it() { + let _serial = lock_vpi(); + let source = "module Top(output int count); initial begin count=7; #1 count=9; #1 $finish; end endmodule"; + let image = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("capture.sv"))], + "Top", + ) + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let session = install_timed_runtime(image, simulation).unwrap(); + assert!(session.save_state().unwrap().schedule.is_none()); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("timed.state"); + let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap(); + let mut time = VpiTime { + type_: VPI_SIM_TIME, + ..VpiTime::default() + }; + let callback = VpiCbData { + reason: CB_READ_ONLY_SYNCH, + cb_rtn: Some(capture_timed_read_only), + obj: ptr::null_mut(), + time: &mut time, + value: ptr::null_mut(), + index: 0, + user_data: c_path.as_ptr().cast_mut(), + }; + TIMED_CAPTURE_STATUS.store(0, Ordering::SeqCst); + unsafe { + assert!(!vpi_register_cb(&callback).is_null()); + } + assert!(run_callbacks_result().unwrap()); + assert_eq!(TIMED_CAPTURE_STATUS.load(Ordering::SeqCst), 1); + let saved = celox::StateFile::read_from(std::fs::File::open(path).unwrap()).unwrap(); + assert!(saved.schedule.is_none()); + assert_eq!( + saved + .objects + .iter() + .find(|o| o.path == "count") + .unwrap() + .value, + [7, 0, 0, 0] + ); + let final_state = session.save_state().unwrap(); + assert_eq!( + final_state + .objects + .iter() + .find(|o| o.path == "count") + .unwrap() + .value, + [9, 0, 0, 0] + ); +} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index b605d44113b..c30da3975dd 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -491,6 +491,11 @@ impl NativeProgramImage { &self.reflection } + /// Design metadata used to name saved state objects. + pub(crate) fn state_design(&self) -> &crate::ir::RuntimeDesign { + &self.design + } + /// Source-independent runtime diagnostics and combinational observers. pub(crate) fn runtime_schema(&self) -> &NativeRuntimeSchema { &self.runtime_schema diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index c13435839e2..ba5433e1228 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -126,6 +126,27 @@ impl NativeProgramInstance { unsafe { Self::from_image(appended.image) } } + /// Capture HDL values as last evaluated, without executing code or callbacks. + /// + /// This diagnostic state file excludes VPI callbacks, pending writes, force + /// registrations, plugin memory and time scheduling. It has no schedule and + /// is not a resumable VPI session. Signal values include currently applied + /// forces; output already emitted is not withdrawn. + pub fn save_state(&self) -> Result { + let image = self.shared.program_image(); + let schema = image.runtime_schema(); + crate::StateSchema::from_design( + &self.backend, + image.state_design(), + |address| schema.comb_writes.contains(address), + schema + .time_slots + .iter() + .chain(schema.scheduler.iter().flat_map(|s| s.slots.iter())), + ) + .capture(&self.backend) + } + /// Physical duration of one tick in the attached design. pub fn time_precision(&self) -> celox_design::TimePrecision { self.shared.program_image().time_precision() diff --git a/crates/celox/src/comb_activation.rs b/crates/celox/src/comb_activation.rs index 293f2e5eecf..060e674f50c 100644 --- a/crates/celox/src/comb_activation.rs +++ b/crates/celox/src/comb_activation.rs @@ -39,7 +39,7 @@ pub(crate) struct ObserverReads { } /// The values one observer's reads returned. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(crate) struct ObserverSnapshot { words: Vec, wide: Vec<(BigUint, BigUint)>, diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index b7dc82d5a5f..7055ed180c1 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -118,7 +118,9 @@ mod host_api { }; pub use crate::debug::CompilationTraceResult; pub use crate::diagnostics::DiagnosticsOptions; - pub use crate::simulation::{Simulation, SimulationCheckpoint, SlotObserver}; + pub use crate::simulation::{ + CheckpointFileError, Simulation, SimulationCheckpoint, SlotObserver, + }; #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -197,6 +199,16 @@ mod host_api { } } + /// Capture current HDL values without running any simulation regions. + /// Use the schema obtained from this simulation before entering the slot. + /// This diagnostic file has no schedule and is not a resumable checkpoint. + pub fn capture_state( + &self, + schema: &crate::StateSchema, + ) -> Result { + schema.capture(self.io.backend) + } + /// End the simulation when this observer callback returns, before /// any further scheduled work runs. Earlier host writes remain in state. pub fn request_finish(&mut self) { @@ -318,3 +330,6 @@ pub use signal_access::SignalAccessOptions; mod timescale; pub use timescale::SvTimescale; + +/// Host-injected file I/O and snapshot contracts. +pub use celox_runtime::file_io_backend::{FileMode, FileSystem, FileSystemFactory, HostFileSystem}; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index dfc7e05abd1..8ea525314f2 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -11,6 +11,8 @@ use celox_runtime::{ UnitExecutor, host_watch, }; +mod checkpoint_file; +pub use checkpoint_file::CheckpointFileError; mod differential; mod vcd_tasks; @@ -479,6 +481,8 @@ impl Simulation { } /// Save the design state, simulation time, clocks and pending events. + /// Effect-handler state (including file I/O and VPI) is excluded. The host + /// system coordinates its own handler snapshots with this core checkpoint. pub fn checkpoint(&self) -> Result, CheckpointError> { if self.state.is_suspended() { return Err(CheckpointError::Stopped); @@ -490,6 +494,27 @@ impl Simulation { }) } + /// File-I/O effect state owned by the embedding system, outside core checkpoints. + pub fn file_io(&self) -> &celox_runtime::file_io::FileIo { + self.simulator.file_io() + } + + /// Install a host-prepared file-I/O handler at an execution boundary. + pub fn replace_file_io(&mut self, file_io: celox_runtime::file_io::FileIo) { + self.simulator.replace_file_io(file_io); + } + + /// The schema used for diagnostic HDL captures, including observer callbacks. + pub fn state_schema(&self) -> std::sync::Arc { + self.simulator.state_schema() + } + + /// Capture current HDL values without settling or advancing time. The file + /// has no schedule and cannot resume a timed simulation or a VPI session. + pub fn capture_state(&self) -> Result { + self.state_schema().capture(&self.simulator.backend) + } + /// Save the value of every state object by path, together with the /// simulation time, clocks and pending events by name. pub fn save_state(&mut self) -> Result { @@ -563,7 +588,8 @@ impl Simulation { .filter(|local| local.addr() == event.addr()) }) .map_err(|_| CheckpointError::DesignMismatch)?; - self.simulator.restore(&checkpoint.simulator)?; + self.simulator + .restore_checkpoint_prepared(&checkpoint.simulator)?; self.state.retain_activation_roots(&mut self.simulator); self.simulator.declaration_phase = false; self.simulator diff --git a/crates/celox/src/simulation/checkpoint_file.rs b/crates/celox/src/simulation/checkpoint_file.rs new file mode 100644 index 00000000000..7ce107a4170 --- /dev/null +++ b/crates/celox/src/simulation/checkpoint_file.rs @@ -0,0 +1,105 @@ +//! Persistence of core execution state. Effect-handler state belongs to the host. +use super::{Simulation, SimulationCheckpoint}; +use crate::{CheckpointError, SimBackend, simulator::checkpoint::PersistedCheckpoint}; +use celox_runtime::PersistedSimulationSnapshot; +use serde::{Deserialize, Serialize}; + +const MAGIC: &[u8; 8] = b"CELOXCP1"; +// Bump whenever a serialized core-state schema or its interpretation changes. +const VERSION: u32 = 1; + +#[derive(Debug, thiserror::Error)] +pub enum CheckpointFileError { + #[error("invalid or incompatible checkpoint container")] + InvalidContainer, + #[error("checkpoint encoding failed: {0}")] + Encoding(#[from] postcard::Error), + #[error(transparent)] + Checkpoint(#[from] CheckpointError), +} + +#[derive(Serialize, Deserialize)] +struct CoreState { + version: u32, + release: String, + architecture: String, + little_endian: bool, + simulator: PersistedCheckpoint, + schedule: PersistedSimulationSnapshot, + host_writes: Vec<(crate::ir::SignalRef, celox_runtime::timing::Value)>, +} + +fn checksum(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf29ce484222325, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3) + }) +} + +impl SimulationCheckpoint { + /// Encode core execution state, including live fork activations and heap + /// objects. No effect-handler state or machine-code addresses are included. + /// This is a versioned implementation format, not a portable StateFile. + pub fn to_bytes(&self) -> Result, CheckpointFileError> { + let payload = postcard::to_allocvec(&CoreState { + version: VERSION, + release: env!("CARGO_PKG_VERSION").into(), + architecture: std::env::consts::ARCH.into(), + little_endian: cfg!(target_endian = "little"), + simulator: self.simulator.persisted(), + schedule: self.schedule.persisted(), + host_writes: self.host_writes.clone(), + })?; + let mut bytes = Vec::with_capacity(24 + payload.len()); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(&(payload.len() as u64).to_le_bytes()); + bytes.extend_from_slice(&checksum(&payload).to_le_bytes()); + bytes.extend(payload); + Ok(bytes) + } +} + +impl Simulation { + /// Decode a checkpoint and bind its event IDs to this compiled instance. + /// This does not change the simulation or any effect handler. + /// + /// # Safety + /// `bytes` must be an unmodified result of `SimulationCheckpoint::to_bytes` + /// from a compatible Celox build. The container checks version, layout and + /// accidental corruption; it does not authenticate arbitrary memory offsets + /// or process state supplied by an attacker. Never load untrusted checkpoints. + pub unsafe fn checkpoint_from_bytes( + &self, + bytes: &[u8], + ) -> Result, CheckpointFileError> { + if bytes.len() < 24 || &bytes[..8] != MAGIC { + return Err(CheckpointFileError::InvalidContainer); + } + let size = u64::from_le_bytes(bytes[8..16].try_into().unwrap()); + let hash = u64::from_le_bytes(bytes[16..24].try_into().unwrap()); + let payload = &bytes[24..]; + if size != payload.len() as u64 || hash != checksum(payload) { + return Err(CheckpointFileError::InvalidContainer); + } + let (state, remainder): (CoreState, _) = postcard::take_from_bytes(payload)?; + if !remainder.is_empty() + || state.version != VERSION + || state.release != env!("CARGO_PKG_VERSION") + || state.architecture != std::env::consts::ARCH + || state.little_endian != cfg!(target_endian = "little") + { + return Err(CheckpointFileError::InvalidContainer); + } + Ok(SimulationCheckpoint { + simulator: state.simulator.bind(&self.simulator)?, + // SAFETY: the caller guarantees a trusted checkpoint and bind above + // checked that its core layout belongs to this design. + schedule: unsafe { + state + .schedule + .bind::(self.simulator.backend.id_to_event_slice()) + } + .ok_or(CheckpointError::DesignMismatch)?, + host_writes: state.host_writes, + }) + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d0e1e8c7398..b44cae3cbf5 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1,6 +1,6 @@ mod builder; #[cfg(feature = "host-runtime")] -mod checkpoint; +pub(crate) mod checkpoint; mod error; #[cfg(feature = "host-runtime")] mod heap; @@ -130,7 +130,7 @@ mod host { /// may run: between the polls of concurrent testbench processes. pub(crate) heap_safepoints_blocked: bool, pub(crate) process_heap_roots: Vec, - file_io: celox_runtime::file_io::FileIo, + pub(super) file_io: celox_runtime::file_io::FileIo, pending_host_events: Arc>, pub(crate) program: RuntimeProgram, /// The program's scheduling facts. diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index c1d98a11ac8..701aa5286ed 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1704,6 +1704,8 @@ mod host { pub dpi: crate::DpiSymbols, /// Ordered command-line arguments for SystemVerilog plusargs queries. pub plusargs: Vec, + /// Host I/O factory; each simulator receives an independent instance. + pub file_system: celox_runtime::file_io_backend::FileSystemFactory, /// The loop that runs the time slots of a [`crate::Simulation`]. #[doc(hidden)] pub scheduler: crate::SchedulerMode, @@ -1798,6 +1800,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Err(error) = validate_native_vcd_layout(sim.layout(), &sim.program, &vcd_path) { return Err(error.with_warnings(std::mem::take(&mut sim.warnings))); } @@ -2003,6 +2006,7 @@ mod host { allow_inferred_latches: false, dpi: crate::DpiSymbols::default(), plusargs: Vec::new(), + file_system: Default::default(), scheduler: crate::SchedulerMode::default(), } } @@ -2162,6 +2166,21 @@ mod host { self } + /// Supply the host filesystem for runtime file tasks. The factory is + /// invoked before declaration initialization for each simulator. + /// Snapshot behavior is defined by the returned [`crate::FileSystem`]. + pub fn file_system( + mut self, + factory: impl Fn() -> Box + + Send + + Sync + + 'static, + ) -> Self { + self.options.file_system = + celox_runtime::file_io_backend::FileSystemFactory::new(factory); + self + } + /// Set the ordered arguments queried by `$test$plusargs` and /// `$value$plusargs`. A leading `+` is optional on each argument. /// Queries currently require a timed procedural process, such as an @@ -3049,6 +3068,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3103,6 +3123,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3160,6 +3181,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3231,6 +3253,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3445,6 +3468,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3663,6 +3687,8 @@ mod host { .set_injected(self.injected_components.clone()); sim.diagnostics = self.options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(self.options.plusargs.clone()); + sim.file_io = + celox_runtime::file_io::FileIo::new(self.options.file_system.create()); sim.apply_initial_values(); sim.modify(|_| {}).map_err(|error| { SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) @@ -3989,12 +4015,10 @@ mod host { )?; // Host state outside the memory image, such as open files, // cannot be shared with a shadow. - Ok(Some( - match shadow.simulator.check_host_checkpoint_support() { - Ok(()) => Ok(Box::new(shadow)), - Err(_) => Err("the design keeps host state outside its memory image"), - }, - )) + Ok(Some(match shadow.simulator.check_host_restore_support() { + Ok(()) => Ok(Box::new(shadow)), + Err(_) => Err("the design keeps host state outside its memory image"), + })) } /// Load `image` into executable memory and start a timed simulation @@ -4087,6 +4111,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 29d48e87623..ecbd56e5388 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -121,17 +121,13 @@ impl std::fmt::Debug for Checkpoint { /// Reasons a checkpoint cannot be taken or restored. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CheckpointError { - /// External component instances hold opaque state. They currently exist - /// only while a testbench runs, when no checkpoint can be taken. - #[error( - "checkpoints are not supported for designs with external components, whose state Celox cannot capture" - )] + /// Portable state-file APIs exclude opaque external component instances. + /// Core checkpoint capture and restore do not depend on their state. + #[error("portable state files do not capture opaque external component state")] ExternalComponents, /// Source-driven files and waveform controls have host state that is /// not represented in the saved HDL memory image. - #[error( - "checkpoints and state files are not supported for designs with SystemVerilog file I/O or VCD control tasks" - )] + #[error("the saved state does not include restorable external file I/O or VCD control state")] ExternalSystemTasks, #[error("the checkpoint was taken from a different design")] DesignMismatch, @@ -154,13 +150,13 @@ pub enum CheckpointError { impl Simulator { /// Save the current design state. /// + /// This captures only core execution state. Effect handlers, including file + /// I/O and VPI, retain their own state. The embedding system coordinates + /// their checkpoints with this one at a quiescent execution boundary. + /// /// Inputs written since the last evaluation are part of the saved state; /// combinational logic is settled again after a restore. pub fn checkpoint(&self) -> Result { - self.check_host_checkpoint_support()?; - if !self.components.is_empty() { - return Err(CheckpointError::ExternalComponents); - } Ok(Checkpoint { image: StateImage::capture(&self.backend, self.state_fingerprint()), comb_observer_snapshots: self.comb_observer_snapshots.clone(), @@ -177,6 +173,13 @@ impl Simulator { /// simulation, continue in a new file with [`Self::switch_vcd`]. pub fn restore(&mut self, checkpoint: &Checkpoint) -> Result<(), CheckpointError> { self.validate_restore(checkpoint)?; + self.restore_checkpoint_prepared(checkpoint) + } + + pub(crate) fn restore_checkpoint_prepared( + &mut self, + checkpoint: &Checkpoint, + ) -> Result<(), CheckpointError> { let fingerprint = self.state_fingerprint(); self.frozen = checkpoint.frozen; checkpoint @@ -195,17 +198,24 @@ impl Simulator { /// Check every precondition of [`Self::restore`] without changing state. pub(crate) fn validate_restore(&self, checkpoint: &Checkpoint) -> Result<(), CheckpointError> { - self.check_host_checkpoint_support()?; - if !self.components.is_empty() { - return Err(CheckpointError::ExternalComponents); - } if !checkpoint.image.matches(self.state_fingerprint()) { return Err(CheckpointError::DesignMismatch); } Ok(()) } - pub(crate) fn check_host_checkpoint_support(&self) -> Result<(), CheckpointError> { + /// The file-I/O effect handler. Its state is deliberately outside core + /// checkpoints; an embedding system may snapshot it separately. + pub fn file_io(&self) -> &celox_runtime::file_io::FileIo { + &self.file_io + } + + /// Replace the file-I/O effect handler at a host execution boundary. + pub fn replace_file_io(&mut self, file_io: celox_runtime::file_io::FileIo) { + self.file_io = file_io; + } + + pub(crate) fn check_host_restore_support(&self) -> Result<(), CheckpointError> { if self .program .runtime_schema @@ -231,3 +241,50 @@ impl Simulator { .get_or_init(|| crate::ir::state_fingerprint(self.backend.layout(), &self.program)) } } + +// Only this private wire type implements Deserialize: a safe API must not be +// able to construct a Checkpoint containing arbitrary memory offsets. +#[derive(serde::Serialize, serde::Deserialize)] +pub(crate) struct PersistedCheckpoint { + fingerprint: u64, + bytes: Box<[u8]>, + heap: celox_heap::Heap, + observers: Vec, + initial_eval: bool, + frozen: bool, +} +impl Checkpoint { + pub(crate) fn persisted(&self) -> PersistedCheckpoint { + PersistedCheckpoint { + fingerprint: self.image.fingerprint, + bytes: self.image.bytes.clone(), + heap: self.image.heap.clone(), + observers: self.comb_observer_snapshots.clone(), + initial_eval: self.comb_observer_initial_eval, + frozen: self.frozen, + } + } +} +impl PersistedCheckpoint { + pub(crate) fn bind( + self, + simulator: &Simulator, + ) -> Result { + if self.fingerprint != simulator.state_fingerprint() + || self.bytes.len() != state_range(&simulator.backend).len() + || self.observers.len() != simulator.comb_observer_snapshots.len() + { + return Err(CheckpointError::DesignMismatch); + } + Ok(Checkpoint { + image: StateImage { + fingerprint: self.fingerprint, + bytes: self.bytes, + heap: self.heap, + }, + comb_observer_snapshots: self.observers, + comb_observer_initial_eval: self.initial_eval, + frozen: self.frozen, + }) + } +} diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 1420c5d1975..913589e4aea 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -253,19 +253,20 @@ impl Simulator { ) }) .collect(); - celox_runtime::file_io::FileIo::write_memory( - path, - site.operation == 5, - words.iter().map(|(value, mask)| DisplayFormatArg { - value, - mask: Some(mask), - width, - signed: false, - is_string: false, - float_precision: None, - }), - ) - .map_err(|err| error(format!("$writemem: {err}")))?; + self.file_io + .write_memory_with_backend( + path, + site.operation == 5, + words.iter().map(|(value, mask)| DisplayFormatArg { + value, + mask: Some(mask), + width, + signed: false, + is_string: false, + float_precision: None, + }), + ) + .map_err(|err| error(format!("$writemem: {err}")))?; } _ => return Err(error("unknown file I/O request".into())), } diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 3ef0f4727cf..c65ea6a9156 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -129,6 +129,65 @@ pub struct StateSchema { } impl StateSchema { + pub(crate) fn from_design<'a, B: SimBackend>( + backend: &B, + design: &crate::ir::RuntimeDesign, + is_comb: impl Fn(&crate::AbsoluteAddr) -> bool, + time_slots: impl Iterator, + ) -> Self { + let time_slots: crate::HashSet<_> = time_slots.collect(); + // Build-specific partitioned-settle flags are recomputed on load. + let settle_flags = backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags_offset); + let mut objects: Vec<_> = backend + .layout() + .offsets + .keys() + .filter(|address| !time_slots.contains(address)) + .filter(|address| Some(backend.layout().offsets[*address]) != settle_flags) + .map(|&address| (design.get_path(&address), address)) + .collect(); + objects.sort_unstable(); + let mut named = Vec::with_capacity(objects.len()); + let mut index = 0; + while index < objects.len() { + let path = &objects[index].0; + let end = objects[index..] + .iter() + .position(|(other, _)| other != path) + .map_or(objects.len(), |offset| index + offset); + for (ordinal, (path, address)) in objects[index..end].iter().enumerate() { + named.push(NamedObject { + path: if end - index == 1 { + path.clone() + } else { + format!("{path}#{ordinal}") + }, + signal: backend.resolve_signal(address), + role: if is_comb(address) { + StateRole::Comb + } else { + StateRole::State + }, + strings: design.state_objects.get(address).is_some_and(|metadata| { + metadata.value_kind == celox_design::ValueKind::StrRef + }), + objects: design.state_objects.get(address).is_some_and(|metadata| { + metadata.value_kind == celox_design::ValueKind::ObjRef + }), + }); + } + index = end; + } + StateSchema { + four_state: backend.layout().four_state, + objects: named, + } + } + /// Save the value of every state object of `backend` as last evaluated. /// /// Fails if a variable holds a class object. @@ -300,7 +359,9 @@ impl Simulator { /// Save the value of every state object, by path. /// /// Combinational values are settled first, so the file shows the values - /// a read would return. + /// a read would return. Unlike [`Self::checkpoint`], this portable format + /// does not include a host filesystem snapshot. File/VCD designs can be + /// saved for inspection, but loading them is rejected. pub fn save_state(&mut self) -> Result { self.prepare_save_state()?; self.state_schema().capture(&self.backend) @@ -309,7 +370,6 @@ impl Simulator { /// Validate support and settle before a timed owner synchronizes termination. /// Capture must follow that synchronization, since final procedures can write state. pub(crate) fn prepare_save_state(&mut self) -> Result<(), StateError> { - self.check_host_checkpoint_support()?; if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -343,6 +403,7 @@ impl Simulator { if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } + self.check_host_restore_support()?; // Evaluating the loaded state can still fail (an oscillating // combinational loop), so keep the current state to return to. let previous = self.checkpoint()?; @@ -379,76 +440,16 @@ impl Simulator { /// Name the state objects: the hierarchical path, followed by `#n` when /// several objects share it. fn build_state_schema(&self) -> StateSchema { - let comb_writes = &self.program.runtime_schema.comb_writes; - // A timed simulation stores its time into the time slots, and a state - // file keeps the time in its schedule; an untimed one reads zero. - // A compiled scheduler's slots hold nothing between runs, and the - // flags of a partitioned settle describe how this build settles, - // not the design: loading state sets them. - let time_slots: crate::HashSet<_> = self - .program - .runtime_schema - .time_slots - .iter() - .chain( - self.program - .runtime_schema - .scheduler - .iter() - .flat_map(|scheduler| scheduler.slots.iter()), - ) - .collect(); - let settle_flags = self - .backend - .layout() - .settle - .as_ref() - .map(|settle| settle.flags_offset); - let mut objects: Vec<_> = self - .backend - .layout() - .offsets - .keys() - .filter(|address| !time_slots.contains(address)) - .filter(|address| Some(self.backend.layout().offsets[*address]) != settle_flags) - .map(|&address| (self.program.get_path(&address), address)) - .collect(); - objects.sort_unstable(); - let mut named = Vec::with_capacity(objects.len()); - let mut index = 0; - while index < objects.len() { - let path = &objects[index].0; - let end = objects[index..] + let schema = &self.program.runtime_schema; + StateSchema::from_design( + &self.backend, + &self.program.design, + |address| schema.comb_writes.contains(address), + schema + .time_slots .iter() - .position(|(other, _)| other != path) - .map_or(objects.len(), |offset| index + offset); - for (ordinal, (path, address)) in objects[index..end].iter().enumerate() { - named.push(NamedObject { - path: if end - index == 1 { - path.clone() - } else { - format!("{path}#{ordinal}") - }, - signal: self.backend.resolve_signal(address), - role: if comb_writes.contains(address) { - StateRole::Comb - } else { - StateRole::State - }, - strings: self.program.design.state_objects.get(address).is_some_and( - |metadata| metadata.value_kind == celox_design::ValueKind::StrRef, - ), - objects: self.program.design.state_objects.get(address).is_some_and( - |metadata| metadata.value_kind == celox_design::ValueKind::ObjRef, - ), - }); - } - index = end; - } - StateSchema { - four_state: self.backend.layout().four_state, - objects: named, - } + .chain(schema.scheduler.iter().flat_map(|s| s.slots.iter())), + ) } /// Express a schedule by event and signal names. diff --git a/crates/celox/tests/checkpoint.rs b/crates/celox/tests/checkpoint.rs index 1735334528f..978a023f83f 100644 --- a/crates/celox/tests/checkpoint.rs +++ b/crates/celox/tests/checkpoint.rs @@ -314,6 +314,9 @@ fn simulation_restore_rewinds_time_and_clocks() { sim.add_clock("clk", 10, 5); timed_trace(&mut sim, 100); let checkpoint = sim.checkpoint().unwrap(); + let bytes = checkpoint.to_bytes().unwrap(); + // SAFETY: this is the unchanged encoding of this simulation's checkpoint. + let checkpoint = unsafe { sim.checkpoint_from_bytes(&bytes) }.unwrap(); assert_eq!(checkpoint.time(), sim.time()); let expected = timed_trace(&mut sim, 400); sim.restore(&checkpoint).unwrap(); @@ -365,3 +368,63 @@ fn simulation_restore_refuses_to_rewind_vcd_until_switched() { sim.flush_vcd().unwrap(); assert_eq!(std::fs::read_to_string(&second).unwrap(), vcd); } + +#[cfg(feature = "systemverilog")] +mod persisted_core { + use std::path::Path; + const SOURCE: &str = r#" +module Top(output int value, output string text); + timeunit 1ns; timeprecision 1ns; + initial begin + text = "checkpoint"; + fork + begin #2; value += 3; text = {text, "-child"}; end + begin #4; value += 7; end + join + #1; value += 10; + end +endmodule +"#; + macro_rules! case { + ($name:ident, $build:ident) => { + #[test] + fn $name() { + let build = || { + celox::Simulation::from_sv_sources( + vec![(SOURCE, Path::new("persisted.sv"))], + "Top", + ) + .$build() + .unwrap() + }; + let mut source = build(); + source.run_until(1).unwrap(); + let bytes = source.checkpoint().unwrap().to_bytes().unwrap(); + source.run_until(6).unwrap(); + let expected = source.capture_state().unwrap(); + let mut restored = build(); + // SAFETY: unchanged bytes from the same build's checkpoint encoder. + let checkpoint = unsafe { restored.checkpoint_from_bytes(&bytes) }.unwrap(); + restored.restore(&checkpoint).unwrap(); + assert_eq!(restored.time(), 1); + restored.run_until(6).unwrap(); + assert_eq!(restored.capture_state().unwrap(), expected); + for length in [0, 8, 23, bytes.len() - 1] { + assert!(unsafe { restored.checkpoint_from_bytes(&bytes[..length]) }.is_err()); + } + let mut corrupt = bytes.clone(); + *corrupt.last_mut().unwrap() ^= 1; + assert!(unsafe { restored.checkpoint_from_bytes(&corrupt) }.is_err()); + } + }; + } + case!(interpreter, build_interpreter); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + case!(native, build_native); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + case!(tiered, build_tiered); + #[cfg(feature = "cranelift")] + case!(cranelift, build_cranelift); + #[cfg(feature = "wasm-runtime")] + case!(wasm, build_wasm); +} diff --git a/crates/celox/tests/sv_host_requests.rs b/crates/celox/tests/sv_host_requests.rs index 9c0263d47b7..031b3eecb89 100644 --- a/crates/celox/tests/sv_host_requests.rs +++ b/crates/celox/tests/sv_host_requests.rs @@ -83,7 +83,7 @@ mixed_requests!(wasm, build_wasm); mixed_requests!(native, build_native); #[test] -fn external_host_state_rejects_checkpoints_and_state_files() { +fn core_checkpoint_does_not_own_external_host_state() { for statement in ["$fwrite(1, \"output\");", "$dumpvars;"] { let source = format!("module Top(output bit q); initial begin {statement} q = 1; end endmodule"); @@ -93,16 +93,175 @@ fn external_host_state_rejects_checkpoints_and_state_files() { ) .build_interpreter() .unwrap(); - assert!(matches!( - simulation.checkpoint(), - Err(celox::CheckpointError::ExternalSystemTasks) - )); - assert!( - simulation - .save_state() - .unwrap_err() - .to_string() - .contains("SystemVerilog file I/O or VCD") - ); + let checkpoint = simulation.checkpoint().unwrap(); + let file = simulation.save_state().unwrap(); + simulation.restore(&checkpoint).unwrap(); + assert!(simulation.load_state(&file).is_err()); } } + +#[path = "test_utils/file_system.rs"] +mod file_system; + +const IO_SNAPSHOT_SOURCE: &str = r#" +module Top(output int value, count); + timeunit 1ps; timeprecision 1ps; + int fd = $fopen("input", "r"); + int n; + initial begin + n = $fscanf(fd, "%d", value); + #1; + value = $fgetc(fd); + count++; + $fclose(fd); + fd = $fopen("output", "w"); + $fwrite(fd, "%c", value); + $fclose(fd); + #1; + end +endmodule +"#; + +macro_rules! io_snapshot { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let build = || { + celox::Simulation::from_sv_sources( + vec![(IO_SNAPSHOT_SOURCE, Path::new("io_snapshot.sv"))], + "Top", + ) + .file_system(|| Box::::default()) + }; + let mut sim = build().$backend().unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 12u32.into()); + let checkpoint = sim.checkpoint().unwrap(); + let effects = sim.file_io().snapshot(); + for _ in 0..2 { + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 81u32.into()); + assert_eq!(sim.get(sim.signal("count")), 1u32.into()); + // The old input descriptor was closed and its HDL number reused + // for output. Both the mapping and fscanf lookahead must return. + let restored = sim.file_io().prepare_restore(&effects).unwrap(); + sim.replace_file_io(restored); + sim.restore(&checkpoint).unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.get(sim.signal("value")), 12u32.into()); + } + let mut fork = build().$backend().unwrap(); + let restored = fork.file_io().prepare_restore(&effects).unwrap(); + fork.replace_file_io(restored); + fork.restore(&checkpoint).unwrap(); + fork.run_until(1).unwrap(); + assert_eq!(fork.get(fork.signal("value")), 81u32.into()); + let mut rejected = celox::Simulation::from_sv_sources( + vec![(IO_SNAPSHOT_SOURCE, Path::new("io_snapshot.sv"))], + "Top", + ) + .file_system(|| { + let mut host = file_system::TestIo::default(); + host.reject_restore = true; + Box::new(host) + }) + .$backend() + .unwrap(); + rejected.run_until(1).unwrap(); + let before = rejected.save_state().unwrap(); + assert!( + rejected + .file_io() + .prepare_restore(&effects) + .unwrap_err() + .to_string() + .contains("host rejected restore") + ); + assert_eq!(before, rejected.save_state().unwrap()); + assert_eq!(rejected.time(), 1); + } + }; +} +io_snapshot!(io_snapshot_interpreter, build_interpreter); +io_snapshot!(io_snapshot_cranelift, build_cranelift); +io_snapshot!(io_snapshot_wasm, build_wasm); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +io_snapshot!(io_snapshot_native, build_native); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +io_snapshot!(io_snapshot_tiered, build_tiered); + +#[test] +fn io_manager_restores_eof_pushback_channels_and_standard_streams() { + use celox_runtime::file_io::FileIo; + let mut io = FileIo::new(Box::::default()); + let fd = io.open("input", Some("r")); + while io.read_byte(fd).unwrap().is_some() {} + assert!(io.eof(fd).unwrap()); + let eof = io.snapshot(); + io.rewind(fd).unwrap(); + io = io.prepare_restore(&eof).unwrap(); + assert!(io.eof(fd).unwrap()); + io.unread_byte(fd, b'X').unwrap(); + assert_eq!(io.read_byte(0x8000_0000).unwrap(), Some(b's')); + let channel = io.open("output", None); + io.write(channel, b"before").unwrap(); + let saved = io.snapshot(); + io.write(channel, b"after").unwrap(); + io.close(fd).unwrap(); + io.close(channel).unwrap(); + io.close(0x8000_0000).unwrap(); + io = io.prepare_restore(&saved).unwrap(); + assert!(!io.eof(fd).unwrap()); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'X')); + assert_eq!(io.read_byte(0x8000_0000).unwrap(), Some(b't')); + io.write(channel, b"!").unwrap(); + let output = io.open("output", Some("r")); + let mut bytes = Vec::new(); + while let Some(byte) = io.read_byte(output).unwrap() { + bytes.push(byte); + } + assert_eq!(bytes, b"before!"); + let mut incompatible = file_system::TestIo::default(); + incompatible.format = "other-host/v2".into(); + let incompatible = FileIo::new(Box::new(incompatible)); + assert!( + incompatible + .prepare_restore(&saved) + .unwrap_err() + .to_string() + .contains("format mismatch") + ); +} + +#[test] +fn rejected_io_restore_preserves_live_stream_position() { + use celox_runtime::file_io::FileIo; + let mut host = file_system::TestIo::default(); + host.reject_restore = true; + let mut io = FileIo::new(Box::new(host)); + let fd = io.open("input", Some("r")); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'1')); + let saved = io.snapshot(); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'2')); + assert!(io.prepare_restore(&saved).is_err()); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'Q')); +} + +#[test] +fn writemem_uses_injected_io() { + let source = r#"module Top(output int value); + logic [7:0] words [0:1]; int fd; + initial begin + words[0]=8'h41; words[1]=8'h42; + $writememh("output", words); + fd=$fopen("output", "r"); + value=$fgetc(fd); + end + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources(vec![(source, Path::new("write.sv"))], "Top") + .file_system(|| Box::::default()) + .build_interpreter() + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("value")), u32::from(b'4').into()); +} diff --git a/crates/celox/tests/sv_scan.rs b/crates/celox/tests/sv_scan.rs index 53728da9e57..d1b6a7b14ef 100644 --- a/crates/celox/tests/sv_scan.rs +++ b/crates/celox/tests/sv_scan.rs @@ -73,7 +73,7 @@ backend!(wasm, build_wasm); backend!(native, build_native); #[test] -fn fscanf_preserves_mismatch_lookahead_and_rejects_checkpoint() { +fn fscanf_preserves_mismatch_lookahead_and_allows_checkpoint() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("input.txt"); std::fs::write(&path, b"12 34Q 7").unwrap(); @@ -99,9 +99,8 @@ fn fscanf_preserves_mismatch_lookahead_and_rejects_checkpoint() { let signal = simulation.signal(name); assert_eq!(simulation.get(signal), value.into(), "{name}"); } - assert!( - format!("{:?}", simulation.checkpoint().unwrap_err()).contains("ExternalSystemTasks") - ); + simulation.checkpoint().unwrap(); + simulation.save_state().unwrap(); } let build = || Simulation::from_sv_sources(vec![(&source, Path::new("scan.sv"))], "Top"); check(build().build_interpreter().unwrap()); @@ -151,7 +150,7 @@ fn rejected_formats_are_explicit() { } #[test] -fn fscanf_on_standard_input_rejects_snapshots_before_execution() { +fn fscanf_on_standard_input_allows_snapshots_before_execution() { let source = r#"module Top; int n, value; initial begin #1; n = $fscanf(32'h80000000, "%d", value); end endmodule"#; @@ -159,6 +158,6 @@ fn fscanf_on_standard_input_rejects_snapshots_before_execution() { Simulation::from_sv_sources(vec![(source, Path::new("scan_stdin.sv"))], "Top") .build_interpreter() .unwrap(); - assert!(format!("{:?}", simulation.checkpoint().unwrap_err()).contains("ExternalSystemTasks")); - assert!(simulation.save_state().is_err()); + simulation.checkpoint().unwrap(); + simulation.save_state().unwrap(); } diff --git a/crates/celox/tests/test_utils/file_system.rs b/crates/celox/tests/test_utils/file_system.rs new file mode 100644 index 00000000000..6690e6d7ba6 --- /dev/null +++ b/crates/celox/tests/test_utils/file_system.rs @@ -0,0 +1,146 @@ +//! An embedding-host fixture, not a production filesystem. Its private JSON +//! snapshot format demonstrates that Celox does not interpret backend state. +use celox::{FileMode, FileSystem}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + io::{self, Read, Seek, SeekFrom, Write}, + path::Path, +}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Stream { + path: String, + position: u64, + read: bool, + write: bool, + append: bool, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TestIo { + files: BTreeMap>, + streams: BTreeMap, + next: u64, + stdin: u64, + stderr: Vec, + pub reject_restore: bool, + pub format: String, +} +impl Default for TestIo { + fn default() -> Self { + Self { + files: BTreeMap::from([("input".into(), b"12Q34".to_vec())]), + streams: BTreeMap::new(), + next: 0, + stdin: 0, + stderr: Vec::new(), + reject_restore: false, + format: "celox-test-host/v1".into(), + } + } +} +impl TestIo { + fn stream(&mut self, id: u64) -> io::Result<&mut Stream> { + self.streams + .get_mut(&id) + .ok_or_else(|| io::Error::other("closed handle")) + } +} +impl FileSystem for TestIo { + fn open(&mut self, path: &Path, mode: FileMode) -> io::Result { + let path = path.to_str().unwrap().to_owned(); + if mode.create { + self.files.entry(path.clone()).or_default(); + } + let bytes = self + .files + .get_mut(&path) + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; + if mode.truncate { + bytes.clear(); + } + let id = self.next; + self.next += 1; + self.streams.insert( + id, + Stream { + path, + position: 0, + read: mode.read, + write: mode.write, + append: mode.append, + }, + ); + Ok(id) + } + fn close(&mut self, id: u64) -> io::Result<()> { + self.streams + .remove(&id) + .ok_or_else(|| io::Error::other("closed handle"))?; + Ok(()) + } + fn read(&mut self, id: u64, bytes: &mut [u8]) -> io::Result { + let stream = self.stream(id)?.clone(); + if !stream.read { + return Err(io::ErrorKind::PermissionDenied.into()); + } + let mut cursor = io::Cursor::new(&self.files[&stream.path]); + cursor.set_position(stream.position); + let count = cursor.read(bytes)?; + self.stream(id)?.position += count as u64; + Ok(count) + } + fn write(&mut self, id: u64, bytes: &[u8]) -> io::Result { + let stream = self.stream(id)?.clone(); + if !stream.write { + return Err(io::ErrorKind::PermissionDenied.into()); + } + let data = self.files.get_mut(&stream.path).unwrap(); + let position = if stream.append { + data.len() as u64 + } else { + stream.position + }; + let mut cursor = io::Cursor::new(data); + cursor.set_position(position); + let count = cursor.write(bytes)?; + self.stream(id)?.position = position + count as u64; + Ok(count) + } + fn seek(&mut self, id: u64, position: SeekFrom) -> io::Result { + let stream = self.stream(id)?.clone(); + let mut cursor = io::Cursor::new(&self.files[&stream.path]); + cursor.set_position(stream.position); + let result = cursor.seek(position)?; + self.stream(id)?.position = result; + Ok(result) + } + fn flush(&mut self, id: u64) -> io::Result<()> { + self.stream(id)?; + Ok(()) + } + fn read_stdin(&mut self, bytes: &mut [u8]) -> io::Result { + let mut cursor = io::Cursor::new(b"stdin"); + cursor.set_position(self.stdin); + let count = cursor.read(bytes)?; + self.stdin += count as u64; + Ok(count) + } + fn write_stderr(&mut self, bytes: &[u8]) -> io::Result<()> { + self.stderr.extend_from_slice(bytes); + Ok(()) + } + fn snapshot_format(&self) -> &str { + &self.format + } + fn snapshot(&self) -> io::Result> { + serde_json::to_vec(self).map_err(io::Error::other) + } + fn restore(&self, state: &[u8]) -> io::Result> { + if self.reject_restore { + return Err(io::Error::other("host rejected restore")); + } + let state: Self = serde_json::from_slice(state).map_err(io::Error::other)?; + Ok(Box::new(state)) + } +} diff --git a/docs/guide/checkpoints.md b/docs/guide/checkpoints.md index 36a22fb532d..d43775c30e8 100644 --- a/docs/guide/checkpoints.md +++ b/docs/guide/checkpoints.md @@ -57,6 +57,93 @@ sim.time(); // 100 - Checkpoints live in memory. To keep state across processes, use a state file. +## External resources: file I/O and VPI {#external-resources} + +A design containing file I/O, `$fscanf` (including stdin), or VCD tasks can +be captured at the normal API boundary. `checkpoint()` copies state without +executing HDL; `save_state()` / `saveState()` retain their usual combinational +settling behavior. A simulation suspended mid-slot by `$stop` must still be +continued before capture. + +Rust hosts can supply runtime I/O through `FileSystem`, keeping the OS-backed +`HostFileSystem` as the default: + +```rust +let mut sim = Simulation::from_sv_sources(sources, "Top") + .file_system(|| Box::new(MyHostIo::new())) + .build()?; +let saved = sim.checkpoint()?; +// Advance the simulation, then restore both HDL and host I/O state. +sim.restore(&saved)?; +``` + +`MyHostIo` implements `celox::FileSystem`. The factory runs before declaration +initialization and creates an independent backend for each simulator. It handles +open/read/write/seek/close/flush, stdin and stderr; runtime `$writemem*` operations +also use it. This boundary covers runtime file tasks, not compiler source-file +loading, compile-time memory initialization, or VCD writers. It does not require +any particular filesystem or storage strategy. + +Core checkpoints contain HDL memory, heap values, process state and scheduling +state. They do **not** contain effect-handler state. A design using file I/O or +VPI can take and restore a core checkpoint without asking its handlers to save +anything. Restoring only the core leaves those handlers attached and unchanged; +subsequent SV calls are interpreted by their current state. + +The file-I/O handler owns HDL descriptor allocation, FD/MCD mappings, readability, +EOF flags, scan lookahead and standard-stream flags. Its injected `FileSystem` +owns the backing resources and defines their effect semantics. Rust hosts can +compose these independently at a quiescent execution boundary: + +```rust,ignore +let core = simulation.checkpoint()?; +let io = simulation.file_io().snapshot(); +// ... execute a scenario ... +let restored_io = simulation.file_io().prepare_restore(&io)?; +simulation.replace_file_io(restored_io); +simulation.restore(&core)?; +``` + +The host chooses which handlers to include, how external effects are retained, +and the persistence format of its **system checkpoint**. Core does not require +a memory filesystem, a disk overlay, or handler persistence. The default Rust +`HostFileSystem` continues to use the OS directly. Its lack of an independent +resource snapshot does not prevent core checkpoint capture or restore. + +`FileSystem::restore()` prepares a replacement handler with the saved private +handle identities. This helper's contract leaves the existing handler and +external resources untouched during preparation. A host with a different effect +commit protocol can coordinate its own replacement instead. Validation and +commit order belong to that host system, not to the core checkpoint. + +`SimulationCheckpoint::to_bytes()` encodes the core, including live fork +activations and heap objects, without event-code pointers. An instance built +from the same design binds saved event IDs through +`unsafe Simulation::checkpoint_from_bytes()`. This implementation format is +versioned and checks layout and accidental corruption; load only trusted, +unmodified artifacts from a compatible build. It is separate from portable +`StateFile`, which contains named HDL values and an optional schedule. + +Portable state-file restore retains its existing host-resource restrictions. +System hosts can compose core and effect-handler snapshots into their own +resumable checkpoint format. + +For native VPI hosts, Rust `VpiSession::save_state()` and +`NativeProgramInstance::save_state()` return the same `StateFile` format, +without evaluating HDL or dispatching callbacks. Capture between dispatch runs +or in a read-only synchronization callback for settled values. In other callback +phases, the file contains the values currently visible to VPI reads, which may +not yet be settled. The file has no simulation schedule: pending VPI writes, +callback registrations, force registrations, plugin memory, and cocotb/Python +coroutines are excluded. Applied force values are visible in the HDL data. +These files support inspection, comparison, and HDL-only initialization; they +are not resumable VPI sessions. C plugins can call +`int celox_vpi_save_state(const char *path)` under the same contract (1 for +success, 0 for failure). The path is UTF-8; an existing file is overwritten. + +Opaque external component state also remains with its host. Core checkpoints +do not capture it; portable state-file APIs retain their component restrictions. + ## Waveforms VCD output keeps recording across a restore: the next `dump()` writes the diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index b1446e6d85f..f1d1a67a29b 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -93,7 +93,9 @@ To compare two runs or two simulators, `celox run` can save | `--save-state-dir DIR` | Write the files to `DIR` (default: the current directory). | A cycle that the run never reaches is an error. These options are available for -SystemVerilog testbenches on every backend. +SystemVerilog testbenches on every backend, including designs with file I/O or +VCD tasks. The saved file contains HDL state; external resources are excluded +under the [snapshot contract](checkpoints.md#external-resources). ```sh celox run c906.v --top tb --save-state-on tb.clk --save-state-at 1000,2000 --save-state-dir states