feat(vm): add reference identity and deterministic value hashing
This commit is contained in:
@@ -235,12 +235,13 @@ pub type IntrinsicHostImplementation =
|
||||
pub enum IntrinsicImplementation {
|
||||
Host(IntrinsicHostImplementation),
|
||||
VmOwned,
|
||||
BorrowedInline(crate::IntrinsicInlineImplementation),
|
||||
}
|
||||
impl IntrinsicImplementation {
|
||||
pub fn host_callback(self) -> Option<IntrinsicHostImplementation> {
|
||||
match self {
|
||||
Self::Host(f) => Some(f),
|
||||
Self::VmOwned => None,
|
||||
Self::VmOwned | Self::BorrowedInline(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -249,12 +250,14 @@ impl IntrinsicImplementation {
|
||||
pub enum IntrinsicCostModel {
|
||||
Fixed,
|
||||
RandomRejectionV1,
|
||||
ArgumentUtf8BytesV1,
|
||||
}
|
||||
impl IntrinsicCostModel {
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Fixed => "fixed",
|
||||
Self::RandomRejectionV1 => "random_rejection_v1",
|
||||
Self::ArgumentUtf8BytesV1 => "argument_utf8_bytes_v1",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -266,11 +269,14 @@ pub struct IntrinsicMeta {
|
||||
pub name: &'static str,
|
||||
pub version: u16,
|
||||
pub arg_layout: &'static [AbiType],
|
||||
pub arg_nullable: &'static [bool],
|
||||
pub ret_layout: &'static [AbiType],
|
||||
pub parameter_names: &'static [&'static str],
|
||||
/// Full fixed cost, or base cost for a variable model.
|
||||
pub cost_cycles: u64,
|
||||
pub cost_model: IntrinsicCostModel,
|
||||
pub cost_arg_index: Option<usize>,
|
||||
pub cost_per_byte: u64,
|
||||
pub attempt_cost_cycles: u64,
|
||||
pub max_attempts: u32,
|
||||
pub mutates_guest_state: bool,
|
||||
@@ -300,7 +306,16 @@ impl IntrinsicMeta {
|
||||
&self,
|
||||
values: &[Value],
|
||||
) -> Result<(), IntrinsicExecutionError> {
|
||||
Self::validate_values(values, self.arg_layout)
|
||||
Self::validate_values(values, self.arg_layout)?;
|
||||
for (index, (value, nullable)) in values.iter().zip(self.arg_nullable).enumerate() {
|
||||
if matches!(value, Value::Null) && !nullable {
|
||||
return Err(IntrinsicExecutionError::TypeMismatch {
|
||||
index,
|
||||
expected: self.arg_layout[index],
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_values(
|
||||
@@ -563,10 +578,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "dot",
|
||||
version: 1,
|
||||
arg_layout: &VEC2_DOT_ARGS,
|
||||
arg_nullable: &[false; VEC2_DOT_ARGS.len()],
|
||||
ret_layout: &SINGLE_FLOAT_RET,
|
||||
parameter_names: &["ax", "ay", "bx", "by"],
|
||||
cost_cycles: 10,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -580,10 +598,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "length",
|
||||
version: 1,
|
||||
arg_layout: &VEC2_LENGTH_ARGS,
|
||||
arg_nullable: &[false; VEC2_LENGTH_ARGS.len()],
|
||||
ret_layout: &SINGLE_FLOAT_RET,
|
||||
parameter_names: &["x", "y"],
|
||||
cost_cycles: 40,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -597,10 +618,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "from_raw",
|
||||
version: 1,
|
||||
arg_layout: &INT_RET,
|
||||
arg_nullable: &[false; INT_RET.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["raw"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -614,10 +638,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "rgb",
|
||||
version: 1,
|
||||
arg_layout: &COLOR_RGB_ARGS,
|
||||
arg_nullable: &[false; COLOR_RGB_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["r", "g", "b"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -631,10 +658,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "rgba",
|
||||
version: 1,
|
||||
arg_layout: &COLOR_RGBA_ARGS,
|
||||
arg_nullable: &[false; COLOR_RGBA_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["r", "g", "b", "a"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -648,10 +678,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "html_rgba",
|
||||
version: 1,
|
||||
arg_layout: &COLOR_HTML_RGBA_ARGS,
|
||||
arg_nullable: &[false; COLOR_HTML_RGBA_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["value"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -665,10 +698,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "gray_scale",
|
||||
version: 1,
|
||||
arg_layout: &INT_RET,
|
||||
arg_nullable: &[false; INT_RET.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &["value"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -682,10 +718,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "hex",
|
||||
version: 1,
|
||||
arg_layout: &COLOR_ARGS,
|
||||
arg_nullable: &[false; COLOR_ARGS.len()],
|
||||
ret_layout: &INT_RET,
|
||||
parameter_names: &["color"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -699,10 +738,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "alpha",
|
||||
version: 1,
|
||||
arg_layout: &COLOR_ARGS,
|
||||
arg_nullable: &[false; COLOR_ARGS.len()],
|
||||
ret_layout: &INT_RET,
|
||||
parameter_names: &["color"],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -716,10 +758,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "black",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -733,10 +778,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "white",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -750,10 +798,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "red",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -767,10 +818,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "green",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -784,10 +838,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "blue",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -801,10 +858,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "yellow",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -818,10 +878,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "orange",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -835,10 +898,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "indigo",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -852,10 +918,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "gray",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -869,10 +938,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "cyan",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -886,10 +958,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "magenta",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -903,10 +978,13 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
|
||||
name: "transparent",
|
||||
version: 1,
|
||||
arg_layout: &NO_ARGS,
|
||||
arg_nullable: &[false; NO_ARGS.len()],
|
||||
ret_layout: &COLOR_RET,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
@@ -944,6 +1022,7 @@ pub fn lookup_intrinsic(owner: &str, name: &str, version: u16) -> Option<&'stati
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
.chain(crate::hash_intrinsics::HASH_INTRINSICS.iter())
|
||||
.find(|meta| meta.owner == owner && meta.name == name && meta.version == version)
|
||||
}
|
||||
|
||||
@@ -953,6 +1032,7 @@ pub fn lookup_intrinsic_by_id(id: u32) -> Option<&'static IntrinsicMeta> {
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
.chain(crate::hash_intrinsics::HASH_INTRINSICS.iter())
|
||||
.find(|meta| meta.id == id)
|
||||
}
|
||||
|
||||
@@ -1254,9 +1334,17 @@ pub(crate) fn metered_lookup_intrinsic(
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
.chain(crate::hash_intrinsics::HASH_INTRINSICS.iter())
|
||||
{
|
||||
budget.work(1)?;
|
||||
if meta.id == id {
|
||||
budget.work(meta.arg_slots() + 1)?;
|
||||
meta.validate_descriptor().map_err(|_| {
|
||||
prometeu_bytecode::load_limits::LoadFailure::new(
|
||||
prometeu_bytecode::load_limits::LoadCode::InvalidCode,
|
||||
prometeu_bytecode::load_limits::LoadReason::NativeId,
|
||||
)
|
||||
})?;
|
||||
return Ok(Some(meta));
|
||||
}
|
||||
}
|
||||
@@ -1270,6 +1358,7 @@ pub fn intrinsic_catalog() -> impl Iterator<Item = &'static IntrinsicMeta> {
|
||||
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
|
||||
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
|
||||
.chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter())
|
||||
.chain(crate::hash_intrinsics::HASH_INTRINSICS.iter())
|
||||
}
|
||||
pub fn builtin_constant_catalog() -> impl Iterator<Item = &'static BuiltinConstMeta> {
|
||||
BUILTIN_CONSTS.iter()
|
||||
|
||||
@@ -16,14 +16,15 @@ 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,mutates_guest_state,cost_model,attempt_cost_cycles,max_attempts\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,schema_version,arg_nullable,invocation_model,scratch_model,context_access,cost_arg_index,cost_per_byte\n",
|
||||
);
|
||||
let mut entries: Vec<_> = intrinsic_catalog().collect();
|
||||
entries.sort_by_key(|m| m.id);
|
||||
for m in entries {
|
||||
m.validate_descriptor().expect("valid canonical intrinsic descriptor");
|
||||
writeln!(
|
||||
&mut out,
|
||||
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}",
|
||||
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},2,{},{},{},{},{},{}",
|
||||
m.id,
|
||||
m.id,
|
||||
m.owner,
|
||||
@@ -42,7 +43,13 @@ pub fn intrinsic_catalog_csv() -> String {
|
||||
m.mutates_guest_state,
|
||||
m.cost_model.name(),
|
||||
m.attempt_cost_cycles,
|
||||
m.max_attempts
|
||||
m.max_attempts,
|
||||
m.arg_nullable.iter().map(bool::to_string).collect::<Vec<_>>().join("|"),
|
||||
m.invocation_model(),
|
||||
m.scratch_model(),
|
||||
m.context_access(),
|
||||
m.cost_arg_index.map_or_else(String::new, |i| i.to_string()),
|
||||
m.cost_per_byte
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
use crate::{
|
||||
AbiType, BuiltinScalarType as S, IntrinsicCostModel as C, IntrinsicExecutionError as E,
|
||||
IntrinsicImplementation as I, IntrinsicMeta, IntrinsicResults,
|
||||
};
|
||||
use prometeu_bytecode::Value;
|
||||
|
||||
const fn entry(
|
||||
id: u32,
|
||||
name: &'static str,
|
||||
abi: AbiType,
|
||||
nullable: bool,
|
||||
handler: crate::IntrinsicInlineImplementation,
|
||||
) -> IntrinsicMeta {
|
||||
IntrinsicMeta {
|
||||
id,
|
||||
owner: "hash",
|
||||
name,
|
||||
version: 1,
|
||||
arg_layout: match abi {
|
||||
AbiType::Scalar(S::Int64) => &[AbiType::Scalar(S::Int64)],
|
||||
AbiType::Scalar(S::Float) => &[AbiType::Scalar(S::Float)],
|
||||
AbiType::Scalar(S::String) => &[AbiType::Scalar(S::String)],
|
||||
_ => panic!("unsupported hash input ABI"),
|
||||
},
|
||||
ret_layout: &[AbiType::Scalar(S::Int64)],
|
||||
arg_nullable: if nullable { &[true] } else { &[false] },
|
||||
parameter_names: &["value"],
|
||||
cost_cycles: 8,
|
||||
cost_model: if matches!(abi, AbiType::Scalar(S::String)) {
|
||||
C::ArgumentUtf8BytesV1
|
||||
} else {
|
||||
C::Fixed
|
||||
},
|
||||
cost_arg_index: if matches!(abi, AbiType::Scalar(S::String)) { Some(0) } else { None },
|
||||
cost_per_byte: if matches!(abi, AbiType::Scalar(S::String)) { 1 } else { 0 },
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
deterministic: true,
|
||||
may_allocate: false,
|
||||
implementation: I::BorrowedInline(handler),
|
||||
}
|
||||
}
|
||||
pub(crate) const HASH_INTRINSICS: [IntrinsicMeta; 3] = [
|
||||
entry(0x4100, "i64", AbiType::Scalar(S::Int64), false, hash_i64),
|
||||
entry(0x4101, "float", AbiType::Scalar(S::Float), false, hash_float),
|
||||
entry(0x4102, "string", AbiType::Scalar(S::String), true, hash_string),
|
||||
];
|
||||
fn hash_i64(args: &[Value], out: &mut IntrinsicResults) -> Result<(), E> {
|
||||
let Value::Int64(value) = args[0] else { unreachable!("exact validated Int64") };
|
||||
out.push(Value::Int64(crate::hashing::xxh64(&value.to_le_bytes()) as i64))
|
||||
}
|
||||
fn hash_float(args: &[Value], out: &mut IntrinsicResults) -> Result<(), E> {
|
||||
let Value::Float(value) = args[0] else { unreachable!("exact validated Float") };
|
||||
crate::numeric::check_inputs(&[value])?;
|
||||
let bits = if value == 0.0 { 0 } else { value.to_bits() };
|
||||
out.push(Value::Int64(crate::hashing::xxh64(&bits.to_le_bytes()) as i64))
|
||||
}
|
||||
fn hash_string(args: &[Value], out: &mut IntrinsicResults) -> Result<(), E> {
|
||||
let hash = match &args[0] {
|
||||
Value::Null => 0,
|
||||
Value::String(s) => crate::hashing::xxh64(s.as_bytes()) as i64,
|
||||
_ => unreachable!("exact validated nullable String"),
|
||||
};
|
||||
out.push(Value::Int64(hash))
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Hash-v1: portable XXH64, seed zero, over explicit machine byte encodings.
|
||||
use prometeu_bytecode::HeapRef;
|
||||
|
||||
const P1: u64 = 0x9E3779B185EBCA87;
|
||||
const P2: u64 = 0xC2B2AE3D27D4EB4F;
|
||||
const P3: u64 = 0x165667B19E3779F9;
|
||||
const P4: u64 = 0x85EBCA77C2B2AE63;
|
||||
const P5: u64 = 0x27D4EB2F165667C5;
|
||||
|
||||
fn word(bytes: &[u8]) -> u64 {
|
||||
u64::from_le_bytes(bytes[..8].try_into().expect("complete XXH64 lane"))
|
||||
}
|
||||
fn round(acc: u64, lane: u64) -> u64 {
|
||||
acc.wrapping_add(lane.wrapping_mul(P2)).rotate_left(31).wrapping_mul(P1)
|
||||
}
|
||||
fn merge(acc: u64, lane: u64) -> u64 {
|
||||
(acc ^ round(0, lane)).wrapping_mul(P1).wrapping_add(P4)
|
||||
}
|
||||
|
||||
pub(crate) fn xxh64(mut bytes: &[u8]) -> u64 {
|
||||
let length = bytes.len() as u64;
|
||||
let mut hash = if bytes.len() >= 32 {
|
||||
let mut acc = [P1.wrapping_add(P2), P2, 0, 0u64.wrapping_sub(P1)];
|
||||
while bytes.len() >= 32 {
|
||||
for (index, value) in acc.iter_mut().enumerate() {
|
||||
*value = round(*value, word(&bytes[index * 8..]));
|
||||
}
|
||||
bytes = &bytes[32..];
|
||||
}
|
||||
let mut hash = acc[0]
|
||||
.rotate_left(1)
|
||||
.wrapping_add(acc[1].rotate_left(7))
|
||||
.wrapping_add(acc[2].rotate_left(12))
|
||||
.wrapping_add(acc[3].rotate_left(18));
|
||||
for value in acc {
|
||||
hash = merge(hash, value);
|
||||
}
|
||||
hash
|
||||
} else {
|
||||
P5
|
||||
};
|
||||
hash = hash.wrapping_add(length);
|
||||
while bytes.len() >= 8 {
|
||||
hash ^= round(0, word(bytes));
|
||||
hash = hash.rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
|
||||
bytes = &bytes[8..];
|
||||
}
|
||||
if bytes.len() >= 4 {
|
||||
hash ^= u64::from(u32::from_le_bytes(bytes[..4].try_into().unwrap())).wrapping_mul(P1);
|
||||
hash = hash.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
|
||||
bytes = &bytes[4..];
|
||||
}
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte).wrapping_mul(P5);
|
||||
hash = hash.rotate_left(11).wrapping_mul(P1);
|
||||
}
|
||||
hash ^= hash >> 33;
|
||||
hash = hash.wrapping_mul(P2);
|
||||
hash ^= hash >> 29;
|
||||
hash = hash.wrapping_mul(P3);
|
||||
hash ^ (hash >> 32)
|
||||
}
|
||||
|
||||
pub(crate) fn reference(value: Option<HeapRef>) -> i64 {
|
||||
value.map_or(0, |reference| {
|
||||
let mut bytes = [0; 8];
|
||||
bytes[..4].copy_from_slice(&reference.index.to_le_bytes());
|
||||
bytes[4..].copy_from_slice(&reference.generation.to_le_bytes());
|
||||
xxh64(&bytes) as i64
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn matches_all_independent_c_reference_vectors() {
|
||||
let mut count = 0;
|
||||
for row in include_str!("../tests/fixtures/hash-conformance.tsv").lines().skip(1) {
|
||||
let f: Vec<_> = row.split('\t').collect();
|
||||
let expected = u64::from_str_radix(f[2], 16).unwrap();
|
||||
let actual = match f[0] {
|
||||
"bytes" | "string" => {
|
||||
let bytes: Vec<_> = (0..f[1].len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&f[1][i..i + 2], 16).unwrap())
|
||||
.collect();
|
||||
xxh64(&bytes)
|
||||
}
|
||||
"i64" => xxh64(&f[1].parse::<i64>().unwrap().to_le_bytes()),
|
||||
"float" => {
|
||||
let bits = u64::from_str_radix(f[1], 16).unwrap();
|
||||
let bits = if f64::from_bits(bits) == 0.0 { 0 } else { bits };
|
||||
xxh64(&bits.to_le_bytes())
|
||||
}
|
||||
"reference" => {
|
||||
let (index, generation) = f[1].split_once(',').unwrap();
|
||||
reference(Some(HeapRef {
|
||||
index: index.parse().unwrap(),
|
||||
generation: generation.parse().unwrap(),
|
||||
})) as u64
|
||||
}
|
||||
"null" => reference(None) as u64,
|
||||
kind => panic!("unknown vector {kind}"),
|
||||
};
|
||||
assert_eq!(actual, expected, "{row}");
|
||||
count += 1;
|
||||
}
|
||||
assert_eq!(count, 118);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequential_handles_spread_and_bucket_collisions_do_not_imply_identity() {
|
||||
let mut buckets = [0; 256];
|
||||
let mut first = [None; 256];
|
||||
let mut collisions = 0;
|
||||
for index in 1..=16384 {
|
||||
let handle = HeapRef { index, generation: 1 };
|
||||
let bucket = reference(Some(handle)) as u64 as usize & 255;
|
||||
buckets[bucket] += 1;
|
||||
if let Some(previous) = first[bucket] {
|
||||
assert_ne!(previous, handle);
|
||||
collisions += 1;
|
||||
} else {
|
||||
first[bucket] = Some(handle);
|
||||
}
|
||||
}
|
||||
assert!(buckets.iter().all(|&count| (32..=100).contains(&count)), "{buckets:?}");
|
||||
assert_eq!(collisions, 16384 - 256);
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,13 @@ const fn query(
|
||||
name,
|
||||
version: 1,
|
||||
arg_layout: &[],
|
||||
arg_nullable: &[],
|
||||
ret_layout,
|
||||
parameter_names: &[],
|
||||
cost_cycles: 1,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! The native handler variant and descriptor jointly define the invocation contract.
|
||||
use crate::{
|
||||
AbiType, BuiltinScalarType, IntrinsicCostModel, IntrinsicExecutionError as E,
|
||||
IntrinsicImplementation as I, IntrinsicMeta,
|
||||
};
|
||||
use prometeu_bytecode::Value;
|
||||
|
||||
pub type IntrinsicInlineImplementation = fn(&[Value], &mut IntrinsicResults) -> Result<(), E>;
|
||||
const INLINE_SLOTS: usize = 3;
|
||||
|
||||
/// Fixed native staging only; no heap buffer or mutable execution context.
|
||||
#[derive(Debug)]
|
||||
pub struct IntrinsicResults {
|
||||
values: [Value; INLINE_SLOTS],
|
||||
len: usize,
|
||||
limit: usize,
|
||||
overflowed: bool,
|
||||
}
|
||||
impl IntrinsicResults {
|
||||
pub(crate) fn new(limit: usize) -> Self {
|
||||
assert!(limit <= INLINE_SLOTS);
|
||||
Self { values: [const { Value::Null }; INLINE_SLOTS], len: 0, limit, overflowed: false }
|
||||
}
|
||||
pub fn push(&mut self, value: Value) -> Result<(), E> {
|
||||
if self.len >= self.limit {
|
||||
self.overflowed = true;
|
||||
return Err(E::ArityMismatch { expected: self.limit, got: self.len + 1 });
|
||||
}
|
||||
self.values[self.len] = value;
|
||||
self.len += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn validate(&self, meta: &IntrinsicMeta) -> Result<(), E> {
|
||||
if self.overflowed {
|
||||
return Err(E::ArityMismatch { expected: self.limit, got: self.limit + 1 });
|
||||
}
|
||||
meta.validate_result_values(&self.values[..self.len])
|
||||
}
|
||||
pub(crate) fn as_slice(&self) -> &[Value] {
|
||||
&self.values[..self.len]
|
||||
}
|
||||
pub(crate) fn into_values(self) -> impl Iterator<Item = Value> {
|
||||
self.values.into_iter().take(self.len)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntrinsicMeta {
|
||||
pub fn invocation_model(&self) -> &'static str {
|
||||
match self.implementation {
|
||||
I::Host(_) => "host_buffered_v1",
|
||||
I::VmOwned => "vm_owned_v1",
|
||||
I::BorrowedInline(_) => "borrowed_inline_v1",
|
||||
}
|
||||
}
|
||||
pub fn scratch_model(&self) -> &'static str {
|
||||
match self.implementation {
|
||||
I::BorrowedInline(_) => "none",
|
||||
_ => "existing_contract_v1",
|
||||
}
|
||||
}
|
||||
pub fn context_access(&self) -> &'static str {
|
||||
match self.implementation {
|
||||
I::Host(_) => "host",
|
||||
I::VmOwned => "vm_state",
|
||||
I::BorrowedInline(_) => "none",
|
||||
}
|
||||
}
|
||||
/// Derivation from the handler variant makes incompatible profile claims unrepresentable.
|
||||
pub fn validate_descriptor(&self) -> Result<(), &'static str> {
|
||||
if self.arg_nullable.len() != self.arg_slots()
|
||||
|| self.parameter_names.len() != self.arg_slots()
|
||||
{
|
||||
return Err("argument metadata widths disagree");
|
||||
}
|
||||
for abi in self.arg_layout.iter().chain(self.ret_layout) {
|
||||
if !matches!(abi, AbiType::Scalar(_))
|
||||
&& !matches!(abi, AbiType::Builtin(key) if (key.name == "Random" || key.name == "color") && key.version == 1)
|
||||
{
|
||||
return Err("unsupported intrinsic ABI layout");
|
||||
}
|
||||
}
|
||||
for (abi, nullable) in self.arg_layout.iter().zip(self.arg_nullable) {
|
||||
let permits_null = matches!(abi, AbiType::Scalar(BuiltinScalarType::String))
|
||||
|| matches!(abi, AbiType::Builtin(key) if key.name == "Random" && key.version == 1);
|
||||
if *nullable && !permits_null {
|
||||
return Err("non-nullable ABI carrier declared nullable");
|
||||
}
|
||||
}
|
||||
match self.cost_model {
|
||||
IntrinsicCostModel::Fixed => {
|
||||
if self.cost_arg_index.is_some()
|
||||
|| self.cost_per_byte != 0
|
||||
|| self.attempt_cost_cycles != 0
|
||||
|| self.max_attempts != 0
|
||||
{
|
||||
return Err("fixed cost has variable parameters");
|
||||
}
|
||||
}
|
||||
IntrinsicCostModel::RandomRejectionV1 => {
|
||||
if !matches!(self.implementation, I::VmOwned)
|
||||
|| self.cost_arg_index.is_some()
|
||||
|| self.cost_per_byte != 0
|
||||
|| self.attempt_cost_cycles == 0
|
||||
|| self.max_attempts == 0
|
||||
{
|
||||
return Err("invalid random rejection cost parameters");
|
||||
}
|
||||
}
|
||||
IntrinsicCostModel::ArgumentUtf8BytesV1 => {
|
||||
if !matches!(self.implementation, I::BorrowedInline(_))
|
||||
|| self.cost_arg_index.and_then(|i| self.arg_layout.get(i))
|
||||
!= Some(&AbiType::Scalar(BuiltinScalarType::String))
|
||||
|| self.cost_per_byte == 0
|
||||
|| self.attempt_cost_cycles != 0
|
||||
|| self.max_attempts != 0
|
||||
{
|
||||
return Err("invalid String byte-cost parameters");
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(self.implementation, I::BorrowedInline(_))
|
||||
&& (self.ret_slots() > INLINE_SLOTS
|
||||
|| self.ret_slots() > self.arg_slots()
|
||||
|| self.may_allocate
|
||||
|| self.mutates_guest_state
|
||||
|| !self.deterministic)
|
||||
{
|
||||
return Err("handler violates bounded invocation capabilities");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// None is checked cost overflow. Wrong/missing carriers have no inferred length.
|
||||
pub(crate) fn attempted_cost(&self, args: &[Value]) -> Option<u64> {
|
||||
if self.cost_model != IntrinsicCostModel::ArgumentUtf8BytesV1 {
|
||||
return Some(self.cost_cycles);
|
||||
}
|
||||
let bytes = match self.cost_arg_index.and_then(|i| args.get(i)) {
|
||||
Some(Value::String(value)) => value.len() as u64,
|
||||
_ => 0,
|
||||
};
|
||||
bytes.checked_mul(self.cost_per_byte)?.checked_add(self.cost_cycles)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,11 @@
|
||||
extern crate self as prometeu_vm;
|
||||
mod builtins;
|
||||
mod catalog;
|
||||
mod hash_intrinsics;
|
||||
mod hashing;
|
||||
mod intrinsic_contract;
|
||||
pub use catalog::{builtin_constant_catalog_csv, intrinsic_catalog_csv};
|
||||
pub use intrinsic_contract::{IntrinsicInlineImplementation, IntrinsicResults};
|
||||
mod call_frame;
|
||||
mod input_intrinsics;
|
||||
mod math_intrinsics;
|
||||
|
||||
@@ -20,10 +20,17 @@ const fn entry<const ID: u32>(
|
||||
name,
|
||||
version: 1,
|
||||
arg_layout,
|
||||
arg_nullable: match arg_layout.len() {
|
||||
1 => &[false],
|
||||
2 => &[false, false],
|
||||
_ => &[false, false, false],
|
||||
},
|
||||
ret_layout,
|
||||
parameter_names,
|
||||
cost_cycles,
|
||||
cost_model: crate::IntrinsicCostModel::Fixed,
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: 0,
|
||||
max_attempts: 0,
|
||||
mutates_guest_state: false,
|
||||
|
||||
@@ -21,6 +21,13 @@ const fn entry(
|
||||
name,
|
||||
version: 1,
|
||||
arg_layout: args,
|
||||
arg_nullable: if id == 0x4000 {
|
||||
&[false]
|
||||
} else if rejection {
|
||||
&[true, false, false]
|
||||
} else {
|
||||
&[true]
|
||||
},
|
||||
ret_layout: ret,
|
||||
parameter_names: names,
|
||||
cost_cycles: cost,
|
||||
@@ -29,6 +36,8 @@ const fn entry(
|
||||
} else {
|
||||
IntrinsicCostModel::Fixed
|
||||
},
|
||||
cost_arg_index: None,
|
||||
cost_per_byte: 0,
|
||||
attempt_cost_cycles: if rejection { 8 } else { 0 },
|
||||
max_attempts: if rejection { crate::random::MAX_ATTEMPTS } else { 0 },
|
||||
deterministic: true,
|
||||
|
||||
@@ -485,6 +485,10 @@ fn transfer(
|
||||
group(&mut working[base..], registry, ty, (instruction.pc as u64) << 32, budget)?;
|
||||
}
|
||||
}
|
||||
Op::RefIdentityHash => {
|
||||
budget.work(1)?;
|
||||
working[base] = Fact::Carrier(I64);
|
||||
}
|
||||
Op::RefCast | Op::RefToTrait => {
|
||||
group(
|
||||
&mut working[base..],
|
||||
@@ -503,6 +507,7 @@ fn transfer(
|
||||
| Op::And
|
||||
| Op::Or
|
||||
| Op::Not
|
||||
| Op::RefIdentityEq
|
||||
| Op::RefIsExact
|
||||
| Op::RefImplements
|
||||
| Op::DynCanUnpack => {
|
||||
@@ -818,6 +823,21 @@ fn check(
|
||||
return Err(mismatch(1));
|
||||
}
|
||||
}
|
||||
Op::RefIdentityHash | Op::RefIdentityEq => {
|
||||
let (left, right) = if instruction.opcode == Op::RefIdentityHash {
|
||||
(instruction.imm_u32().unwrap(), None)
|
||||
} else {
|
||||
let (a, b) = instruction.imm_u32x2().unwrap();
|
||||
(a, Some(b))
|
||||
};
|
||||
let lw = registry.type_layout(TypeId(left)).unwrap().storage.slots as usize;
|
||||
let rw = right
|
||||
.map_or(0, |id| registry.type_layout(TypeId(id)).unwrap().storage.slots as usize);
|
||||
check_group(&working[end - lw - rw..end - rw], TypeId(left), registry, budget)?;
|
||||
if let Some(id) = right {
|
||||
check_group(&working[end - rw..end], TypeId(id), registry, budget)?;
|
||||
}
|
||||
}
|
||||
Op::RefCast | Op::RefToTrait | Op::RefIsExact | Op::RefImplements => {
|
||||
budget.work(1)?;
|
||||
let ty = TypeId(instruction.imm_u32x2().unwrap().0);
|
||||
@@ -830,7 +850,12 @@ fn check(
|
||||
.unwrap();
|
||||
let base = end - native.arg_slots();
|
||||
for (part, abi) in native.arg_layout.iter().enumerate() {
|
||||
require(working[base + part], abi_mask(*abi), part, registry, budget)?;
|
||||
let accepted = if native.arg_nullable[part] {
|
||||
abi_mask(*abi) | NULL
|
||||
} else {
|
||||
abi_mask(*abi) & !NULL
|
||||
};
|
||||
require(working[base + part], accepted, part, registry, budget)?;
|
||||
}
|
||||
}
|
||||
Op::JmpIfTrue | Op::JmpIfFalse | Op::Not => {
|
||||
|
||||
@@ -221,6 +221,24 @@ pub(crate) fn unpack_dynamic(
|
||||
|
||||
// All reference operations validate complete source values before querying the
|
||||
// underlying concrete object. Invalid handles/pairs never become false or null.
|
||||
pub(crate) fn identity_reference(
|
||||
registry: &Registry,
|
||||
heap: &Heap,
|
||||
source: TypeId,
|
||||
values: &[Value],
|
||||
) -> Result<Option<HeapRef>, ValueError> {
|
||||
let kind = registry.declarations().types.get(source.0 as usize).ok_or(ValueError::Type)?;
|
||||
if !kind.kind.is_identity_reference() {
|
||||
return Err(ValueError::Type);
|
||||
}
|
||||
validate(registry, heap, source, values)?;
|
||||
match values.first() {
|
||||
Some(Value::Null) => Ok(None),
|
||||
Some(Value::HeapRef(reference)) => Ok(Some(*reference)),
|
||||
_ => Err(ValueError::Type),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference(
|
||||
registry: &Registry,
|
||||
heap: &Heap,
|
||||
|
||||
@@ -7,6 +7,8 @@ mod collections_tests;
|
||||
mod control;
|
||||
mod dynamic;
|
||||
mod gc;
|
||||
mod identity;
|
||||
mod intrinsic;
|
||||
mod lifecycle;
|
||||
mod loader;
|
||||
mod native_arrays;
|
||||
@@ -330,8 +332,10 @@ impl VirtualMachine {
|
||||
}
|
||||
|
||||
let charged_math = if opcode == OpCode::Intrinsic {
|
||||
lookup_intrinsic_by_id(instr.imm_u32().unwrap())
|
||||
.filter(|m| m.owner == "vec2" || m.owner == "mathf" || m.owner.starts_with("math."))
|
||||
lookup_intrinsic_by_id(instr.imm_u32().unwrap()).filter(|m| {
|
||||
matches!(m.implementation, crate::IntrinsicImplementation::Host(_))
|
||||
&& (m.owner == "vec2" || m.owner == "mathf" || m.owner.starts_with("math."))
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -955,6 +959,12 @@ impl VirtualMachine {
|
||||
)
|
||||
})?;
|
||||
|
||||
if matches!(
|
||||
intrinsic.implementation,
|
||||
crate::IntrinsicImplementation::BorrowedInline(_)
|
||||
) {
|
||||
return self.execute_inline_intrinsic(intrinsic, pc_at_intrinsic);
|
||||
}
|
||||
if matches!(intrinsic.implementation, crate::IntrinsicImplementation::VmOwned) {
|
||||
return self.execute_random(intrinsic, pc_at_intrinsic);
|
||||
}
|
||||
@@ -1086,6 +1096,15 @@ impl VirtualMachine {
|
||||
let (source, target) = instr.imm_u32x2().unwrap();
|
||||
return self.execute_reference(opcode, source, target, start_pc as u32);
|
||||
}
|
||||
OpCode::RefIdentityHash | OpCode::RefIdentityEq => {
|
||||
let (left, right) = if opcode == OpCode::RefIdentityHash {
|
||||
(instr.imm_u32().unwrap(), None)
|
||||
} else {
|
||||
let (left, right) = instr.imm_u32x2().unwrap();
|
||||
(left, Some(right))
|
||||
};
|
||||
return self.execute_identity(opcode, left, right, start_pc as u32);
|
||||
}
|
||||
OpCode::FieldsPublish => {
|
||||
return self.execute_fields_publication(instr.imm_u32().unwrap(), start_pc as u32);
|
||||
}
|
||||
@@ -3910,3 +3929,7 @@ mod callable_tests;
|
||||
|
||||
#[cfg(feature = "resource-diagnostics")]
|
||||
pub mod string_provenance_qualification;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "virtual_machine/identity_tests.rs"]
|
||||
mod identity_tests;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
use super::*;
|
||||
use crate::value_contract;
|
||||
use prometeu_bytecode::registry::TypeId;
|
||||
|
||||
impl VirtualMachine {
|
||||
pub(super) fn execute_identity(
|
||||
&mut self,
|
||||
opcode: OpCode,
|
||||
left: u32,
|
||||
right: Option<u32>,
|
||||
pc: u32,
|
||||
) -> Result<(), LogicalFrameEndingReason> {
|
||||
let image = self.validated_image.clone().ok_or_else(|| {
|
||||
self.trap(
|
||||
prometeu_bytecode::TRAP_ILLEGAL_INSTRUCTION,
|
||||
opcode as u16,
|
||||
"Identity instruction requires a validated Registry".into(),
|
||||
pc,
|
||||
)
|
||||
})?;
|
||||
let registry = image.registry();
|
||||
let left = TypeId(left);
|
||||
let right = right.map(TypeId);
|
||||
let lw = registry.type_layout(left).unwrap().storage.slots as usize;
|
||||
let rw = right.map_or(0, |ty| registry.type_layout(ty).unwrap().storage.slots as usize);
|
||||
self.cycles += opcode.cycles() + (lw + rw) as u64;
|
||||
if self.temporary_slots() < lw + rw {
|
||||
return Err(self.trap(
|
||||
TRAP_STACK_UNDERFLOW,
|
||||
opcode as u16,
|
||||
"Incomplete identity operands".into(),
|
||||
pc,
|
||||
));
|
||||
}
|
||||
let base = self.operand_stack.len() - lw - rw;
|
||||
let first = value_contract::identity_reference(
|
||||
registry,
|
||||
&self.heap,
|
||||
left,
|
||||
&self.operand_stack[base..base + lw],
|
||||
)
|
||||
.map_err(|e| self.value_trap(e, opcode, pc))?;
|
||||
let result = if let Some(ty) = right {
|
||||
let second = value_contract::identity_reference(
|
||||
registry,
|
||||
&self.heap,
|
||||
ty,
|
||||
&self.operand_stack[base + lw..],
|
||||
)
|
||||
.map_err(|e| self.value_trap(e, opcode, pc))?;
|
||||
Value::Boolean(first == second)
|
||||
} else {
|
||||
Value::Int64(crate::hashing::reference(first))
|
||||
};
|
||||
self.operand_stack.truncate(base);
|
||||
self.operand_stack.push(result).expect("identity result replaces existing inputs");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
use super::*;
|
||||
#[path = "../../tests/support/identity.rs"]
|
||||
mod support;
|
||||
use crate::{
|
||||
IntrinsicExecutionError, IntrinsicImplementation, IntrinsicMeta, IntrinsicResults,
|
||||
hash_intrinsics::HASH_INTRINSICS,
|
||||
};
|
||||
use prometeu_bytecode::{HeapRef, RuntimeResource as Q, registry::TypeId};
|
||||
use std::sync::Arc;
|
||||
use support::*;
|
||||
|
||||
fn empty() -> VirtualMachine {
|
||||
vm(&[("RET", sig(&[], &[]))], &[])
|
||||
}
|
||||
fn push(v: &mut VirtualMachine, values: &[Value]) {
|
||||
for value in values {
|
||||
v.operand_stack.push(value.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
fn usage(v: &VirtualMachine) -> Vec<u64> {
|
||||
[
|
||||
Q::GuestBytes,
|
||||
Q::HandleSlots,
|
||||
Q::AuxiliaryBytes,
|
||||
Q::TemporaryBytes,
|
||||
Q::StringBytes,
|
||||
Q::StringAllocations,
|
||||
]
|
||||
.map(|q| v.budget.used(q))
|
||||
.to_vec()
|
||||
}
|
||||
fn fault(result: Result<(), LogicalFrameEndingReason>, expected: u32) {
|
||||
assert!(
|
||||
matches!(result,Err(LogicalFrameEndingReason::Trap(ref t)) if t.code==expected),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
fn hash(v: &mut VirtualMachine, ty: u32, values: &[Value]) -> i64 {
|
||||
push(v, values);
|
||||
v.execute_identity(OpCode::RefIdentityHash, ty, None, 0).unwrap();
|
||||
let Value::Int64(value) = v.operand_stack.pop().unwrap() else { panic!() };
|
||||
value
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_faults_preserve_complete_groups_and_charge_once_in_left_to_right_order() {
|
||||
let mut v = empty();
|
||||
let registry = v.validated_image.as_ref().unwrap().registry().clone();
|
||||
let live = v.heap.allocate_typed_struct(registry.clone(), TypeId(5)).unwrap();
|
||||
let wrong = v.heap.allocate_typed_struct(registry, TypeId(11)).unwrap();
|
||||
let stale = HeapRef { index: 999999, generation: 1 };
|
||||
for (left, right, values, code) in [
|
||||
(5, None, vec![Value::HeapRef(stale)], TRAP_INVALID_HANDLE),
|
||||
(5, None, vec![Value::HeapRef(wrong)], TRAP_TYPE),
|
||||
(5, None, vec![Value::HeapRef(HeapRef::NULL)], TRAP_TYPE),
|
||||
(6, None, vec![Value::HeapRef(live)], TRAP_TYPE),
|
||||
(9, None, vec![Value::HeapRef(HeapRef::NULL)], TRAP_TYPE),
|
||||
(10, None, vec![Value::HeapRef(HeapRef::NULL)], TRAP_INVALID_HANDLE),
|
||||
(7, None, vec![Value::Null, Value::Int64(0)], TRAP_TYPE),
|
||||
(7, None, vec![Value::HeapRef(live), Value::Null], TRAP_TYPE),
|
||||
(7, None, vec![Value::HeapRef(live), Value::Int64(1)], TRAP_TYPE),
|
||||
(7, None, vec![Value::HeapRef(live), Value::Int64(-1)], TRAP_TYPE),
|
||||
(7, None, vec![Value::HeapRef(live), Value::Int64(999)], TRAP_TYPE),
|
||||
(7, None, vec![Value::HeapRef(stale), Value::Int64(0)], TRAP_INVALID_HANDLE),
|
||||
// A null left side still validates the complete right group.
|
||||
(5, Some(7), vec![Value::Null, Value::HeapRef(live), Value::Int64(1)], TRAP_TYPE),
|
||||
(5, Some(11), vec![Value::Null, Value::HeapRef(stale)], TRAP_INVALID_HANDLE),
|
||||
// Both invalid: left TYPE takes precedence over right INVALID_HANDLE.
|
||||
(5, Some(5), vec![Value::HeapRef(wrong), Value::HeapRef(stale)], TRAP_TYPE),
|
||||
] {
|
||||
v.operand_stack.truncate(8); // Entry's eight reserved local slots.
|
||||
push(&mut v, &values);
|
||||
let operands = v.operand_stack.as_slice().to_vec();
|
||||
let before = usage(&v);
|
||||
let cycles = v.cycles;
|
||||
let op = if right.is_some() { OpCode::RefIdentityEq } else { OpCode::RefIdentityHash };
|
||||
let width = if left == 7 { 2 } else { 1 } + right.map_or(0, |r| if r == 7 { 2 } else { 1 });
|
||||
fault(v.execute_identity(op, left, right, 0), code);
|
||||
assert_eq!(v.operand_stack.as_slice(), operands);
|
||||
assert_eq!(usage(&v), before);
|
||||
assert_eq!(v.cycles - cycles, op.cycles() + width);
|
||||
}
|
||||
v.operand_stack.truncate(8);
|
||||
let before = v.cycles;
|
||||
fault(v.execute_identity(OpCode::RefIdentityEq, 7, Some(7), 0), TRAP_STACK_UNDERFLOW);
|
||||
assert_eq!(v.cycles - before, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gc_preserves_live_aliases_but_hashes_do_not_root_collected_handles() {
|
||||
let mut v = empty();
|
||||
let registry = v.validated_image.as_ref().unwrap().registry().clone();
|
||||
let live = v.heap.allocate_typed_struct(registry.clone(), TypeId(5)).unwrap();
|
||||
let dead = v.heap.allocate_typed_struct(registry.clone(), TypeId(5)).unwrap();
|
||||
let live_hash = hash(&mut v, 5, &[Value::HeapRef(live)]);
|
||||
let dead_hash = hash(&mut v, 5, &[Value::HeapRef(dead)]);
|
||||
v.globals.push(Value::HeapRef(live)).unwrap();
|
||||
v.globals.push(Value::Int64(dead_hash)).unwrap();
|
||||
v.gc_alloc_threshold = 1;
|
||||
v.handle_safepoint().unwrap();
|
||||
assert!(v.heap.is_valid(live));
|
||||
assert!(!v.heap.is_valid(dead));
|
||||
assert_eq!(hash(&mut v, 7, &[Value::HeapRef(live), Value::Int64(0)]), live_hash);
|
||||
let replacement = v.heap.allocate_typed_struct(registry, TypeId(5)).unwrap();
|
||||
assert_eq!(replacement.index, dead.index);
|
||||
assert_ne!(replacement.generation, dead.generation);
|
||||
push(&mut v, &[Value::HeapRef(dead), Value::HeapRef(replacement)]);
|
||||
fault(v.execute_identity(OpCode::RefIdentityEq, 5, Some(5), 0), TRAP_INVALID_HANDLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_queries_ignore_exhausted_guest_and_scratch_quotas_and_do_not_collect() {
|
||||
let mut v = empty();
|
||||
let registry = v.validated_image.as_ref().unwrap().registry().clone();
|
||||
let live = v.heap.allocate_typed_struct(registry, TypeId(5)).unwrap();
|
||||
push(&mut v, &[Value::HeapRef(live)]);
|
||||
for q in [
|
||||
Q::GuestBytes,
|
||||
Q::HandleSlots,
|
||||
Q::AuxiliaryBytes,
|
||||
Q::TemporaryBytes,
|
||||
Q::StringBytes,
|
||||
Q::StringAllocations,
|
||||
] {
|
||||
v.budget.test_lower_limit(q, v.budget.used(q));
|
||||
}
|
||||
let before = usage(&v);
|
||||
let allocations = v.heap.allocation_count();
|
||||
v.gc_alloc_threshold = 1;
|
||||
v.execute_identity(OpCode::RefIdentityHash, 5, None, 0).unwrap();
|
||||
v.execute_inline_intrinsic(&HASH_INTRINSICS[0], 0).unwrap();
|
||||
assert_eq!(v.heap.allocation_count(), allocations);
|
||||
assert!(v.heap.is_valid(live)); // No root remains, but neither operation is a safepoint.
|
||||
assert_eq!(usage(&v), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_faults_preserve_float_bits_owners_and_attempted_cost() {
|
||||
let mut v = empty();
|
||||
for bits in [f64::INFINITY.to_bits(), f64::NEG_INFINITY.to_bits(), 0x7ff8000000001234] {
|
||||
push(&mut v, &[Value::Float(f64::from_bits(bits))]);
|
||||
let before = usage(&v);
|
||||
let cycles = v.cycles;
|
||||
fault(
|
||||
v.execute_inline_intrinsic(&HASH_INTRINSICS[1], 0),
|
||||
prometeu_bytecode::TRAP_NON_FINITE,
|
||||
);
|
||||
assert!(matches!(v.operand_stack.last(),Some(Value::Float(f)) if f.to_bits()==bits));
|
||||
assert_eq!(usage(&v), before);
|
||||
assert_eq!(v.cycles - cycles, 8);
|
||||
v.operand_stack.pop();
|
||||
}
|
||||
let foreign: Arc<str> = Arc::from("owner outside image and session");
|
||||
push(&mut v, &[Value::String(foreign.clone())]);
|
||||
let refs = Arc::strong_count(&foreign);
|
||||
let before = usage(&v);
|
||||
let cycles = v.cycles;
|
||||
fault(v.execute_inline_intrinsic(&HASH_INTRINSICS[2], 0), TRAP_TYPE);
|
||||
assert_eq!(Arc::strong_count(&foreign), refs);
|
||||
assert_eq!(usage(&v), before);
|
||||
assert_eq!(v.cycles - cycles, 8 + foreign.len() as u64);
|
||||
let mut overflow = HASH_INTRINSICS[2].clone();
|
||||
overflow.cost_per_byte = u64::MAX;
|
||||
let cycles = v.cycles;
|
||||
fault(v.execute_inline_intrinsic(&overflow, 0), TRAP_RESOURCE_LIMIT);
|
||||
assert_eq!(v.cycles - cycles, 8);
|
||||
assert_eq!(Arc::strong_count(&foreign), refs);
|
||||
v.operand_stack.pop();
|
||||
let cycles = v.cycles;
|
||||
fault(v.execute_inline_intrinsic(&HASH_INTRINSICS[2], 0), TRAP_STACK_UNDERFLOW);
|
||||
assert_eq!(v.cycles - cycles, 8);
|
||||
push(&mut v, &[Value::Int64(7)]);
|
||||
let cycles = v.cycles;
|
||||
fault(v.execute_inline_intrinsic(&HASH_INTRINSICS[2], 0), TRAP_TYPE);
|
||||
assert_eq!(v.cycles - cycles, 8);
|
||||
assert_eq!(v.operand_stack.last(), Some(&Value::Int64(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_string_content_hashes_across_image_session_and_import_owners() {
|
||||
use prometeu_bytecode::model::ConstantPoolEntry as K;
|
||||
let mut v = vm(
|
||||
&[("PUSH_CONST 0\nINTRINSIC 0x4102\nRET", sig(&[], &[0]))],
|
||||
&[K::String("same\0π".into())],
|
||||
);
|
||||
step(&mut v).unwrap();
|
||||
let Value::String(image_owner) = v.operand_stack.last().unwrap().clone() else { panic!() };
|
||||
v.strings = Some(crate::string_ledger::StringLedger::new(v.budget.clone()).unwrap());
|
||||
let session = v.strings.as_ref().unwrap().concat("same", "\0π").unwrap();
|
||||
let imported = v.strings.as_ref().unwrap().import("same\0π").unwrap();
|
||||
assert!(!Arc::ptr_eq(&session, &imported));
|
||||
let mut hashes = vec![];
|
||||
v.operand_stack.pop();
|
||||
for owner in [&image_owner, &session, &imported] {
|
||||
push(&mut v, &[Value::String(owner.clone())]);
|
||||
let before = usage(&v);
|
||||
let count = Arc::strong_count(owner);
|
||||
v.execute_inline_intrinsic(&HASH_INTRINSICS[2], 0).unwrap();
|
||||
assert_eq!(usage(&v), before);
|
||||
assert_eq!(Arc::strong_count(owner), count - 1);
|
||||
hashes.push(v.operand_stack.pop().unwrap());
|
||||
}
|
||||
assert!(hashes.windows(2).all(|pair| pair[0] == pair[1]));
|
||||
}
|
||||
|
||||
fn missing(_: &[Value], _: &mut IntrinsicResults) -> Result<(), IntrinsicExecutionError> {
|
||||
Ok(())
|
||||
}
|
||||
fn wrong(_: &[Value], out: &mut IntrinsicResults) -> Result<(), IntrinsicExecutionError> {
|
||||
out.push(Value::Boolean(true))
|
||||
}
|
||||
fn excess(_: &[Value], out: &mut IntrinsicResults) -> Result<(), IntrinsicExecutionError> {
|
||||
out.push(Value::Int64(1))?;
|
||||
let _ = out.push(Value::Int64(2)); // Ignoring the error cannot publish a partial result.
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn shared_invocation_rejects_bad_outputs_without_consuming_original_string_owner() {
|
||||
let mut v = empty();
|
||||
let Value::String(content) = v.import_string_value(&Value::String(Arc::from("kept"))).unwrap()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
push(&mut v, &[Value::String(content.clone())]);
|
||||
let count = Arc::strong_count(&content);
|
||||
let before = usage(&v);
|
||||
for handler in [missing, wrong, excess] {
|
||||
let mut meta: IntrinsicMeta = HASH_INTRINSICS[2].clone();
|
||||
meta.owner = "test"; // The shared executor is independent of the hash namespace.
|
||||
meta.implementation = IntrinsicImplementation::BorrowedInline(handler);
|
||||
fault(v.execute_inline_intrinsic(&meta, 0), TRAP_INVALID_INTRINSIC);
|
||||
assert_eq!(Arc::strong_count(&content), count);
|
||||
assert_eq!(usage(&v), before);
|
||||
assert!(matches!(v.operand_stack.last(),Some(Value::String(s)) if Arc::ptr_eq(s,&content)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Shared borrowed invocation; algorithms receive no host/VM context.
|
||||
use super::*;
|
||||
use crate::{
|
||||
AbiType, IntrinsicExecutionError as E, IntrinsicImplementation as I, IntrinsicMeta,
|
||||
IntrinsicResults,
|
||||
};
|
||||
|
||||
impl VirtualMachine {
|
||||
fn inline_values(
|
||||
&self,
|
||||
values: &[Value],
|
||||
layout: &[AbiType],
|
||||
) -> Result<(), crate::value_contract::ValueError> {
|
||||
use crate::value_contract::ValueError;
|
||||
for (value, abi) in values.iter().zip(layout) {
|
||||
match value {
|
||||
Value::String(content) if self.validated_image.is_some() => {
|
||||
if !self.validated_image.as_ref().unwrap().retains_string(content)
|
||||
&& !self.strings.as_ref().is_some_and(|domain| domain.retains(content))
|
||||
{
|
||||
return Err(ValueError::Type);
|
||||
}
|
||||
}
|
||||
Value::HeapRef(reference) if matches!(abi, AbiType::Builtin(key) if key.name == "Random") =>
|
||||
{
|
||||
self.heap.random_state(*reference)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn execute_inline_intrinsic(
|
||||
&mut self,
|
||||
meta: &IntrinsicMeta,
|
||||
pc: u32,
|
||||
) -> Result<(), LogicalFrameEndingReason> {
|
||||
let op = OpCode::Intrinsic;
|
||||
let consumed = meta.arg_slots();
|
||||
let enough = self.temporary_slots() >= consumed;
|
||||
let args =
|
||||
if enough { &self.operand_stack[self.operand_stack.len() - consumed..] } else { &[] };
|
||||
let Some(cost) = meta.attempted_cost(args) else {
|
||||
self.cycles += meta.cost_cycles;
|
||||
return Err(self.trap(
|
||||
TRAP_RESOURCE_LIMIT,
|
||||
op as u16,
|
||||
"Intrinsic attempted cost overflow".into(),
|
||||
pc,
|
||||
));
|
||||
};
|
||||
self.cycles += cost;
|
||||
meta.validate_descriptor()
|
||||
.map_err(|message| self.trap(TRAP_INVALID_INTRINSIC, op as u16, message.into(), pc))?;
|
||||
if !enough {
|
||||
return Err(self.trap(
|
||||
TRAP_STACK_UNDERFLOW,
|
||||
op as u16,
|
||||
"Incomplete intrinsic operands".into(),
|
||||
pc,
|
||||
));
|
||||
}
|
||||
let I::BorrowedInline(handler) = meta.implementation else {
|
||||
return Err(self.trap(
|
||||
TRAP_INVALID_INTRINSIC,
|
||||
op as u16,
|
||||
"Wrong invocation profile".into(),
|
||||
pc,
|
||||
));
|
||||
};
|
||||
let base = self.operand_stack.len() - consumed;
|
||||
let args = &self.operand_stack[base..];
|
||||
meta.validate_argument_values(args).map_err(|_| {
|
||||
self.trap(TRAP_TYPE, op as u16, "Invalid intrinsic argument carrier".into(), pc)
|
||||
})?;
|
||||
self.inline_values(args, meta.arg_layout)
|
||||
.map_err(|error| self.value_trap(error, op, pc))?;
|
||||
let mut out = IntrinsicResults::new(meta.ret_slots());
|
||||
handler(args, &mut out).map_err(|error| match error {
|
||||
E::Numeric(error) => {
|
||||
self.trap(error.code, op as u16, format!("Intrinsic numeric fault: {error:?}"), pc)
|
||||
}
|
||||
_ => self.trap(
|
||||
TRAP_INVALID_INTRINSIC,
|
||||
op as u16,
|
||||
format!("Invalid intrinsic handler output: {error:?}"),
|
||||
pc,
|
||||
),
|
||||
})?;
|
||||
out.validate(meta).map_err(|error| {
|
||||
self.trap(
|
||||
TRAP_INVALID_INTRINSIC,
|
||||
op as u16,
|
||||
format!("Invalid intrinsic result: {error:?}"),
|
||||
pc,
|
||||
)
|
||||
})?;
|
||||
self.inline_values(out.as_slice(), meta.ret_layout).map_err(|_| {
|
||||
self.trap(
|
||||
TRAP_INVALID_INTRINSIC,
|
||||
op as u16,
|
||||
"Invalid intrinsic result ownership".into(),
|
||||
pc,
|
||||
)
|
||||
})?;
|
||||
self.operand_stack.truncate(base);
|
||||
for value in out.into_values() {
|
||||
self.operand_stack.push(value).expect("bounded result replaces admitted inputs");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user