From 0e8194228aea23558908d3e45dcd72d9c9419cca Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 19:03:54 +0900 Subject: [PATCH 1/3] feat(sv): support the $swrite family Implement `$swrite`, `$swriteb`, `$swriteo` and `$swriteh` (IEEE 1800-2023 21.3.3). Like `$write`, a string literal that no conversion consumes is a format, a later one included, and each value without a conversion of its own is written in the task's radix, a string as text and a real as `$write` writes it. `$display`, `$write`, `$fdisplay` and `$fwrite` now also treat a later unconsumed string literal as a further format, as Verilator, Icarus and xezim do (21.2.1.1), instead of printing its conversions literally. The analyzer builds that format and binds the call as the `$sformatf` string operation, then assigns the result to the output, a string variable, a function's return variable or a string class property. The shared swrite_matches_write case compares each form with `$write` of the same arguments; Verilator 5.052, Icarus 13.0 and xezim 0.11.3 pass it. Change-Id: Ie03af76400361cd0410abcac91959d1c272c56a1 --- .../src/ast/expression_binding.rs | 6 +- .../src/ast/expression_binding/direct.rs | 19 +- .../celox-sv-analyzer/src/ast/procedural.rs | 237 ++++++++++++++++-- .../celox-sv-analyzer/src/system_functions.rs | 6 +- crates/celox-test-suite/LIMITATIONS.md | 4 +- .../src/sv/cases/string_format.vtest | 60 +++++ .../frontends/systemverilog/string_format.rs | 40 +++ docs/guide/systemverilog-reference.md | 12 +- 8 files changed, 340 insertions(+), 44 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index a05aad62f55..730ee1d4d03 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -13,7 +13,8 @@ mod strings; pub(super) use calls::{statement as call_statement, statement_root as call_statement_root}; pub(super) use direct::{ arguments, bind_value, call_name as native_name, callable_name, cast_target_native, - format_arguments, member_context, real_value, remove_real_division_guards, ungroup, + format_arguments, member_context, real_value, remove_real_division_guards, + string_literal_bytes, ungroup, }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ @@ -25,7 +26,8 @@ pub(super) use objects::{ receiver as object_receiver, static_property as object_static_property, this as object_this, }; pub(super) use strings::{ - call as string_call, method as string_method, native_string, to_string as string_operand, + call as string_call, method as string_method, native_string, string_value, + to_string as string_operand, }; fn disagreement() -> AnalyzerError { AnalyzerError::Parse("invalid native expression ownership".into()) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index b44348c89ed..847b186a6fb 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1879,6 +1879,18 @@ pub(in crate::ast) fn format_arguments( /// String literals in integral contexts are unsigned packed arrays of bytes /// (IEEE 1800-2023 5.9). Keep the semantic IR integral, including escapes. fn packed_string_literal(text: &str) -> Option { + let bytes = string_literal_bytes(text)?; + let width = (bytes.len() * 8).max(8); + Some(format!( + "{}'h{}", + width, + num_bigint::BigUint::from_bytes_be(&bytes).to_str_radix(16) + )) +} + +/// The bytes of string literal `text`, written with its quotes, after its +/// escapes (IEEE 1800-2023 5.9.1). +pub(in crate::ast) fn string_literal_bytes(text: &str) -> Option> { let text = if let Some(text) = text.strip_prefix("\"\"\"") { text.strip_suffix("\"\"\"")? } else { @@ -1939,12 +1951,7 @@ fn packed_string_literal(text: &str) -> Option { }; bytes.push(value); } - let width = (bytes.len() * 8).max(8); - Some(format!( - "{}'h{}", - width, - num_bigint::BigUint::from_bytes_be(&bytes).to_str_radix(16) - )) + Some(bytes) } pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> bool { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index d5ff37e914e..95062607189 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -665,6 +665,76 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .map(Some) } + /// Fold the arguments of a display or write task after its first format + /// into that format when a later string literal is a further format: a + /// string literal that no conversion consumes continues the format, and + /// a value without a conversion of its own is written in the radix of the + /// task (IEEE 1800-2023 21.2.1.1). + fn merge_display_formats( + &self, + task: SystemTask, + args: &mut Vec>, + ids: &mut Vec>, + ) { + let (SystemTask::Display(radix) + | SystemTask::Write(radix) + | SystemTask::Fdisplay(radix) + | SystemTask::Fwrite(radix)) = task + else { + return; + }; + let Some(start) = template_index(task, args) else { + return; + }; + let Some(SystemTaskArg::Str(first)) = args.get(start) else { + return; + }; + let mut text = first.clone(); + let mut pending = format_conversions(&text).len(); + let mut later_format = false; + for arg in &args[start + 1..] { + match arg { + SystemTaskArg::Str(literal) if pending == 0 => { + later_format = true; + pending = format_conversions(literal).len(); + text.push_str(literal); + } + _ if pending > 0 => pending -= 1, + SystemTaskArg::Expr(value) => text.push_str(&default_conversion( + expression_binding::string_value(value, &self.dims), + expression_binding::real_value(value, &self.dims), + radix, + )), + SystemTaskArg::Str(_) => unreachable!("an unconsumed literal is a format"), + SystemTaskArg::Empty => text.push_str(&default_conversion(false, false, radix)), + } + } + if !later_format { + return; + } + // The values keep their places; the further formats are folded into + // the first one. + let mut pending = format_conversions(first).len(); + let mut kept = vec![SystemTaskArg::Str(text)]; + let mut kept_ids = vec![ids.get(start).copied().flatten()]; + for (position, arg) in args.iter().enumerate().skip(start + 1) { + match arg { + SystemTaskArg::Str(literal) if pending == 0 => { + pending = format_conversions(literal).len(); + } + arg => { + pending = pending.saturating_sub(1); + kept.push(arg.clone()); + kept_ids.push(ids.get(position).copied().flatten()); + } + } + } + args.truncate(start); + args.extend(kept); + ids.truncate(start); + ids.extend(kept_ids); + } + /// `output = value` for the string `value` of `$sformat`, which assigns /// its output as a string literal is assigned (IEEE 1800-2023 21.3.3, /// 5.9). @@ -1453,6 +1523,74 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { ); return Ok(vec![self.format_assignment(output, value)?]); } + // `$swrite(output, args...)` assigns what `$write(args...)` would + // print, in the radix of its name (IEEE 1800-2023 21.3.3). + if let Some(radix) = swrite_radix(name) { + if arguments.iter().any(|arg| arg.name.is_some()) { + return Err(unsupported(format!("named arguments of `{name}`"))); + } + let output = arguments.first().and_then(|arg| arg.value).ok_or_else(|| { + AnalyzerError::InvalidSystemTfCall { + name: name.into(), + detail: "expected an output argument".into(), + } + })?; + // As for `$write`, a string literal that no conversion consumes + // continues the format, and a value without a conversion of its + // own is written in the radix of the task (21.2.1.1). + let mut text = Vec::new(); + let mut values = Vec::new(); + let mut pending = 0; + for (position, arg) in arguments.iter().enumerate().skip(1) { + let id = arg + .value + .ok_or_else(|| AnalyzerError::InvalidSystemTfCall { + name: name.into(), + detail: format!("argument {} is omitted", position + 1), + })?; + let literal = match &declarations.expression(id).kind { + celox_sv_syntax::ExprKind::Literal(text) => { + expression_binding::string_literal_bytes(text) + } + _ => None, + }; + if pending == 0 + && let Some(literal) = literal + { + pending = format_conversions(&String::from_utf8_lossy(&literal)).len(); + text.extend_from_slice(&literal); + continue; + } + let value = + expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?; + if pending > 0 { + pending -= 1; + } else { + text.extend_from_slice( + default_conversion( + literal.is_some() + || expression_binding::string_value(&value, &self.dims), + expression_binding::real_value(&value, &self.dims), + radix, + ) + .as_bytes(), + ); + } + values.push(value); + } + let format = Expr::Literal(format!( + "{}'h{}", + (text.len() * 8).max(8), + num_bigint::BigUint::from_bytes_be(&text).to_str_radix(16) + )); + let value = expression_binding::string_call( + StringOp::Format { + ticks_per_unit: timescales::time_divisor(root, self.tree)?, + }, + std::iter::once(format).chain(values).collect(), + ); + return Ok(vec![self.format_assignment(output, value)?]); + } if name == "$sformatf" { let mut value = expression_binding::bind_value(root, declarations, self.tree, &self.dims, None)?; @@ -1526,17 +1664,26 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { return Ok(SystemTaskArg::Str(text.to_string())); } - let mut value = + // Renamed below, once the types of the source names have + // chosen the conversions of the format. + let value = expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?; - self.rename_expr(&mut value); Ok(SystemTaskArg::Expr(value)) }) .collect::, AnalyzerError>>()?; let mut args = args; + // The native expression of each argument, kept in step with `args`. + let mut ids = arguments.iter().map(|arg| arg.value).collect::>(); + self.merge_display_formats(task, &mut args, &mut ids); + for arg in &mut args { + if let SystemTaskArg::Expr(value) = arg { + self.rename_expr(value); + } + } // A string literal that %t converts is bound as a value: the binder // handles every literal form, triple quotes and escapes included. let mut bind = |index: usize| -> Result, AnalyzerError> { - let Some(id) = arguments.get(index).and_then(|arg| arg.value) else { + let Some(id) = ids.get(index).copied().flatten() else { return Ok(None); }; let mut value = @@ -3386,34 +3533,49 @@ pub(super) fn process_site( }) } -/// `%t` reports a time value in the units of `$timeformat`, by default the -/// smallest time precision of the design (IEEE 1800-2023 20.4.3, Table 20-3), -/// in which the simulation counts its time. The value is in the time unit of -/// the calling scope, of which `ticks_per_unit` simulation time units make -/// one, so each value a `%t` of the template converts is scaled by it. -fn scale_time_conversions( - task: SystemTask, - args: &mut [SystemTaskArg], - ticks_per_unit: u64, - bind: &mut impl FnMut(usize) -> Result, AnalyzerError>, -) -> Result<(), AnalyzerError> { - if ticks_per_unit == 1 { - return Ok(()); - } - let template = match task { +/// The position of the format among the arguments of a display, write or +/// severity task, which a leading string literal there is. +fn template_index(task: SystemTask, args: &[SystemTaskArg]) -> Option { + Some(match task { SystemTask::Display(_) | SystemTask::Write(_) | SystemTask::Severity(_) => 0, SystemTask::Fatal => usize::from(matches!(args.first(), Some(SystemTaskArg::Expr(_)))), SystemTask::Fdisplay(_) | SystemTask::Fwrite(_) | SystemTask::Assert | SystemTask::AssertContinue => 1, - _ => return Ok(()), - }; - let Some(SystemTaskArg::Str(text)) = args.get(template) else { - return Ok(()); - }; - // The conversions of the template, in the order they take arguments - // (21.2.1.2): flags, a width and a precision may precede each. + _ => return None, + }) +} + +/// The conversion that writes a value without one of its own in a task of +/// `radix` (IEEE 1800-2023 21.2.1.1): a string as text, a real as `$write` +/// writes reals. +fn default_conversion(string: bool, real: bool, radix: system_functions::Radix) -> String { + if real { + "%#g".into() + } else if string { + "%s".into() + } else { + format!("%{}", radix.letter()) + } +} + +/// The radix of a `$swrite` task named `name`. +fn swrite_radix(name: &str) -> Option { + use system_functions::Radix; + Some(match name { + "$swrite" => Radix::Decimal, + "$swriteb" => Radix::Binary, + "$swriteo" => Radix::Octal, + "$swriteh" => Radix::Hexadecimal, + _ => return None, + }) +} + +/// The conversions of a format, in the order they take arguments +/// (IEEE 1800-2023 21.2.1.2): flags, a width and a precision may precede +/// each. +fn format_conversions(text: &str) -> Vec { let mut conversions = Vec::new(); let mut chars = text.chars().peekable(); while let Some(ch) = chars.next() { @@ -3434,7 +3596,30 @@ fn scale_time_conversions( conversions.push(spec); } } - for (offset, spec) in conversions.into_iter().enumerate() { + conversions +} + +/// `%t` reports a time value in the units of `$timeformat`, by default the +/// smallest time precision of the design (IEEE 1800-2023 20.4.3, Table 20-3), +/// in which the simulation counts its time. The value is in the time unit of +/// the calling scope, of which `ticks_per_unit` simulation time units make +/// one, so each value a `%t` of the template converts is scaled by it. +fn scale_time_conversions( + task: SystemTask, + args: &mut [SystemTaskArg], + ticks_per_unit: u64, + bind: &mut impl FnMut(usize) -> Result, AnalyzerError>, +) -> Result<(), AnalyzerError> { + if ticks_per_unit == 1 { + return Ok(()); + } + let Some(template) = template_index(task, args) else { + return Ok(()); + }; + let Some(SystemTaskArg::Str(text)) = args.get(template) else { + return Ok(()); + }; + for (offset, spec) in format_conversions(text).into_iter().enumerate() { if !matches!(spec, 't' | 'T') { continue; } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index d1b6cc97e63..d1c53dc514d 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -1557,13 +1557,13 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$fmonitorb", Task), unsupported("$fmonitoro", Task), unsupported("$fmonitorh", Task), + // The binders convert `$swrite`, `$sformat` and `$sformatf` into string + // operations (`StringOp::Format`) before consulting the catalog, which + // rejects them anywhere else, such as in a constant expression. unsupported("$swrite", Task), unsupported("$swriteb", Task), unsupported("$swriteo", Task), unsupported("$swriteh", Task), - // The binders convert `$sformat` and `$sformatf` into string operations - // (`StringOp::Format`) before consulting the catalog, which rejects them - // anywhere else, such as in a constant expression. unsupported("$sformat", Task), unsupported("$sformatf", Function), function(SystemFunction::Fgetc, 1, Some(1)), diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index f08dae60b4a..cfce249e732 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -628,8 +628,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_string_associative_arrays_and_property_queue_methods` | compile | icarus | 2 | Icarus 13.0 rejects associative arrays with `string` and `bit [63:0]` indices and queue methods called on a class property ("Can't find task push_back in class Log"), which IEEE 1800-2023 7.8 and 7.10 define; Verilator 5.052 and xezim 0.11.3 compile the cases. | | `sv_verilator_associative_index_cast` | execute | verilator | 1 | Verilator 5.052 evaluates an associative index `x + 32'd1` at 32 bits and stores key 0; IEEE 1800-2023 7.8.4 evaluates it as a cast to the `bit [63:0]` index type (6.24.1), giving `64'h100000000`. xezim 0.11.3 also stores key 0 (`sv_associative_index_cast` in its review). [Evidence](verification/repros/sv_associative_index_cast.json). | -The `string_format` cases compare `$sformatf` and `$sformat` with `$display` -of the same format and arguments. The [Icarus observations](verification/sv/limitations/string-format-icarus.json) +The `string_format` cases compare `$sformatf`, `$sformat` and `$swrite` with +`$display` / `$write` of the same format and arguments. The [Icarus observations](verification/sv/limitations/string-format-icarus.json) retain the three failing runs with reduced adapter-free sources; the remaining cases pass in all three tools, except that Verilator 5.052 does not run the four-state case. `%m` is checked only in Celox, as each adapter wraps the diff --git a/crates/celox-test-suite/src/sv/cases/string_format.vtest b/crates/celox-test-suite/src/sv/cases/string_format.vtest index 1a28ab9d2a0..0d9ed8ee4f3 100644 --- a/crates/celox-test-suite/src/sv/cases/string_format.vtest +++ b/crates/celox-test-suite/src/sv/cases/string_format.vtest @@ -341,3 +341,63 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "a1<2>3-\n")) + +; 21.3.3: `$swrite` and its radix forms assign what `$write` and its radix +; forms print for the same arguments; a string literal that no conversion +; consumes is a further format (21.2.1.1). +(case swrite_matches_write + (source "swrite_write.sv" #" +module Top(output bit done); + string s, name; + int i; + bit [7:0] b; + initial begin + i = 12; + b = 8'h5a; + name = "n"; + $write("a=", i, " b=", b, " ", name, "\n"); + $swrite(s, "a=", i, " b=", b, " ", name, "\n"); + $write("%s", s); + $writeh(i, " ", b, "\n"); + $swriteh(s, i, " ", b, "\n"); + $write("%s", s); + $writeb(b, "\n"); + $swriteb(s, b, "\n"); + $write("%s", s); + $writeo(b, "\n"); + $swriteo(s, b, "\n"); + $write("%s", s); + $write("%0d-%s|", i, name, i, "\n"); + $swrite(s, "%0d-%s|", i, name, i, "\n"); + $write("%s", s); + $write(name, i, "\n"); + $swrite(s, name, i, "\n"); + $write("%s", s); + $write("a=%0d ", 1, "b=%0d", i, "|%s", "c", 2, "\n"); + $swrite(s, "a=%0d ", 1, "b=%0d", i, "|%s", "c", 2, "\n"); + $write("%s", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "a= 12 b= 90 n\na= 12 b= 90 n\n0000000c 5a\n0000000c 5a\n01011010\n01011010\n132\n132\n12-n| 12\n12-n| 12\nn 12\nn 12\na=1 b=12|c 2\na=1 b=12|c 2\n")) + +; 21.2.1.1: a later format literal of `$display` keeps the conversions of the +; values without one, here a block-local string, and a `%t` in it converts the +; value that follows it. Timed cases run at 1 ns / 1 ps. +(case display_later_formats + (source "display_later_formats.sv" #" +module Top(output bit done); + initial begin + string s; + s = "hello"; + $display("", s, "!"); + $display("[", "%t", "A", "]"); + $display("[%t]", "A"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "hello!\n[ 65000]\n[ 65000]\n")) diff --git a/crates/celox/tests/frontends/systemverilog/string_format.rs b/crates/celox/tests/frontends/systemverilog/string_format.rs index 8647f7943c1..9f4d1b542a5 100644 --- a/crates/celox/tests/frontends/systemverilog/string_format.rs +++ b/crates/celox/tests/frontends/systemverilog/string_format.rs @@ -15,6 +15,8 @@ sv_backends! { fn sformatf_in_container_operands(sim) { @case "string_format::sformatf_in_container_operands"; } fn sformatf_with_associative_index(sim) { @case "string_format::sformatf_with_associative_index"; } fn sformatf_with_reference_argument(sim) { @case "string_format::sformatf_with_reference_argument"; } + fn swrite_matches_write(sim) { @case "string_format::swrite_matches_write"; } + fn display_later_formats(sim) { @case "string_format::display_later_formats"; } // External testbenches wrap the design, so the hierarchical name `%m` // prints differs between simulators; Celox prints the same for both. fn sformatf_scope_matches_display(sim) { @@ -83,3 +85,41 @@ fn container_owner_is_captured_before_formatting_operands() { assert_eq!(sim.get(first), BigUint::from(1u8)); assert_eq!(sim.get(other), BigUint::from(0u8)); } + +/// A value without a conversion of its own keeps its default conversion when a +/// later format literal is folded into the format: block-local strings and +/// reals print as they do without one (IEEE 1800-2023 21.2.1.1). +#[test] +fn later_formats_keep_default_conversions_of_locals() { + let source = r#" + module Top; + initial begin + string s; + real r; + s = "text"; + r = 1.5; + $write(s, r, "\n"); + $write("", s, r, "", "\n"); + end + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources(vec![(source, Path::new("locals.sv"))], "Top") + .build() + .unwrap(); + sim.run_until(0).unwrap(); + let messages: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Write { message } => message, + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(messages.len(), 2); + assert_eq!(messages[0], messages[1]); + assert!( + messages[0].starts_with(b"text"), + "{:?}", + String::from_utf8_lossy(&messages[0]) + ); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index a762a2f78b9..f0d706c6d46 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -32,7 +32,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Dynamic containers | one-dimensional dynamic arrays, queues (including bounded queues), and associative arrays with integral or string keys; element access, value assignment, equality, `foreach` and built-in container methods. See [dynamic containers](#dynamic-containers) | -| Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values; text formatted by `$sformatf` / `$sformat`. See [strings](#strings) | +| Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values; text formatted by `$sformatf` / `$sformat` / `$swrite`. See [strings](#strings) | | Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types up to 64 bits (4-state properties start as X and keep X/Z bits), `string` and class handle types, plus dynamic arrays, queues and associative arrays, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments; shallow copies (`new h`). See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | @@ -318,7 +318,7 @@ waits zero. | Simulation time | `$time`, `$stime` and `$realtime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | | Sampled values | `$sampled` in processes, combinational logic and the subroutines they call; `$past`, `$rose`, `$fell`, `$stable` and `$changed` in edge-triggered processes whose clock they infer and the subroutines those call; see [Sampled values](#sampled-values) | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | -| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, `$sformatf` / `$sformat` (see [Formatted output to strings](#formatted-output-to-strings)), and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | +| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, `$sformatf` / `$sformat` / `$swrite` and its radix variants (see [Formatted output to strings](#formatted-output-to-strings)), and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -1147,13 +1147,15 @@ be checkpointed; `$fscanf` uses external file state and prevents checkpoints. `$sformatf(format, args...)` returns, as a `string`, the text `$write` prints for the same format and arguments, and `$sformat(output, format, args...)` -assigns it to `output` (IEEE 1800-2023 21.3.3). Every conversion of `$display` +assigns it to `output` (IEEE 1800-2023 21.3.3). `$swrite(output, args...)` and +its `b` / `o` / `h` forms assign what `$write` and its radix forms print for +the same arguments. Every conversion of `$display` is available, with the same field widths, X/Z digits and `%t` scaling. `$sformatf` can appear in any expression of a procedural statement, including function results, arguments, concatenations and conditional operands. The format can be a string literal or, evaluated when the call runs, a `string` or integral -value. The output of `$sformat` must be a `string` variable or class property; -integral outputs, `%p` and the `$swrite` family are unsupported. +value. The output of `$sformat` and `$swrite` must be a `string` variable or +class property; integral outputs and `%p` are unsupported. Each call with conversions is a host request of a timed `Simulation`, like the file output tasks below; a format without conversions and arguments is a From 943ba42ba1e6f1d0a73c7ea793bcb196ea52c58a Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 03:56:58 +0900 Subject: [PATCH 2/3] perf(native): keep attached machine code in file mappings Loading an attached image allocated an owned copy of its machine code before copying it again into executable memory. Retain immutable mapped code with Arc ownership and use aligned file pages directly on Linux x86-64. Unsupported or unaligned mappings retain the anonymous executable allocation path. Align newly attached code to 4 KiB, or 2 MiB for large images. A checksummed optional prefix descriptor records the original runtime length so replacement across Postcard length boundaries cannot accumulate padding. The Postcard payload, generic Serde representation and container version remain compatible. Keep image bytes and offset resolution tied to a private immutable base, even when callers replace the public entry pointer. Cover both owned and external backing lifetimes with entry-swap and owner-drop regressions. Validation: 20 native units, 627 x86 backend units, 36 native image/cache consumer tests, 68 VPI unit/API tests, 10 cocotb integrations, 330 native common cases (including wide, four-state and parallel execution), affected-target clippy with warnings denied, and formatting. Regressions cover retained owner lifetimes, legacy payload encoding, bounded replacement and corrupt padding. Change-Id: Idc33e7f4db1b90e2cf48d03f0fd39049aebda302 --- .../src/backend/native/jit_mem.rs | 130 ++++++++++- crates/celox/src/backend/native/backend.rs | 150 +++++++++++-- crates/celox/src/backend/native/code_bytes.rs | 47 ++++ .../src/backend/native/executable_mapping.rs | 34 +++ crates/celox/src/backend/native/image_file.rs | 207 +++++++++++++++--- crates/celox/src/backend/native/mod.rs | 1 + crates/celox/tests/shared_jit_cache.rs | 15 +- 7 files changed, 532 insertions(+), 52 deletions(-) create mode 100644 crates/celox/src/backend/native/code_bytes.rs diff --git a/crates/celox-backend-x86/src/backend/native/jit_mem.rs b/crates/celox-backend-x86/src/backend/native/jit_mem.rs index 52b03e3bb19..420f4853903 100644 --- a/crates/celox-backend-x86/src/backend/native/jit_mem.rs +++ b/crates/celox-backend-x86/src/backend/native/jit_mem.rs @@ -1,6 +1,10 @@ //! JIT memory: load emitted machine code into executable memory and call it. -use std::{io::Write, sync::Mutex}; +use std::{ + any::Any, + io::Write, + sync::{Arc, Mutex}, +}; use memmap2::{Mmap, MmapMut}; @@ -24,7 +28,13 @@ pub struct JitSymbol { /// Executable code region holding JIT-compiled machine code. /// The code can be called as `fn(*mut u8) -> i64`. pub struct JitCode { - _mmap: Mmap, + _mmap: Option, + _external_owner: Option>, + code_len: usize, + // Keep the retained allocation independent of the public, mutable entry. + // A function pointer preserves JitCode's Send/Sync traits without a raw + // pointer Send/Sync implementation. + image_base: JitFn, pub fn_ptr: JitFn, } @@ -85,8 +95,43 @@ impl JitCode { write_perf_map_entries(mmap.as_ptr() as usize, code.len().max(1), name, symbols)?; } + let code_len = mmap.len(); Ok(Self { - _mmap: mmap, + _mmap: Some(mmap), + _external_owner: None, + code_len, + image_base: fn_ptr, + fn_ptr, + }) + } + + /// Retain an existing immutable executable region without copying it. + /// + /// # Safety + /// `code` must point to `len` readable, executable bytes of valid target + /// code. The bytes must remain immutable and accessible while `owner` is + /// alive, and the entry must follow this backend's function ABI. + pub unsafe fn from_executable_owner( + owner: Arc, + code: *const u8, + len: usize, + name: &str, + symbols: &[JitSymbol], + perf_map: bool, + ) -> Result { + if code.is_null() || len == 0 || len > isize::MAX as usize { + return Err(std::io::Error::other("invalid executable code region")); + } + if perf_map { + write_perf_map_entries(code as usize, len, name, symbols)?; + } + // Safety: the caller supplies a live region with this entry ABI. + let fn_ptr: JitFn = unsafe { std::mem::transmute(code) }; + Ok(Self { + _mmap: None, + _external_owner: Some(owner), + code_len: len, + image_base: fn_ptr, fn_ptr, }) } @@ -124,14 +169,16 @@ impl JitCode { /// trailing constant tables are copied together, so the runtime can retain /// entry offsets and resolve them after placing the combined image. pub fn entry_ptr(&self, offset: usize) -> Option<*const u8> { - (offset < self._mmap.len()).then(|| unsafe { self._mmap.as_ptr().add(offset) }) + (offset < self.code_len).then(|| unsafe { (self.image_base as *const u8).add(offset) }) } /// Bytes of the executable image, including alignment padding and constant /// tables. This is the exact image that can later be copied into an AOT /// container. pub fn image(&self) -> &[u8] { - &self._mmap + // Safety: either owned mapping or external owner keeps this immutable + // executable region alive for the lifetime of this borrow. + unsafe { std::slice::from_raw_parts(self.image_base as *const u8, self.code_len) } } } @@ -190,6 +237,79 @@ fn sanitize_perf_symbol(name: &str) -> String { mod tests { use super::*; + #[test] + fn external_executable_owner_survives_until_last_code_user() { + let bytes = [0xb8, 42, 0, 0, 0, 0xc3]; + let owner = Arc::new(JitCode::new(&bytes).unwrap()); + let weak = Arc::downgrade(&owner); + // Safety: the source is an immutable executable JitCode and the clone + // retained by this new region owns its complete backing allocation. + let borrowed = unsafe { + JitCode::from_executable_owner( + owner.clone(), + owner.image().as_ptr(), + owner.image().len(), + "owned_test_code", + &[], + false, + ) + } + .unwrap(); + drop(owner); + assert!(weak.upgrade().is_some()); + assert_eq!(borrowed.image(), bytes); + assert!(borrowed.entry_ptr(bytes.len()).is_none()); + assert_eq!(unsafe { borrowed.call(&mut []) }, 42); + drop(borrowed); + assert!(weak.upgrade().is_none()); + } + + fn assert_image_survives_entry_swap(mut code: JitCode, bytes: &[u8]) { + let base = code.image().as_ptr(); + // Use an allocation of a different size, and release it after swapping + // the public entries. Neither image accessor may follow the new entry. + let mut other = JitCode::new(&[0xc3]).unwrap(); + std::mem::swap(&mut code.fn_ptr, &mut other.fn_ptr); + assert_eq!(code.entry_ptr(0), Some(base)); + drop(other); + assert_eq!(code.image(), bytes); + assert_eq!( + code.entry_ptr(bytes.len() - 1), + Some(unsafe { base.add(bytes.len() - 1) }) + ); + assert!(code.entry_ptr(bytes.len()).is_none()); + // Execute through the retained image entry, not the swapped fn_ptr. + let entry: JitFn = unsafe { std::mem::transmute(code.entry_ptr(0).unwrap()) }; + assert_eq!(unsafe { entry(std::ptr::null_mut()) }, 42); + } + + #[test] + fn owned_image_is_independent_of_mutable_entry() { + let bytes = [0xb8, 42, 0, 0, 0, 0xc3]; + assert_image_survives_entry_swap(JitCode::new(&bytes).unwrap(), &bytes); + } + + #[test] + fn external_image_is_independent_of_mutable_entry() { + let bytes = [0xb8, 42, 0, 0, 0, 0xc3]; + let owner = Arc::new(JitCode::new(&bytes).unwrap()); + // Safety: owner retains the immutable executable allocation with the + // required entry ABI until the external JitCode is dropped. + let code = unsafe { + JitCode::from_executable_owner( + owner.clone(), + owner.image().as_ptr(), + owner.image().len(), + "entry_swap_test", + &[], + false, + ) + } + .unwrap(); + drop(owner); + assert_image_survives_entry_swap(code, &bytes); + } + #[test] fn large_images_preserve_bytes_bounds_and_entry_points() { for size in [4096, 2 * 1024 * 1024, 6 * 1024 * 1024 + 37] { diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 7b8be141152..dda7a05dfeb 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -28,6 +28,7 @@ use super::super::RuntimeEventBuffer; use super::super::compile_cancel::{CompileCancel, cancelled, cancelled_error}; use super::super::traits::SimulatorErrorCode; use super::super::{MemoryLayout, get_byte_size, memory_image::MemoryImage}; +use super::code_bytes::NativeCodeBytes; #[cfg(any( feature = "x86_64-codegen", all(target_arch = "x86_64", not(feature = "arm64-codegen")) @@ -243,13 +244,57 @@ impl SharedNativeCode { name: symbol.name.clone(), }) .collect::>(); - let jit_image = jit_mem::JitCode::new_named_with_symbols_profiled( - program_image.code_image(), - "celox_native_image", - &symbols, - program_image.options.perf_map, - ) - .map_err(|source| codegen_err(CodegenError::NativeMemory { source }))?; + #[cfg(all( + target_os = "linux", + target_arch = "x86_64", + not(feature = "arm64-codegen") + ))] + let mapped = match &program_image.code { + NativeCodeBytes::Mapped { owner, range } + if program_image + .code_image() + .as_ptr() + .addr() + .is_multiple_of(64) => + { + // Retain the previous executable allocation as a fallback if + // file execution is unavailable (for example a no-exec mount). + if owner.make_executable(range.clone()).is_ok() { + // Safety: image validation and the caller establish trusted + // target code; the Arc retains its immutable executable + // file mapping for every entry pointer's lifetime. + Some(unsafe { + jit_mem::JitCode::from_executable_owner( + owner.clone(), + program_image.code_image().as_ptr(), + program_image.code_image().len(), + "celox_native_image", + &symbols, + program_image.options.perf_map, + ) + }) + } else { + None + } + } + _ => None, + }; + #[cfg(not(all( + target_os = "linux", + target_arch = "x86_64", + not(feature = "arm64-codegen") + )))] + let mapped: Option> = None; + let jit_image = mapped + .unwrap_or_else(|| { + jit_mem::JitCode::new_named_with_symbols_profiled( + program_image.code_image(), + "celox_native_image", + &symbols, + program_image.options.perf_map, + ) + }) + .map_err(|source| codegen_err(CodegenError::NativeMemory { source }))?; let kernel_addresses = program_image .runtime_schema .native_kernel_offsets @@ -460,7 +505,7 @@ pub(crate) struct NativeRuntimeSchema { /// precompiled Celox runtime. #[derive(Clone, Serialize, Deserialize)] pub struct NativeProgramImage { - code: Vec, + code: NativeCodeBytes, code_entries: Vec, symbols: Vec, comb_offset: usize, @@ -487,14 +532,14 @@ pub struct NativeProgramImage { // Keep this private Postcard decoder in field order with NativeProgramImage. // Postcard encodes both Vec and byte slices as a length followed by raw -// bytes. Borrowing that slice and copying once avoids per-byte sequence visits -// for large code images. The public Serde representation and container writer +// bytes. Borrowing that slice avoids per-byte sequence visits and allows file +// storage to back the code directly. The public Serde representation and payload // remain unchanged, including for formats that distinguish arrays and bytes. #[derive(Deserialize)] #[serde(remote = "NativeProgramImage")] struct PostcardNativeProgramImage { #[serde(deserialize_with = "deserialize_postcard_code")] - code: Vec, + code: NativeCodeBytes, code_entries: Vec, symbols: Vec, comb_offset: usize, @@ -519,16 +564,50 @@ struct PostcardNativeProgramImage { lanes: Option, } -fn deserialize_postcard_code<'de, D>(deserializer: D) -> Result, D::Error> +fn deserialize_postcard_code<'de, D>(deserializer: D) -> Result where D: serde::Deserializer<'de>, { - <&[u8]>::deserialize(deserializer).map(<[u8]>::to_vec) + // The caller installs owned or mapped storage after decoding metadata. + <&[u8]>::deserialize(deserializer).map(|_| NativeCodeBytes::Owned(Vec::new())) } impl NativeProgramImage { pub(super) fn from_postcard_bytes(bytes: &[u8]) -> Result { - PostcardNativeProgramImage::deserialize(&mut postcard::Deserializer::from_bytes(bytes)) + let (code, _) = postcard::take_from_bytes::<&[u8]>(bytes)?; + let mut image = PostcardNativeProgramImage::deserialize( + &mut postcard::Deserializer::from_bytes(bytes), + )?; + image.code = code.to_vec().into(); + Ok(image) + } + + #[cfg(target_os = "linux")] + pub(super) fn from_mapped_postcard_bytes( + bytes: &[u8], + owner: Arc, + ) -> Result { + let (code, _) = postcard::take_from_bytes::<&[u8]>(bytes)?; + let mut image = PostcardNativeProgramImage::deserialize( + &mut postcard::Deserializer::from_bytes(bytes), + )?; + if !code.is_empty() { + // The container reader passes a payload slice from this same owner. + let start = code + .as_ptr() + .addr() + .checked_sub(owner.as_bytes().as_ptr().addr()) + .ok_or(postcard::Error::DeserializeBadEncoding)?; + let end = start + .checked_add(code.len()) + .filter(|&end| end <= owner.as_bytes().len()) + .ok_or(postcard::Error::DeserializeBadEncoding)?; + image.code = NativeCodeBytes::Mapped { + owner, + range: start..end, + }; + } + Ok(image) } /// Physical duration of one tick, retained in serialized native images. @@ -3006,7 +3085,7 @@ fn compile_program_with_outlining_threshold( Ok(( NativeProgramImage { - code: packed_image, + code: packed_image.into(), code_entries, symbols: image_symbols, comb_offset, @@ -4199,6 +4278,40 @@ mod tests { BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue, }; + #[test] + fn replacing_images_does_not_accumulate_alignment_padding() { + let source = + "module Top(a: input bit<8>, b: input bit<8>, y: output bit<8>) { assign y = a + b; }"; + let mut image = crate::Simulator::builder(source, "Top") + .compile_native() + .unwrap() + .into_program_image(); + let original_code = image.code.to_vec(); + assert!(original_code.len() < 16_383); + let directory = tempfile::tempdir().unwrap(); + let runtime = directory.path().join("runtime"); + std::fs::write(&runtime, b"precompiled runtime").unwrap(); + let mut sizes = Vec::new(); + // Crossing a Postcard length-prefix boundary changes the required + // padding. Trailing zeros test framing only and are never executed. + for length in [16_383, 16_384, 16_383, 16_384] { + let mut code = original_code.clone(); + code.resize(length, 0); + image.code = code.into(); + image.write_attached_runtime(&runtime, &runtime).unwrap(); + let bytes = std::fs::read(&runtime).unwrap(); + let found = NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap(); + assert_eq!(found.image.code_image().len(), length); + assert!(bytes.starts_with(b"precompiled runtime")); + sizes.push(bytes.len()); + } + assert_eq!(sizes[0], sizes[2]); + assert_eq!(sizes[1], sizes[3]); + assert_eq!(sizes[1], sizes[0] + 1); + } + #[test] fn postcard_code_decoder_preserves_legacy_payloads() { let source = "module Top(clk: input clock, d: input bit<8>, q: output bit<8>) { always_ff (clk) { q = d; } }"; @@ -4209,11 +4322,14 @@ mod tests { // These byte patterns exercise the wire decoder only; no synthetic // machine code is validated, mapped executable, or invoked. for length in [0, 1, 127, 128, 255, 256, 1024] { - image.code = (0..length).map(|index| index as u8).collect(); + image.code = (0..length) + .map(|index| index as u8) + .collect::>() + .into(); let payload = postcard::to_allocvec(&image).unwrap(); let legacy: NativeProgramImage = postcard::from_bytes(&payload).unwrap(); let decoded = NativeProgramImage::from_postcard_bytes(&payload).unwrap(); - assert_eq!(decoded.code, image.code); + assert_eq!(&*decoded.code, &*image.code); assert_eq!( postcard::to_allocvec(&decoded).unwrap(), postcard::to_allocvec(&legacy).unwrap(), diff --git a/crates/celox/src/backend/native/code_bytes.rs b/crates/celox/src/backend/native/code_bytes.rs new file mode 100644 index 00000000000..93f83cdb7b8 --- /dev/null +++ b/crates/celox/src/backend/native/code_bytes.rs @@ -0,0 +1,47 @@ +use std::ops::Deref; +#[cfg(target_os = "linux")] +use std::{ops::Range, sync::Arc}; + +#[cfg(target_os = "linux")] +use super::executable_mapping::ExecutableMapping; +use serde::{Deserialize, Serialize}; + +#[derive(Clone)] +pub(super) enum NativeCodeBytes { + Owned(Vec), + #[cfg(target_os = "linux")] + Mapped { + owner: Arc, + range: Range, + }, +} + +impl From> for NativeCodeBytes { + fn from(bytes: Vec) -> Self { + Self::Owned(bytes) + } +} + +impl Deref for NativeCodeBytes { + type Target = [u8]; + fn deref(&self) -> &[u8] { + match self { + Self::Owned(bytes) => bytes, + #[cfg(target_os = "linux")] + Self::Mapped { owner, range } => &owner.as_bytes()[range.clone()], + } + } +} + +// Preserve the generic Vec Serde representation, including array-based +// formats. Only the private container decoder borrows Postcard byte spans. +impl Serialize for NativeCodeBytes { + fn serialize(&self, serializer: S) -> Result { + self.deref().serialize(serializer) + } +} +impl<'de> Deserialize<'de> for NativeCodeBytes { + fn deserialize>(deserializer: D) -> Result { + Vec::::deserialize(deserializer).map(Self::Owned) + } +} diff --git a/crates/celox/src/backend/native/executable_mapping.rs b/crates/celox/src/backend/native/executable_mapping.rs index dda28f1961f..251dafb9b14 100644 --- a/crates/celox/src/backend/native/executable_mapping.rs +++ b/crates/celox/src/backend/native/executable_mapping.rs @@ -6,6 +6,12 @@ pub(super) struct ExecutableMapping { len: usize, } +// Safety: the executing inode cannot be written while it is running. This +// owner only changes page permissions from read-only to read/execute, never +// makes bytes mutable, and unmaps only after the last Arc owner/borrow ends. +unsafe impl Send for ExecutableMapping {} +unsafe impl Sync for ExecutableMapping {} + impl ExecutableMapping { pub(super) fn current() -> io::Result { // Open the executing inode, even after its pathname has been replaced. @@ -42,6 +48,34 @@ impl ExecutableMapping { Ok(Self { address, len }) } + #[cfg(all(target_arch = "x86_64", not(feature = "arm64-codegen")))] + pub(super) fn make_executable(&self, range: std::ops::Range) -> io::Result<()> { + if range.is_empty() || range.end > self.len { + return Err(io::Error::other("invalid executable code range")); + } + // Safety: sysconf has no pointer arguments and does not mutate memory. + let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + let page = usize::try_from(page) + .ok() + .filter(|&page| page != 0) + .ok_or_else(|| io::Error::other("cannot determine page size"))?; + let start = range.start / page * page; + // mprotect rounds the end up to the final mapped page itself. + // Safety: the checked subrange belongs to this live mapping. Read + // permission is retained; no writable alias is introduced. + let result = unsafe { + libc::mprotect( + self.address.as_ptr().add(start).cast(), + range.end - start, + libc::PROT_READ | libc::PROT_EXEC, + ) + }; + if result != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + pub(super) fn as_bytes(&self) -> &[u8] { // Safety: this owner retains an immutable mapping of the checked size; // the returned slice cannot outlive it. diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 1140e4ac56d..d3e948fe8a4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -13,6 +13,14 @@ const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; // Concurrent assertion kernels suspend into Observed and Reactive regions. const CONTAINER_VERSION: u16 = 52; const TRAILER_SIZE: usize = 32; +// This optional prefix descriptor does not change the Postcard payload. Older +// readers ignore framing flags and continue to locate the payload at EOF. +const RUNTIME_PADDING_FLAG: u8 = 1; +const RUNTIME_PADDING_MAGIC: &[u8; 8] = b"CELOXPAD"; +const RUNTIME_PADDING_SIZE: usize = 32; +const SMALL_CODE_ALIGNMENT: usize = 4096; +const HUGE_CODE_ALIGNMENT: usize = 2 * 1024 * 1024; + const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; @@ -62,7 +70,7 @@ impl fmt::Display for NativeImageArchitecture { /// Result of finding and decoding an image appended to another byte sequence. pub struct AppendedNativeImage { - /// Length of the original runtime prefix before the serialized image. + /// Length of the runtime prefix, including alignment padding, before the serialized image. pub runtime_len: usize, /// Decoded pointer-free program image. pub image: NativeProgramImage, @@ -72,6 +80,7 @@ struct AppendedNativePayload<'a> { runtime_len: usize, version: u16, architecture: u8, + flags: u8, payload: &'a [u8], } @@ -128,11 +137,37 @@ impl NativeProgramImage { /// the runtime discover the payload without parsing its own executable /// format. pub fn append_to_runtime(&self, runtime: &[u8]) -> Result, NativeImageContainerError> { + self.append_to_runtime_aligned(runtime, 1) + } + + fn append_to_runtime_aligned( + &self, + runtime: &[u8], + alignment: usize, + ) -> Result, NativeImageContainerError> { + debug_assert!(alignment.is_power_of_two()); self.validate() .map_err(NativeImageContainerError::InvalidImage)?; let payload = postcard::to_allocvec(self)?; - let total_len = runtime + let (code, remaining) = postcard::take_from_bytes::<&[u8]>(&payload)?; + let code_prefix = payload.len() - remaining.len() - code.len(); + let descriptor_size = if alignment > 1 { + RUNTIME_PADDING_SIZE + } else { + 0 + }; + let code_start = runtime .len() + .checked_add(descriptor_size) + .and_then(|size| size.checked_add(code_prefix)) + .ok_or(NativeImageContainerError::SizeOverflow)?; + let padding = (alignment - code_start % alignment) % alignment; + let runtime_len = runtime + .len() + .checked_add(padding) + .and_then(|size| size.checked_add(descriptor_size)) + .ok_or(NativeImageContainerError::SizeOverflow)?; + let total_len = runtime_len .checked_add(payload.len()) .and_then(|size| size.checked_add(TRAILER_SIZE)) .ok_or(NativeImageContainerError::SizeOverflow)?; @@ -141,11 +176,25 @@ impl NativeProgramImage { let mut output = Vec::with_capacity(total_len); output.extend_from_slice(runtime); + output.resize(runtime_len - descriptor_size, 0); + if descriptor_size != 0 { + let mut descriptor = [0u8; RUNTIME_PADDING_SIZE]; + descriptor[..8].copy_from_slice(RUNTIME_PADDING_MAGIC); + descriptor[8..16].copy_from_slice(&(runtime.len() as u64).to_le_bytes()); + descriptor[16..24].copy_from_slice(&(padding as u64).to_le_bytes()); + let hash = checksum(&descriptor[..24]); + descriptor[24..32].copy_from_slice(&hash.to_le_bytes()); + output.extend_from_slice(&descriptor); + } output.extend_from_slice(&payload); output.extend_from_slice(TRAILER_MAGIC); output.extend_from_slice(&CONTAINER_VERSION.to_le_bytes()); output.push(NativeImageArchitecture::current() as u8); - output.push(0); // flags, reserved for future container revisions + output.push(if descriptor_size != 0 { + RUNTIME_PADDING_FLAG + } else { + 0 + }); output.extend_from_slice(&(TRAILER_SIZE as u32).to_le_bytes()); output.extend_from_slice(&payload_len.to_le_bytes()); output.extend_from_slice(&checksum(&payload).to_le_bytes()); @@ -167,10 +216,18 @@ impl NativeProgramImage { let output_path = output_path.as_ref(); let metadata = std::fs::metadata(runtime_path)?; let runtime = std::fs::read(runtime_path)?; - let runtime_len = discover_appended_payload(&runtime)? - .map(|appended| appended.runtime_len) - .unwrap_or(runtime.len()); - let output = self.append_to_runtime(&runtime[..runtime_len])?; + let runtime_len = match discover_appended_payload(&runtime)? { + Some(appended) => unpadded_runtime_len(&runtime, &appended)?, + None => runtime.len(), + }; + // The Postcard payload stays unchanged; padding belongs to the runtime + // prefix so older format-compatible readers can still load the image. + let alignment = if self.code_image().len() >= HUGE_CODE_ALIGNMENT { + HUGE_CODE_ALIGNMENT + } else { + SMALL_CODE_ALIGNMENT + }; + let output = self.append_to_runtime_aligned(&runtime[..runtime_len], alignment)?; std::fs::write(output_path, output)?; std::fs::set_permissions(output_path, metadata.permissions())?; Ok(()) @@ -195,24 +252,10 @@ impl NativeProgramImage { let Some(appended) = discover_appended_payload(bytes)? else { return Ok(None); }; - if appended.version != CONTAINER_VERSION { - return Err(NativeImageContainerError::UnsupportedVersion( - appended.version, - )); - } - let found = NativeImageArchitecture::decode(appended.architecture)?; - let expected = NativeImageArchitecture::current(); - if found != expected { - return Err(NativeImageContainerError::ArchitectureMismatch { expected, found }); - } - let image = NativeProgramImage::from_postcard_bytes(appended.payload)?; - image - .validate() - .map_err(NativeImageContainerError::InvalidImage)?; - Ok(Some(AppendedNativeImage { - runtime_len: appended.runtime_len, - image, - })) + Ok(Some(decode_appended_image( + appended, + Self::from_postcard_bytes, + )?)) } /// Read the running executable and discover an image attached at EOF. @@ -220,9 +263,13 @@ impl NativeProgramImage { -> Result, NativeImageContainerError> { #[cfg(target_os = "linux")] if let Ok(mapping) = super::executable_mapping::ExecutableMapping::current() { - // The decoder returns owned metadata/code, so the temporary input - // mapping can be released immediately after decoding. - return Self::discover_appended(mapping.as_bytes()); + let owner = std::sync::Arc::new(mapping); + let Some(appended) = discover_appended_payload(owner.as_bytes())? else { + return Ok(None); + }; + return Ok(Some(decode_appended_image(appended, |payload| { + Self::from_mapped_postcard_bytes(payload, owner.clone()) + })?)); } let executable = std::env::current_exe()?; let mut file = std::fs::File::open(executable)?; @@ -230,6 +277,30 @@ impl NativeProgramImage { } } +fn decode_appended_image( + appended: AppendedNativePayload<'_>, + decode: impl FnOnce(&[u8]) -> Result, +) -> Result { + if appended.version != CONTAINER_VERSION { + return Err(NativeImageContainerError::UnsupportedVersion( + appended.version, + )); + } + let found = NativeImageArchitecture::decode(appended.architecture)?; + let expected = NativeImageArchitecture::current(); + if found != expected { + return Err(NativeImageContainerError::ArchitectureMismatch { expected, found }); + } + let image = decode(appended.payload)?; + image + .validate() + .map_err(NativeImageContainerError::InvalidImage)?; + Ok(AppendedNativeImage { + runtime_len: appended.runtime_len, + image, + }) +} + // Read the trailer first so ordinary CLI commands do not copy the runtime // executable and attached runs allocate only their serialized image. fn discover_reader( @@ -312,10 +383,50 @@ fn discover_appended_payload( runtime_len, version: u16::from_le_bytes(trailer[8..10].try_into().unwrap()), architecture: trailer[10], + flags: trailer[11], payload, })) } +fn unpadded_runtime_len( + bytes: &[u8], + appended: &AppendedNativePayload<'_>, +) -> Result { + if appended.flags & RUNTIME_PADDING_FLAG == 0 { + return Ok(appended.runtime_len); + } + let invalid = || { + NativeImageContainerError::Io(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "invalid attached-runtime padding descriptor", + )) + }; + let start = appended + .runtime_len + .checked_sub(RUNTIME_PADDING_SIZE) + .ok_or_else(invalid)?; + let descriptor = bytes.get(start..appended.runtime_len).ok_or_else(invalid)?; + if &descriptor[..8] != RUNTIME_PADDING_MAGIC { + return Err(invalid()); + } + let expected = u64::from_le_bytes(descriptor[24..32].try_into().unwrap()); + if checksum(&descriptor[..24]) != expected { + return Err(NativeImageContainerError::ChecksumMismatch); + } + let raw_len = usize::try_from(u64::from_le_bytes(descriptor[8..16].try_into().unwrap())) + .map_err(|_| NativeImageContainerError::SizeOverflow)?; + let padding = usize::try_from(u64::from_le_bytes(descriptor[16..24].try_into().unwrap())) + .map_err(|_| NativeImageContainerError::SizeOverflow)?; + if raw_len.checked_add(padding) != Some(start) + || bytes + .get(raw_len..start) + .is_none_or(|padding| padding.iter().any(|&byte| byte != 0)) + { + return Err(invalid()); + } + Ok(raw_len) +} + fn checksum(bytes: &[u8]) -> u64 { bytes.iter().fold(FNV_OFFSET_BASIS, |hash, byte| { (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME) @@ -410,6 +521,46 @@ mod tests { } } + #[test] + fn aligned_prefix_preserves_the_legacy_payload_and_original_runtime() { + let image = image(); + let runtime = b"precompiled runtime"; + let legacy = image.append_to_runtime(runtime).unwrap(); + let aligned = image + .append_to_runtime_aligned(runtime, HUGE_CODE_ALIGNMENT) + .unwrap(); + let old = discover_appended_payload(&legacy).unwrap().unwrap(); + let new = discover_appended_payload(&aligned).unwrap().unwrap(); + assert_eq!(old.flags, 0); + assert_eq!(new.flags, RUNTIME_PADDING_FLAG); + assert_eq!(new.payload, old.payload); + assert_eq!(unpadded_runtime_len(&aligned, &new).unwrap(), runtime.len()); + let (code, remaining) = postcard::take_from_bytes::<&[u8]>(new.payload).unwrap(); + let offset = aligned.len() - TRAILER_SIZE - remaining.len() - code.len(); + assert!(offset.is_multiple_of(HUGE_CODE_ALIGNMENT)); + let decoded: NativeProgramImage = postcard::from_bytes(new.payload).unwrap(); + assert_eq!(decoded.code_image(), image.code_image()); + } + + #[test] + fn corrupt_padding_descriptor_does_not_overwrite_the_runtime() { + let image = image(); + let mut bytes = image + .append_to_runtime_aligned(b"runtime", HUGE_CODE_ALIGNMENT) + .unwrap(); + let frame = discover_appended_payload(&bytes).unwrap().unwrap(); + let descriptor = frame.runtime_len - RUNTIME_PADDING_SIZE; + bytes[descriptor + 8] ^= 1; + let directory = tempfile::tempdir().unwrap(); + let runtime = directory.path().join("runtime"); + std::fs::write(&runtime, &bytes).unwrap(); + assert!(matches!( + image.write_attached_runtime(&runtime, &runtime), + Err(NativeImageContainerError::ChecksumMismatch) + )); + assert_eq!(std::fs::read(runtime).unwrap(), bytes); + } + #[test] fn reader_ignores_runtime_prefix_and_preserves_image_and_offset() { let image = image(); diff --git a/crates/celox/src/backend/native/mod.rs b/crates/celox/src/backend/native/mod.rs index 49bc3968db2..f8ba60caa24 100644 --- a/crates/celox/src/backend/native/mod.rs +++ b/crates/celox/src/backend/native/mod.rs @@ -1,5 +1,6 @@ pub mod backend; mod clock_aliases; +mod code_bytes; mod compile_resources; #[cfg(target_os = "linux")] mod executable_mapping; diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 1bf274b058a..7f7cf95f8f6 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -861,8 +861,19 @@ fn native_program_image_writes_an_executable_runtime_file() { let appended = celox::NativeProgramImage::discover_appended(&output) .unwrap() .unwrap(); - assert_eq!(appended.runtime_len, b"precompiled runtime".len()); - assert_eq!(&output[..appended.runtime_len], b"precompiled runtime"); + let prefix = b"precompiled runtime"; + assert_eq!(&output[..prefix.len()], prefix); + assert!(appended.runtime_len >= prefix.len()); + let payload = &output[appended.runtime_len..output.len() - NATIVE_IMAGE_TRAILER_SIZE]; + let (code, remaining) = postcard::take_from_bytes::<&[u8]>(payload).unwrap(); + let code_start = output.len() - NATIVE_IMAGE_TRAILER_SIZE - remaining.len() - code.len(); + let alignment = if code.len() >= 2 * 1024 * 1024 { + 2 * 1024 * 1024 + } else { + 4096 + }; + assert!(code_start.is_multiple_of(alignment)); + assert_eq!(code, image.code_image()); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; From 2717a14b4a73371de4fe60b79c52b0eade9c8c5f Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 04:56:42 +0900 Subject: [PATCH 3/3] ci: key the vtest dependency cache by the executor's build plan After #2467 moved the test build to the `vtest` profile, Rust Tests jobs still restored the old `vtest-v1` cache, built for the previous plan, and compiled the dependencies again in the executor step (10 minutes and more). The warm workflow ran on the merge but found the same key and skipped its build, since the rust-cache key does not change with Cargo commands or profiles. Key the cache by `scripts/run-vtest.mjs`, which holds the executor's profile, scope and features, in both CI and the warm workflow. A change of the plan is then a new key that the warm run on master populates. Validation: repository workflow tests (26) pass, including the key parity between CI and the warm workflow; actionlint reports only its unknown `ubuntu-26.04-arm` label. Change-Id: I9b8d55c3142c7a3b00a751b6f005cbb57fa5d2f4 --- .github/workflows/ci.yml | 4 +++- .github/workflows/rust-cache.yml | 4 +++- scripts/ci-workflow.test.mjs | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0f114b6dd93..a7bcaf86474 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -247,7 +247,9 @@ jobs: - uses: Swatinem/rust-cache@v2 with: - key: vtest-v1 + # The vtest executor's build plan (profile, scope, features) lives in + # run-vtest.mjs; a change of it is a different cache. + key: vtest-${{ hashFiles('scripts/run-vtest.mjs') }} save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - name: Initialize Rust test reports diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml index 78b9386e612..5fdc8fd8895 100644 --- a/.github/workflows/rust-cache.yml +++ b/.github/workflows/rust-cache.yml @@ -48,7 +48,9 @@ jobs: - uses: Swatinem/rust-cache@v2 id: cache with: - key: vtest-v1 + # The vtest executor's build plan (profile, scope, features) lives in + # run-vtest.mjs; a change of it is a different cache. + key: vtest-${{ hashFiles('scripts/run-vtest.mjs') }} - name: Install cargo-nextest if: steps.cache.outputs.cache-hit != 'true' uses: taiki-e/install-action@v2 diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 408d4a8933e..186149c511c 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -372,7 +372,7 @@ test("cache warming shares the Rust Tests key and builds without running tests", ); assert.match(warm, /steps.cache.outputs.cache-hit != 'true'/); for (const text of [warm, job("rust-tests")]) { - assert.match(text, /key: vtest-v1/); + assert.match(text, /key: vtest-\$\{\{ hashFiles\('scripts\/run-vtest\.mjs'\) \}\}/); assert.match(text, /run: node scripts\/run-vtest.mjs --prepare-ci/); } assert.match(warm, /name: Build the optimized vtest executor to populate dependencies\n if: steps.cache.outputs.cache-hit != 'true'/);