From f22d0d670675539e00795c9ceba3452e27e1c8f0 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 04:37:40 +0900 Subject: [PATCH 1/2] feat(sim): build a timed Simulation from a native image Simulation's builder gets compile_native, which returns a NativeCompilation whose image carries the process kernels and the compiled scheduler, and build_native_from_image, which starts a timed simulation of such an image without code generation. A differential simulation loads a second copy of the image for its reference-loop shadow. Simulation::advance_to runs the slots before a time and stops there, so a host can act at the start of that slot. NativeProgramInstance now fails to attach an image with process kernels, as every Simulator loader already does. Part of #1730 Change-Id: I94db5d6a6ee51fd7059303f78a0c7b8cadd9312c --- .../celox/src/backend/native/runtime_image.rs | 10 + crates/celox/src/simulation.rs | 22 ++ crates/celox/src/simulator/builder.rs | 238 ++++++++++++++++-- .../tests/frontends/systemverilog/suite.rs | 12 + .../tests/frontends/systemverilog/timing.rs | 10 +- crates/celox/tests/native_simulation_image.rs | 196 +++++++++++++++ 6 files changed, 462 insertions(+), 26 deletions(-) create mode 100644 crates/celox/tests/native_simulation_image.rs diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index ff7cbbfbb6e..4320699814e 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -59,7 +59,17 @@ impl NativeProgramInstance { /// /// The image's machine code must come from a trusted source. Image /// validation is structural and does not authenticate executable code. + /// + /// An image with process kernels, which only a timed + /// [`crate::Simulation`] runs, fails to attach. pub unsafe fn from_image(image: NativeProgramImage) -> Result { + let schema = image.runtime_schema(); + if !schema.processes.is_empty() { + let origin = schema.process_origins.first().cloned().unwrap_or_default(); + return Err(NativeProgramLoadError::Attach(SimulatorError::new( + crate::SimulatorErrorKind::ProcessRequiresSimulation(origin), + ))); + } // Safety: upheld by this constructor's caller. let shared = Arc::new( unsafe { SharedNativeCode::from_image(image) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index fa8d71e731d..e1f60ae082d 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -608,6 +608,28 @@ impl Simulation { Ok(()) } + /// Run every time slot before `time`, then move to `time` without + /// running its slot: the next [`Self::step`] or [`Self::run_until`] + /// runs it, together with the host writes made in between. A target not + /// after the current time changes nothing. Like [`Self::run_until`], it + /// returns early, before `time`, at a `$stop` or `$finish`. + pub fn advance_to(&mut self, time: u64) -> Result<(), RuntimeErrorCode> { + let Some(last) = time.checked_sub(1).filter(|&last| last >= self.time()) else { + return Ok(()); + }; + self.run_until(last)?; + if self.time() != last || self.is_finished() || self.is_stopped() { + return Ok(()); + } + self.state.advance_time(&mut self.simulator.backend, time); + if let Some(shadow) = &mut self.shadow { + shadow + .state + .advance_time(&mut shadow.simulator.backend, time); + } + Ok(()) + } + /// Like [`Self::run_until`], but takes at most `max_steps` steps. /// Returns `false`, with the simulation at the time of its last step, /// when another step would be needed to reach `end_time`, including when diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 7f8b600c462..2335c89efa3 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1710,20 +1710,24 @@ mod host { /// /// Keeping compilation separate from initialization lets compiler-only /// clients stop after native code generation without applying initial - /// values or executing the first combinational settle. + /// values or executing the first combinational settle. `Target` is what + /// [`Self::initialize`] builds: a [`Simulator`], or a timed + /// [`crate::Simulation`] whose image carries the process kernels and the + /// compiled scheduler. #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", target_arch = "aarch64" ))] #[must_use] - pub struct NativeCompilation { + pub struct NativeCompilation { image: crate::backend::native::NativeProgramImage, program: LaidOutProgram, warnings: Vec, options: SimulatorOptions, vcd_path: Option, injected_components: crate::InjectedComponents, + _target: std::marker::PhantomData, } /// `Simulator` runs no process kernel, so a design with one would @@ -1851,7 +1855,7 @@ mod host { feature = "arm64-codegen", target_arch = "aarch64" ))] - impl NativeCompilation { + impl NativeCompilation { /// Warnings emitted while compiling this artifact. pub fn warnings(&self) -> &[CompilationWarning] { &self.warnings @@ -1885,7 +1889,14 @@ mod host { ) -> Result<(), crate::backend::native::NativeImageContainerError> { self.image.write_container(output_path) } + } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { /// Load the image into executable memory and initialize runtime state. pub fn initialize( self, @@ -1897,6 +1908,7 @@ mod host { options, vcd_path, injected_components, + _target, } = self; initialize_native_image( image, @@ -1909,6 +1921,38 @@ mod host { } } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { + /// Load the image into executable memory and start a timed + /// simulation of it. + pub fn initialize( + self, + ) -> Result, SimulatorError> + { + let Self { + image, + program, + warnings, + options, + vcd_path, + injected_components, + _target, + } = self; + SimulatorBuilder::::start_native_image( + image, + program.into_runtime(), + warnings, + options, + vcd_path, + injected_components, + ) + } + } + impl Default for SimulatorOptions { fn default() -> Self { let opt = crate::optimizer::OptimizeOptions::default(); @@ -3175,6 +3219,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }) } @@ -3230,6 +3275,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }, trace, )) @@ -3716,6 +3762,68 @@ mod host { ) } + /// Compiles a timed simulation into a native image without loading + /// it. The image carries the process kernels and the compiled + /// scheduler; [`NativeCompilation::initialize`] or + /// [`Self::build_native_from_image`] starts a simulation of it. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn compile_native( + mut self, + ) -> Result, SimulatorError> { + self.options.emit_triggers = true; + let (laid_out, mut warnings, options, vcd_path, injected_components) = self + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + )?; + let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + Ok(NativeCompilation { + image, + program: laid_out, + warnings, + options, + vcd_path, + injected_components, + _target: std::marker::PhantomData, + }) + } + + /// Starts a timed simulation of a native image from + /// [`Self::compile_native`], without code generation. The design's + /// runtime metadata comes from `image`; the sources of this builder + /// are not used, its runtime options (scheduler, DPI symbols, + /// plusargs, VCD output) are. + /// + /// An image from [`Simulator::builder`] has no compiled scheduler, + /// so every time slot runs in the reference loop. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn build_native_from_image( + self, + image: crate::backend::native::NativeProgramImage, + ) -> Result, SimulatorError> + { + let mut options = self.options; + options.four_state = image.four_state(); + options.emit_triggers = true; + let program = image.runtime_program(); + Self::start_native_image( + image, + program, + Vec::new(), + options, + self.vcd_path, + self.injected_components, + ) + } + /// Compiles a timed simulation using the Wasmtime WASM backend. pub fn build_wasm( self, @@ -3758,36 +3866,116 @@ mod host { self.into_laid_out_program(layout_mode)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; - let shadow = if !matches!( + let shadow = Self::start_shadow( + |shadow_options| compile(&laid_out, shadow_options), + &laid_out.runtime, + &options, + &injected_components, + )?; + let mut simulation = Self::start_simulation( + backend, + laid_out.into_runtime(), + warnings, + &options, + vcd_path, + injected_components, + )?; + if let Some(shadow) = shadow { + simulation.set_shadow(shadow); + } + Ok(simulation) + } + + /// The reference-loop shadow of a differential simulation of + /// `program`, with `backend` providing its own copy of the code, or + /// why it has none. Other scheduler modes have no shadow. + #[allow(clippy::type_complexity)] + fn start_shadow( + backend: impl FnOnce(&SimulatorOptions) -> Result, + program: &crate::ir::RuntimeProgram, + options: &SimulatorOptions, + injected_components: &crate::InjectedComponents, + ) -> Result>, &'static str>>, SimulatorError> + { + if !matches!( options.scheduler, crate::SchedulerMode::Differential | crate::SchedulerMode::DifferentialRuns ) { - None - } else if !injected_components.definitions.is_empty() { - Some(Err("the design has external components")) - } else { - let mut shadow_options = options.clone(); - shadow_options.trace = Default::default(); - shadow_options.scheduler = crate::SchedulerMode::Reference; - let backend = compile(&laid_out, &shadow_options)?; - let shadow = Self::start_simulation( - backend, - laid_out.runtime.clone(), - Vec::new(), - &shadow_options, - None, - Default::default(), - )?; - // Host state outside the memory image, such as open files, - // cannot be shared with a shadow. - Some(match shadow.simulator.check_host_checkpoint_support() { + return Ok(None); + } + if !injected_components.definitions.is_empty() { + return Ok(Some(Err("the design has external components"))); + } + let mut shadow_options = options.clone(); + shadow_options.trace = Default::default(); + shadow_options.scheduler = crate::SchedulerMode::Reference; + let backend = backend(&shadow_options)?; + let shadow = Self::start_simulation( + backend, + program.clone(), + Vec::new(), + &shadow_options, + None, + Default::default(), + )?; + // 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"), - }) + }, + )) + } + + /// Load `image` into executable memory and start a timed simulation + /// of `program`, its runtime metadata. A differential simulation + /// loads a second copy of the image for its shadow. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + #[allow(unreachable_code)] + fn start_native_image( + image: crate::backend::native::NativeProgramImage, + program: crate::ir::RuntimeProgram, + mut warnings: Vec, + options: SimulatorOptions, + vcd_path: Option, + injected_components: crate::InjectedComponents, + ) -> Result, SimulatorError> + { + #[cfg(any( + all(feature = "arm64-codegen", not(target_arch = "aarch64")), + all(feature = "x86_64-codegen", not(target_arch = "x86_64")) + ))] + { + let _ = (image, program, options, vcd_path, injected_components); + return Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(warnings)); + } + + let load = |image, options: &SimulatorOptions| { + // Safety: callers either produced the image in this process + // or loaded it from an explicitly trusted native-image + // artifact, and `from_image` validates its structure first. + unsafe { + crate::backend::native::NativeBackend::from_image_with_dpi(image, &options.dpi) + } }; + let shadow = Self::start_shadow( + |shadow_options| load(image.clone(), shadow_options), + &program, + &options, + &injected_components, + ) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + let backend = load(image, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut simulation = Self::start_simulation( backend, - laid_out.into_runtime(), + program, warnings, &options, vcd_path, diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index f10ac99fc15..772ad6c685a 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -301,6 +301,18 @@ fn build(design: &Design, backend: &str) -> Result> { ); return Ok(match backend { "native" => Box::new(TimedBackend::new(builder.build_native()?)), + // The image goes through its container bytes, as an attached + // image does, and the simulation takes its metadata from it. + "native-image" => { + let image = builder.compile_native()?.into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes()?)?; + Box::new(TimedBackend::new( + Simulation::from_sv_sources(Vec::new(), &design.top) + .scheduler_mode(scheduler_mode()) + .build_native_from_image(image)?, + )) + } "cranelift" => Box::new(TimedBackend::new(builder.build_cranelift()?)), "native-parallel" => Box::new(TimedBackend::new( builder diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 96516fab864..a7afb9772eb 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -2,7 +2,8 @@ //! processes, driven through the timed `Simulation`. //! //! Every exclusion names what Celox lacks for the case, so the change that -//! adds it removes the exclusion. Supported cases run on every backend. +//! adds it removes the exclusion. Supported cases run on every backend, +//! and natively also from a serialized native image. macro_rules! timed_cases { () => {}; @@ -25,6 +26,13 @@ macro_rules! timed_cases { crate::suite::run_case($case, "cranelift"); } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + $(#[$attr])* + fn native_image() { + crate::suite::run_case($case, "native-image"); + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] #[test] $(#[$attr])* diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs new file mode 100644 index 00000000000..5f6808ff839 --- /dev/null +++ b/crates/celox/tests/native_simulation_image.rs @@ -0,0 +1,196 @@ +//! A timed `Simulation` built from a native image: the image carries the +//! process kernels and the compiled scheduler, so a serialized image runs as +//! the in-process build does (#1730). +#![cfg(all( + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) +))] + +use std::path::Path; + +use celox::{ + NativeProgramImage, NativeProgramInstance, RuntimeEvent, SchedulerMode, Simulation, + SimulatorErrorKind, +}; + +const PROCESSES: &str = r#"`timescale 1ns/1ns +module Top(output logic [7:0] count, output logic [7:0] seen); + logic clk = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 1; + initial begin + count = 0; + seen = 0; + #12 $display("at %0t count=%0d", $time, count); + @(posedge clk) seen = count; + #20 $display("at %0t seen=%0d count=%0d", $time, seen, count); + end +endmodule +"#; + +fn builder(source: &str) -> celox::SimulatorBuilder<'_, Simulation> { + Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") +} + +/// The image, through its container bytes. +fn reloaded(image: &NativeProgramImage) -> NativeProgramImage { + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap() +} + +/// What a simulation shows up to `end`: its events and outputs. +fn transcript( + sim: &mut Simulation, + end: u64, +) -> (Vec, u64, u64) { + sim.run_until(end).unwrap(); + let count = sim.get(sim.signal("count")).try_into().unwrap(); + let seen = sim.get(sim.signal("seen")).try_into().unwrap(); + (sim.drain_runtime_events(), count, seen) +} + +#[test] +fn a_serialized_native_image_runs_its_processes() { + let expected = transcript(&mut builder(PROCESSES).build_native().unwrap(), 60); + assert_eq!( + expected.0, + vec![ + RuntimeEvent::Display { + message: b"at 12 count=1".to_vec() + }, + RuntimeEvent::Display { + message: b"at 35 seen=1 count=3".to_vec() + }, + ] + ); + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); + assert!(sim.scheduler_stats().compiled_slots > 0); + let mut sim = builder(PROCESSES) + .compile_native() + .unwrap() + .initialize() + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); +} + +#[test] +fn a_differential_simulation_loads_its_shadow_from_the_image() { + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native_from_image(image) + .unwrap(); + let (events, count, _) = transcript(&mut sim, 60); + assert_eq!(events.len(), 2); + assert_eq!(count, 6); + assert!(sim.scheduler_stats().checked_steps > 0); +} + +/// An image from `Simulator` has no compiled scheduler: every slot runs in +/// the reference loop, to the same state as a fresh `Simulation` build. +#[test] +fn an_untimed_image_runs_as_a_simulation_in_the_reference_loop() { + let source = "module Top(input logic clk, input logic [7:0] step, output logic [7:0] count, + output logic [7:0] sum); + always_ff @(posedge clk) count <= count + 1; + always_ff @(negedge clk) sum <= sum + count + step; + endmodule"; + let run = |sim: &mut Simulation| { + let step = sim.signal("step"); + sim.modify(|io| io.set(step, 3u8)).unwrap(); + sim.add_clock("clk", 10, 5); + sim.run_until(97).unwrap(); + sim.save_state().unwrap() + }; + let mut fresh = builder(source).build_native().unwrap(); + let expected = run(&mut fresh); + let image = celox::Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(reloaded(&image)) + .unwrap(); + assert_eq!(run(&mut sim), expected); + assert_eq!(sim.get(sim.signal("count")), 10u8.into()); + assert_eq!(sim.scheduler_stats().compiled_slots, 0); +} + +#[test] +fn process_images_do_not_load_as_untimed_programs() { + let image = builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = + celox::Simulator::from_sv_sources(Vec::new(), "Top").build_native_from_image(image.clone()) + else { + panic!("a Simulator runs no process"); + }; + assert!(matches!( + error.kind(), + SimulatorErrorKind::ProcessRequiresSimulation(_) + )); + // SAFETY: the image was compiled from the trusted source above. + let Err(error) = (unsafe { NativeProgramInstance::from_image(image) }) else { + panic!("a native program instance runs no process"); + }; + assert!(error.to_string().contains("is a process"), "{error}"); +} + +#[test] +fn advance_to_stops_before_the_slot_and_its_host_writes_join_it() { + let source = r#"`timescale 1ns/1ns +module Top(input logic [7:0] value, output logic [7:0] seen); + initial begin + seen = 0; + #5 seen = value; + $display("at %0t value=%0d", $time, value); + end +endmodule +"#; + let image = reloaded( + &builder(source) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + // The write is the host's at time 5, before the process resumes there. + let value = sim.signal("value"); + sim.modify(|io| io.set(value, 7u8)).unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 7u8.into()); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: b"at 5 value=7".to_vec() + }] + ); + sim.advance_to(3).unwrap(); + assert_eq!(sim.time(), 5); +} From 7e97e2ef65ebf42e06831581c9cebcc270f27cd9 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 04:47:38 +0900 Subject: [PATCH 2/2] fix(sim): reject VCD runs of strided timed images build_native_from_image and NativeCompilation::initialize now make the packed-array check of the untimed native loader, through one shared validate_native_vcd_layout: an image compiled without VCD cannot record element-strided unpacked arrays. Change-Id: I4d968bb5136d9fe772ec0afedb8f648161900f3a --- crates/celox/src/simulator/builder.rs | 51 +++++++++++++------ crates/celox/tests/native_simulation_image.rs | 47 +++++++++++++++++ 2 files changed, 82 insertions(+), 16 deletions(-) diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 2335c89efa3..bb675f04160 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1745,6 +1745,37 @@ mod host { )) } + /// A native image records waveforms only if its arrays are packed, + /// which an image compiled with VCD enabled has: a VCD file of the host + /// (`vcd_path`) or of the design (`$dumpvars`) needs one. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + fn validate_native_vcd_layout( + layout: &crate::MemoryLayout, + program: &crate::ir::RuntimeProgram, + vcd_path: &Option, + ) -> Result<(), SimulatorError> { + let source_vcd = program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + if (vcd_path.is_some() || source_vcd) + && layout.unpacked_arrays.values().any(|array| { + !array.element_width.is_multiple_of(8) + || array.element_stride != array.element_width / 8 + }) + { + return Err(SimulatorError::from(crate::CodegenError::message( + "VCD requires packed array storage; compile this native image with VCD enabled", + ))); + } + Ok(()) + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -1763,22 +1794,8 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); - let source_vcd = sim - .program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.kind == celox_design::HostRequestKind::Vcd); - if vcd_path.is_some() || source_vcd { - if sim.layout().unpacked_arrays.values().any(|array| { - !array.element_width.is_multiple_of(8) - || array.element_stride != array.element_width / 8 - }) { - return Err(SimulatorError::from(crate::CodegenError::message( - "VCD requires packed array storage; compile this native image with VCD enabled", - )) - .with_warnings(std::mem::take(&mut sim.warnings))); - } + 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))); } if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -3956,6 +3973,8 @@ mod host { .with_warnings(warnings)); } + validate_native_vcd_layout(image.layout(), &program, &vcd_path) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let load = |image, options: &SimulatorOptions| { // Safety: callers either produced the image in this process // or loaded it from an explicitly trusted native-image diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs index 5f6808ff839..aab956b1f94 100644 --- a/crates/celox/tests/native_simulation_image.rs +++ b/crates/celox/tests/native_simulation_image.rs @@ -194,3 +194,50 @@ endmodule sim.advance_to(3).unwrap(); assert_eq!(sim.time(), 5); } + +/// Element-strided unpacked arrays cannot be dumped: an image compiled +/// without VCD is rejected for a VCD run, as `Simulator` rejects it, and one +/// compiled with VCD records the elements. +#[test] +fn a_vcd_run_needs_an_image_compiled_with_vcd() { + let source = r#"`timescale 1ns/1ns +module Top; + logic [2:0] values [4]; + initial begin + values[2] = 3'd0; + #1 values[2] = 3'd5; + end +endmodule +"#; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("top.vcd"); + let strided = builder(source) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&strided)) + else { + panic!("a strided image cannot record VCD"); + }; + assert!( + error + .to_string() + .contains("compile this native image with VCD enabled"), + "{error}" + ); + let packed = builder(source) + .vcd(&path) + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&packed)) + .unwrap(); + sim.run_until(2).unwrap(); + drop(sim); + let vcd = std::fs::read_to_string(&path).unwrap(); + assert!(vcd.contains("b101"), "{vcd}"); +}