feat(vm): add VM-owned PCG64 random and coverage headroom
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
Implement GC-managed random generators, next/nextf intrinsics, bounded ranges and deterministic conformance coverage. Publish the runtime contract and producer guidance. Give coverage domains at least five percentage points of measured headroom while preserving sufficient floors. Record local qualification: make ci-domains passes with 939 tests and all domain gates green.
This commit is contained in:
@@ -83,6 +83,7 @@ pub enum BuiltinTypeShape {
|
||||
Scalar,
|
||||
Aggregate,
|
||||
Dynamic,
|
||||
Reference,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -137,13 +138,23 @@ impl BuiltinTypeMeta {
|
||||
// This context-free catalogue must never claim to validate it.
|
||||
return Err(BuiltinValueError::RegistryRequired);
|
||||
}
|
||||
if self.shape == BuiltinTypeShape::Reference {
|
||||
if values.len() != 1 {
|
||||
return Err(BuiltinValueError::ArityMismatch { expected: 1, got: values.len() });
|
||||
}
|
||||
return if matches!(values, [Value::Null]) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(BuiltinValueError::RegistryRequired)
|
||||
};
|
||||
}
|
||||
let layout = self.flatten_layout();
|
||||
validate_values_against_layout(values, &layout)
|
||||
}
|
||||
|
||||
fn flatten_into(&self, out: &mut Vec<AbiType>) {
|
||||
match self.shape {
|
||||
BuiltinTypeShape::Scalar | BuiltinTypeShape::Dynamic => {
|
||||
BuiltinTypeShape::Scalar | BuiltinTypeShape::Dynamic | BuiltinTypeShape::Reference => {
|
||||
out.extend_from_slice(self.flat_slot_layout)
|
||||
}
|
||||
BuiltinTypeShape::Aggregate => {
|
||||
@@ -216,9 +227,38 @@ pub enum BuiltinValueError {
|
||||
TypeMismatch { index: usize, expected: AbiType },
|
||||
}
|
||||
|
||||
pub type IntrinsicImplementation =
|
||||
pub type IntrinsicHostImplementation =
|
||||
fn(&[Value], &mut HostContext<'_>) -> Result<Vec<Value>, IntrinsicExecutionError>;
|
||||
|
||||
/// VM-owned operations cannot be invoked through a HostContext callback.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum IntrinsicImplementation {
|
||||
Host(IntrinsicHostImplementation),
|
||||
VmOwned,
|
||||
}
|
||||
impl IntrinsicImplementation {
|
||||
pub fn host_callback(self) -> Option<IntrinsicHostImplementation> {
|
||||
match self {
|
||||
Self::Host(f) => Some(f),
|
||||
Self::VmOwned => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IntrinsicCostModel {
|
||||
Fixed,
|
||||
RandomRejectionV1,
|
||||
}
|
||||
impl IntrinsicCostModel {
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Fixed => "fixed",
|
||||
Self::RandomRejectionV1 => "random_rejection_v1",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct IntrinsicMeta {
|
||||
pub id: u32,
|
||||
@@ -228,8 +268,12 @@ pub struct IntrinsicMeta {
|
||||
pub arg_layout: &'static [AbiType],
|
||||
pub ret_layout: &'static [AbiType],
|
||||
pub parameter_names: &'static [&'static str],
|
||||
/// Total virtual call cost; math attempts are charged before checks.
|
||||
/// Full fixed cost, or base cost for a variable model.
|
||||
pub cost_cycles: u64,
|
||||
pub cost_model: IntrinsicCostModel,
|
||||
pub attempt_cost_cycles: u64,
|
||||
pub max_attempts: u32,
|
||||
pub mutates_guest_state: bool,
|
||||
pub deterministic: bool,
|
||||
pub may_allocate: bool,
|
||||
pub implementation: IntrinsicImplementation,
|
||||
@@ -343,7 +387,7 @@ const PIXEL_FIELDS: [BuiltinFieldMeta; 3] = [
|
||||
},
|
||||
];
|
||||
|
||||
const BUILTIN_TYPES: [BuiltinTypeMeta; 9] = [
|
||||
const BUILTIN_TYPES: [BuiltinTypeMeta; 10] = [
|
||||
BuiltinTypeMeta {
|
||||
id: 0x0001,
|
||||
name: COLOR.name,
|
||||
@@ -371,6 +415,15 @@ const BUILTIN_TYPES: [BuiltinTypeMeta; 9] = [
|
||||
flat_slot_layout: &PIXEL_LAYOUT,
|
||||
flat_slot_width: 3,
|
||||
},
|
||||
BuiltinTypeMeta {
|
||||
id: 0x16,
|
||||
name: "Random",
|
||||
version: 1,
|
||||
shape: BuiltinTypeShape::Reference,
|
||||
fields: &[],
|
||||
flat_slot_layout: &[AbiType::Builtin(BuiltinTypeKey::new("Random", 1))],
|
||||
flat_slot_width: 1,
|
||||
},
|
||||
scalar_meta(0x10, "Int32", &[AbiType::Scalar(BuiltinScalarType::Int32)]),
|
||||
scalar_meta(0x11, "Int64", &[AbiType::Scalar(BuiltinScalarType::Int64)]),
|
||||
scalar_meta(0x12, "Float", &[AbiType::Scalar(BuiltinScalarType::Float)]),
|
||||
@@ -513,9 +566,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &SINGLE_FLOAT_RET,
|
||||
parameter_names: &["ax", "ay", "bx", "by"],
|
||||
cost_cycles: 10,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: vec2_dot,
|
||||
implementation: crate::IntrinsicImplementation::Host(vec2_dot),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1001,
|
||||
@@ -526,9 +583,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &SINGLE_FLOAT_RET,
|
||||
parameter_names: &["x", "y"],
|
||||
cost_cycles: 40,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: vec2_length,
|
||||
implementation: crate::IntrinsicImplementation::Host(vec2_length),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1100,
|
||||
@@ -539,9 +600,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["raw"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_from_raw,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_from_raw),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1101,
|
||||
@@ -552,9 +617,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["r", "g", "b"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_rgb,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_rgb),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1102,
|
||||
@@ -565,9 +634,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["r", "g", "b", "a"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_rgba,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_rgba),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1103,
|
||||
@@ -578,9 +651,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["value"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_html_rgba,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_html_rgba),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1104,
|
||||
@@ -591,9 +668,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["value"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_gray_scale,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_gray_scale),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1105,
|
||||
@@ -604,9 +685,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &INT_RET,
|
||||
parameter_names: &["color"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_hex,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_hex),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1106,
|
||||
@@ -617,9 +702,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &INT_RET,
|
||||
parameter_names: &["color"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_alpha,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_alpha),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1120,
|
||||
@@ -630,9 +719,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_black,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_black),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1121,
|
||||
@@ -643,9 +736,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_white,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_white),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1122,
|
||||
@@ -656,9 +753,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_red,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_red),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1123,
|
||||
@@ -669,9 +770,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_green,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_green),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1124,
|
||||
@@ -682,9 +787,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_blue,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_blue),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1125,
|
||||
@@ -695,9 +804,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_yellow,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_yellow),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1126,
|
||||
@@ -708,9 +821,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_orange,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_orange),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1127,
|
||||
@@ -721,9 +838,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_indigo,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_indigo),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1128,
|
||||
@@ -734,9 +855,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_gray,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_gray),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x1129,
|
||||
@@ -747,9 +872,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_cyan,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_cyan),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x112A,
|
||||
@@ -760,9 +889,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_magenta,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_magenta),
|
||||
},
|
||||
IntrinsicMeta {
|
||||
id: 0x112B,
|
||||
@@ -773,9 +906,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: color_transparent,
|
||||
implementation: crate::IntrinsicImplementation::Host(color_transparent),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -806,6 +943,7 @@ pub fn lookup_intrinsic(owner: &str, name: &str, version: u16) -> Option<&'stati
|
||||
.iter()
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
.find(|meta| meta.owner == owner && meta.name == name && meta.version == version)
|
||||
}
|
||||
|
||||
@@ -814,6 +952,7 @@ pub fn lookup_intrinsic_by_id(id: u32) -> Option<&'static IntrinsicMeta> {
|
||||
.iter()
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
.find(|meta| meta.id == id)
|
||||
}
|
||||
|
||||
@@ -877,6 +1016,9 @@ fn value_matches_abi_type(value: &Value, expected: AbiType) -> bool {
|
||||
AbiType::Scalar(BuiltinScalarType::String) => {
|
||||
matches!(value, Value::String(_) | Value::Null)
|
||||
}
|
||||
AbiType::Builtin(key) if key.name == "Random" && key.version == 1 => {
|
||||
matches!(value, Value::HeapRef(_) | Value::Null)
|
||||
}
|
||||
AbiType::Builtin(key) if key == COLOR => {
|
||||
matches!(value, Value::Int64(raw) if u32::try_from(*raw).is_ok())
|
||||
}
|
||||
@@ -1111,6 +1253,7 @@ pub(crate) fn metered_lookup_intrinsic(
|
||||
.iter()
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
{
|
||||
budget.work(1)?;
|
||||
if meta.id == id {
|
||||
@@ -1226,7 +1369,7 @@ mod tests {
|
||||
fn intrinsic_implementations_are_registered_without_syscalls() {
|
||||
let dot = lookup_intrinsic("vec2", "dot", 1).expect("vec2.dot must exist");
|
||||
let mut ctx = HostContext::new(None);
|
||||
let result = (dot.implementation)(
|
||||
let result = (dot.implementation.host_callback().expect("host intrinsic"))(
|
||||
&[Value::Float(1.0), Value::Float(2.0), Value::Float(3.0), Value::Float(4.0)],
|
||||
&mut ctx,
|
||||
)
|
||||
@@ -1234,8 +1377,11 @@ mod tests {
|
||||
assert_eq!(result, vec![Value::Float(11.0)]);
|
||||
|
||||
let length = lookup_intrinsic("vec2", "length", 1).expect("vec2.length must exist");
|
||||
let result = (length.implementation)(&[Value::Float(3.0), Value::Float(4.0)], &mut ctx)
|
||||
.expect("length implementation must execute");
|
||||
let result = (length.implementation.host_callback().expect("host intrinsic"))(
|
||||
&[Value::Float(3.0), Value::Float(4.0)],
|
||||
&mut ctx,
|
||||
)
|
||||
.expect("length implementation must execute");
|
||||
assert_eq!(result, vec![Value::Float(5.0)]);
|
||||
}
|
||||
|
||||
@@ -1244,7 +1390,7 @@ mod tests {
|
||||
let mut ctx = HostContext::new(None);
|
||||
|
||||
let rgba = lookup_intrinsic("color", "rgba", 1).expect("color.rgba must exist");
|
||||
let result = (rgba.implementation)(
|
||||
let result = (rgba.implementation.host_callback().expect("host intrinsic"))(
|
||||
&[Value::Int64(0x11), Value::Int64(0x22), Value::Int64(0x33), Value::Int64(0x44)],
|
||||
&mut ctx,
|
||||
)
|
||||
@@ -1252,13 +1398,19 @@ mod tests {
|
||||
assert_eq!(result, vec![Value::Int64(0x11223344)]);
|
||||
|
||||
let html = lookup_intrinsic("color", "html_rgba", 1).expect("color.html_rgba must exist");
|
||||
let result = (html.implementation)(&[Value::String("#AABBCCDD".into())], &mut ctx)
|
||||
.expect("html_rgba implementation must execute");
|
||||
let result = (html.implementation.host_callback().expect("host intrinsic"))(
|
||||
&[Value::String("#AABBCCDD".into())],
|
||||
&mut ctx,
|
||||
)
|
||||
.expect("html_rgba implementation must execute");
|
||||
assert_eq!(result, vec![Value::Int64(0xAABBCCDD)]);
|
||||
|
||||
let alpha = lookup_intrinsic("color", "alpha", 1).expect("color.alpha must exist");
|
||||
let result = (alpha.implementation)(&[Value::Int64(0xAABBCCDD)], &mut ctx)
|
||||
.expect("alpha implementation must execute");
|
||||
let result = (alpha.implementation.host_callback().expect("host intrinsic"))(
|
||||
&[Value::Int64(0xAABBCCDD)],
|
||||
&mut ctx,
|
||||
)
|
||||
.expect("alpha implementation must execute");
|
||||
assert_eq!(result, vec![Value::Int64(0xDD)]);
|
||||
}
|
||||
|
||||
@@ -1266,7 +1418,7 @@ mod tests {
|
||||
fn input_intrinsic_requires_hardware_context() {
|
||||
let mut ctx = HostContext::new(None);
|
||||
let touch_x = lookup_intrinsic("input.touch", "x", 1).expect("input.touch.x must exist");
|
||||
let err = (touch_x.implementation)(&[], &mut ctx)
|
||||
let err = (touch_x.implementation.host_callback().expect("host intrinsic"))(&[], &mut ctx)
|
||||
.expect_err("touch.x must fail without hardware context");
|
||||
assert_eq!(err, IntrinsicExecutionError::HardwareUnavailable);
|
||||
}
|
||||
@@ -1287,6 +1439,7 @@ pub fn intrinsic_catalog() -> impl Iterator<Item = &'static IntrinsicMeta> {
|
||||
.iter()
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
}
|
||||
pub fn builtin_constant_catalog() -> impl Iterator<Item = &'static BuiltinConstMeta> {
|
||||
BUILTIN_CONSTS.iter()
|
||||
|
||||
@@ -16,14 +16,14 @@ fn atom(t: AbiType) -> String {
|
||||
}
|
||||
pub fn intrinsic_catalog_csv() -> String {
|
||||
let mut out = String::from(
|
||||
"final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles\n",
|
||||
"final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles,mutates_guest_state,cost_model,attempt_cost_cycles,max_attempts\n",
|
||||
);
|
||||
let mut entries: Vec<_> = intrinsic_catalog().collect();
|
||||
entries.sort_by_key(|m| m.id);
|
||||
for m in entries {
|
||||
writeln!(
|
||||
&mut out,
|
||||
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{}",
|
||||
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}",
|
||||
m.id,
|
||||
m.id,
|
||||
m.owner,
|
||||
@@ -38,7 +38,11 @@ pub fn intrinsic_catalog_csv() -> String {
|
||||
m.deterministic,
|
||||
m.may_allocate,
|
||||
m.parameter_names.join("|"),
|
||||
m.cost_cycles
|
||||
m.cost_cycles,
|
||||
m.mutates_guest_state,
|
||||
m.cost_model.name(),
|
||||
m.attempt_cost_cycles,
|
||||
m.max_attempts
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
mod dynamic_box;
|
||||
mod random;
|
||||
use crate::object::{ObjectHeader, ObjectKind};
|
||||
use crate::resource_budget::{
|
||||
BudgetVec, Reservation, ResourceFailure, ResourceReason, RuntimeBudget, RuntimeResource as Q,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Quota-accounted opaque leaf payload and infallible state publication.
|
||||
use super::*;
|
||||
use crate::random::{INCREMENT, Pcg64};
|
||||
|
||||
impl Heap {
|
||||
pub(crate) fn allocate_random(&mut self, seed: i64) -> Result<HeapRef, ResourceFailure> {
|
||||
let prepared = self.prepare_insertion()?;
|
||||
let mut payload = BudgetVec::new(&self.budget, Q::GuestBytes);
|
||||
payload.reserve(32)?;
|
||||
let state = Pcg64::new(seed);
|
||||
payload.extend_from_slice(&state.state.to_le_bytes()).expect("reserved random state");
|
||||
payload.extend_from_slice(&state.inc.to_le_bytes()).expect("reserved random increment");
|
||||
Ok(self.commit_insertion(
|
||||
prepared,
|
||||
StoredObject {
|
||||
header: ObjectHeader::new(ObjectKind::Random, 32),
|
||||
payload,
|
||||
array_elems: None,
|
||||
closure_env: None,
|
||||
typed: None,
|
||||
dynamic_box: None,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn random_state(&self, r: HeapRef) -> Result<Pcg64, ValueError> {
|
||||
if !self.is_valid(r) {
|
||||
return Err(ValueError::InvalidHandle);
|
||||
}
|
||||
let obj = self.objects[r.index as usize].as_ref().unwrap();
|
||||
if obj.header.kind != ObjectKind::Random || obj.payload.len() != 32 {
|
||||
return Err(ValueError::Type);
|
||||
}
|
||||
let state = u128::from_le_bytes(obj.payload[..16].try_into().unwrap());
|
||||
let inc = u128::from_le_bytes(obj.payload[16..].try_into().unwrap());
|
||||
if inc != INCREMENT {
|
||||
return Err(ValueError::Type);
|
||||
}
|
||||
Ok(Pcg64 { state, inc })
|
||||
}
|
||||
|
||||
/// Caller validated this handle and retained its roots, with no intervening
|
||||
/// safepoint. Mutation is fixed-width and cannot allocate or fail.
|
||||
pub(crate) fn commit_random(&mut self, r: HeapRef, state: Pcg64) {
|
||||
let obj = self.objects[r.index as usize].as_mut().expect("validated random object");
|
||||
obj.payload[..16].copy_from_slice(&state.state.to_le_bytes());
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ const fn query(
|
||||
owner: &'static str,
|
||||
name: &'static str,
|
||||
ret_layout: &'static [AbiType],
|
||||
implementation: crate::IntrinsicImplementation,
|
||||
implementation: crate::IntrinsicHostImplementation,
|
||||
) -> IntrinsicMeta {
|
||||
IntrinsicMeta {
|
||||
id,
|
||||
@@ -23,9 +23,13 @@ const fn query(
|
||||
ret_layout,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation,
|
||||
implementation: crate::IntrinsicImplementation::Host(implementation),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ mod call_frame;
|
||||
mod input_intrinsics;
|
||||
mod math_intrinsics;
|
||||
mod numeric;
|
||||
mod random;
|
||||
mod random_intrinsics;
|
||||
pub use numeric::NumericError;
|
||||
mod local_addressing;
|
||||
// Keep the verifier internal in production builds, but expose it for integration tests
|
||||
@@ -38,10 +40,10 @@ mod vm_init_error;
|
||||
pub use builtins::{
|
||||
AbiType, BuiltinConstKey, BuiltinConstMaterializer, BuiltinConstMeta, BuiltinConstSlotValue,
|
||||
BuiltinFieldMeta, BuiltinLayoutType, BuiltinScalarType, BuiltinTypeKey, BuiltinTypeMeta,
|
||||
BuiltinTypeShape, BuiltinValueError, IntrinsicExecutionError, IntrinsicImplementation,
|
||||
IntrinsicKey, IntrinsicMeta, builtin_constant_catalog, intrinsic_catalog,
|
||||
lookup_builtin_constant, lookup_builtin_type, lookup_intrinsic, lookup_intrinsic_by_id,
|
||||
materialize_builtin_constant,
|
||||
BuiltinTypeShape, BuiltinValueError, IntrinsicCostModel, IntrinsicExecutionError,
|
||||
IntrinsicHostImplementation, IntrinsicImplementation, IntrinsicKey, IntrinsicMeta,
|
||||
builtin_constant_catalog, intrinsic_catalog, lookup_builtin_constant, lookup_builtin_type,
|
||||
lookup_intrinsic, lookup_intrinsic_by_id, materialize_builtin_constant,
|
||||
};
|
||||
pub use prometeu_hal::{HostContext, HostReturn, NativeInterface, SyscallId};
|
||||
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
|
||||
|
||||
@@ -23,9 +23,13 @@ const fn entry<const ID: u32>(
|
||||
ret_layout,
|
||||
parameter_names,
|
||||
cost_cycles,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: execute::<ID>,
|
||||
implementation: crate::IntrinsicImplementation::Host(execute::<ID>),
|
||||
}
|
||||
}
|
||||
pub(crate) const MATH_INTRINSICS: [IntrinsicMeta; 26] = [
|
||||
|
||||
@@ -86,6 +86,9 @@ pub enum ObjectKind {
|
||||
|
||||
/// Internal immutable multi-slot Dynamic payload, never a nominal guest type.
|
||||
DynamicBox = 8,
|
||||
|
||||
/// Opaque PCG64 generator, with no transitive references.
|
||||
Random = 9,
|
||||
// Future kinds must be appended here to keep tag numbers stable.
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! PCG-XSL-RR 128/64 setseq. No host entropy or floating arithmetic.
|
||||
use crate::numeric;
|
||||
use prometeu_bytecode::TRAP_RANDOM_REJECTION_LIMIT;
|
||||
|
||||
const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645;
|
||||
pub(crate) const INCREMENT: u128 = 109;
|
||||
pub(crate) const MAX_ATTEMPTS: u32 = 64;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct Pcg64 {
|
||||
pub state: u128,
|
||||
pub inc: u128,
|
||||
}
|
||||
impl Pcg64 {
|
||||
pub fn new(seed: i64) -> Self {
|
||||
let bits = u128::from(seed as u64);
|
||||
Self {
|
||||
state: bits.wrapping_add(INCREMENT).wrapping_mul(MULTIPLIER).wrapping_add(INCREMENT),
|
||||
inc: INCREMENT,
|
||||
}
|
||||
}
|
||||
pub fn next(&mut self) -> u64 {
|
||||
self.state = self.state.wrapping_mul(MULTIPLIER).wrapping_add(self.inc);
|
||||
let x = self.state as u64 ^ (self.state >> 64) as u64;
|
||||
x.rotate_right((self.state >> 122) as u32)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn float_word(word: u64) -> f64 {
|
||||
// k <= 2^53-1 is exactly representable; dividing by 2^53 is exact.
|
||||
numeric::div(numeric::from_i64((word >> 11) as i64), f64::from_bits(0x4340_0000_0000_0000))
|
||||
.expect("finite exact random grid division")
|
||||
}
|
||||
|
||||
/// Bounds were checked by the VM before reservations. The callback performs
|
||||
/// one charged candidate draw. It can be injected only inside private tests.
|
||||
pub(crate) fn bounded(min: i64, max: i64, mut draw: impl FnMut() -> u64) -> Result<i64, u32> {
|
||||
debug_assert!(min < max);
|
||||
let n = (i128::from(max) - i128::from(min)) as u64;
|
||||
let threshold = n.wrapping_neg() % n;
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let word = draw();
|
||||
if word >= threshold {
|
||||
return Ok((i128::from(min) + i128::from(word % n)) as i64);
|
||||
}
|
||||
}
|
||||
Err(TRAP_RANDOM_REJECTION_LIMIT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zero_rotation_state_and_float_endpoints() {
|
||||
let mut p = Pcg64 { state: 0, inc: INCREMENT };
|
||||
assert_eq!(p.next(), 109);
|
||||
assert_eq!(float_word(0).to_bits(), 0);
|
||||
assert_eq!(float_word(u64::MAX).to_bits(), 0x3fef_ffff_ffff_ffff);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threshold_boundaries_full_width_and_unit_consumption() {
|
||||
for (min, max) in [(0, 1), (-3, 3), (i64::MIN, i64::MAX), (-1, i64::MAX)] {
|
||||
let n = (i128::from(max) - i128::from(min)) as u64;
|
||||
let threshold = n.wrapping_neg() % n;
|
||||
let mut attempts = 0;
|
||||
let value = bounded(min, max, || {
|
||||
attempts += 1;
|
||||
if attempts == 1 && threshold > 0 { threshold - 1 } else { threshold }
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(attempts, if threshold > 0 { 2 } else { 1 });
|
||||
assert_eq!(value, (i128::from(min) + i128::from(threshold % n)) as i64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixty_fourth_success_and_cap_are_distinct() {
|
||||
let mut n = 0;
|
||||
assert_eq!(
|
||||
bounded(0, 3, || {
|
||||
n += 1;
|
||||
if n == 64 { 1 } else { 0 }
|
||||
}),
|
||||
Ok(1)
|
||||
);
|
||||
assert_eq!(n, 64);
|
||||
n = 0;
|
||||
assert_eq!(
|
||||
bounded(0, 3, || {
|
||||
n += 1;
|
||||
0
|
||||
}),
|
||||
Err(TRAP_RANDOM_REJECTION_LIMIT)
|
||||
);
|
||||
assert_eq!(n, 64);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! The shared catalog owns IDs, layouts, effects and charging descriptors.
|
||||
use crate::{
|
||||
AbiType, BuiltinScalarType, BuiltinTypeKey, IntrinsicCostModel, IntrinsicImplementation,
|
||||
IntrinsicMeta,
|
||||
};
|
||||
const I64: AbiType = AbiType::Scalar(BuiltinScalarType::Int64);
|
||||
const FLOAT: AbiType = AbiType::Scalar(BuiltinScalarType::Float);
|
||||
const RANDOM: AbiType = AbiType::Builtin(BuiltinTypeKey::new("Random", 1));
|
||||
const fn entry(
|
||||
id: u32,
|
||||
name: &'static str,
|
||||
args: &'static [AbiType],
|
||||
ret: &'static [AbiType],
|
||||
names: &'static [&'static str],
|
||||
cost: u64,
|
||||
) -> IntrinsicMeta {
|
||||
let rejection = id == 0x4003;
|
||||
IntrinsicMeta {
|
||||
id,
|
||||
owner: "random",
|
||||
name,
|
||||
version: 1,
|
||||
arg_layout: args,
|
||||
ret_layout: ret,
|
||||
parameter_names: names,
|
||||
cost_cycles: cost,
|
||||
cost_model: if rejection {
|
||||
IntrinsicCostModel::RandomRejectionV1
|
||||
} else {
|
||||
IntrinsicCostModel::Fixed
|
||||
},
|
||||
attempt_cost_cycles: if rejection { 8 } else { 0 },
|
||||
max_attempts: if rejection { crate::random::MAX_ATTEMPTS } else { 0 },
|
||||
deterministic: true,
|
||||
mutates_guest_state: true,
|
||||
may_allocate: id == 0x4000,
|
||||
implementation: IntrinsicImplementation::VmOwned,
|
||||
}
|
||||
}
|
||||
pub(crate) const RANDOM_INTRINSICS: [IntrinsicMeta; 4] = [
|
||||
entry(0x4000, "new", &[I64], &[RANDOM], &["seed"], 32),
|
||||
entry(0x4001, "next", &[RANDOM], &[I64], &["rng"], 8),
|
||||
entry(0x4002, "nextf", &[RANDOM], &[FLOAT], &["rng"], 12),
|
||||
entry(0x4003, "range", &[RANDOM, I64, I64], &[I64], &["rng", "min", "max"], 4),
|
||||
];
|
||||
@@ -204,6 +204,7 @@ fn component(registry: &Registry, ty: TypeId, part: u32, budget: &mut LoadBudget
|
||||
TypeKind::Builtin(B::FLOAT | B::VEC2) => FLOAT,
|
||||
TypeKind::Builtin(B::BOOL) => BOOL,
|
||||
TypeKind::Builtin(B::STRING) => STRING | NULL,
|
||||
TypeKind::Builtin(B::RANDOM) => REFERENCE | NULL,
|
||||
TypeKind::Builtin(B::DYNAMIC) => {
|
||||
if part == 0 {
|
||||
I64 | NULL
|
||||
@@ -558,6 +559,7 @@ fn abi_mask(abi: AbiType) -> u8 {
|
||||
AbiType::Scalar(BuiltinScalarType::Bool) => BOOL,
|
||||
AbiType::Scalar(BuiltinScalarType::String) => STRING,
|
||||
AbiType::Builtin(key) if key.name == "color" => I64,
|
||||
AbiType::Builtin(key) if key.name == "Random" => REFERENCE | NULL,
|
||||
AbiType::DynamicTag => I64 | NULL,
|
||||
_ => ANY,
|
||||
}
|
||||
|
||||
@@ -103,9 +103,10 @@ impl TypedStorage {
|
||||
// until every native value is constructed. Count advances only after init.
|
||||
unsafe {
|
||||
match self.registry.declarations().types[ty.0 as usize].kind {
|
||||
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_) => {
|
||||
self.data.init(offset, HeapRef::NULL)
|
||||
}
|
||||
TypeKind::Struct(_)
|
||||
| TypeKind::Array(_)
|
||||
| TypeKind::Fn(_)
|
||||
| TypeKind::Builtin(B::RANDOM) => self.data.init(offset, HeapRef::NULL),
|
||||
TypeKind::Trait(_) => self.data.init(
|
||||
offset,
|
||||
TraitSlot { receiver: HeapRef::NULL, implementation: 0, padding: 0 },
|
||||
@@ -135,7 +136,10 @@ impl TypedStorage {
|
||||
// immutable Registry. Only matching typed writes can change its contents.
|
||||
let result = unsafe {
|
||||
match self.registry.declarations().types[ty.0 as usize].kind {
|
||||
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_) => {
|
||||
TypeKind::Struct(_)
|
||||
| TypeKind::Array(_)
|
||||
| TypeKind::Fn(_)
|
||||
| TypeKind::Builtin(B::RANDOM) => {
|
||||
let r = *self.data.get::<HeapRef>(offset);
|
||||
ValueGroup::new(&[if r.is_null() { Value::Null } else { Value::HeapRef(r) }])
|
||||
}
|
||||
@@ -205,11 +209,18 @@ impl TypedStorage {
|
||||
// &mut self gives exclusive access. Native assignment drops exactly once.
|
||||
unsafe {
|
||||
match (&self.registry.declarations().types[ty.0 as usize].kind, values) {
|
||||
(TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_), [Value::Null]) => {
|
||||
self.data.replace(offset, HeapRef::NULL)
|
||||
}
|
||||
(
|
||||
TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Fn(_),
|
||||
TypeKind::Struct(_)
|
||||
| TypeKind::Array(_)
|
||||
| TypeKind::Fn(_)
|
||||
| TypeKind::Builtin(B::RANDOM),
|
||||
[Value::Null],
|
||||
) => self.data.replace(offset, HeapRef::NULL),
|
||||
(
|
||||
TypeKind::Struct(_)
|
||||
| TypeKind::Array(_)
|
||||
| TypeKind::Fn(_)
|
||||
| TypeKind::Builtin(B::RANDOM),
|
||||
[Value::HeapRef(r)],
|
||||
) => self.data.replace(offset, *r),
|
||||
(TypeKind::Trait(_), [Value::Null, Value::Null]) => self.data.replace(
|
||||
|
||||
@@ -68,6 +68,14 @@ pub(crate) fn validate(
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
TypeKind::Builtin(B::RANDOM) => match &values[0] {
|
||||
Value::Null => true,
|
||||
Value::HeapRef(r) => {
|
||||
heap.random_state(*r)?;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
TypeKind::Fn(_) => match &values[0] {
|
||||
Value::Null => true,
|
||||
Value::HeapRef(r) if !r.is_null() => heap.closure_type(*r)? == type_id,
|
||||
|
||||
@@ -8,6 +8,7 @@ mod control;
|
||||
mod dynamic;
|
||||
mod gc;
|
||||
mod loader;
|
||||
mod random;
|
||||
mod reference;
|
||||
mod runtime;
|
||||
mod stack;
|
||||
@@ -892,6 +893,10 @@ impl VirtualMachine {
|
||||
)
|
||||
})?;
|
||||
|
||||
if matches!(intrinsic.implementation, crate::IntrinsicImplementation::VmOwned) {
|
||||
return self.execute_random(intrinsic, pc_at_intrinsic);
|
||||
}
|
||||
|
||||
let args_count = intrinsic.arg_slots();
|
||||
let mut args = BudgetVec::new(&self.budget, RuntimeResource::TemporaryBytes);
|
||||
args.reserve(args_count)
|
||||
@@ -923,7 +928,11 @@ impl VirtualMachine {
|
||||
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
||||
let results = intrinsic
|
||||
.validate_argument_values(&args)
|
||||
.and_then(|()| (intrinsic.implementation)(&args, ctx))
|
||||
.and_then(|()| {
|
||||
(intrinsic.implementation.host_callback().expect("host intrinsic"))(
|
||||
&args, ctx,
|
||||
)
|
||||
})
|
||||
.map_err(|err| match err {
|
||||
crate::IntrinsicExecutionError::ArityMismatch { expected, got } => self
|
||||
.trap(
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
//! Validate/reserve/stage/commit while retaining source operands and roots.
|
||||
use super::*;
|
||||
use crate::random::{self, Pcg64};
|
||||
use crate::value_contract::ValueError;
|
||||
|
||||
impl VirtualMachine {
|
||||
pub(super) fn execute_random(
|
||||
&mut self,
|
||||
meta: &crate::IntrinsicMeta,
|
||||
pc: u32,
|
||||
) -> Result<(), LogicalFrameEndingReason> {
|
||||
self.execute_random_with(meta, pc, Pcg64::next)
|
||||
}
|
||||
|
||||
fn execute_random_with(
|
||||
&mut self,
|
||||
meta: &crate::IntrinsicMeta,
|
||||
pc: u32,
|
||||
mut draw: impl FnMut(&mut Pcg64) -> u64,
|
||||
) -> Result<(), LogicalFrameEndingReason> {
|
||||
let op = OpCode::Intrinsic;
|
||||
self.cycles += meta.cost_cycles;
|
||||
let consumed = meta.arg_slots();
|
||||
if self.temporary_slots() < consumed {
|
||||
return Err(self.trap(
|
||||
TRAP_STACK_UNDERFLOW,
|
||||
op as u16,
|
||||
"Incomplete random operands".into(),
|
||||
pc,
|
||||
));
|
||||
}
|
||||
let base = self.operand_stack.len() - consumed;
|
||||
meta.validate_argument_values(&self.operand_stack[base..])
|
||||
.map_err(|_| self.value_trap(ValueError::Type, op, pc))?;
|
||||
let receiver = if meta.id != 0x4000 {
|
||||
match self.operand_stack[base] {
|
||||
Value::Null => return Err(self.value_trap(ValueError::NullReference, op, pc)),
|
||||
Value::HeapRef(r) => Some(r),
|
||||
_ => unreachable!("checked random carrier"),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut candidate = receiver
|
||||
.map(|r| self.heap.random_state(r))
|
||||
.transpose()
|
||||
.map_err(|e| self.value_trap(e, op, pc))?;
|
||||
let bounds = if meta.id == 0x4003 {
|
||||
let (Value::Int64(min), Value::Int64(max)) =
|
||||
(&self.operand_stack[base + 1], &self.operand_stack[base + 2])
|
||||
else {
|
||||
unreachable!("checked integer carriers")
|
||||
};
|
||||
if min >= max {
|
||||
return Err(self.trap(
|
||||
prometeu_bytecode::TRAP_NUMERIC_DOMAIN,
|
||||
op as u16,
|
||||
"random.range requires min < max".into(),
|
||||
pc,
|
||||
));
|
||||
}
|
||||
Some((*min, *max))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let growth = self
|
||||
.operand_stack
|
||||
.prepare_growth(meta.ret_slots().saturating_sub(consumed))
|
||||
.map_err(|e| self.resource_trap(e, op, pc))?;
|
||||
let _result_charge = self
|
||||
.budget
|
||||
.reserve(
|
||||
RuntimeResource::TemporaryBytes,
|
||||
self.budget
|
||||
.bytes::<Value>(1, RuntimeResource::TemporaryBytes)
|
||||
.map_err(|e| self.resource_trap(e, op, pc))?,
|
||||
)
|
||||
.map_err(|e| self.resource_trap(e, op, pc))?;
|
||||
let result = match meta.id {
|
||||
0x4000 => {
|
||||
let Value::Int64(seed) = self.operand_stack[base] else {
|
||||
unreachable!("checked seed carrier")
|
||||
};
|
||||
Value::HeapRef(
|
||||
self.heap.allocate_random(seed).map_err(|e| self.resource_trap(e, op, pc))?,
|
||||
)
|
||||
}
|
||||
0x4001 => Value::Int64(draw(candidate.as_mut().unwrap()) as i64),
|
||||
0x4002 => Value::Float(random::float_word(draw(candidate.as_mut().unwrap()))),
|
||||
0x4003 => {
|
||||
let (min, max) = bounds.unwrap();
|
||||
let value = random::bounded(min, max, || {
|
||||
self.cycles += meta.attempt_cost_cycles;
|
||||
draw(candidate.as_mut().unwrap())
|
||||
})
|
||||
.map_err(|code| {
|
||||
self.trap(code, op as u16, "Random rejection limit reached".into(), pc)
|
||||
})?;
|
||||
Value::Int64(value)
|
||||
}
|
||||
_ => unreachable!("shared catalog VM-owned identity"),
|
||||
};
|
||||
// All fallible work finished. Source roots remained live throughout.
|
||||
if let Some(r) = receiver {
|
||||
self.heap.commit_random(r, candidate.unwrap());
|
||||
}
|
||||
self.operand_stack.commit_growth(growth);
|
||||
self.operand_stack.truncate(base);
|
||||
self.operand_stack.push(result).expect("reserved random result slot");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../../tests/support/random.rs"]
|
||||
mod support;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::ObjectKind;
|
||||
use crate::random::MAX_ATTEMPTS;
|
||||
use prometeu_bytecode::registry::TypeId;
|
||||
use prometeu_bytecode::{TRAP_NUMERIC_DOMAIN, TRAP_RANDOM_REJECTION_LIMIT, assemble};
|
||||
use support::{Native, run, sig, step, vm};
|
||||
|
||||
fn trap_code(r: &LogicalFrameEndingReason) -> u32 {
|
||||
let LogicalFrameEndingReason::Trap(t) = r else { panic!("{r:?}") };
|
||||
t.code
|
||||
}
|
||||
fn fault_vm(id: u32, args: &[Value]) -> VirtualMachine {
|
||||
let mut v =
|
||||
VirtualMachine::fault_session(assemble(&format!("INTRINSIC {id}")).unwrap(), vec![]);
|
||||
v.operand_stack.extend_from_slice(args).unwrap();
|
||||
v
|
||||
}
|
||||
fn charges(v: &VirtualMachine) -> Vec<u64> {
|
||||
[
|
||||
RuntimeResource::GuestBytes,
|
||||
RuntimeResource::HandleSlots,
|
||||
RuntimeResource::AuxiliaryBytes,
|
||||
RuntimeResource::TemporaryBytes,
|
||||
]
|
||||
.iter()
|
||||
.map(|&q| v.budget.used(q))
|
||||
.collect()
|
||||
}
|
||||
#[test]
|
||||
fn carrier_receiver_bounds_precedence_and_all_faults_retain_sources() {
|
||||
for id in [0x4001, 0x4002, 0x4003] {
|
||||
for case in 0..9 {
|
||||
let mut v = fault_vm(id, &[]);
|
||||
let live = v.heap.allocate_random(42).unwrap();
|
||||
let wrong = v.heap.allocate_object(ObjectKind::Bytes, &[]).unwrap();
|
||||
let (receiver, lo, hi, code) = match case {
|
||||
0 => (Value::Boolean(false), Value::Int64(1), Value::Int64(2), TRAP_TYPE),
|
||||
1 => (
|
||||
Value::Null,
|
||||
Value::Int32(1),
|
||||
Value::Int64(2),
|
||||
if id == 0x4003 { TRAP_TYPE } else { TRAP_NULL_REFERENCE },
|
||||
),
|
||||
2 => (
|
||||
Value::HeapRef(HeapRef { index: 99, generation: 1 }),
|
||||
Value::Int64(2),
|
||||
Value::Int64(1),
|
||||
TRAP_INVALID_HANDLE,
|
||||
),
|
||||
3 => (
|
||||
Value::HeapRef(HeapRef {
|
||||
index: live.index,
|
||||
generation: live.generation + 1,
|
||||
}),
|
||||
Value::Int64(1),
|
||||
Value::Int64(2),
|
||||
TRAP_INVALID_HANDLE,
|
||||
),
|
||||
4 => (
|
||||
Value::HeapRef(HeapRef::NULL),
|
||||
Value::Int64(1),
|
||||
Value::Int64(2),
|
||||
TRAP_INVALID_HANDLE,
|
||||
),
|
||||
5 => (Value::HeapRef(wrong), Value::Int64(2), Value::Int64(1), TRAP_TYPE),
|
||||
6 => (Value::Null, Value::Int64(2), Value::Int64(1), TRAP_NULL_REFERENCE),
|
||||
7 => (
|
||||
Value::HeapRef(live),
|
||||
Value::Int64(2),
|
||||
Value::Int64(1),
|
||||
TRAP_NUMERIC_DOMAIN,
|
||||
),
|
||||
_ => (Value::HeapRef(live), Value::Int64(1), Value::Boolean(false), TRAP_TYPE),
|
||||
};
|
||||
if id != 0x4003 && case >= 7 {
|
||||
continue;
|
||||
}
|
||||
let mut args = vec![receiver];
|
||||
if id == 0x4003 {
|
||||
args.extend([lo, hi]);
|
||||
}
|
||||
v.operand_stack.extend_from_slice(&args).unwrap();
|
||||
let state = v.heap.random_state(live).unwrap();
|
||||
let ownership = charges(&v);
|
||||
let r = v.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(trap_code(&r.reason), code, "id={id}, case={case}");
|
||||
assert_eq!(
|
||||
(r.cycles_used, r.steps_executed),
|
||||
(
|
||||
if id == 0x4001 {
|
||||
8
|
||||
} else if id == 0x4002 {
|
||||
12
|
||||
} else {
|
||||
4
|
||||
},
|
||||
0
|
||||
)
|
||||
);
|
||||
assert_eq!(v.operand_stack.as_slice(), args);
|
||||
assert_eq!(v.heap.random_state(live).unwrap(), state);
|
||||
assert_eq!(charges(&v), ownership);
|
||||
let LogicalFrameEndingReason::Trap(t) = r.reason else { unreachable!() };
|
||||
assert_eq!((t.pc, t.opcode), (0, OpCode::Intrinsic as u16));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn short_stack_and_seed_carriers_charge_without_consumption() {
|
||||
for id in 0x4000..=0x4003 {
|
||||
let mut v = fault_vm(id, &[]);
|
||||
let r = run(&mut v, 1);
|
||||
assert_eq!(trap_code(&r.reason), TRAP_STACK_UNDERFLOW);
|
||||
assert_eq!(r.steps_executed, 0);
|
||||
assert_eq!(r.cycles_used, crate::lookup_intrinsic_by_id(id).unwrap().cost_cycles);
|
||||
}
|
||||
for seed in [Value::Null, Value::Int32(42), Value::Float(42.)] {
|
||||
let mut v = fault_vm(0x4000, std::slice::from_ref(&seed));
|
||||
let r = run(&mut v, 1);
|
||||
assert_eq!(trap_code(&r.reason), TRAP_TYPE);
|
||||
assert_eq!(v.operand_stack.as_slice(), &[seed]);
|
||||
assert_eq!(v.heap.len(), 0);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn synthetic_rejections_use_real_transaction_cost_and_rollback() {
|
||||
for accept in [None, Some(1), Some(3), Some(MAX_ATTEMPTS)] {
|
||||
let mut v = fault_vm(0x4003, &[]);
|
||||
let r = v.heap.allocate_random(42).unwrap();
|
||||
let args = [Value::HeapRef(r), Value::Int64(0), Value::Int64(3)];
|
||||
v.operand_stack.extend_from_slice(&args).unwrap();
|
||||
let original = v.heap.random_state(r).unwrap();
|
||||
let owned = charges(&v);
|
||||
let mut attempts = 0;
|
||||
let result =
|
||||
v.execute_random_with(crate::lookup_intrinsic_by_id(0x4003).unwrap(), 0, |state| {
|
||||
attempts += 1;
|
||||
state.next();
|
||||
if Some(attempts) == accept { 1 } else { 0 }
|
||||
});
|
||||
assert_eq!(v.cycles, 4 + 8 * u64::from(attempts));
|
||||
assert_eq!(attempts, accept.unwrap_or(64));
|
||||
assert_eq!(charges(&v), owned);
|
||||
if accept.is_some() {
|
||||
result.unwrap();
|
||||
assert_eq!(v.operand_stack.as_slice(), &[Value::Int64(1)]);
|
||||
let mut expected = original;
|
||||
for _ in 0..attempts {
|
||||
expected.next();
|
||||
}
|
||||
assert_eq!(v.heap.random_state(r).unwrap(), expected);
|
||||
} else {
|
||||
assert_eq!(trap_code(&result.unwrap_err()), TRAP_RANDOM_REJECTION_LIMIT);
|
||||
assert_eq!(v.heap.random_state(r).unwrap(), original);
|
||||
assert_eq!(v.operand_stack.as_slice(), &args);
|
||||
// A subsequent normal draw sees the first canonical word, proving rollback.
|
||||
v.operand_stack.truncate(1);
|
||||
v.execute_random(crate::lookup_intrinsic_by_id(0x4001).unwrap(), 0).unwrap();
|
||||
assert_eq!(v.operand_stack[0], Value::Int64(0x86b1_da1d_7206_2b68u64 as i64));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn resource_refusals_preserve_all_charges_seed_and_candidate_state() {
|
||||
for limit in [0, 1, size_of::<crate::heap::StoredObject>() as u64 + 16] {
|
||||
let mut v = fault_vm(0x4000, &[Value::Int64(42)]);
|
||||
v.budget.test_lower_limit(RuntimeResource::GuestBytes, limit);
|
||||
let owned = charges(&v);
|
||||
let err =
|
||||
v.execute_random(crate::lookup_intrinsic_by_id(0x4000).unwrap(), 0).unwrap_err();
|
||||
assert_eq!(trap_code(&err), TRAP_RESOURCE_LIMIT);
|
||||
assert_eq!(charges(&v), owned);
|
||||
assert_eq!(v.heap.allocation_count(), 0);
|
||||
assert_eq!(v.operand_stack.as_slice(), &[Value::Int64(42)]);
|
||||
}
|
||||
for q in [RuntimeResource::AuxiliaryBytes, RuntimeResource::HandleSlots] {
|
||||
let mut v = fault_vm(0x4000, &[Value::Int64(42)]);
|
||||
v.budget.test_lower_limit(q, v.budget.used(q));
|
||||
let owned = charges(&v);
|
||||
let err =
|
||||
v.execute_random(crate::lookup_intrinsic_by_id(0x4000).unwrap(), 0).unwrap_err();
|
||||
assert_eq!(trap_code(&err), TRAP_RESOURCE_LIMIT);
|
||||
assert_eq!(charges(&v), owned);
|
||||
assert_eq!(v.heap.len(), 0);
|
||||
}
|
||||
for id in [0x4001, 0x4002, 0x4003] {
|
||||
let mut v = fault_vm(id, &[]);
|
||||
let r = v.heap.allocate_random(42).unwrap();
|
||||
let state = v.heap.random_state(r).unwrap();
|
||||
let mut args = vec![Value::HeapRef(r)];
|
||||
if id == 0x4003 {
|
||||
args.extend([Value::Int64(0), Value::Int64(3)]);
|
||||
}
|
||||
v.operand_stack.extend_from_slice(&args).unwrap();
|
||||
v.budget.test_lower_limit(RuntimeResource::TemporaryBytes, 0);
|
||||
let owned = charges(&v);
|
||||
let mut draws = 0;
|
||||
let err = v
|
||||
.execute_random_with(crate::lookup_intrinsic_by_id(id).unwrap(), 0, |p| {
|
||||
draws += 1;
|
||||
p.next()
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(trap_code(&err), TRAP_RESOURCE_LIMIT);
|
||||
assert_eq!(draws, 0);
|
||||
assert_eq!(charges(&v), owned);
|
||||
assert_eq!(v.operand_stack.as_slice(), args);
|
||||
assert_eq!(v.heap.random_state(r).unwrap(), state);
|
||||
assert_eq!(v.cycles, crate::lookup_intrinsic_by_id(id).unwrap().cost_cycles);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn every_random_root_survives_gc_then_releases_and_stale_handles_fault() {
|
||||
// Local, global, typed field, typed array, capture and direct Dynamic roots.
|
||||
for root in 0..6 {
|
||||
let mut v = vm(&[
|
||||
("RET", sig(&[], &[]), vec![], 1),
|
||||
("GET_CAPTURE 0\nINTRINSIC 16385\nRET", sig(&[], &[0]), vec![TypeId(1)], 0),
|
||||
]);
|
||||
let registry = v.validated_image.as_ref().unwrap().registry().clone();
|
||||
let r = v.heap.allocate_random(42).unwrap();
|
||||
match root {
|
||||
0 => v.operand_stack[0] = Value::HeapRef(r),
|
||||
1 => v.globals.push(Value::HeapRef(r)).unwrap(),
|
||||
2 => {
|
||||
let s = v.heap.allocate_typed_struct(registry.clone(), TypeId(4)).unwrap();
|
||||
v.heap.store_typed(®istry, s, 0, &[Value::HeapRef(r)]).unwrap();
|
||||
v.globals.push(Value::HeapRef(s)).unwrap();
|
||||
}
|
||||
3 => {
|
||||
let s = v.heap.allocate_typed_array(registry.clone(), TypeId(5), 1).unwrap();
|
||||
v.heap.store_typed(®istry, s, 0, &[Value::HeapRef(r)]).unwrap();
|
||||
v.globals.push(Value::HeapRef(s)).unwrap();
|
||||
}
|
||||
4 => {
|
||||
let s = v.heap.alloc_typed_closure(1, TypeId(6), &[Value::HeapRef(r)]).unwrap();
|
||||
v.globals.push(Value::HeapRef(s)).unwrap();
|
||||
}
|
||||
_ => {
|
||||
let d = crate::value_contract::pack_dynamic(
|
||||
®istry,
|
||||
&mut v.heap,
|
||||
TypeId(1),
|
||||
&[Value::HeapRef(r)],
|
||||
)
|
||||
.unwrap();
|
||||
v.globals.extend_from_slice(d.as_slice()).unwrap();
|
||||
}
|
||||
}
|
||||
let original = v.heap.random_state(r).unwrap();
|
||||
v.gc_alloc_threshold = 1;
|
||||
v.handle_safepoint().unwrap();
|
||||
assert!(v.heap.is_valid(r));
|
||||
assert_eq!(v.heap.random_state(r).unwrap(), original);
|
||||
v.globals.clear();
|
||||
v.operand_stack[0] = Value::Null;
|
||||
v.last_gc_live_count = 0;
|
||||
v.handle_safepoint().unwrap();
|
||||
assert!(!v.heap.is_valid(r));
|
||||
assert_eq!(v.heap.len(), 0);
|
||||
assert_eq!(v.budget.used(RuntimeResource::GuestBytes), 0);
|
||||
v.operand_stack.push(Value::HeapRef(r)).unwrap();
|
||||
let err =
|
||||
v.execute_random(crate::lookup_intrinsic_by_id(0x4001).unwrap(), 0).unwrap_err();
|
||||
assert_eq!(trap_code(&err), TRAP_INVALID_HANDLE);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn dynamic_defaults_exact_types_wrong_objects_and_no_trait_adaptation() {
|
||||
let mut v = vm(&[("RET", sig(&[], &[]), vec![], 0)]);
|
||||
let registry = v.validated_image.as_ref().unwrap().registry().clone();
|
||||
let r = v.heap.allocate_random(42).unwrap();
|
||||
let packed = crate::value_contract::pack_dynamic(
|
||||
®istry,
|
||||
&mut v.heap,
|
||||
TypeId(1),
|
||||
&[Value::HeapRef(r)],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(packed.as_slice(), &[Value::Int64(1), Value::HeapRef(r)]);
|
||||
assert_eq!(v.heap.allocation_count(), 1);
|
||||
assert_eq!(
|
||||
crate::value_contract::unpack_dynamic(®istry, &v.heap, TypeId(1), packed.as_slice())
|
||||
.unwrap()
|
||||
.as_slice(),
|
||||
&[Value::HeapRef(r)]
|
||||
);
|
||||
assert!(
|
||||
crate::value_contract::ref_to_trait(
|
||||
®istry,
|
||||
&v.heap,
|
||||
TypeId(1),
|
||||
TypeId(8),
|
||||
&[Value::HeapRef(r)]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
for ty in [4, 5] {
|
||||
let object = if ty == 4 {
|
||||
v.heap.allocate_typed_struct(registry.clone(), TypeId(4)).unwrap()
|
||||
} else {
|
||||
v.heap.allocate_typed_array(registry.clone(), TypeId(5), 1).unwrap()
|
||||
};
|
||||
assert_eq!(v.heap.load_typed(®istry, object, 0).unwrap().as_slice(), &[Value::Null]);
|
||||
let before = v.heap.load_typed(®istry, object, 0).unwrap();
|
||||
assert_eq!(
|
||||
v.heap.store_typed(®istry, object, 0, &[Value::HeapRef(object)]),
|
||||
Err(ValueError::Type)
|
||||
);
|
||||
assert_eq!(
|
||||
v.heap.load_typed(®istry, object, 0).unwrap().as_slice(),
|
||||
before.as_slice()
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn real_unknown_carriers_wrong_kind_and_domain_rollback_resume() {
|
||||
let code = "GET_GLOBAL 0\nGET_GLOBAL 1\nGET_GLOBAL 2\nINTRINSIC 16387\nPOP\nGET_GLOBAL 0\nINTRINSIC 16385\nRET";
|
||||
for bad in 0..4 {
|
||||
let mut v = vm(&[(code, sig(&[], &[0]), vec![], 0)]);
|
||||
let r = v.heap.allocate_random(42).unwrap();
|
||||
let receiver = if bad == 0 {
|
||||
Value::Null
|
||||
} else if bad == 1 {
|
||||
Value::HeapRef(v.heap.allocate_object(ObjectKind::Bytes, &[]).unwrap())
|
||||
} else {
|
||||
Value::HeapRef(r)
|
||||
};
|
||||
let lo = if bad == 2 { Value::Int32(0) } else { Value::Int64(2) };
|
||||
let hi = Value::Int64(1);
|
||||
v.globals.extend_from_slice(&[receiver, lo, hi]).unwrap();
|
||||
for _ in 0..3 {
|
||||
step(&mut v);
|
||||
}
|
||||
let args = v.operand_stack.as_slice().to_vec();
|
||||
let report = run(&mut v, 1);
|
||||
assert_eq!(report.cycles_used, 4);
|
||||
assert_eq!(report.steps_executed, 0);
|
||||
assert_eq!(v.operand_stack.as_slice(), args);
|
||||
assert_eq!(
|
||||
trap_code(&report.reason),
|
||||
[TRAP_NULL_REFERENCE, TRAP_TYPE, TRAP_TYPE, TRAP_NUMERIC_DOMAIN][bad]
|
||||
);
|
||||
assert_eq!(v.heap.random_state(r).unwrap(), Pcg64::new(42));
|
||||
// Resume after fault with the retained generator and verify first word.
|
||||
v.globals[0] = Value::HeapRef(r);
|
||||
v.operand_stack.clear();
|
||||
v.operand_stack.push(Value::Int64(0)).unwrap();
|
||||
assert_eq!(run(&mut v, 1000).reason, LogicalFrameEndingReason::EndOfRom);
|
||||
assert_eq!(v.operand_stack[0], Value::Int64(0x86b1_da1d_7206_2b68u64 as i64));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn reset_unload_and_other_session_do_not_import_snapshot_handles() {
|
||||
let bodies = [
|
||||
("PUSH_I64 42\nINTRINSIC 16384\nRET", sig(&[], &[1]), vec![], 0),
|
||||
("GET_LOCAL 0\nRET", sig(&[1], &[1]), vec![], 0),
|
||||
];
|
||||
let mut v = vm(&bodies);
|
||||
run(&mut v, 1000);
|
||||
let snapshot = v.operand_stack_top(1);
|
||||
let Value::HeapRef(r) = snapshot[0] else { panic!() };
|
||||
let owned = v.budget.clone();
|
||||
let mut other =
|
||||
VirtualMachine::from_image(support::image(&bodies).unwrap(), RuntimeLimits::default());
|
||||
assert!(matches!(
|
||||
other.prepare_call_with_args("1", &snapshot),
|
||||
Err(VmInitError::EntrypointArgumentsInvalid { trap_code: TRAP_INVALID_HANDLE, .. })
|
||||
));
|
||||
v.initialize(support::bytes(&bodies)).unwrap();
|
||||
assert!(!v.heap.is_valid(r));
|
||||
assert_eq!(owned.used(RuntimeResource::GuestBytes), 0);
|
||||
assert_eq!(owned.used(RuntimeResource::HandleSlots), 0);
|
||||
assert!(matches!(
|
||||
v.prepare_call_with_args("1", &snapshot),
|
||||
Err(VmInitError::EntrypointArgumentsInvalid { trap_code: TRAP_INVALID_HANDLE, .. })
|
||||
));
|
||||
v.prepare_boot_call().unwrap();
|
||||
run(&mut v, 1000);
|
||||
let owned = v.budget.clone();
|
||||
drop(v);
|
||||
assert_eq!(owned.used(RuntimeResource::GuestBytes), 0);
|
||||
assert_eq!(owned.used(RuntimeResource::HandleSlots), 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user