From a2237aa4ef028ddc7bfe6b8535e5495a04ad985b Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 18:40:13 +0900 Subject: [PATCH] feat(cli)!: checkpoint SystemVerilog runs on SIGUSR1 On Unix, celox run accepts SIGUSR1 by default and saves a resumable CLI system checkpoint at the next complete simulation boundary while continuing execution. Use --no-checkpoint-on-signal to opt out, --save-state-dir for the destination, and --restore-checkpoint to resume a trusted artifact with the same design and options. The CLI composes core execution bytes with its file-effect handler, source waveform controls and accumulated assertion/error outcome. Handler state remains outside the core checkpoint. Restore targets defer initialization so declaration effects do not truncate previously delivered files. If stepped without restore, pending startup initializes sampled copies and history defaults after declarations (IEEE 1800-2023 16.5.1); restoring completed startup preserves saved samples, and a previously reported failure stays failed after resume. Pending scheduled saves, cycle counts and edge baselines are restored as CLI state, so consumed saves are not replayed. The restored schedule is authoritative; output directory and signal registration are local invocation options. The file handler keeps a disk-backed working view keyed by normalized path. Temporary contents reopen only during operations, bounding OS descriptor use even after many files have been closed or restored. Different paths, including hard links to the same host file, have independent views; callers coordinate aliases. Active output streams retain their original host handle until close, preserving writes across rename/unlink without inferring aliases. Restored streams reconnect to their recorded paths lazily; subsequent writes publish the restored branch without retracting previously delivered output during restore. Write-only append retains its unreadable prefix externally without requiring read permission. Standard streams, pipes and devices remain live external channels. Source-driven waveform recording resumes into a unique .resume-.vcd segment beside the original trace. Each segment preserves selected signals and dump controls, begins at the restored time, and has a fresh per-file byte-limit budget. Rust hosts can separately capture SourceWaveformState and choose their new output destination. Original traces are not overwritten. The signal handler only sets an atomic flag. Saves use checksummed containers and no-clobber publication; repeated pending signals coalesce. Save failures report to stderr without terminating the run. Validation: 284 Rust regressions passed (CLI, core checkpoint, declaration startup, sampled values, history and VCD), plus 24 NAPI/JS checkpoint/timing tests with a rebuilt addon. Coverage includes separate-process resume on interpreter, native, tiered, Cranelift and WASM; delayed-startup sampling and saved-sample preservation; scheduled saves across high/low clock phases; rename/unlink output behavior; 128 closed files with descriptor limit 64; waveform controls. Formatting and affected-crate clippy passed. BREAKING CHANGE: SimulatorOptions gains defer_initialization. Explicit options literals must initialize it or use ..Default::default(). The default preserves eager timed initialization. Change-Id: I262b57df801bf7309e6858f55dc52f84440851f8 --- Cargo.lock | 1 + crates/celox-runtime/src/vcd.rs | 4 +- crates/celox-vpi/Cargo.toml | 1 + crates/celox-vpi/src/bin/celox.rs | 196 ++++++- .../celox-vpi/src/bin/celox/checkpoint_fs.rs | 553 ++++++++++++++++++ .../celox-vpi/src/bin/celox/state_signal.rs | 91 +++ .../src/bin/celox/system_checkpoint.rs | 307 ++++++++++ crates/celox-vpi/tests/run_cli.rs | 171 ++++++ crates/celox/src/lib.rs | 2 +- crates/celox/src/simulation.rs | 25 +- crates/celox/src/simulation/vcd_tasks.rs | 4 +- crates/celox/src/simulation/waveform_state.rs | 110 ++++ crates/celox/src/simulator.rs | 2 +- crates/celox/src/simulator/builder.rs | 28 +- crates/celox/tests/sv_declaration_startup.rs | 63 ++ docs/guide/cocotb.md | 65 ++ 16 files changed, 1592 insertions(+), 31 deletions(-) create mode 100644 crates/celox-vpi/src/bin/celox/checkpoint_fs.rs create mode 100644 crates/celox-vpi/src/bin/celox/state_signal.rs create mode 100644 crates/celox-vpi/src/bin/celox/system_checkpoint.rs create mode 100644 crates/celox/src/simulation/waveform_state.rs diff --git a/Cargo.lock b/Cargo.lock index 47908e1d40d..03444e468bf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,6 +842,7 @@ dependencies = [ "celox", "celox-design", "celox-frontend-veryl", + "celox-runtime", "celox-sv-analyzer", "clap", "fxhash", diff --git a/crates/celox-runtime/src/vcd.rs b/crates/celox-runtime/src/vcd.rs index 1747c6eb6b0..b8aec4e0751 100644 --- a/crates/celox-runtime/src/vcd.rs +++ b/crates/celox-runtime/src/vcd.rs @@ -13,7 +13,7 @@ use std::path::Path; /// Self-contained — does not reference any IR types. Can be cached /// alongside a shared backend artifact so that VCD /// works even on cache-hit paths. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct VcdSignalDesc { /// VCD scope name (e.g. instance path). pub scope: String, @@ -29,7 +29,7 @@ pub struct VcdSignalDesc { /// Describes a signal whose value is supplied by an external runtime rather /// than stored in Celox's flat simulation memory. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct VcdExternalSignalDesc { pub scope: String, pub name: String, diff --git a/crates/celox-vpi/Cargo.toml b/crates/celox-vpi/Cargo.toml index d866e6d7603..b4d8179c9ce 100644 --- a/crates/celox-vpi/Cargo.toml +++ b/crates/celox-vpi/Cargo.toml @@ -50,6 +50,7 @@ thiserror.workspace = true tempfile.workspace = true tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "env-filter"] } celox-design.workspace = true +celox-runtime.workspace = true celox-sv-analyzer = { workspace = true, optional = true } clap.workspace = true fxhash.workspace = true diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index a33363f19ab..225e09851ca 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -13,10 +13,20 @@ use celox::{ }; use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand}; +#[cfg(feature = "systemverilog")] +#[path = "celox/checkpoint_fs.rs"] +mod checkpoint_fs; #[path = "celox/project.rs"] mod project; #[path = "celox/runner.rs"] mod runner; +#[cfg(feature = "systemverilog")] +#[path = "celox/state_signal.rs"] +mod state_signal; +#[cfg(feature = "systemverilog")] +#[path = "celox/system_checkpoint.rs"] +mod system_checkpoint; + use project::{Design, DesignArgs}; #[derive(Parser)] @@ -88,15 +98,23 @@ struct SaveStateArgs { /// the design's global time precision. #[arg(long, value_name = "T", value_delimiter = ',')] save_state_at_time: Vec, + /// Disable the default SIGUSR1 checkpoint handler (Unix, SystemVerilog). + #[arg(long)] + no_checkpoint_on_signal: bool, + /// Resume a trusted CLI checkpoint with the same design and options. + #[arg(long, value_name = "FILE")] + restore_checkpoint: Option, /// The directory of the saved files, `-.state` and - /// `time-.state` (default: the current directory). + /// `time-.state` or `signal--.checkpoint` (default: the current directory). #[arg(long, value_name = "DIR")] save_state_dir: Option, } impl SaveStateArgs { fn is_empty(&self) -> bool { - self.save_state_on.is_none() && self.save_state_at_time.is_empty() + self.save_state_on.is_none() + && self.save_state_at_time.is_empty() + && self.restore_checkpoint.is_none() } } @@ -202,7 +220,7 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { } if !arguments.save_state.is_empty() { return Err( - "--save-state-on and --save-state-at-time currently require a SystemVerilog testbench" + "--save-state-on, --save-state-at-time and --restore-checkpoint currently require a SystemVerilog testbench" .into(), ); } @@ -219,6 +237,11 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { arguments.execution.validate_sv().unwrap_or_else(|message| { clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, message).exit() }); + // Install before compiling so requests received during compilation are + // deferred until the first safe simulation boundary. + let signal = (cfg!(unix) && !arguments.save_state.no_checkpoint_on_signal) + .then(state_signal::StateSignal::install) + .transpose()?; let sources = arguments.design.sv_sources()?; let source_refs = sources .iter() @@ -231,7 +254,13 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .diagnostic_policy(arguments.design.diagnostics.clone()) .sv_timescale(arguments.design.timescale) .signal_access(arguments.design.signal_access.clone()) - .plusargs(arguments.plusargs.iter().cloned()); + .plusargs(arguments.plusargs.iter().cloned()) + .defer_initialization(arguments.save_state.restore_checkpoint.is_some()); + let builder = if signal.is_some() || arguments.save_state.restore_checkpoint.is_some() { + builder.file_system(|| Box::::default()) + } else { + builder + }; let builder = arguments.design.apply_parameters(builder); let max_steps = if arguments.execution.unlimited { u64::MAX @@ -240,11 +269,24 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { }; macro_rules! execute { ($build:ident) => {{ - let simulation = builder + let mut simulation = builder .$build() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulation.warnings())?; - let saves = StateSaves::new(&simulation, &arguments.design.top, &arguments.save_state)?; + let progress = if let Some(path) = &arguments.save_state.restore_checkpoint { + Some(system_checkpoint::restore(&mut simulation, path)?) + } else { + None + }; + let mut saves = StateSaves::new( + &simulation, + &arguments.design.top, + &arguments.save_state, + signal, + )?; + if let Some(progress) = progress { + saves.restore_progress(&simulation, &arguments.design.top, progress)?; + } simulate_sv(simulation, max_steps, saves, &mut std::io::stdout().lock()) }}; } @@ -266,11 +308,11 @@ fn simulate_sv( mut saves: StateSaves, output: &mut impl Write, ) -> Result<(), String> { - let mut failed = false; let initial = simulation.eval_comb(); - drain_sv_output(&mut simulation, output, &mut failed)?; + drain_sv_output(&mut simulation, output, &mut saves.failed)?; initial.map_err(|error| error.to_string())?; saves.start(&mut simulation); + saves.service_signal(&mut simulation); let mut steps = 0; while !simulation.is_finished() && let Some(next) = simulation.next_event_time() @@ -280,7 +322,7 @@ fn simulate_sv( } saves.before(&mut simulation, next)?; let step = simulation.step(); - drain_sv_output(&mut simulation, output, &mut failed)?; + drain_sv_output(&mut simulation, output, &mut saves.failed)?; if step.map_err(|error| error.to_string())?.is_none() { break; } @@ -288,10 +330,10 @@ fn simulate_sv( steps += 1; } let finished = simulation.finish(); - drain_sv_output(&mut simulation, output, &mut failed)?; + drain_sv_output(&mut simulation, output, &mut saves.failed)?; finished.map_err(|error| error.to_string())?; saves.finish(&mut simulation)?; - if failed { + if saves.failed { return Err("SystemVerilog testbench reported an assertion failure or $error".to_string()); } Ok(()) @@ -315,14 +357,66 @@ struct StateSaves { /// The times still to save, in descending order. times: Vec, directory: PathBuf, + signal: Option, + signal_sequence: u64, + failed: bool, + started: bool, +} + +/// Persistent CLI bookkeeping; signal registration and output directory are local. +#[cfg(feature = "systemverilog")] +#[derive(Default, serde::Serialize, serde::Deserialize)] +struct SavedStateSaves { + counted: Option, + cycles: Vec, + count: u64, + high: bool, + times: Vec, + signal_sequence: u64, + failed: bool, + started: bool, } #[cfg(feature = "systemverilog")] impl StateSaves { + fn progress(&self) -> SavedStateSaves { + SavedStateSaves { + counted: self.counted.as_ref().map(|(name, _)| name.clone()), + cycles: self.cycles.clone(), + count: self.count, + high: self.high, + times: self.times.clone(), + signal_sequence: self.signal_sequence, + failed: self.failed, + started: self.started, + } + } + + fn restore_progress( + &mut self, + simulation: &celox::Simulation, + top: &str, + saved: SavedStateSaves, + ) -> Result<(), String> { + self.counted = saved + .counted + .map(|name| resolve_signal_path(simulation, top, &name).map(|signal| (name, signal))) + .transpose()?; + self.cycles = saved.cycles; + self.count = saved.count; + self.high = saved.high; + self.times = saved.times; + self.signal_sequence = saved.signal_sequence; + self.failed = saved.failed; + self.started = saved.started; + Ok(()) + } + fn new( simulation: &celox::Simulation, top: &str, arguments: &SaveStateArgs, + signal: Option, ) -> Result { let counted = match &arguments.save_state_on { Some(path) => Some((path.clone(), resolve_signal_path(simulation, top, path)?)), @@ -338,11 +432,23 @@ impl StateSaves { .save_state_dir .clone() .unwrap_or_else(|| PathBuf::from(".")); - if !arguments.is_empty() { + if !arguments.is_empty() || signal.is_some() { std::fs::create_dir_all(&directory) .map_err(|error| format!("cannot create {}: {error}", directory.display()))?; } + if signal.is_some() { + let _ = writeln!( + std::io::stderr().lock(), + "SIGUSR1 checkpoint ready (pid {}): {}", + std::process::id(), + directory.display() + ); + } Ok(Self { + signal, + signal_sequence: 0, + failed: false, + started: false, counted, cycles: descending(&arguments.save_state_at), count: 0, @@ -361,8 +467,11 @@ impl StateSaves { } fn start(&mut self, simulation: &mut celox::Simulation) { - if let Some((_, signal)) = self.counted { - self.high = Self::level(simulation, signal); + if !self.started { + if let Some((_, signal)) = self.counted { + self.high = Self::level(simulation, signal); + } + self.started = true; } } @@ -372,6 +481,7 @@ impl StateSaves { simulation: &mut celox::Simulation, next: u64, ) -> Result<(), String> { + self.service_signal(simulation); while let Some(&time) = self.times.last() && time < next { @@ -386,6 +496,7 @@ impl StateSaves { simulation: &mut celox::Simulation, ) -> Result<(), String> { let Some((name, signal)) = &self.counted else { + self.service_signal(simulation); return Ok(()); }; let (name, signal) = (name.clone(), *signal); @@ -399,6 +510,7 @@ impl StateSaves { self.save(simulation, format!("{name}-{}.state", self.count))?; } } + self.service_signal(simulation); Ok(()) } @@ -419,6 +531,62 @@ impl StateSaves { Ok(()) } + /// A signal request must never turn a diagnostic failure into loss of the + /// ongoing run. Keep requests pending across `$stop` suspensions. + fn service_signal(&mut self, simulation: &mut celox::Simulation) { + if simulation.is_stopped() + || !self + .signal + .as_ref() + .is_some_and(|signal| signal.take_request()) + { + return; + } + let Some(sequence) = self.signal_sequence.checked_add(1) else { + let _ = writeln!( + std::io::stderr().lock(), + "cannot save SIGUSR1 checkpoint: request sequence exhausted" + ); + return; + }; + self.signal_sequence = sequence; + let path = self.directory.join(format!( + "signal-{}-{sequence}.checkpoint", + std::process::id() + )); + let result = (|| -> Result<(), String> { + let state = system_checkpoint::capture(simulation, self)?; + // Publish only complete files, without overwriting earlier captures. + let mut temporary = tempfile::NamedTempFile::new_in(&self.directory) + .map_err(|error| error.to_string())?; + temporary + .as_file_mut() + .write_all(&state) + .map_err(|error| error.to_string())?; + temporary + .as_file_mut() + .sync_all() + .map_err(|error| error.to_string())?; + temporary + .persist_noclobber(&path) + .map_err(|error| error.to_string())?; + Ok(()) + })(); + let _ = match result { + Ok(()) => writeln!( + std::io::stderr().lock(), + "saved SIGUSR1 checkpoint: {} (time {})", + path.display(), + simulation.time() + ), + Err(error) => writeln!( + std::io::stderr().lock(), + "cannot save SIGUSR1 checkpoint {}: {error}; continuing simulation", + path.display() + ), + }; + } + fn save( &self, simulation: &mut celox::Simulation, diff --git a/crates/celox-vpi/src/bin/celox/checkpoint_fs.rs b/crates/celox-vpi/src/bin/celox/checkpoint_fs.rs new file mode 100644 index 00000000000..7df7a992a92 --- /dev/null +++ b/crates/celox-vpi/src/bin/celox/checkpoint_fs.rs @@ -0,0 +1,553 @@ +//! CLI file effects: a disk-backed working view plus immediate host output. +//! Checkpoints retain the working view; already delivered host output is not +//! undone. A later write publishes the new working contents again. +use celox::{FileMode, FileSystem}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs::{File, OpenOptions}, + io::{self, Read, Seek, SeekFrom, Write}, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Stream { + path: PathBuf, + position: u64, + read: bool, + write: bool, + append: bool, + live: bool, +} +#[derive(Serialize, Deserialize)] +struct State { + files: BTreeMap>, + opaque_prefixes: BTreeMap, + streams: BTreeMap, + next: u64, +} +#[derive(Debug, Default)] +pub(super) struct CheckpointFs { + files: BTreeMap, + opaque_prefixes: BTreeMap, + live_files: BTreeMap, + outputs: BTreeMap, + pending_publish: BTreeSet, + streams: BTreeMap, + next: u64, +} +// TempPath owns cleanup but no OS descriptor. Reopen only for each operation, +// including snapshot/restore, so closed files do not consume the descriptor limit. +fn working_file(path: &Path) -> io::Result { + OpenOptions::new().read(true).write(true).open(path) +} + +impl CheckpointFs { + fn stream(&self, id: u64) -> io::Result { + self.streams + .get(&id) + .cloned() + .ok_or_else(|| io::Error::other("closed file effect handle")) + } + fn live_file(&mut self, id: u64, stream: &Stream) -> io::Result<&mut File> { + if let std::collections::btree_map::Entry::Vacant(entry) = self.live_files.entry(id) { + // External channels reconnect lazily: restoring a system checkpoint + // must not block waiting for a pipe peer. + entry.insert( + OpenOptions::new() + .read(stream.read) + .write(stream.write) + .append(stream.append) + .open(&stream.path)?, + ); + } + Ok(self.live_files.get_mut(&id).unwrap()) + } + fn output_file(&mut self, id: u64, stream: &Stream) -> io::Result<&mut File> { + if let std::collections::btree_map::Entry::Vacant(entry) = self.outputs.entry(id) { + // Restored streams reconnect to their recorded path on first output. + // Ordinary active streams retain their original host handle until close. + entry.insert( + OpenOptions::new() + .write(true) + .append(stream.append) + .create( + self.pending_publish.contains(&stream.path) + && !self.opaque_prefixes.contains_key(&stream.path), + ) + .open(&stream.path)?, + ); + } + Ok(self.outputs.get_mut(&id).unwrap()) + } + fn publish(&mut self, id: u64, stream: &Stream) -> io::Result<()> { + let key = &stream.path; + let prefix = self.opaque_prefixes.get(key).copied().unwrap_or(0); + let mut file = working_file(&self.files[key])?; + file.seek(SeekFrom::Start(prefix))?; + // Do not replace an unreadable, externally owned append prefix. + let mut output = self.output_file(id, stream)?; + if output.metadata()?.len() < prefix { + return Err(io::Error::other( + "external append prefix is shorter than the checkpoint", + )); + } + output.set_len(prefix)?; + output.seek(SeekFrom::Start(prefix))?; + io::copy(&mut file, &mut output)?; + output.flush()?; + self.pending_publish.remove(key); + Ok(()) + } +} +impl FileSystem for CheckpointFs { + fn open(&mut self, path: &Path, mode: FileMode) -> io::Result { + let absolute = std::path::absolute(path)?; + let path = std::fs::canonicalize(&absolute).unwrap_or(absolute); + let live = std::fs::metadata(&path).is_ok_and(|metadata| !metadata.is_file()); + if live { + let file = OpenOptions::new() + .read(mode.read) + .write(mode.write) + .append(mode.append) + .create(mode.create) + .truncate(mode.truncate) + .open(&path)?; + let id = self.next; + self.next = self + .next + .checked_add(1) + .ok_or_else(|| io::Error::other("file handle space exhausted"))?; + self.live_files.insert(id, file); + self.streams.insert( + id, + Stream { + path, + position: 0, + read: mode.read, + write: mode.write, + append: mode.append, + live: true, + }, + ); + return Ok(id); + } + // Request only the permissions in the HDL mode. In particular, append + // is a write effect and does not grant read access to an existing prefix. + let cached = self.files.contains_key(&path); + let needs_host = + mode.write || !cached || (mode.read && self.opaque_prefixes.contains_key(&path)); + let host = if needs_host { + Some( + OpenOptions::new() + .read(mode.read) + .write(mode.write) + .append(mode.append) + .create(mode.create) + .truncate(mode.truncate) + .open(&path)?, + ) + } else { + None + }; + let key = path.clone(); + if !self.files.contains_key(&key) { + let mut file = tempfile::NamedTempFile::new()?; + if !mode.truncate { + match File::open(&path) { + Ok(mut source) => { + io::copy(&mut source, &mut file)?; + } + Err(error) + if mode.append + && !mode.read + && error.kind() == io::ErrorKind::PermissionDenied => + { + let prefix = host + .as_ref() + .expect("append file opened above") + .metadata()? + .len(); + file.as_file().set_len(prefix)?; + self.opaque_prefixes.insert(key.clone(), prefix); + } + Err(error) => return Err(error), + } + } + self.files.insert(key.clone(), file.into_temp_path()); + } + if mode.truncate { + working_file(&self.files[&key])?.set_len(0)?; + self.opaque_prefixes.remove(&key); + self.pending_publish.remove(&key); + } + if mode.read + && let Some(prefix) = self.opaque_prefixes.get(&key).copied() + { + let mut source = File::open(&path)?.take(prefix); + let mut file = working_file(&self.files[&key])?; + file.rewind()?; + if io::copy(&mut source, &mut file)? != prefix { + return Err(io::Error::other("external append prefix is truncated")); + } + self.opaque_prefixes.remove(&key); + } + let id = self.next; + self.next = self + .next + .checked_add(1) + .ok_or_else(|| io::Error::other("file handle space exhausted"))?; + if mode.write { + self.outputs.insert(id, host.expect("write opened above")); + } + self.streams.insert( + id, + Stream { + path, + position: 0, + read: mode.read, + write: mode.write, + append: mode.append, + live: false, + }, + ); + Ok(id) + } + fn close(&mut self, id: u64) -> io::Result<()> { + self.live_files.remove(&id); + self.outputs.remove(&id); + self.streams + .remove(&id) + .ok_or_else(|| io::Error::other("closed file effect handle"))?; + Ok(()) + } + fn read(&mut self, id: u64, bytes: &mut [u8]) -> io::Result { + let stream = self.stream(id)?; + if stream.live { + return self.live_file(id, &stream)?.read(bytes); + } + if !stream.read { + return Err(io::ErrorKind::PermissionDenied.into()); + } + let mut file = working_file(&self.files[&stream.path])?; + file.seek(SeekFrom::Start(stream.position))?; + let count = file.read(bytes)?; + self.streams.get_mut(&id).unwrap().position += count as u64; + Ok(count) + } + fn write(&mut self, id: u64, bytes: &[u8]) -> io::Result { + let stream = self.stream(id)?; + if stream.live { + return self.live_file(id, &stream)?.write(bytes); + } + if !stream.write { + return Err(io::ErrorKind::PermissionDenied.into()); + } + if self.pending_publish.contains(&stream.path) { + self.publish(id, &stream)?; + } + let mut file = working_file(&self.files[&stream.path])?; + let position = file.seek(if stream.append { + SeekFrom::End(0) + } else { + SeekFrom::Start(stream.position) + })?; + let count = file.write(bytes)?; + self.streams.get_mut(&id).unwrap().position = position + count as u64; + // Ordinary writes publish only their byte range. A restored branch + // materializes its saved baseline once, before its first output effect. + let output = self.output_file(id, &stream)?; + if !stream.append { + output.seek(SeekFrom::Start(position))?; + } + output.write_all(&bytes[..count])?; + Ok(count) + } + fn seek(&mut self, id: u64, from: SeekFrom) -> io::Result { + let stream = self.stream(id)?; + if stream.live { + return self.live_file(id, &stream)?.seek(from); + } + let mut file = working_file(&self.files[&stream.path])?; + file.seek(SeekFrom::Start(stream.position))?; + let position = file.seek(from)?; + self.streams.get_mut(&id).unwrap().position = position; + Ok(position) + } + fn flush(&mut self, id: u64) -> io::Result<()> { + let stream = self.stream(id)?; + if stream.live { + self.live_file(id, &stream)?.flush()?; + } + Ok(()) + } + // Standard streams are live external channels, not files in the working view. + fn read_stdin(&mut self, bytes: &mut [u8]) -> io::Result { + io::stdin().lock().read(bytes) + } + fn write_stderr(&mut self, bytes: &[u8]) -> io::Result<()> { + io::stderr().lock().write_all(bytes) + } + fn flush_stdout(&mut self) -> io::Result<()> { + io::stdout().lock().flush() + } + fn flush_stderr(&mut self) -> io::Result<()> { + io::stderr().lock().flush() + } + fn snapshot_format(&self) -> &str { + "celox-cli-file-effects/v3" + } + fn snapshot(&self) -> io::Result> { + let mut files = BTreeMap::new(); + for (path, file) in &self.files { + let mut file = working_file(file)?; + file.seek(SeekFrom::Start( + self.opaque_prefixes.get(path).copied().unwrap_or(0), + ))?; + let mut bytes = Vec::new(); + let read = file.read_to_end(&mut bytes); + read?; + files.insert(path.clone(), bytes); + } + serde_json::to_vec(&State { + files, + streams: self.streams.clone(), + opaque_prefixes: self.opaque_prefixes.clone(), + next: self.next, + }) + .map_err(io::Error::other) + } + fn restore(&self, bytes: &[u8]) -> io::Result> { + let state: State = serde_json::from_slice(bytes).map_err(io::Error::other)?; + let mut files = BTreeMap::new(); + for (path, bytes) in state.files { + let mut file = tempfile::NamedTempFile::new()?; + let prefix = state.opaque_prefixes.get(&path).copied().unwrap_or(0); + file.as_file().set_len(prefix)?; + file.seek(SeekFrom::Start(prefix))?; + file.write_all(&bytes)?; + files.insert(path, file.into_temp_path()); + } + if state.streams.iter().any(|(id, stream)| { + *id >= state.next || (!stream.live && !files.contains_key(&stream.path)) + }) { + return Err(io::Error::other("invalid file effect state")); + } + Ok(Box::new(Self { + pending_publish: files.keys().cloned().collect(), + files, + opaque_prefixes: state.opaque_prefixes, + live_files: BTreeMap::new(), + outputs: BTreeMap::new(), + streams: state.streams, + next: state.next, + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn checkpoint_keeps_file_effect_state_separate_from_delivered_output() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("output"); + let mode = FileMode { + read: true, + write: true, + create: true, + truncate: true, + append: false, + }; + let mut effects = CheckpointFs::default(); + let fd = effects.open(&path, mode).unwrap(); + effects.write(fd, b"before").unwrap(); + effects.seek(fd, SeekFrom::Start(0)).unwrap(); + let saved = effects.snapshot().unwrap(); + effects.write(fd, b"after!").unwrap(); + effects.close(fd).unwrap(); + let mut restored = effects.restore(&saved).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"after!"); + let mut buffer = [0; 6]; + restored.read(fd, &mut buffer).unwrap(); + assert_eq!(&buffer, b"before"); + restored.write(fd, b" again").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"before again"); + let mut second = effects.restore(&saved).unwrap(); + second.read(fd, &mut buffer).unwrap(); + assert_eq!(&buffer, b"before"); + } +} + +#[cfg(all(test, unix))] +#[test] +fn device_effects_reconnect_as_live_channels() { + let mode = FileMode { + read: true, + write: true, + append: false, + create: false, + truncate: false, + }; + let mut effects = CheckpointFs::default(); + let fd = effects.open(Path::new("/dev/null"), mode).unwrap(); + let saved = effects.snapshot().unwrap(); + effects.close(fd).unwrap(); + let mut restored = effects.restore(&saved).unwrap(); + assert_eq!(restored.write(fd, b"output").unwrap(), 6); + assert_eq!(restored.read(fd, &mut [0; 1]).unwrap(), 0); +} + +#[cfg(all(test, unix))] +#[test] +fn write_only_append_preserves_the_external_prefix_across_restore() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("write-only"); + std::fs::write(&path, b"prefix").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o200)).unwrap(); + // Root can read despite the permission bits, but still exercises append. + let unreadable = File::open(&path).is_err(); + let mode = FileMode { + read: false, + write: true, + append: true, + create: true, + truncate: false, + }; + let mut effects = CheckpointFs::default(); + let fd = effects.open(&path, mode).unwrap(); + if unreadable { + assert_eq!( + effects + .opaque_prefixes + .values() + .copied() + .collect::>(), + [6] + ); + } + effects.write(fd, b"A").unwrap(); + let saved = effects.snapshot().unwrap(); + effects.write(fd, b"B").unwrap(); + let mut restored = effects.restore(&saved).unwrap(); + restored.write(fd, b"C").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"prefixAC"); +} + +#[cfg(all(test, unix))] +#[test] +fn closed_working_files_do_not_retain_descriptors() { + const CHILD: &str = "CELOX_TEST_BOUNDED_FILE_DESCRIPTORS"; + if std::env::var_os(CHILD).is_none() { + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "checkpoint_fs::closed_working_files_do_not_retain_descriptors", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + return; + } + // This subprocess contains only this test; do not change the parent runner's limit. + let limit = libc::rlimit { + rlim_cur: 64, + rlim_max: 64, + }; + // SAFETY: pointer to an initialized rlimit; no pointers retained by the OS. + assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0); + let directory = tempfile::tempdir().unwrap(); + let mode = FileMode { + read: true, + write: true, + create: true, + truncate: false, + append: false, + }; + let mut effects = CheckpointFs::default(); + for index in 0..128 { + let fd = effects + .open(&directory.path().join(index.to_string()), mode) + .unwrap(); + effects.write(fd, &[index]).unwrap(); + effects.close(fd).unwrap(); + } + let saved = effects.snapshot().unwrap(); + let mut restored = effects.restore(&saved).unwrap(); + for index in 0..128 { + let path = directory.path().join(index.to_string()); + std::fs::write(&path, b"external").unwrap(); + let fd = restored.open(&path, mode).unwrap(); + let mut byte = [0]; + assert_eq!(restored.read(fd, &mut byte).unwrap(), 1); + assert_eq!(byte, [index]); + restored.close(fd).unwrap(); + } +} + +#[cfg(test)] +#[test] +fn closed_working_contents_can_be_reopened_without_the_host_file() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input"); + std::fs::write(&path, b"saved").unwrap(); + let mode = FileMode { + read: true, + write: false, + append: false, + create: false, + truncate: false, + }; + let mut effects = CheckpointFs::default(); + let fd = effects.open(&path, mode).unwrap(); + effects.close(fd).unwrap(); + let saved = effects.snapshot().unwrap(); + std::fs::remove_file(&path).unwrap(); + let mut restored = effects.restore(&saved).unwrap(); + let fd = restored.open(&path, mode).unwrap(); + let mut bytes = [0; 5]; + assert_eq!(restored.read(fd, &mut bytes).unwrap(), 5); + assert_eq!(&bytes, b"saved"); +} + +#[cfg(all(test, unix))] +#[test] +fn active_outputs_keep_the_open_file_across_rotation_and_unlink() { + for append in [false, true] { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("output"); + let rotated = directory.path().join("rotated"); + let mut effects = CheckpointFs::default(); + let mode = FileMode { + read: true, + write: true, + create: true, + truncate: false, + append, + }; + let fd = effects.open(&path, mode).unwrap(); + effects.write(fd, b"A").unwrap(); + std::fs::rename(&path, &rotated).unwrap(); + std::fs::write(&path, b"replacement").unwrap(); + effects.write(fd, b"B").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"replacement"); + assert_eq!(std::fs::read(&rotated).unwrap(), b"AB"); + let mut original = File::open(&rotated).unwrap(); + std::fs::remove_file(&rotated).unwrap(); + std::fs::remove_file(&path).unwrap(); + effects.write(fd, b"C").unwrap(); + effects.close(fd).unwrap(); + let mut bytes = Vec::new(); + original.read_to_end(&mut bytes).unwrap(); + assert_eq!(&bytes, b"ABC"); + assert!(!path.exists()); + } +} diff --git a/crates/celox-vpi/src/bin/celox/state_signal.rs b/crates/celox-vpi/src/bin/celox/state_signal.rs new file mode 100644 index 00000000000..23e1d75638d --- /dev/null +++ b/crates/celox-vpi/src/bin/celox/state_signal.rs @@ -0,0 +1,91 @@ +//! Process-local SIGUSR1 requests. Only an atomic flag is touched by the signal +//! handler; the CLI services it between complete simulation time steps. + +#[cfg(unix)] +mod unix { + use std::sync::atomic::{AtomicBool, Ordering}; + + static REQUESTED: AtomicBool = AtomicBool::new(false); + static INSTALLED: AtomicBool = AtomicBool::new(false); + + extern "C" fn request_state(_signal: libc::c_int) { + REQUESTED.store(true, Ordering::Relaxed); + } + + pub(super) struct Registration { + previous: libc::sigaction, + } + + impl Registration { + pub(super) fn install() -> Result { + if INSTALLED.swap(true, Ordering::Relaxed) { + return Err("SIGUSR1 state capture is already installed".into()); + } + REQUESTED.store(false, Ordering::Relaxed); + // Safety: a zeroed sigaction is initialized below before use. The + // handler has the C signal ABI, lives for the process lifetime, and + // performs only a lock-free atomic store (no allocation or I/O). + unsafe { + let mut action: libc::sigaction = std::mem::zeroed(); + let mut previous: libc::sigaction = std::mem::zeroed(); + action.sa_sigaction = request_state as *const () as libc::sighandler_t; + action.sa_flags = libc::SA_RESTART; + libc::sigemptyset(&mut action.sa_mask); + if libc::sigaction(libc::SIGUSR1, &action, &mut previous) != 0 { + INSTALLED.store(false, Ordering::Relaxed); + return Err(format!( + "cannot install SIGUSR1 state capture: {}", + std::io::Error::last_os_error() + )); + } + Ok(Self { previous }) + } + } + + pub(super) fn take_request(&self) -> bool { + REQUESTED.swap(false, Ordering::Relaxed) + } + } + + impl Drop for Registration { + fn drop(&mut self) { + // Safety: previous is the action returned by successful installation. + // Restore the caller's action rather than imposing a default handler. + unsafe { + libc::sigaction(libc::SIGUSR1, &self.previous, std::ptr::null_mut()); + } + INSTALLED.store(false, Ordering::Relaxed); + } + } +} + +pub(super) struct StateSignal { + #[cfg(unix)] + registration: unix::Registration, +} + +impl StateSignal { + pub(super) fn install() -> Result { + #[cfg(unix)] + { + Ok(Self { + registration: unix::Registration::install()?, + }) + } + #[cfg(not(unix))] + { + Err("SIGUSR1 checkpoint handling requires Unix".into()) + } + } + + pub(super) fn take_request(&self) -> bool { + #[cfg(unix)] + { + self.registration.take_request() + } + #[cfg(not(unix))] + { + false + } + } +} diff --git a/crates/celox-vpi/src/bin/celox/system_checkpoint.rs b/crates/celox-vpi/src/bin/celox/system_checkpoint.rs new file mode 100644 index 00000000000..6230d4b67b1 --- /dev/null +++ b/crates/celox-vpi/src/bin/celox/system_checkpoint.rs @@ -0,0 +1,307 @@ +//! The CLI system owns composition; core checkpoint bytes know nothing of effects. +use celox::{SimBackend, Simulation}; +use serde::{Deserialize, Serialize}; +use std::path::Path; + +#[derive(Serialize, Deserialize)] +struct CliCheckpoint { + format: String, + checksum: String, + time: u64, + progress: crate::SavedStateSaves, + core: Vec, + waveform: celox::SourceWaveformState, + file_effects: celox_runtime::file_io::FileIoSnapshot, +} + +pub(super) fn capture( + simulation: &Simulation, + saves: &crate::StateSaves, +) -> Result, String> { + let mut state = CliCheckpoint { + format: "celox-cli-checkpoint/v4".into(), + checksum: String::new(), + time: simulation.time(), + progress: saves.progress(), + core: simulation + .checkpoint() + .map_err(|error| error.to_string())? + .to_bytes() + .map_err(|error| error.to_string())?, + waveform: simulation.source_waveform_state(), + file_effects: simulation + .file_io() + .try_snapshot() + .map_err(|error| error.to_string())?, + }; + let bytes = serde_json::to_vec(&state).map_err(|error| error.to_string())?; + state.checksum = blake3::hash(&bytes).to_hex().to_string(); + serde_json::to_vec(&state).map_err(|error| error.to_string()) +} + +pub(super) fn restore( + simulation: &mut Simulation, + path: &Path, +) -> Result { + let bytes = std::fs::read(path).map_err(|error| error.to_string())?; + let mut state: CliCheckpoint = + serde_json::from_slice(&bytes).map_err(|error| error.to_string())?; + let expected = std::mem::take(&mut state.checksum); + let encoded = serde_json::to_vec(&state).map_err(|error| error.to_string())?; + if blake3::hash(&encoded).to_hex().as_str() != expected { + return Err("CLI checkpoint checksum mismatch".into()); + } + if state.format != "celox-cli-checkpoint/v4" { + return Err("incompatible CLI checkpoint".into()); + } + // Safety: --restore-checkpoint, like --native-image, explicitly loads a + // trusted artifact produced by this application. Never use it on untrusted data. + let core = unsafe { simulation.checkpoint_from_bytes(&state.core) } + .map_err(|error| error.to_string())?; + let effects = simulation + .file_io() + .prepare_restore(&state.file_effects) + .map_err(|error| error.to_string())?; + // Install effects before settling the restored core can issue another effect. + simulation.replace_file_io(effects); + simulation + .restore(&core) + .map_err(|error| error.to_string())?; + let output = if state.waveform.is_active() { + let requested = + std::path::absolute(state.waveform.path()).map_err(|error| error.to_string())?; + let prefix = format!( + "{}.resume-", + requested.file_name().unwrap_or_default().to_string_lossy() + ); + let segment = tempfile::Builder::new() + .prefix(&prefix) + .suffix(".vcd") + .tempfile_in(requested.parent().unwrap_or(Path::new("."))) + .map_err(|error| error.to_string())?; + let (file, path) = segment.keep().map_err(|error| error.to_string())?; + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "Restored waveform segment: {}", + path.display() + ); + Some((path, file)) + } else { + None + }; + // SAFETY: same trusted system artifact as the core decoded above, restored + // only after core layout compatibility has been checked. + unsafe { simulation.restore_source_waveform(state.waveform, output) } + .map_err(|error| error.to_string())?; + Ok(state.progress) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn system_checkpoint_restores_file_effects_with_a_fresh_core() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("input"); + std::fs::write(&input, b"ABCD").unwrap(); + let source = format!( + r#" +module Top(output int value); + timeunit 1ns; timeprecision 1ns; + int fd = $fopen("{}", "r"); + always #1 value = $fgetc(fd); +endmodule +"#, + input.display() + ); + let build = |defer| { + Simulation::from_sv_sources(vec![(&source, Path::new("io.sv"))], "Top") + .defer_initialization(defer) + .file_system(|| Box::::default()) + .build_interpreter() + .unwrap() + }; + let mut original = build(false); + original.run_until(1).unwrap(); + assert_eq!(original.get(original.signal("value")), 65u32.into()); + let saved = capture(&original, &crate::StateSaves::default()).unwrap(); + original.run_until(2).unwrap(); + std::fs::write(&input, b"WXYZ").unwrap(); + let path = dir.path().join("saved.checkpoint"); + std::fs::write(&path, saved).unwrap(); + let mut resumed = build(true); + restore(&mut resumed, &path).unwrap(); + assert_eq!(resumed.time(), 1); + resumed.run_until(2).unwrap(); + assert_eq!(resumed.get(resumed.signal("value")), 66u32.into()); + assert_eq!(std::fs::read(&input).unwrap(), b"WXYZ"); + } + #[test] + fn restored_cli_retains_a_previously_reported_failure() { + let source = r#"module Top; timeunit 1ns; timeprecision 1ns; + initial begin $error("before checkpoint"); #2; $finish; end + endmodule"#; + let build = |defer| { + Simulation::from_sv_sources(vec![(source, Path::new("failure.sv"))], "Top") + .defer_initialization(defer) + .file_system(|| Box::::default()) + .build_interpreter() + .unwrap() + }; + let mut original = build(false); + original.run_until(1).unwrap(); + let mut failed = false; + crate::drain_sv_output(&mut original, &mut Vec::new(), &mut failed).unwrap(); + assert!(failed); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("failed.checkpoint"); + std::fs::write( + &path, + capture( + &original, + &crate::StateSaves { + failed, + ..Default::default() + }, + ) + .unwrap(), + ) + .unwrap(); + let mut resumed = build(true); + let progress = restore(&mut resumed, &path).unwrap(); + let mut saves = crate::StateSaves::default(); + saves.restore_progress(&resumed, "Top", progress).unwrap(); + let error = crate::simulate_sv(resumed, 10, saves, &mut Vec::new()).unwrap_err(); + assert!(error.contains("assertion failure or $error"), "{error}"); + } +} + +#[cfg(test)] +#[test] +fn waveform_controls_survive_system_restore() { + for pause in ["$dumpoff;", "$dumplimit(1);"] { + let dir = tempfile::tempdir().unwrap(); + let original_path = dir.path().join("original.vcd"); + let source = format!( + r#" +module Top(output int value, output int excluded); + timeunit 1ns; timeprecision 1ns; + initial begin + $dumpfile("{}"); $dumpvars(0, Top.value); + #1; {}; #3; $dumplimit(0); $dumpon; + end + always #1 begin value++; excluded++; end +endmodule +"#, + original_path.display(), + pause + ); + let build = |defer| { + Simulation::from_sv_sources(vec![(&source, Path::new("wave.sv"))], "Top") + .defer_initialization(defer) + .file_system(|| Box::::default()) + .build_interpreter() + .unwrap() + }; + let mut original = build(false); + original.run_until(2).unwrap(); + original.flush_vcd().unwrap(); + let checkpoint = dir.path().join("wave.checkpoint"); + std::fs::write( + &checkpoint, + capture(&original, &crate::StateSaves::default()).unwrap(), + ) + .unwrap(); + let delivered = std::fs::read(&original_path).unwrap(); + let mut resumed = build(true); + restore(&mut resumed, &checkpoint).unwrap(); + resumed.run_until(5).unwrap(); + resumed.flush_vcd().unwrap(); + assert_eq!(std::fs::read(&original_path).unwrap(), delivered); + let segment = std::fs::read_dir(dir.path()) + .unwrap() + .filter_map(Result::ok) + .find(|entry| { + entry + .file_name() + .to_string_lossy() + .starts_with("original.vcd.resume-") + }) + .unwrap(); + let text = std::fs::read_to_string(segment.path()).unwrap(); + assert!(text.contains(" value $end"), "{pause}: {text}"); + assert!(!text.contains(" excluded $end"), "{pause}: {text}"); + assert!(!text.contains("#3\n"), "{pause}: {text}"); + assert!( + text.contains("#4\n") && text.contains("#5\n"), + "{pause}: {text}" + ); + assert!(text.contains("$dumpon"), "{pause}: {text}"); + } +} + +#[cfg(test)] +#[test] +fn restore_keeps_consumed_saves_cycle_count_and_edge_baseline() { + // Capture both high and low clock phases, including immediately after a + // counted edge. Neither start() nor the next step may count that edge twice. + for checkpoint_time in [9, 10] { + let dir = tempfile::tempdir().unwrap(); + let source = r#"module Top(output bit clk); + timeunit 1ns; timeprecision 1ns; + always #1 clk = !clk; + initial begin #13; $finish; end + endmodule"#; + let build = |defer| { + Simulation::from_sv_sources(vec![(source, Path::new("saves.sv"))], "Top") + .defer_initialization(defer) + .file_system(|| Box::::default()) + .build_interpreter() + .unwrap() + }; + let arguments = crate::SaveStateArgs { + save_state_on: Some("clk".into()), + save_state_at: vec![2, 6], + save_state_at_time: vec![5, 11], + save_state_dir: Some(dir.path().into()), + ..Default::default() + }; + let mut original = build(false); + let mut saves = crate::StateSaves::new(&original, "Top", &arguments, None).unwrap(); + saves.start(&mut original); + while let Some(next) = original.next_event_time() { + if next > checkpoint_time { + break; + } + saves.before(&mut original, next).unwrap(); + original.step().unwrap(); + saves.after_step(&mut original).unwrap(); + } + assert_eq!(saves.count, 5); + assert_eq!(saves.cycles, [6]); + assert_eq!(saves.times, [11]); + let first_time = std::fs::read(dir.path().join("time-5.state")).unwrap(); + let first_cycle = std::fs::read(dir.path().join("clk-2.state")).unwrap(); + let checkpoint = dir.path().join("scheduled.checkpoint"); + std::fs::write(&checkpoint, capture(&original, &saves).unwrap()).unwrap(); + let mut restored = build(true); + let progress = restore(&mut restored, &checkpoint).unwrap(); + let mut saves = crate::StateSaves::new(&restored, "Top", &arguments, None).unwrap(); + saves.restore_progress(&restored, "Top", progress).unwrap(); + crate::simulate_sv(restored, 20, saves, &mut Vec::new()).unwrap(); + assert_eq!( + std::fs::read(dir.path().join("time-5.state")).unwrap(), + first_time + ); + assert_eq!( + std::fs::read(dir.path().join("clk-2.state")).unwrap(), + first_cycle + ); + for name in ["clk-6.state", "time-11.state"] { + let file = std::fs::File::open(dir.path().join(name)).unwrap(); + let state = celox::StateFile::read_from(file).unwrap(); + assert_eq!(state.schedule.unwrap().time, 11, "{name}"); + } + } +} diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index 41b68e1aa44..723dca18793 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -757,3 +757,174 @@ endmodule "iterations=7000 mode=slow verbose=0\n" ); } + +#[cfg(all(unix, feature = "systemverilog"))] +#[test] +fn sigusr1_checkpoints_by_default_and_resumes_in_a_new_process() { + use std::{ + io::BufRead, + process::{Child, Stdio}, + sync::mpsc, + time::Duration, + }; + struct Running(Child); + impl Drop for Running { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + for backend in [ + "interpreter", + "native", + "tiered", + #[cfg(feature = "cranelift")] + "cranelift", + #[cfg(feature = "wasm-runtime")] + "wasm", + ] { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("top.sv"); + let output_path = dir.path().join("output.log"); + let waveform_path = dir.path().join("trace.vcd"); + std::fs::write( + &source, + format!( + r#" +module Top(output longint unsigned count); + timeunit 1ns; timeprecision 1ns; + int fd = $fopen("{}", "w"); + initial begin $dumpfile("{}"); $dumpvars(0, Top); end + always #1 begin count++; $display("%0d", count); end +endmodule +"#, + output_path.display(), + waveform_path.display() + ), + ) + .unwrap(); + let mut process = Running( + Command::new(env!("CARGO_BIN_EXE_celox")) + .arg("run") + .arg(&source) + .args([ + "--top", + "Top", + "--backend", + backend, + "--unlimited", + "--save-state-dir", + ]) + .arg(dir.path()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(), + ); + let stderr = process.0.stderr.take().unwrap(); + let (tx, rx) = mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in std::io::BufReader::new(stderr).lines() { + if tx.send(line.unwrap()).is_err() { + break; + } + } + }); + let wait = |message: &str| { + let deadline = std::time::Instant::now() + Duration::from_secs(60); + let mut logs = String::new(); + loop { + let line = rx + .recv_timeout(deadline.saturating_duration_since(std::time::Instant::now())) + .unwrap_or_else(|error| panic!("{backend}: {message}: {error}; {logs}")); + logs.push_str(&line); + logs.push('\n'); + if line.contains(message) { + break; + } + } + }; + wait("SIGUSR1 checkpoint ready"); + let deadline = std::time::Instant::now() + Duration::from_secs(60); + while !waveform_path.exists() { + assert!( + std::time::Instant::now() < deadline, + "waveform did not start: {backend}" + ); + std::thread::sleep(Duration::from_millis(10)); + } + let pid = process.0.id(); + // SAFETY: signal a live child owned by this test. + assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGUSR1) }, 0); + wait("saved SIGUSR1 checkpoint"); + assert!(process.0.try_wait().unwrap().is_none()); + let checkpoint = dir.path().join(format!("signal-{pid}-1.checkpoint")); + let state: serde_json::Value = + serde_json::from_slice(&std::fs::read(&checkpoint).unwrap()).unwrap(); + let time = state["time"].as_u64().unwrap(); + // A failed request must leave the old file and running simulation intact. + let collision = dir.path().join(format!("signal-{pid}-2.checkpoint")); + std::fs::write(&collision, b"keep").unwrap(); + assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGUSR1) }, 0); + wait("cannot save SIGUSR1 checkpoint"); + assert_eq!(std::fs::read(&collision).unwrap(), b"keep"); + assert!(process.0.try_wait().unwrap().is_none()); + drop(process); + reader.join().unwrap(); + std::fs::write(&output_path, b"delivered after checkpoint").unwrap(); + let original_waveform = std::fs::read(&waveform_path).unwrap(); + let resumed = Command::new(env!("CARGO_BIN_EXE_celox")) + .arg("run") + .arg(&source) + .args([ + "--top", + "Top", + "--backend", + backend, + "--max-steps", + "3", + "--no-checkpoint-on-signal", + "--restore-checkpoint", + ]) + .arg(&checkpoint) + .output() + .unwrap(); + assert_eq!( + std::fs::read(&output_path).unwrap(), + b"delivered after checkpoint" + ); + assert_eq!(std::fs::read(&waveform_path).unwrap(), original_waveform); + let segments = std::fs::read_dir(dir.path()) + .unwrap() + .filter_map(Result::ok) + .filter(|entry| { + entry + .file_name() + .to_string_lossy() + .starts_with("trace.vcd.resume-") + }) + .collect::>(); + assert_eq!( + segments.len(), + 1, + "{backend}: {}", + String::from_utf8_lossy(&resumed.stderr) + ); + let waveform = std::fs::read_to_string(segments[0].path()).unwrap(); + assert!(waveform.contains("$enddefinitions $end"), "{waveform}"); + assert!( + waveform.contains(&format!("#{}\n", time + 3)), + "{backend}: {waveform}" + ); + let output = String::from_utf8(resumed.stdout).unwrap(); + let counts: Vec = output.lines().map(|line| line.parse().unwrap()).collect(); + // A checkpoint before the initial time-zero slot needs one step to + // start the always process; otherwise all three steps advance time. + assert!((2..=3).contains(&counts.len()), "{output}"); + assert_eq!( + counts, + (time + 1..=time + counts.len() as u64).collect::>() + ); + assert!(String::from_utf8_lossy(&resumed.stderr).contains("exceeded --max-steps 3")); + } +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 7055ed180c1..586e3424da4 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -119,7 +119,7 @@ mod host_api { pub use crate::debug::CompilationTraceResult; pub use crate::diagnostics::DiagnosticsOptions; pub use crate::simulation::{ - CheckpointFileError, Simulation, SimulationCheckpoint, SlotObserver, + CheckpointFileError, Simulation, SimulationCheckpoint, SlotObserver, SourceWaveformState, }; #[cfg(any( target_arch = "x86_64", diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index bf3862eb9ab..892beb50362 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -15,6 +15,8 @@ mod checkpoint_file; pub use checkpoint_file::CheckpointFileError; mod differential; mod vcd_tasks; +mod waveform_state; +pub use waveform_state::SourceWaveformState; /// Saved state of a [`Simulation`], created by [`Simulation::checkpoint`]: /// the design state together with simulation time, clocks and pending events. @@ -174,6 +176,10 @@ impl UnitExecutor for Simulator { } fn apply_declaration_startup(&mut self) -> Result<(), Halt> { self.apply_ordinary_initial_state(); + // Runtime declarations may also run on the first deferred step. Initialize + // sampled copies and history defaults then (IEEE 1800-2023 16.5.1). + // Restoring a completed declaration phase never calls this hook. + self.initialize_copies(); Ok(()) } @@ -457,7 +463,15 @@ impl Simulation { Self::try_new(simulator).expect("runtime static declaration initialization failed") } - pub(crate) fn try_new(mut simulator: Simulator) -> Result { + #[cfg(test)] + pub(crate) fn try_new(simulator: Simulator) -> Result { + Self::try_new_with_initialization(simulator, true) + } + + pub(crate) fn try_new_with_initialization( + mut simulator: Simulator, + initialize: bool, + ) -> Result { let mut state = simulation_state(&simulator); simulator.host_watch = host_watch(&simulator.backend, &simulator.schedule); // Only a timed simulation ends at an RTL `$finish`; a bare @@ -465,10 +479,11 @@ impl Simulation { simulator.finish_sites = simulator.schedule.finish_sites; simulator.timed = true; simulator.skip_runtime_finish(); - state.initialize_declarations(&mut simulator)?; - // Before the first slot, a sampled value is the declared or default - // value (IEEE 1800-2023 16.5.1), which declarations may have set. - simulator.initialize_copies(); + if initialize { + state.initialize_declarations(&mut simulator)?; + // Initialize sampled values and histories before the first slot. + simulator.initialize_copies(); + } Ok(Self { simulator, state, diff --git a/crates/celox/src/simulation/vcd_tasks.rs b/crates/celox/src/simulation/vcd_tasks.rs index 3700f2439ef..e40e4ac3e31 100644 --- a/crates/celox/src/simulation/vcd_tasks.rs +++ b/crates/celox/src/simulation/vcd_tasks.rs @@ -254,7 +254,9 @@ impl Simulator { Ok(()) } - fn source_vcd_external_values(&self) -> Vec<(num_bigint::BigUint, num_bigint::BigUint)> { + pub(super) fn source_vcd_external_values( + &self, + ) -> Vec<(num_bigint::BigUint, num_bigint::BigUint)> { let values = self.components.trace_values(); self.sv_vcd .external_selections diff --git a/crates/celox/src/simulation/waveform_state.rs b/crates/celox/src/simulation/waveform_state.rs new file mode 100644 index 00000000000..aedfbfa8c95 --- /dev/null +++ b/crates/celox/src/simulation/waveform_state.rs @@ -0,0 +1,110 @@ +//! Source waveform effects are owned and persisted by the embedding system. +use super::Simulation; +use crate::{SimBackend, simulator::SvVcdControl}; +use serde::{Deserialize, Serialize}; +use std::{ + fs::File, + io, + path::{Path, PathBuf}, +}; + +/// Source-driven waveform configuration, separate from core execution state. +/// A host can serialize this alongside a core checkpoint and reconnect output +/// to a new segment when restoring. Already delivered waveform bytes stay external. +#[derive(Clone, Serialize, Deserialize)] +pub struct SourceWaveformState { + control: SvVcdControl, +} + +impl SourceWaveformState { + /// Whether `$dumpvars` has started recording (including `$dumpoff`). + pub fn is_active(&self) -> bool { + self.control.started.is_some() + } + + /// Requested source output path, or the SystemVerilog default. + pub fn path(&self) -> &Path { + self.control + .path + .as_deref() + .unwrap_or(Path::new("dump.vcd")) + } +} + +impl Simulation { + /// Capture source-driven waveform controls, without capturing output bytes + /// or modifying the core checkpoint. Explicit host-installed writers are + /// managed by their host instead. + pub fn source_waveform_state(&self) -> SourceWaveformState { + SourceWaveformState { + control: self.simulator.sv_vcd.clone(), + } + } + + /// Restore waveform controls after restoring the core. Supply a destination path and empty file + /// exactly when `state.is_active()` is true. The host chooses its destination; + /// the writer starts a standalone segment at the restored simulation time, + /// with saved selections, suspension and a fresh per-file byte-limit budget. + /// + /// # Safety + /// State must be an unmodified snapshot from this same compiled design and + /// compatible Celox build. Serialized selections contain memory offsets and + /// external signal indices; never restore untrusted or foreign state. + pub unsafe fn restore_source_waveform( + &mut self, + state: SourceWaveformState, + output: Option<(PathBuf, File)>, + ) -> io::Result<()> { + if state.is_active() != output.is_some() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "waveform output does not match saved recording state", + )); + } + self.simulator.flush_vcd()?; + self.simulator.vcd_writer = None; + self.simulator.sv_vcd = state.control; + let Some((path, output)) = output else { + return Ok(()); + }; + let sim = &mut self.simulator; + sim.sv_vcd.path = Some(path); + let mut writer = crate::VcdWriter::from_writer_with_time_precision( + output, + &sim.sv_vcd.selections, + sim.program.design.time_precision, + ); + writer.set_byte_limit(sim.sv_vcd.limit); + writer.add_external_signals( + &sim.sv_vcd + .external_selections + .iter() + .map(|(_, desc)| desc.clone()) + .collect::>(), + )?; + sim.sv_vcd.active_external_indices = sim + .sv_vcd + .external_selections + .iter() + .map(|(index, _)| *index) + .collect(); + sim.sv_vcd.source_writer = true; + sim.sv_vcd.pending = false; + let (ptr, size) = sim.backend.memory_as_ptr(); + // SAFETY: execution is suspended and the caller guarantees valid selections. + let memory = unsafe { std::slice::from_raw_parts(ptr, size) }; + writer.checkpoint( + if sim.sv_vcd.suspended { + "dumpoff" + } else { + "dumpall" + }, + self.state.time(), + memory, + &sim.source_vcd_external_values(), + )?; + writer.flush()?; + sim.vcd_writer = Some(writer); + Ok(()) + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 0a0e5881c72..4b623c820b0 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -69,7 +69,7 @@ mod host { }; use num_bigint::BigUint; - #[derive(Default)] + #[derive(Default, Clone, serde::Serialize, serde::Deserialize)] pub(crate) struct SvVcdControl { pub path: Option, pub started: Option, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 701aa5286ed..d1f2aed25c8 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1706,6 +1706,9 @@ mod host { pub plusargs: Vec, /// Host I/O factory; each simulator receives an independent instance. pub file_system: celox_runtime::file_io_backend::FileSystemFactory, + /// Leave timed initialization pending so a host can install a checkpoint + /// before any declaration or combinational effect executes. + pub defer_initialization: bool, /// The loop that runs the time slots of a [`crate::Simulation`]. #[doc(hidden)] pub scheduler: crate::SchedulerMode, @@ -2007,6 +2010,7 @@ mod host { dpi: crate::DpiSymbols::default(), plusargs: Vec::new(), file_system: Default::default(), + defer_initialization: false, scheduler: crate::SchedulerMode::default(), } } @@ -3726,6 +3730,14 @@ mod host { } impl<'a> SimulatorBuilder<'a, crate::Simulation> { + /// Build without executing declaration or combinational initialization. + /// Use when preparing a checkpoint restore target. Without a restore, + /// the first simulation step performs the pending initialization. + pub fn defer_initialization(mut self, defer: bool) -> Self { + self.options.defer_initialization = defer; + self + } + pub(crate) fn new(code: &'a str, top: &'a str) -> Self { Self { sources: vec![(code, Path::new(""))], @@ -4127,19 +4139,21 @@ mod host { } sim.apply_initial_values(); // Runtime static declarations precede every comb activation. - if !sim - .program - .runtime_schema - .processes - .iter() - .any(|slots| slots.kind == celox_design::ProcessKind::Initializer) + if !options.defer_initialization + && !sim + .program + .runtime_schema + .processes + .iter() + .any(|slots| slots.kind == celox_design::ProcessKind::Initializer) { sim.modify(|_| {}).map_err(|error| { SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) })?; } let warnings = std::mem::take(&mut sim.warnings); - match crate::Simulation::try_new(sim) { + match crate::Simulation::try_new_with_initialization(sim, !options.defer_initialization) + { Ok(mut simulation) => { simulation.simulator.warnings = warnings; simulation.state.set_scheduler_mode(options.scheduler); diff --git a/crates/celox/tests/sv_declaration_startup.rs b/crates/celox/tests/sv_declaration_startup.rs index 2a0558ac244..1d0d302f2f8 100644 --- a/crates/celox/tests/sv_declaration_startup.rs +++ b/crates/celox/tests/sv_declaration_startup.rs @@ -248,6 +248,45 @@ macro_rules! declaration_backend { mod $module { use super::*; + // IEEE 1800-2023 16.5.1: time-zero samples use declaration values. + #[test] + fn deferred_startup_samples_runtime_initializers_and_restore_keeps_samples() { + let source = r#"module Top(output int observed, output int a); + int seed = $test$plusargs("on"); + assign a = seed; + initial begin observed = $sampled(seed); #1; $finish; end + endmodule"#; + for four_state in [false, true] { + let build = |defer| { + Simulation::from_sv_sources( + vec![(source, Path::new("deferred_sample.sv"))], + "Top", + ) + .four_state(four_state) + .plusargs(["+on"]) + .live_signal(Vec::new(), vec!["seed".into()]) + .defer_initialization(defer) + .$build() + .unwrap() + }; + let mut deferred = build(true); + deferred.run_until(0).unwrap(); + assert_eq!(deferred.get(deferred.signal("observed")), 1u8.into()); + + let mut original = build(false); + let seed = original.signal("seed"); + original.modify(|io| io.set(seed, 7u8)).unwrap(); + let bytes = original.checkpoint().unwrap().to_bytes().unwrap(); + let mut restored = build(true); + // SAFETY: just captured from the same compiled design/options. + let checkpoint = unsafe { restored.checkpoint_from_bytes(&bytes) }.unwrap(); + restored.restore(&checkpoint).unwrap(); + restored.run_until(0).unwrap(); + assert_eq!(restored.get(restored.signal("a")), 7u8.into()); + assert_eq!(restored.get(restored.signal("observed")), 1u8.into()); + } + } + #[test] fn runtime_declaration_does_not_wake_wildcard() { finishes( @@ -456,3 +495,27 @@ fn plain_simulator_rejects_initial_kernels() { Some("declaration_plain_simulator.sv:3:3") ); } + +#[test] +fn deferred_declarations_run_on_the_first_step_if_no_checkpoint_is_loaded() { + let dir = tempfile::tempdir().unwrap(); + let output = dir.path().join("declaration.log"); + std::fs::write(&output, b"untouched").unwrap(); + let source = format!( + r#"module Top(output int fd); + int opened = $fopen("{}", "w"); + assign fd = opened; + initial begin #1; $finish; end + endmodule"#, + output.display() + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("deferred.sv"))], "Top") + .defer_initialization(true) + .build_interpreter() + .unwrap(); + assert_eq!(std::fs::read(&output).unwrap(), b"untouched"); + simulation.run_until(0).unwrap(); + assert_eq!(std::fs::read(&output).unwrap(), b""); + assert_ne!(simulation.get(simulation.signal("fd")), 0u32.into()); +} diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index f1d1a67a29b..7ebcbe47d09 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -80,6 +80,71 @@ safe point while preserving pending events. For example: celox run test/Top.sv --top Top --backend tiered --threads 4 ``` +### Signal checkpoints + +On Unix, `celox run` installs a `SIGUSR1` handler by default for SystemVerilog. +After the `SIGUSR1 checkpoint ready` message, request a checkpoint with: + +```sh +kill -USR1 "$sim_pid" +celox run top.sv --top Top --restore-checkpoint "signal-${sim_pid}-1.checkpoint" +``` + +The signal handler only sets a flag. At the next complete simulation time step, +the CLI saves its **system checkpoint** and continues running. Requests arriving +before that boundary coalesce; blocking host I/O and a non-advancing time slot +are not interrupted. Files are `signal--.checkpoint` in +`--save-state-dir` (the current directory by default). Publication is atomic and +never overwrites an existing file. Save failures are reported on stderr and do +not terminate the run. Use `--no-checkpoint-on-signal` to disable the handler. + +The CLI container combines core execution state with its file-effect handler +state, source-driven waveform controls, and the CLI's accumulated assertion/error +outcome. A run that already reported a failure remains failed after resume. +The container also retains pending scheduled-save requests, the counted signal, +cycle count and its previous level. Resume uses that saved schedule, including +when the original `--save-state-at*` flags are repeated or omitted; it does not +reissue consumed requests or restart cycle numbering. `--save-state-dir` and +signal-handler registration come from the resumed invocation. Restore builds the target with +declaration and combinational initialization deferred, so it does not repeat +initialization effects before installing the checkpoint. + +The handler keeps a disk-backed working view of files encountered by the +run, preserving file contents, handle positions, EOF and scan lookahead across +restore. Writes publish that working view to the requested host path immediately. +Restore reconstructs the saved working view without undoing already delivered +external output; subsequent writes publish the restored branch's contents. +Closed working files retain their disk contents without retaining OS descriptors; +operations reopen them temporarily. Active output streams retain their host +handle until close, so renaming or unlinking a file does not redirect ordinary +writes. After restore, output streams reconnect to their recorded paths lazily; +OS handles themselves are not persisted. Working files are keyed by normalized paths +(absolute paths with existing symlinks resolved). Different paths, including hard +links to the same host file, have independent working views. The caller is +responsible for coordinating such aliases; the CLI does not infer file identity. +A write-only append target does not require read permission: its inaccessible existing prefix +stays external, while appended bytes and positions are checkpointed. Resuming +retains that prefix and replaces only the known suffix on the next write; the +host prefix must still exist and be at least as long as when captured. +Standard streams, named pipes and devices remain live external channels. Their already consumed input +and delivered output are not rewound. No handler state enters the core checkpoint. + +Source-driven `$dumpfile`/`$dumpvars` recording resumes in a new, uniquely named +`.resume-.vcd` beside the original file; the CLI reports its path. +The original trace is neither truncated nor appended to. Each segment has its own +header and starts at the restored time with the saved signal selections and +`$dumpoff`/`$dumpon` state. `$dumplimit` retains its configured per-file limit with +a fresh byte budget for the new segment. Later dump controls continue to work. +Waveform configuration lives in the CLI container, not the core checkpoint. +Rust hosts can compose `source_waveform_state()` with their core checkpoint and +use `restore_source_waveform()` to supply their own new output file. + +Resume with the same sources, top, options and a compatible Celox build. +`--restore-checkpoint` loads a trusted artifact, like a native image; do not use +it on files from an untrusted producer. This resumes the CLI simulation, not +VPI plugins or Python coroutines. Scheduled `.state` saves below remain the +portable inspection format. + ### Save state files during a SystemVerilog run To compare two runs or two simulators, `celox run` can save