Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,12 @@ impl<'p, 'a> Ff<'p, 'a> {
}
continue;
}
sv::ir::Callee::Object(op) if matches!(*op, sv::ir::ObjectOp::New { .. }) => {
// Constructor seeding consumes the process RNG. Register it
// before lower_process freezes the persistent target ranges.
self.urandom_state();
continue;
}
sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => continue,
sv::ir::Callee::Subroutine(name) => name,
};
Expand Down
26 changes: 25 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ impl Ff<'_, '_> {
let size = self.constant64(u64::from(*size));
let object =
self.heap_call(ops::encode(ops::OBJECT_NEW, u64::from(*class)), &[size]);
// Object seeding consumes the creating process's RNG once,
// before the constructor body (IEEE 1800-2023 18.14.3).
let seed = self.urandom(None)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Register constructor seeding as an FF state target

When new executes in an edge-triggered process, this reaches urandom_state() only while exec_block lowers the body, but Ff::lower_process has already frozen its target ranges and Ff::scan skips all Callee::Object calls. The hidden process RNG therefore remains in working scratch instead of being committed to stable state; for example, after creating an object, checkpointing, creating another, and restoring, the next object's seed continues from the post-checkpoint scratch value rather than replaying the saved stream. Have the scan recognize ObjectOp::New as a process-RNG consumer before FF targets are computed.

Useful? React with 👍 / 👎.

let seed = self.integer_of_width(&seed, 32, false)?;
self.heap_call(ops::OBJECT_SEED, &[object, seed]);
for &(offset, kind) in handles {
let offset = self.constant64(u64::from(offset));
let kind = self.constant64(match kind {
Expand All @@ -55,6 +60,21 @@ impl Ff<'_, '_> {
let value = self.integer_of_width(&args[1], field.width as usize, field.signed)?;
self.heap_call(ops::OBJECT_STORE, &[object, place, value])
}
ObjectOp::Random | ObjectOp::Check(_) => {
let object = self.handle(&args[0])?;
self.heap_call(
match op {
ObjectOp::Check(class) => ops::encode(ops::OBJECT_CHECK, u64::from(*class)),
_ => ops::OBJECT_RANDOM,
},
&[object],
)
}
ObjectOp::Seed => {
let object = self.handle(&args[0])?;
let seed = self.integer_of_width(&args[1], 32, false)?;
self.heap_call(ops::OBJECT_SEED, &[object, seed])
}
ObjectOp::ClassOf => {
let object = self.handle(&args[0])?;
self.heap_call(ops::OBJECT_CLASS, &[object])
Expand All @@ -70,7 +90,11 @@ impl Ff<'_, '_> {
HandleProperty::String => celox_design::ValueKind::StrRef,
HandleProperty::Object => celox_design::ValueKind::ObjRef,
}),
ObjectOp::Store(_) | ObjectOp::ClassOf => None,
ObjectOp::Store(_)
| ObjectOp::ClassOf
| ObjectOp::Random
| ObjectOp::Seed
| ObjectOp::Check(_) => None,
};
if let Some(kind) = kind {
self.m.variables.get_mut(&temp).unwrap().value_kind = kind;
Expand Down
36 changes: 34 additions & 2 deletions crates/celox-heap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,17 @@ impl Heap {
self.strings.contains_key(&handle)
}

/// Whether `other` holds the same strings under the same handles, the
/// same strings under construction, and names new strings alike.
/// Whether `other` holds the same strings and objects under the same
/// handles, including object RNG state and strings under construction,
/// and assigns the same handles to future allocations.
pub fn same_contents(&self, other: &Heap) -> bool {
self.strings == other.strings
&& self.next == other.next
&& self.buffers == other.buffers
&& self.free_buffers == other.free_buffers
&& self.pinned == other.pinned
&& self.objects == other.objects
&& self.next_object == other.next_object
}

/// The number of live strings, including `""`.
Expand Down Expand Up @@ -261,6 +264,35 @@ impl Heap {
mod tests {
use super::*;

#[test]
fn comparison_detects_object_rng_divergence_before_a_property_write() {
let mut heap = Heap::new();
let object = heap.new_object(7, 8);
heap.seed_object(object, 42);
let mut other = heap.clone();
assert!(heap.same_contents(&other));
let drawn = other.random_object(object);
assert_eq!(heap.load(object, 0, 8), other.load(object, 0, 8));
assert!(!heap.same_contents(&other));
assert_eq!(heap.random_object(object), drawn);
assert!(heap.same_contents(&other));
}

#[test]
fn comparison_detects_object_contents_and_allocation_state() {
let mut heap = Heap::new();
let object = heap.new_object(7, 8);
let mut other = heap.clone();
other.store(object, 0, 8, 99);
assert!(!heap.same_contents(&other));
heap.store(object, 0, 8, 99);
assert!(heap.same_contents(&other));
other.new_object(7, 8);
other.collect([Root::object(object)]);
// The same live object remains, but future allocation handles differ.
assert!(!heap.same_contents(&other));
}

#[test]
fn interning_gives_equal_contents_equal_handles() {
let mut heap = Heap::new();
Expand Down
68 changes: 67 additions & 1 deletion crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ use crate::{Handle, HandleKind, Heap};
/// The handle of `null`, the value of zero-initialized memory.
pub const NULL: Handle = 0;

#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Object {
class: u32,
random_state: u64,
Comment thread
tignear marked this conversation as resolved.
Resolved
bytes: Box<[u8]>,
/// Byte offsets of the handle properties, with what they refer to.
pub(crate) handles: Vec<(u32, HandleKind)>,
Expand All @@ -32,12 +33,17 @@ pub enum Fault {
/// A property access or method call through `null` or a handle of no
/// live object (IEEE 1800-2023 8.4).
NullDereference,
/// The first randomization subset does not implement virtual dispatch.
RandomizationClassMismatch,
}

impl std::fmt::Display for Fault {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NullDereference => f.write_str("null object handle dereferenced"),
Self::RandomizationClassMismatch => {
f.write_str("class randomization through a base handle is unsupported")
}
}
}
}
Expand All @@ -53,6 +59,7 @@ impl Heap {
handle,
Object {
class,
random_state: 0,
bytes: vec![0; size].into(),
handles: Vec::new(),
},
Expand All @@ -61,6 +68,37 @@ impl Heap {
handle
}

/// Seed an object's independent random stream (IEEE 1800-2023 18.13.3).
pub fn seed_object(&mut self, handle: Handle, seed: u32) {
if let Some(object) = self.object_mut(handle) {
object.random_state = u64::from(seed);
}
}

/// SplitMix64: a full-period state transition with a bijective output
/// permutation, including seed zero. The language does not fix the RNG.
pub fn random_object(&mut self, handle: Handle) -> u64 {
let Some(object) = self.object_mut(handle) else {
return 0;
};
object.random_state = object.random_state.wrapping_add(0x9e3779b97f4a7c15);
let mut word = object.random_state;
word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb);
word ^ (word >> 31)
}

pub(crate) fn check_object(&mut self, handle: Handle, class: u32) -> bool {
let Some(object) = self.object_mut(handle) else {
return false;
};
if class != 0 && object.class != class {
self.fault.get_or_insert(Fault::RandomizationClassMismatch);
return false;
}
true
}

/// Declare that the property of `object` at byte `offset` holds a handle
/// of `kind`.
pub fn declare_handle(&mut self, object: Handle, offset: u32, kind: HandleKind) {
Expand Down Expand Up @@ -183,3 +221,31 @@ mod tests {
assert!(!heap.contains(text));
}
}

#[cfg(test)]
mod random_tests {
use super::*;

#[test]
fn random_streams_are_independent_and_checkpointed() {
let mut heap = Heap::new();
let a = heap.new_object(1, 1);
let b = heap.new_object(1, 1);
heap.seed_object(a, 0);
heap.seed_object(b, 0);
let first = heap.random_object(a);
for _ in 0..10 {
heap.random_object(a);
}
assert_eq!(first, heap.random_object(b));
heap.seed_object(a, 0);
assert_eq!(first, heap.random_object(a));
let mut snapshot = heap.clone();
for _ in 0..20 {
assert_eq!(heap.random_object(a), snapshot.random_object(a));
}
assert_eq!(heap.take_fault(), None);
heap.random_object(NULL);
assert_eq!(heap.take_fault(), Some(Fault::NullDereference));
}
}
13 changes: 13 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ pub const OBJECT_LOAD: u64 = 50;
pub const OBJECT_STORE: u64 = 51;
/// `class_of(object)`: its class, or 0 for `null`.
pub const OBJECT_CLASS: u64 = 52;
/// `random(object)`: 64 random bits from the object's RNG.
pub const OBJECT_RANDOM: u64 = 53;
/// `seed(object, seed)`: reset the object's RNG using the low 32 bits.
pub const OBJECT_SEED: u64 = 54;
/// `check(object)`: record a fault for an invalid receiver or, when the
/// parameter is nonzero, a different runtime class. Return 1 on success, 0 on failure.
pub const OBJECT_CHECK: u64 = 55;

/// The opcode word of `op` with parameter `parameter`.
pub const fn encode(op: u64, parameter: u64) -> u64 {
Expand Down Expand Up @@ -168,6 +175,12 @@ impl Heap {
0
}
OBJECT_CLASS => self.class_of(a as Handle).into(),
OBJECT_RANDOM => self.random_object(a as Handle),
OBJECT_SEED => {
self.seed_object(a as Handle, b as u32);
0
}
OBJECT_CHECK => u64::from(self.check_object(a as Handle, parameter as u32)),
other => panic!("unknown heap operation {other}"),
}
}
Expand Down
56 changes: 56 additions & 0 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub(super) struct Property {
pub name: String,
pub r#type: Type,
pub field: ObjectField,
pub rand: bool,
pub randc: bool,
/// The initializer of the declaration, evaluated by the constructor.
pub initializer: Option<celox_sv_syntax::ExprId>,
}
Expand Down Expand Up @@ -88,9 +90,45 @@ pub(super) struct Class {
pub methods: Vec<Method>,
/// Bytes of an object.
pub size: u32,
pub has_constraints: bool,
}

impl Class {
/// Validate the supported unconstrained subset before binding a call.
pub fn check_randomize(&self, tree: &AnalysisContext<'_>) -> Converted<()> {
if self.has_constraints {
return Err(unsupported("class randomize with constraints"));
}
if self.base.is_some() {
return Err(unsupported("class randomize with inheritance"));
}
for property in &self.properties {
if property.randc {
return Err(unsupported("class randomize with randc properties"));
}
if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) {
return Err(unsupported(
"class randomize requires integral non-enum rand properties",
));
}
}
for hook in ["pre_randomize", "post_randomize"] {
if let Some(method) = self.method(hook) {
let native = tree.declarations().subroutine(method.native);
if native.kind != celox_sv_syntax::SubroutineKind::Function
|| native.ports.as_ref().is_some_and(|ports| !ports.is_empty())
|| method.qualifiers.is_static
|| method.qualifiers.is_virtual
{
return Err(unsupported(
"randomization hooks require non-static, non-virtual functions without arguments",
));
}
}
}
Ok(())
}

/// The property `name`; one the class declares hides one of a base
/// (IEEE 1800-2023 8.14).
pub fn property(&self, name: &str) -> Option<&Property> {
Expand Down Expand Up @@ -358,6 +396,14 @@ pub(super) fn class(
.unwrap_or_default();
let mut size = base.as_ref().map_or(0, |base| base.size);
for property in &declaration.properties {
if property.declaration.constant && (property.qualifiers.rand || property.qualifiers.randc)
{
return Err(unsupported("const random class property"));
}
if property.qualifiers.is_static && (property.qualifiers.rand || property.qualifiers.randc)
{
return Err(unsupported("static random class property"));
}
let ty = type_binding::procedural_type(
property.declaration.data_type,
native,
Expand Down Expand Up @@ -389,6 +435,8 @@ pub(super) fn class(
name,
r#type: ty.clone(),
field,
rand: property.qualifiers.rand,
randc: property.qualifiers.randc,
initializer: variable.value,
});
}
Expand All @@ -403,6 +451,11 @@ pub(super) fn class(
for method in &declaration.methods {
let subroutine = native.subroutine(method.subroutine);
let method_name = instances::normalize_identifier(&subroutine.name.spelling);
if matches!(method_name.as_str(), "randomize" | "srandom") {
return Err(unsupported(
"overriding built-in class randomization methods",
));
}
// A method overriding a virtual method is virtual (8.20).
let is_virtual = method.qualifiers.is_virtual
|| methods
Expand Down Expand Up @@ -477,6 +530,8 @@ pub(super) fn class(
let class = Rc::new(Class {
name: name.to_owned(),
id: class_id(name),
has_constraints: declaration.has_constraints
|| base.as_ref().is_some_and(|base| base.has_constraints),
base: base.map(|base| base.name.clone()),
interfaces,
is_abstract: declaration.virtual_class,
Expand Down Expand Up @@ -561,6 +616,7 @@ fn interface_class(
interfaces,
is_abstract: true,
is_interface: true,
has_constraints: false,
properties: Vec::new(),
base_properties: 0,
statics: Vec::new(),
Expand Down
27 changes: 27 additions & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,33 @@ fn class_signatures(
context,
);
}
for method in ["randomize", "srandom"] {
let mut formals = vec![(
FunctionArgumentMetadata {
name: classes::THIS.into(),
direction: ParamDirection::Input,
has_default: false,
},
handle.clone(),
)];
if method == "srandom" {
formals.push((
FunctionArgumentMetadata {
name: "seed".into(),
direction: ParamDirection::Input,
has_default: false,
},
procedural::int_type(),
));
}
publish_signature(
classes::Class::subroutine_name(&class_name, method),
formals,
Some((method == "randomize").then(procedural::int_type)),
tree,
context,
);
}
if !constructor && !class.interface {
publish_signature(
classes::Class::subroutine_name(&class_name, "new"),
Expand Down
Loading
Loading