feat(vm): add reference identity and deterministic value hashing
This commit is contained in:
@@ -134,3 +134,96 @@ fn provenance_queries_allocate_nothing_at_all_qualification_sizes() {
|
||||
assert_eq!(counts, (1, 1), "only snapshot Value storage allocates");
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "support/identity.rs"]
|
||||
mod identity_support;
|
||||
|
||||
#[test]
|
||||
fn identity_and_borrowed_hash_instruction_regions_do_not_allocate() {
|
||||
use prometeu_bytecode::model::ConstantPoolEntry as K;
|
||||
for (name, initialize, operand, operation, steps, closure) in [
|
||||
("hash_i64", "PUSH_I64 -73\nSET_LOCAL 0", "GET_LOCAL 0", "INTRINSIC 0x4100", 4, false),
|
||||
("hash_float", "PUSH_CONST 0\nSET_LOCAL 0", "GET_LOCAL 0", "INTRINSIC 0x4101", 4, false),
|
||||
("hash_string", "PUSH_CONST 1\nSET_LOCAL 0", "GET_LOCAL 0", "INTRINSIC 0x4102", 4, false),
|
||||
(
|
||||
"struct_hash",
|
||||
"STRUCT_NEW 5\nSET_LOCAL 0",
|
||||
"GET_LOCAL 0",
|
||||
"REF_IDENTITY_HASH 5",
|
||||
4,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"array_hash",
|
||||
"PUSH_I64 0\nARRAY_NEW 6\nSET_LOCAL 0",
|
||||
"GET_LOCAL 0",
|
||||
"REF_IDENTITY_HASH 6",
|
||||
4,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"fn_hash",
|
||||
"MAKE_CLOSURE fn=1,type=9\nSET_LOCAL 0",
|
||||
"GET_LOCAL 0",
|
||||
"REF_IDENTITY_HASH 9",
|
||||
4,
|
||||
true,
|
||||
),
|
||||
(
|
||||
"random_hash",
|
||||
"PUSH_I64 1\nINTRINSIC 0x4000\nSET_LOCAL 0",
|
||||
"GET_LOCAL 0",
|
||||
"REF_IDENTITY_HASH 10",
|
||||
4,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"trait_hash",
|
||||
"STRUCT_NEW 5\nREF_TO_TRAIT source=5,target=7\nSET_LOCAL 1\nSET_LOCAL 0",
|
||||
"GET_LOCAL 0\nGET_LOCAL 1",
|
||||
"REF_IDENTITY_HASH 7",
|
||||
5,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"struct_eq",
|
||||
"STRUCT_NEW 5\nSET_LOCAL 0",
|
||||
"GET_LOCAL 0\nGET_LOCAL 0",
|
||||
"REF_IDENTITY_EQ left=5,right=5",
|
||||
5,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"trait_eq",
|
||||
"STRUCT_NEW 5\nREF_TO_TRAIT source=5,target=7\nSET_LOCAL 1\nSET_LOCAL 0",
|
||||
"GET_LOCAL 0\nGET_LOCAL 1\nGET_LOCAL 0\nGET_LOCAL 1",
|
||||
"REF_IDENTITY_EQ left=7,right=7",
|
||||
7,
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let start = assemble(initialize).unwrap().len();
|
||||
let text = format!("{initialize}\n{operand}\n{operation}\nPOP\nJMP {start}");
|
||||
let mut bodies = vec![(text.as_str(), identity_support::sig(&[], &[]))];
|
||||
if closure {
|
||||
bodies.push(("RET", identity_support::sig(&[], &[])));
|
||||
}
|
||||
let mut vm =
|
||||
identity_support::vm(&bodies, &[K::Float64(-0.0), K::String("π\0".repeat(512))]);
|
||||
let mut host = HostContext::new(None);
|
||||
while vm.pc() != start {
|
||||
vm.step(&mut identity_support::Native, &mut host).unwrap();
|
||||
}
|
||||
for _ in 0..steps * 10 {
|
||||
vm.step(&mut identity_support::Native, &mut host).unwrap();
|
||||
}
|
||||
let heap_allocations = vm.heap().allocation_count();
|
||||
COUNTS.with(|c| c.set(Some((0, 0))));
|
||||
for _ in 0..steps * 1000 {
|
||||
vm.step(&mut identity_support::Native, &mut host).unwrap();
|
||||
}
|
||||
let counts = COUNTS.with(|c| c.replace(None).unwrap());
|
||||
assert_eq!(counts, (0, 0), "{name}: allocations and deallocations");
|
||||
assert_eq!(vm.heap().allocation_count(), heap_allocations, "{name}: guest allocations");
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,23 @@
|
||||
# Hash-v1 oracle provenance
|
||||
|
||||
`hash-conformance.tsv` is generated by `hash-oracle.py` against the official C
|
||||
XXH64 reference, not the Rust VM implementation. Ordinary tests read the checked-in
|
||||
vectors and need no library, network or Python dependency.
|
||||
|
||||
Reference: https://github.com/Cyan4973/xxHash/blob/v0.8.3/xxhash.h
|
||||
|
||||
Header SHA-256: `17973c0dc49d9854ca26caa191f0e12f7a424b68858d9a78de3860d959d85e4b`.
|
||||
The generator verifies both the header digest and `XXH_versionNumber()==803`.
|
||||
|
||||
Example reproduction on macOS, after downloading that pinned header:
|
||||
|
||||
```sh
|
||||
clang -dynamiclib -O2 -x c -DXXH_IMPLEMENTATION -DXXH_STATIC_LINKING_ONLY xxhash.h -o libxxhash-oracle.dylib
|
||||
python3 hash-oracle.py --header xxhash.h --library ./libxxhash-oracle.dylib
|
||||
```
|
||||
|
||||
On Linux, use `-shared -fPIC` instead of `-dynamiclib`. The generator explicitly
|
||||
encodes little-endian integers/reference components and finite Float bit patterns,
|
||||
canonicalizes signed zeros, and uses seed zero. The null row is the machine
|
||||
contract's direct zero result, not a hash of an empty message. Arbitrary `bytes`
|
||||
rows exercise the internal algorithm; they do not expose guest byte strings.
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Regenerate hash-v1 vectors using upstream XXH64, never the Rust executor."""
|
||||
import argparse
|
||||
import ctypes
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--library", required=True, type=Path)
|
||||
parser.add_argument("--header", required=True, type=Path)
|
||||
parser.add_argument("--output", type=Path, default=Path(__file__).with_name("hash-conformance.tsv"))
|
||||
args = parser.parse_args()
|
||||
expected = "17973c0dc49d9854ca26caa191f0e12f7a424b68858d9a78de3860d959d85e4b"
|
||||
assert hashlib.sha256(args.header.read_bytes()).hexdigest() == expected
|
||||
library = ctypes.CDLL(str(args.library.resolve()))
|
||||
assert library.XXH_versionNumber() == 803
|
||||
digest = library.XXH64
|
||||
digest.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint64]
|
||||
digest.restype = ctypes.c_uint64
|
||||
rows = ["kind\tinput\texpected_hash_hex"]
|
||||
|
||||
def emit(kind, value, data):
|
||||
buffer = ctypes.create_string_buffer(data)
|
||||
result = digest(ctypes.cast(buffer, ctypes.c_void_p), len(data), 0)
|
||||
rows.append(f"{kind}\t{value}\t{result:016X}")
|
||||
|
||||
for size in list(range(71)) + [95, 96, 97, 127, 128, 129, 255, 256, 257, 1024, 4097]:
|
||||
data = bytes((i * 131 + 17) & 255 for i in range(size))
|
||||
emit("bytes", data.hex(), data)
|
||||
for value in [0, 1, -1, 2, -2, -(2**63), 2**63 - 1, 2**53 + 1, 2**32]:
|
||||
emit("i64", value, struct.pack("<q", value))
|
||||
for bits in [0, 0x8000000000000000, 0x3FF0000000000000, 0xBFF0000000000000,
|
||||
0x3FE0000000000000, 0xBFE0000000000000, 1, 0x8000000000000001,
|
||||
0x000FFFFFFFFFFFFF, 0x0010000000000000,
|
||||
0x7FEFFFFFFFFFFFFF, 0xFFEFFFFFFFFFFFFF, 0x4340000000000000]:
|
||||
canonical = 0 if bits & 0x7FFFFFFFFFFFFFFF == 0 else bits
|
||||
emit("float", f"{bits:016X}", struct.pack("<Q", canonical))
|
||||
for value in ["", "hello", "\0", "ação 😀", "a" * 31, "a" * 32, "a" * 33, "z" * 1025]:
|
||||
data = value.encode("utf-8")
|
||||
emit("string", data.hex(), data)
|
||||
for index, generation in [(0, 1), (1, 1), (1, 2), (1024, 1), (2**32-1, 2**32-1)]:
|
||||
emit("reference", f"{index},{generation}", struct.pack("<II", index, generation))
|
||||
rows.append("null\tnull\t0000000000000000")
|
||||
args.output.write_text("\n".join(rows) + "\n", encoding="utf-8")
|
||||
print(f"Generated {len(rows)-1} vectors with upstream XXH64 v0.8.3, seed 0.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
#[path = "support/identity.rs"]
|
||||
mod support;
|
||||
use prometeu_bytecode::{Value, model::ConstantPoolEntry as K};
|
||||
use prometeu_vm::{HostContext, LogicalFrameEndingReason as End};
|
||||
use support::*;
|
||||
|
||||
#[test]
|
||||
fn scalar_pbx_execution_matches_independent_c_reference_vectors() {
|
||||
let mut count = 0;
|
||||
for row in include_str!("fixtures/hash-conformance.tsv").lines().skip(1) {
|
||||
let fields: Vec<_> = row.split('\t').collect();
|
||||
let expected = u64::from_str_radix(fields[2], 16).unwrap() as i64;
|
||||
let (value, id, bytes) = match fields[0] {
|
||||
"i64" => (K::Int64(fields[1].parse().unwrap()), 0x4100, 0),
|
||||
"float" => {
|
||||
(K::Float64(f64::from_bits(u64::from_str_radix(fields[1], 16).unwrap())), 0x4101, 0)
|
||||
}
|
||||
"string" => {
|
||||
let bytes = hex_bytes(fields[1]);
|
||||
let size = bytes.len();
|
||||
(K::String(String::from_utf8(bytes).unwrap()), 0x4102, size)
|
||||
}
|
||||
"null" => (K::Null, 0x4102, 0),
|
||||
_ => continue,
|
||||
};
|
||||
let source = format!("PUSH_CONST 0\nINTRINSIC {id}\nRET");
|
||||
let mut vm = vm(&[(&source, sig(&[], &[0]))], &[value]);
|
||||
step(&mut vm).unwrap();
|
||||
let report = vm.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(report.reason, End::BudgetExhausted);
|
||||
assert_eq!(report.cycles_used, 8 + bytes as u64, "{row}");
|
||||
assert_eq!(&*vm.operand_stack_top(1), &[Value::Int64(expected)], "{row}");
|
||||
assert_eq!(run(&mut vm).reason, End::EndOfRom);
|
||||
count += 1;
|
||||
}
|
||||
assert_eq!(count, 31);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identities_survive_mutation_and_views_validate_implementation_zero() {
|
||||
let source = "STRUCT_NEW 5\nSET_LOCAL 0\nGET_LOCAL 0\nREF_IDENTITY_HASH 5\nSET_LOCAL 1\nGET_LOCAL 0\nPUSH_I64 73\nSTRUCT_SET type=5,field=0\nGET_LOCAL 0\nREF_IDENTITY_HASH 5\nGET_LOCAL 1\nEQ\nGET_LOCAL 0\nREF_TO_TRAIT source=5,target=7\nREF_IDENTITY_HASH 7\nGET_LOCAL 1\nEQ\nGET_LOCAL 0\nREF_TO_TRAIT source=5,target=7\nGET_LOCAL 0\nREF_TO_TRAIT source=5,target=8\nREF_IDENTITY_EQ left=7,right=8\nGET_LOCAL 0\nSTRUCT_NEW 5\nREF_IDENTITY_EQ left=5,right=5\nRET";
|
||||
let mut vm = vm(&[(source, sig(&[], &[2, 2, 2, 2]))], &[]);
|
||||
assert_eq!(run(&mut vm).reason, End::EndOfRom);
|
||||
assert_eq!(
|
||||
&*vm.operand_stack_top(4),
|
||||
&[Value::Boolean(false), Value::Boolean(true), Value::Boolean(true), Value::Boolean(true)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_closure_and_random_have_instance_identity() {
|
||||
for (source, bodies) in [
|
||||
(
|
||||
"PUSH_I64 1\nARRAY_NEW 6\nSET_LOCAL 0\nGET_LOCAL 0\nREF_IDENTITY_HASH 6\nSET_LOCAL 1\nGET_LOCAL 0\nPUSH_I64 0\nPUSH_I64 42\nARRAY_SET 6\nGET_LOCAL 0\nREF_IDENTITY_HASH 6\nGET_LOCAL 1\nEQ\nRET",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"PUSH_I64 42\nINTRINSIC 0x4000\nSET_LOCAL 0\nGET_LOCAL 0\nREF_IDENTITY_HASH 10\nSET_LOCAL 1\nGET_LOCAL 0\nINTRINSIC 0x4001\nPOP\nGET_LOCAL 0\nREF_IDENTITY_HASH 10\nGET_LOCAL 1\nEQ\nRET",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"MAKE_CLOSURE fn=1,type=9\nSET_LOCAL 0\nGET_LOCAL 0\nGET_LOCAL 0\nREF_IDENTITY_EQ left=9,right=9\nGET_LOCAL 0\nMAKE_CLOSURE fn=1,type=9\nREF_IDENTITY_EQ left=9,right=9\nNOT\nAND\nRET",
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let mut functions = vec![(source, sig(&[], &[2]))];
|
||||
if bodies {
|
||||
functions.push(("RET", sig(&[], &[])));
|
||||
}
|
||||
let mut vm = vm(&functions, &[]);
|
||||
assert_eq!(run(&mut vm).reason, End::EndOfRom);
|
||||
assert_eq!(&*vm.operand_stack_top(1), &[Value::Boolean(true)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_null_groups_compare_and_hash_without_instance_faults() {
|
||||
let source = "PUSH_CONST 0\nPUSH_CONST 0\nREF_IDENTITY_HASH 7\nPUSH_CONST 0\nPUSH_CONST 0\nPUSH_CONST 0\nREF_IDENTITY_EQ left=6,right=7\nRET";
|
||||
let mut vm = vm(&[(source, sig(&[], &[0, 2]))], &[K::Null]);
|
||||
assert_eq!(run(&mut vm).reason, End::EndOfRom);
|
||||
assert_eq!(&*vm.operand_stack_top(2), &[Value::Boolean(true), Value::Int64(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_rejects_ineligible_sources_and_bad_native_ids_even_when_dead() {
|
||||
for instruction in [
|
||||
"REF_IDENTITY_HASH 0",
|
||||
"REF_IDENTITY_HASH 3",
|
||||
"REF_IDENTITY_HASH 4",
|
||||
"REF_IDENTITY_HASH 12",
|
||||
"REF_IDENTITY_HASH 13",
|
||||
"REF_IDENTITY_HASH 14",
|
||||
"REF_IDENTITY_HASH 9999",
|
||||
"REF_IDENTITY_EQ left=5,right=3",
|
||||
"INTRINSIC 0x41FF",
|
||||
] {
|
||||
let text = format!("HALT\n{instruction}");
|
||||
assert!(image(&[(&text, sig(&[], &[]))], &[]).is_err(), "{instruction}");
|
||||
}
|
||||
assert!(image(&[("PUSH_CONST 0\nINTRINSIC 0x4102\nRET", sig(&[], &[0]))], &[K::Null]).is_ok());
|
||||
for id in [0x1103, 0x4100, 0x4101] {
|
||||
let text = format!("PUSH_CONST 0\nINTRINSIC {id}\nPOP\nRET");
|
||||
assert!(image(&[(&text, sig(&[], &[]))], &[K::Null]).is_err(), "{id}");
|
||||
}
|
||||
assert!(image(&[("PUSH_I64 3\nREF_IDENTITY_HASH 5\nRET", sig(&[], &[0]))], &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_instruction_budget_admission_preserves_zero_and_overshoot() {
|
||||
let mut vm = vm(
|
||||
&[("PUSH_CONST 0\nINTRINSIC 0x4102\nRET", sig(&[], &[0]))],
|
||||
&[K::String("x".repeat(65))],
|
||||
);
|
||||
step(&mut vm).unwrap();
|
||||
let before = vm.pc();
|
||||
let zero = vm.run_budget(0, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(zero.cycles_used, 0);
|
||||
assert_eq!(vm.pc(), before);
|
||||
let one = vm.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(one.reason, End::BudgetExhausted);
|
||||
assert_eq!(one.cycles_used, 73);
|
||||
assert_eq!(one.steps_executed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_eligible_absence_has_zero_hash_and_exact_identity_instruction_cost() {
|
||||
for (ty, width) in [(5, 1), (6, 1), (7, 2), (9, 1), (10, 1)] {
|
||||
let source = format!("{}REF_IDENTITY_HASH {ty}\nRET", "PUSH_CONST 0\n".repeat(width));
|
||||
let mut vm = vm(&[(&source, sig(&[], &[0]))], &[K::Null]);
|
||||
for _ in 0..width {
|
||||
step(&mut vm).unwrap();
|
||||
}
|
||||
let before = vm.pc();
|
||||
let zero = vm.run_budget(0, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!((zero.cycles_used, zero.steps_executed), (0, 0));
|
||||
assert_eq!(vm.pc(), before);
|
||||
let one = vm.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!((one.cycles_used, one.steps_executed), (8 + width as u64, 1));
|
||||
assert_eq!(&*vm.operand_stack_top(1), &[Value::Int64(0)]);
|
||||
}
|
||||
for source in [
|
||||
"PUSH_CONST 0\nSTRUCT_NEW 5\nREF_IDENTITY_EQ left=6,right=5\nRET",
|
||||
"STRUCT_NEW 5\nSTRUCT_NEW 11\nREF_IDENTITY_EQ left=5,right=11\nRET",
|
||||
] {
|
||||
let mut vm = vm(&[(source, sig(&[], &[2]))], &[K::Null]);
|
||||
step(&mut vm).unwrap();
|
||||
step(&mut vm).unwrap();
|
||||
let one = vm.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!((one.cycles_used, one.steps_executed), (6, 1));
|
||||
assert_eq!(&*vm.operand_stack_top(1), &[Value::Boolean(false)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_vm::{
|
||||
AbiType, BuiltinScalarType as S, IntrinsicCostModel as C, intrinsic_catalog,
|
||||
intrinsic_catalog_csv, lookup_intrinsic_by_id,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn schema_two_has_exact_columns_profiles_and_per_slot_nullable_lists() {
|
||||
let csv = intrinsic_catalog_csv();
|
||||
assert_eq!(csv, include_str!("../../../../docs/vm-arch/INTRINSICS.csv"));
|
||||
let mut rows = csv.lines();
|
||||
assert_eq!(
|
||||
rows.next().unwrap(),
|
||||
"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"
|
||||
);
|
||||
let mut ids = BTreeSet::new();
|
||||
let mut keys = BTreeSet::new();
|
||||
let mut previous = 0;
|
||||
for row in rows {
|
||||
let f: Vec<_> = row.split(',').collect();
|
||||
assert_eq!(f.len(), 25);
|
||||
assert_eq!(f[18], "2");
|
||||
let id = f[1].parse::<u32>().unwrap();
|
||||
assert!(id > previous);
|
||||
previous = id;
|
||||
assert!(ids.insert(id));
|
||||
assert!(keys.insert((f[2], f[3])));
|
||||
let meta = lookup_intrinsic_by_id(id).unwrap();
|
||||
meta.validate_descriptor().unwrap();
|
||||
assert_eq!(f[19].split('|').filter(|s| !s.is_empty()).count(), meta.arg_slots());
|
||||
assert_eq!(f[20], meta.invocation_model());
|
||||
assert_eq!(f[21], meta.scratch_model());
|
||||
assert_eq!(f[22], meta.context_access());
|
||||
if id < 0x4100 {
|
||||
assert_eq!(f[21], "existing_contract_v1");
|
||||
assert_eq!(f[23], "");
|
||||
assert_eq!(f[24], "0");
|
||||
assert_eq!(f[20], if f[4] == "random" { "vm_owned_v1" } else { "host_buffered_v1" });
|
||||
for (abi, nullable) in meta.arg_layout.iter().zip(meta.arg_nullable) {
|
||||
assert_eq!(*nullable, matches!(abi,AbiType::Builtin(key) if key.name=="Random"));
|
||||
}
|
||||
} else {
|
||||
assert_eq!(&f[20..23], &["borrowed_inline_v1", "none", "none"]);
|
||||
assert_eq!(meta.cost_cycles, 8);
|
||||
assert_eq!(meta.ret_layout, &[AbiType::Scalar(S::Int64)]);
|
||||
assert_eq!(meta.arg_nullable, &[id == 0x4102]);
|
||||
}
|
||||
}
|
||||
assert_eq!(ids.len(), 108);
|
||||
assert_eq!(intrinsic_catalog().count(), 108);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_descriptors_fail_instead_of_gaining_implicit_capabilities() {
|
||||
let original = *lookup_intrinsic_by_id(0x4102).unwrap();
|
||||
for variant in 0..14 {
|
||||
let mut meta = original;
|
||||
match variant {
|
||||
0 => meta.arg_nullable = &[],
|
||||
1 => meta.parameter_names = &[],
|
||||
2 => meta.cost_arg_index = None,
|
||||
3 => meta.cost_arg_index = Some(1),
|
||||
4 => meta.cost_per_byte = 0,
|
||||
5 => meta.attempt_cost_cycles = 1,
|
||||
6 => meta.max_attempts = 1,
|
||||
7 => meta.may_allocate = true,
|
||||
8 => meta.mutates_guest_state = true,
|
||||
9 => meta.deterministic = false,
|
||||
10 => meta.ret_layout = &[AbiType::Scalar(S::Int64); 4],
|
||||
11 => meta.ret_layout = &[AbiType::Scalar(S::Int64); 2],
|
||||
12 => meta.ret_layout = &[AbiType::DynamicPayload],
|
||||
13 => meta.arg_layout = &[AbiType::DynamicTag],
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(meta.validate_descriptor().is_err(), "variant {variant}");
|
||||
}
|
||||
let mut meta = *lookup_intrinsic_by_id(0x4100).unwrap();
|
||||
meta.arg_nullable = &[true];
|
||||
assert!(meta.validate_descriptor().is_err());
|
||||
meta.arg_nullable = &[false];
|
||||
meta.cost_arg_index = Some(0);
|
||||
assert!(meta.validate_descriptor().is_err());
|
||||
meta.cost_model = C::ArgumentUtf8BytesV1;
|
||||
meta.cost_per_byte = 1;
|
||||
assert!(meta.validate_descriptor().is_err());
|
||||
meta.cost_model = C::RandomRejectionV1;
|
||||
meta.cost_arg_index = None;
|
||||
meta.cost_per_byte = 0;
|
||||
meta.attempt_cost_cycles = 8;
|
||||
meta.max_attempts = 64;
|
||||
assert!(meta.validate_descriptor().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nullability_does_not_relax_existing_string_or_numeric_arguments() {
|
||||
for id in [0x4100, 0x4101, 0x1103] {
|
||||
assert!(
|
||||
lookup_intrinsic_by_id(id).unwrap().validate_argument_values(&[Value::Null]).is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
lookup_intrinsic_by_id(0x4102).unwrap().validate_argument_values(&[Value::Null]).is_ok()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
#![allow(dead_code)]
|
||||
use prometeu_bytecode::{
|
||||
assemble, load_limits::LoadBudget, model::ConstantPoolEntry, registry::*,
|
||||
registry_codec::PbxModule,
|
||||
};
|
||||
use prometeu_vm::{
|
||||
HostContext, HostReturn, LogicalFrameEndingReason, NativeInterface, ValidatedProgramImage,
|
||||
VirtualMachine, VmInitError,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct Native;
|
||||
impl NativeInterface for Native {
|
||||
fn syscall(
|
||||
&mut self,
|
||||
_: u32,
|
||||
_: &[prometeu_bytecode::Value],
|
||||
_: &mut HostReturn,
|
||||
_: &mut HostContext,
|
||||
) -> Result<(), prometeu_hal::vm_fault::VmFault> {
|
||||
panic!("identity corpus uses no host syscall")
|
||||
}
|
||||
}
|
||||
pub fn sig(parameters: &[u32], results: &[u32]) -> Signature {
|
||||
Signature {
|
||||
parameters: parameters
|
||||
.iter()
|
||||
.map(|&id| NamedType { type_id: TypeId(id), name: None })
|
||||
.collect(),
|
||||
results: results.iter().copied().map(TypeId).collect(),
|
||||
}
|
||||
}
|
||||
pub fn types() -> Vec<TypeDecl> {
|
||||
let field = || NamedType { type_id: TypeId(0), name: None };
|
||||
vec![
|
||||
TypeKind::Builtin(BuiltinId::INT64),
|
||||
TypeKind::Builtin(BuiltinId::FLOAT),
|
||||
TypeKind::Builtin(BuiltinId::BOOL),
|
||||
TypeKind::Builtin(BuiltinId::STRING),
|
||||
TypeKind::Builtin(BuiltinId::DYNAMIC),
|
||||
TypeKind::Struct(vec![field()]),
|
||||
TypeKind::Array(TypeId(0)),
|
||||
TypeKind::Trait(vec![]),
|
||||
TypeKind::Trait(vec![]),
|
||||
TypeKind::Fn(sig(&[], &[])),
|
||||
TypeKind::Builtin(BuiltinId::RANDOM),
|
||||
TypeKind::Struct(vec![field()]),
|
||||
TypeKind::Builtin(BuiltinId::COLOR),
|
||||
TypeKind::Builtin(BuiltinId::VEC2),
|
||||
TypeKind::Builtin(BuiltinId::PIXEL),
|
||||
TypeKind::Builtin(BuiltinId::INT32),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|kind| TypeDecl { name: None, kind })
|
||||
.collect()
|
||||
}
|
||||
pub fn image(
|
||||
bodies: &[(&str, Signature)],
|
||||
constants: &[ConstantPoolEntry],
|
||||
) -> Result<Arc<ValidatedProgramImage>, VmInitError> {
|
||||
let mut code = vec![];
|
||||
let mut functions = vec![];
|
||||
for (source, signature) in bodies {
|
||||
let body = assemble(source).unwrap();
|
||||
functions.push(FunctionDecl {
|
||||
signature: signature.clone(),
|
||||
local_slots: 8,
|
||||
max_stack_slots: 64,
|
||||
code_offset: code.len() as u32,
|
||||
code_len: body.len() as u32,
|
||||
..Default::default()
|
||||
});
|
||||
code.extend(body);
|
||||
}
|
||||
let mut budget = LoadBudget::new(Default::default());
|
||||
let registry = Registry::resolve(
|
||||
RegistryDeclarations {
|
||||
types: types(),
|
||||
functions,
|
||||
implementations: vec![
|
||||
ImplementationDecl { owner: TypeId(5), trait_id: TypeId(7), methods: vec![] },
|
||||
ImplementationDecl { owner: TypeId(5), trait_id: TypeId(8), methods: vec![] },
|
||||
],
|
||||
},
|
||||
code.len(),
|
||||
&mut budget,
|
||||
)
|
||||
.unwrap();
|
||||
let bytes = PbxModule {
|
||||
registry: ®istry,
|
||||
code: &code,
|
||||
constants,
|
||||
debug: None,
|
||||
exports: &[],
|
||||
syscalls: &[],
|
||||
}
|
||||
.serialize(&mut budget)
|
||||
.unwrap();
|
||||
ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(Default::default()), 0)
|
||||
}
|
||||
pub fn vm(bodies: &[(&str, Signature)], constants: &[ConstantPoolEntry]) -> VirtualMachine {
|
||||
let mut vm = VirtualMachine::from_image(image(bodies, constants).unwrap(), Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
vm
|
||||
}
|
||||
pub fn run(vm: &mut VirtualMachine) -> prometeu_vm::BudgetReport {
|
||||
vm.run_budget(1_000_000, &mut Native, &mut HostContext::new(None)).unwrap()
|
||||
}
|
||||
pub fn step(vm: &mut VirtualMachine) -> Result<(), LogicalFrameEndingReason> {
|
||||
vm.step(&mut Native, &mut HostContext::new(None))
|
||||
}
|
||||
pub fn hex_bytes(value: &str) -> Vec<u8> {
|
||||
(0..value.len()).step_by(2).map(|i| u8::from_str_radix(&value[i..i + 2], 16).unwrap()).collect()
|
||||
}
|
||||
Reference in New Issue
Block a user