feat(vm): add typed array and struct guest operations
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good

Add seven Registry-backed collection opcodes with bounded verification, complete value groups, transactional publication and exact attempt costs. Publish ISA, memory and cycle contracts, producer handoff and the completed lesson.

Validate with 925 workspace tests, optimized collection suites and all eight coverage domain gates. Make headless fixture directory names unique for parallel tests.
This commit is contained in:
2026-10-08 10:36:20 +01:00
parent 8732f4b0f4
commit 86bade3e1f
27 changed files with 1591 additions and 46 deletions
+77 -31
View File
@@ -3,6 +3,7 @@ use crate::call_frame::CallFrame;
use crate::object::{ObjectHeader, ObjectKind};
use crate::resource_budget::{
BudgetVec, Reservation, ResourceFailure, ResourceReason, RuntimeBudget, RuntimeResource as Q,
VecGrowth,
};
use crate::typed_storage::TypedStorage;
use crate::value_contract::{self, ValueError, ValueGroup};
@@ -62,6 +63,19 @@ impl StoredAllocation {
}
}
// Candidate allocations own all reservations until a fully initialized object
// is published. Dropping the candidate leaves handle tables unchanged.
struct PreparedInsertion {
storage: BudgetVec<StoredObject>,
new_slot: Option<PreparedSlot>,
}
struct PreparedSlot {
charge: Reservation,
objects: Option<VecGrowth<Option<StoredAllocation>>>,
generations: Option<VecGrowth<u32>>,
free: Option<VecGrowth<usize>>,
}
/// Execution state of a coroutine.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum CoroutineState {
@@ -157,24 +171,35 @@ impl Heap {
Ok(())
}
fn insert_object(&mut self, obj: StoredObject) -> Result<HeapRef, ResourceFailure> {
fn prepare_insertion(&self) -> Result<PreparedInsertion, ResourceFailure> {
self.check_slot()?;
let mut storage = BudgetVec::new(&self.budget, Q::GuestBytes);
storage.push(obj)?;
let obj = StoredAllocation(storage);
let bytes = obj.bytes();
let handle = if let Some(&idx) = self.free_list.last() {
self.free_list.pop();
debug_assert!(self.objects[idx].is_none());
self.objects[idx] = Some(obj);
HeapRef { index: idx as u32, generation: self.generations[idx] }
storage.reserve(1)?;
let new_slot = if self.free_list.is_empty() {
Some(PreparedSlot {
charge: self.budget.reserve(Q::HandleSlots, 1)?,
objects: self.objects.prepare_growth(1)?,
generations: self.generations.prepare_growth(1)?,
free: self
.free_list
.prepare_growth(self.objects.len() + 1 - self.free_list.len())?,
})
} else {
let slot_charge = self.budget.reserve(Q::HandleSlots, 1)?;
// Stage all three capacities. Failure drops the candidate buffers and
// object, without publishing a slot or retaining partial table growth.
let objects = self.objects.prepare_growth(1)?;
let generations = self.generations.prepare_growth(1)?;
let free =
self.free_list.prepare_growth(self.objects.len() + 1 - self.free_list.len())?;
None
};
Ok(PreparedInsertion { storage, new_slot })
}
fn insert_object(&mut self, obj: StoredObject) -> Result<HeapRef, ResourceFailure> {
let prepared = self.prepare_insertion()?;
Ok(self.commit_insertion(prepared, obj))
}
fn commit_insertion(&mut self, mut prepared: PreparedInsertion, obj: StoredObject) -> HeapRef {
prepared.storage.push(obj).expect("object header reserved before initialization");
let obj = StoredAllocation(prepared.storage);
let bytes = obj.bytes();
let handle = if let Some(PreparedSlot { charge: slot_charge, objects, generations, free }) =
prepared.new_slot
{
self.objects.commit_growth(objects);
self.generations.commit_growth(generations);
self.free_list.commit_growth(free);
@@ -183,10 +208,15 @@ impl Heap {
self.generations.push(1).expect("reserved generation slot");
self.slots_charge.absorb(slot_charge);
HeapRef { index: idx as u32, generation: 1 }
} else {
let idx = self.free_list.pop().expect("reserved reusable handle");
debug_assert!(self.objects[idx].is_none());
self.objects[idx] = Some(obj);
HeapRef { index: idx as u32, generation: self.generations[idx] }
};
self.used_bytes.fetch_add(bytes, Ordering::Relaxed);
self.allocation_count.fetch_add(1, Ordering::Relaxed);
Ok(handle)
handle
}
#[cfg(test)]
@@ -523,14 +553,26 @@ impl Heap {
}
Ok(storage.type_id())
}
pub(crate) fn typed_array_len(
&self,
r: HeapRef,
registry: &Registry,
) -> Result<usize, ValueError> {
self.concrete_type(r, registry)?;
let storage = self.typed_object(r)?;
if registry.type_layout(storage.type_id()).unwrap().array.is_none() {
return Err(ValueError::Type);
}
Ok(storage.len())
}
pub(crate) fn allocate_typed_struct(
&mut self,
registry: Arc<Registry>,
type_id: TypeId,
) -> Result<HeapRef, ValueError> {
self.check_slot()?;
let prepared = self.prepare_insertion()?;
let storage = TypedStorage::new_struct(registry, type_id, &self.budget)?;
self.insert_typed(ObjectKind::Struct, 0, storage)
Ok(self.insert_typed(prepared, ObjectKind::Struct, 0, storage))
}
pub(crate) fn allocate_typed_array(
&mut self,
@@ -538,25 +580,29 @@ impl Heap {
type_id: TypeId,
count: u32,
) -> Result<HeapRef, ValueError> {
self.check_slot()?;
let prepared = self.prepare_insertion()?;
let storage = TypedStorage::new_array(registry, type_id, count, &self.budget)?;
self.insert_typed(ObjectKind::Array, count, storage)
Ok(self.insert_typed(prepared, ObjectKind::Array, count, storage))
}
fn insert_typed(
&mut self,
prepared: PreparedInsertion,
kind: ObjectKind,
count: u32,
storage: TypedStorage,
) -> Result<HeapRef, ValueError> {
Ok(self.insert_object(StoredObject {
header: ObjectHeader::new(kind, count),
payload: BudgetVec::new(&self.budget, Q::GuestBytes),
array_elems: None,
closure_env: None,
coroutine: None,
typed: Some(storage),
dynamic_box: None,
})?)
) -> HeapRef {
self.commit_insertion(
prepared,
StoredObject {
header: ObjectHeader::new(kind, count),
payload: BudgetVec::new(&self.budget, Q::GuestBytes),
array_elems: None,
closure_env: None,
coroutine: None,
typed: Some(storage),
dynamic_box: None,
},
)
}
pub(crate) fn load_typed(
&self,
+2
View File
@@ -1,3 +1,5 @@
#[cfg(test)]
extern crate self as prometeu_vm;
mod builtins;
mod call_frame;
mod input_intrinsics;
@@ -410,6 +410,34 @@ fn transfer(
working[base + offset] = Fact::Carrier(abi_mask(*abi));
}
}
Op::StructNew | Op::ArrayNew => {
group(
&mut working[base..],
registry,
TypeId(instruction.imm_u32().unwrap()),
(instruction.pc as u64) << 32,
budget,
)?;
}
Op::ArrayLen => {
budget.work(1)?;
working[base] = Fact::Carrier(I64);
}
Op::StructGet | Op::ArrayGet => {
budget.work(3)?;
let (id, field) = if instruction.opcode == Op::StructGet {
instruction.imm_u32x2().unwrap()
} else {
(instruction.imm_u32().unwrap(), 0)
};
let layout = registry.type_layout(TypeId(id)).unwrap();
let ty = if instruction.opcode == Op::StructGet {
layout.instance.as_ref().unwrap().fields[field as usize].type_id
} else {
layout.array.unwrap().element_type_id
};
group(&mut working[base..], registry, ty, (instruction.pc as u64) << 32, budget)?;
}
Op::DynPack => {
budget.work(1)?;
let ty = TypeId(instruction.imm_u32().unwrap());
@@ -651,6 +679,32 @@ fn check(
base += registry.type_layout(parameter.type_id).unwrap().storage.slots as usize;
}
}
Op::ArrayNew => require(working[end - 1], I64, 0, registry, budget)?,
Op::StructGet | Op::StructSet | Op::ArrayLen | Op::ArrayGet | Op::ArraySet => {
budget.work(3)?;
let (id, field) = if matches!(instruction.opcode, Op::StructGet | Op::StructSet) {
instruction.imm_u32x2().unwrap()
} else {
(instruction.imm_u32().unwrap(), 0)
};
let ty = TypeId(id);
let effect = instruction.registry_stack_effect(registry)?.unwrap();
let base = end - effect.pops as usize;
check_group(&working[base..base + 1], ty, registry, budget)?;
let array = matches!(instruction.opcode, Op::ArrayGet | Op::ArraySet);
if array {
require(working[base + 1], I64, 1, registry, budget)?;
}
if matches!(instruction.opcode, Op::StructSet | Op::ArraySet) {
let layout = registry.type_layout(ty).unwrap();
let value_ty = if array {
layout.array.unwrap().element_type_id
} else {
layout.instance.as_ref().unwrap().fields[field as usize].type_id
};
check_group(&working[base + 1 + usize::from(array)..], value_ty, registry, budget)?;
}
}
Op::DynPack => {
budget.work(1)?;
let ty = TypeId(instruction.imm_u32().unwrap());
@@ -58,6 +58,10 @@ impl RuntimeBudget {
fn state(&self) -> MutexGuard<'_, State> {
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(test)]
pub(crate) fn test_lower_limit(&self, resource: RuntimeResource, limit: u64) {
self.state().limits.0[resource as usize] = limit;
}
pub fn used(&self, resource: RuntimeResource) -> u64 {
self.state().used[resource as usize]
}
@@ -342,3 +342,6 @@ pub(crate) mod tests;
#[cfg(test)]
mod ownership_tests;
#[cfg(test)]
pub(crate) use allocation::refuse_next_allocation;
@@ -6,6 +6,22 @@ use crate::resource_budget::{
use std::alloc::{Layout, alloc_zeroed, dealloc};
use std::ptr::NonNull;
#[cfg(test)]
thread_local! { static REFUSE_NEXT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
#[cfg(test)]
pub(crate) struct RefusalGuard;
#[cfg(test)]
impl Drop for RefusalGuard {
fn drop(&mut self) {
REFUSE_NEXT.with(|flag| flag.set(false));
}
}
#[cfg(test)]
pub(crate) fn refuse_next_allocation() -> RefusalGuard {
REFUSE_NEXT.with(|flag| flag.set(true));
RefusalGuard
}
#[derive(Debug)]
pub(super) struct Allocation {
ptr: NonNull<u8>,
@@ -26,6 +42,14 @@ impl Allocation {
budget.failure(Q::GuestBytes, ResourceReason::SizeOverflow, size as u64)
})?;
let charge = budget.reserve(Q::GuestBytes, size as u64)?;
#[cfg(test)]
if REFUSE_NEXT.with(|flag| flag.replace(false)) {
return Err(budget.failure(
Q::GuestBytes,
ResourceReason::AllocationFailed,
size as u64,
));
}
let ptr = if size == 0 {
// Never dereferenced/deallocated; no element exists in an empty payload.
NonNull::dangling()
@@ -1,4 +1,7 @@
use crate::resource_budget::BudgetVec;
mod collections;
#[cfg(test)]
mod collections_tests;
mod dynamic;
mod gc;
mod loader;
@@ -1410,6 +1413,20 @@ impl VirtualMachine {
let (source, target) = instr.imm_u32x2().unwrap();
return self.execute_reference(opcode, source, target, start_pc as u32);
}
OpCode::StructNew
| OpCode::StructGet
| OpCode::StructSet
| OpCode::ArrayNew
| OpCode::ArrayLen
| OpCode::ArrayGet
| OpCode::ArraySet => {
let (ty, field) = if matches!(opcode, OpCode::StructGet | OpCode::StructSet) {
instr.imm_u32x2().unwrap()
} else {
(instr.imm_u32().unwrap(), 0)
};
return self.execute_collection(opcode, ty, field, start_pc as u32);
}
OpCode::FrameSync => {
// Marks the logical end of a frame: consume cycles and signal to the driver
self.cycles += OpCode::FrameSync.cycles();
@@ -0,0 +1,194 @@
//! Whole-group collection attempts: charge, validate, reserve, prepare, commit.
use super::*;
use crate::resource_budget::ResourceReason;
use crate::value_contract::{self, ValueError, ValueGroup};
use prometeu_bytecode::registry::TypeId;
impl VirtualMachine {
pub(super) fn execute_collection(
&mut self,
opcode: OpCode,
id: u32,
field: u32,
pc: u32,
) -> Result<(), LogicalFrameEndingReason> {
let image = self.validated_image.clone().ok_or_else(|| {
self.trap(
prometeu_bytecode::TRAP_ILLEGAL_INSTRUCTION,
opcode as u16,
"Instruction requires a validated Program Registry".into(),
pc,
)
})?;
let registry = image.registry();
let ty = TypeId(id);
let layout = registry.type_layout(ty).expect("validated collection type");
let is_array = layout.array.is_some();
let value_ty = if let Some(array) = layout.array {
Some(array.element_type_id)
} else if matches!(opcode, OpCode::StructGet | OpCode::StructSet) {
Some(layout.instance.as_ref().unwrap().fields[field as usize].type_id)
} else {
None
};
let width =
value_ty.map(|t| registry.type_layout(t).unwrap().storage.slots as usize).unwrap_or(0);
let (consumed, produced) = match opcode {
OpCode::StructNew => (0, 1),
OpCode::ArrayNew | OpCode::ArrayLen => (1, 1),
OpCode::StructGet => (1, width),
OpCode::ArrayGet => (2, width),
OpCode::StructSet => (1 + width, 0),
OpCode::ArraySet => (2 + width, 0),
_ => unreachable!(),
};
let available = self.temporary_slots() >= consumed;
let base = self.operand_stack.len().saturating_sub(consumed);
let length = if opcode == OpCode::ArrayNew && available {
match self.operand_stack[base] {
Value::Int64(n) => Some(n),
_ => None,
}
} else {
None
};
let work = match opcode {
OpCode::StructNew => layout.instance.as_ref().unwrap().initialization_slots,
OpCode::ArrayNew => length
.and_then(|n| u32::try_from(n).ok())
.map(|n| {
u64::from(n)
.checked_mul(width as u64)
.ok_or_else(|| self.collection_size_trap(opcode, pc, u64::MAX))
})
.transpose()?
.unwrap_or(0),
OpCode::StructGet | OpCode::ArrayGet | OpCode::StructSet | OpCode::ArraySet => {
width as u64
}
_ => 0,
};
let cost = opcode
.cycles()
.checked_add(work)
.ok_or_else(|| self.collection_size_trap(opcode, pc, u64::MAX))?;
self.cycles += cost;
if !available {
return Err(self.trap(
TRAP_STACK_UNDERFLOW,
opcode as u16,
"Incomplete collection operands".into(),
pc,
));
}
let mut receiver = None;
let mut index = field as usize;
if !matches!(opcode, OpCode::StructNew | OpCode::ArrayNew) {
let r = match self.operand_stack[base] {
Value::Null => return Err(self.value_trap(ValueError::NullReference, opcode, pc)),
Value::HeapRef(r) => r,
_ => return Err(self.value_trap(ValueError::Type, opcode, pc)),
};
let actual =
self.heap.concrete_type(r, registry).map_err(|e| self.value_trap(e, opcode, pc))?;
if actual != ty {
return Err(self.value_trap(ValueError::Type, opcode, pc));
}
receiver = Some(r);
if matches!(opcode, OpCode::ArrayGet | OpCode::ArraySet) {
let n = match self.operand_stack[base + 1] {
Value::Int64(n) => n,
_ => return Err(self.value_trap(ValueError::Type, opcode, pc)),
};
let len = self
.heap
.typed_array_len(r, registry)
.map_err(|e| self.value_trap(e, opcode, pc))?;
index = usize::try_from(n)
.ok()
.filter(|n| *n < len)
.ok_or_else(|| self.value_trap(ValueError::Bounds, opcode, pc))?;
}
}
let count = if opcode == OpCode::ArrayNew {
let n = length.ok_or_else(|| self.value_trap(ValueError::Type, opcode, pc))?;
if n < 0 {
return Err(self.value_trap(ValueError::Bounds, opcode, pc));
}
u32::try_from(n).map_err(|_| self.collection_size_trap(opcode, pc, n as u64))?
} else {
0
};
let set = matches!(opcode, OpCode::StructSet | OpCode::ArraySet);
let source = base + 1 + usize::from(is_array);
if set {
value_contract::validate(
registry,
&self.heap,
value_ty.unwrap(),
&self.operand_stack[source..],
)
.map_err(|e| self.value_trap(e, opcode, pc))?;
}
let growth = self
.operand_stack
.prepare_growth(produced.saturating_sub(consumed))
.map_err(|e| self.resource_trap(e, opcode, pc))?;
let result = match opcode {
OpCode::StructNew => {
let r = self
.heap
.allocate_typed_struct(registry.clone(), ty)
.map_err(|e| self.value_trap(e, opcode, pc))?;
ValueGroup::new(&[Value::HeapRef(r)])
}
OpCode::ArrayNew => {
let r = self
.heap
.allocate_typed_array(registry.clone(), ty, count)
.map_err(|e| self.value_trap(e, opcode, pc))?;
ValueGroup::new(&[Value::HeapRef(r)])
}
OpCode::ArrayLen => {
let len = self
.heap
.typed_array_len(receiver.unwrap(), registry)
.map_err(|e| self.value_trap(e, opcode, pc))?;
ValueGroup::new(&[Value::Int64(len as i64)])
}
OpCode::StructGet | OpCode::ArrayGet => self
.heap
.load_typed(registry, receiver.unwrap(), index)
.map_err(|e| self.value_trap(e, opcode, pc))?,
OpCode::StructSet | OpCode::ArraySet => {
self.heap
.store_typed(registry, receiver.unwrap(), index, &self.operand_stack[source..])
.map_err(|e| self.value_trap(e, opcode, pc))?;
ValueGroup::new(&[])
}
_ => unreachable!(),
};
self.operand_stack.commit_growth(growth);
self.operand_stack.truncate(base);
self.operand_stack
.extend_from_slice(result.as_slice())
.expect("result capacity reserved before publication");
Ok(())
}
fn collection_size_trap(
&self,
opcode: OpCode,
pc: u32,
requested: u64,
) -> LogicalFrameEndingReason {
self.resource_trap(
self.budget.failure(
RuntimeResource::GuestBytes,
ResourceReason::SizeOverflow,
requested,
),
opcode,
pc,
)
}
}
@@ -0,0 +1,508 @@
use super::*;
#[path = "../../tests/support/collections.rs"]
mod support;
use crate::value_contract::ValueError;
use prometeu_bytecode::assemble;
use support::Native;
fn vm(text: &str, limits: RuntimeLimits) -> VirtualMachine {
let mut vm =
VirtualMachine::from_image(support::load(&assemble(text).unwrap()).unwrap(), limits);
vm.prepare_boot_call().unwrap();
vm
}
fn attempt(
text: &str,
values: &[Value],
limits: RuntimeLimits,
cost: u64,
) -> (VirtualMachine, Result<(), LogicalFrameEndingReason>) {
let mut prefix = String::new();
for i in 0..values.len() {
prefix += &format!("GET_GLOBAL {i}\n");
}
let mut vm = vm(&(prefix + text + "\nHALT"), limits);
vm.globals.extend_from_slice(values).unwrap();
for _ in values {
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
let before = vm.cycles;
let result = vm.step(&mut Native, &mut HostContext::new(None));
assert_eq!(vm.cycles - before, cost);
(vm, result)
}
fn trap(result: Result<(), LogicalFrameEndingReason>, code: u32) {
match result.unwrap_err() {
LogicalFrameEndingReason::Trap(info) => assert_eq!(info.code, code),
other => panic!("{other:?}"),
}
}
#[test]
fn new_attempt_costs_budget_and_transactional_refusal() {
for (length, cost, fault) in [
(Value::Int64(-1), 8, TRAP_OOB),
(Value::Int32(10), 8, TRAP_TYPE),
(Value::Null, 8, TRAP_TYPE),
(Value::Int64(u32::MAX as i64 + 1), 8, TRAP_RESOURCE_LIMIT),
(Value::Int64(10), 28, TRAP_RESOURCE_LIMIT),
] {
let limits = RuntimeLimits::default()
.lowered(RuntimeResource::GuestBytes, size_of::<crate::heap::StoredObject>() as u64)
.unwrap();
let (vm, result) = attempt("ARRAY_NEW 12", std::slice::from_ref(&length), limits, cost);
trap(result, fault);
assert_eq!(vm.operand_stack.as_slice(), &[length]);
assert_eq!(
vm.budget.used(RuntimeResource::GuestBytes),
size_of::<crate::heap::StoredObject>() as u64
);
assert_eq!(vm.budget.used(RuntimeResource::HandleSlots), 1);
}
let mut vm = vm("PUSH_I64 10\nARRAY_NEW 12\nHALT", RuntimeLimits::default());
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
let pc = vm.pc;
let cycles = vm.cycles;
let r = vm.run_budget(0, &mut Native, &mut HostContext::new(None)).unwrap();
assert_eq!((r.cycles_used, r.steps_executed), (0, 0));
assert_eq!((vm.pc, vm.cycles), (pc, cycles));
let r = vm.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
assert_eq!(
(r.cycles_used, r.steps_executed, r.reason),
(28, 1, LogicalFrameEndingReason::BudgetExhausted)
);
let limits = RuntimeLimits::default()
.lowered(RuntimeResource::GuestBytes, size_of::<crate::heap::StoredObject>() as u64)
.unwrap();
let mut vm = vm_for_refusal(limits);
let r = vm.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
assert_eq!((r.cycles_used, r.steps_executed), (28, 0));
assert!(matches!(r.reason, LogicalFrameEndingReason::Trap(_)));
}
fn vm_for_refusal(limits: RuntimeLimits) -> VirtualMachine {
let mut v = vm("PUSH_I64 10\nARRAY_NEW 12\nHALT", limits);
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
v
}
#[test]
fn underflow_is_charged_without_consuming_frame_storage() {
let mut vm = vm("GET_GLOBAL 0\nARRAY_NEW 12\nHALT", RuntimeLimits::default());
vm.pc = 6;
let before = vm.cycles;
trap(vm.step(&mut Native, &mut HostContext::new(None)), TRAP_STACK_UNDERFLOW);
assert_eq!(vm.cycles - before, 8);
assert!(vm.operand_stack.is_empty());
}
#[test]
fn receiver_then_index_then_group_checks_preserve_operands_and_storage() {
let mut vm = vm(
"GET_GLOBAL 0\nGET_GLOBAL 1\nGET_GLOBAL 2\nGET_GLOBAL 3\nGET_GLOBAL 4\nARRAY_SET 13\nHALT",
RuntimeLimits::default(),
);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let r = vm
.heap
.allocate_typed_array(registry.clone(), prometeu_bytecode::registry::TypeId(13), 1)
.unwrap();
let old = [Value::Int64(1), Value::Int64(2), Value::Int64(3)];
vm.heap.store_typed(&registry, r, 0, &old).unwrap();
for (receiver, index, fault) in [
(Value::Null, Value::Int32(0), TRAP_NULL_REFERENCE),
(Value::HeapRef(r), Value::Int32(0), TRAP_TYPE),
(Value::HeapRef(r), Value::Int64(1), TRAP_OOB),
(Value::HeapRef(r), Value::Int64(0), TRAP_TYPE),
] {
vm.pc = 0;
vm.operand_stack.clear();
vm.globals.clear();
let inputs = [receiver, index, Value::Int64(7), Value::Int64(8), Value::Int64(-1)];
vm.globals.extend_from_slice(&inputs).unwrap();
for _ in 0..5 {
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
let before = vm.cycles;
trap(vm.step(&mut Native, &mut HostContext::new(None)), fault);
assert_eq!(vm.cycles - before, 7);
assert_eq!(vm.operand_stack.as_slice(), &inputs);
assert_eq!(vm.heap.load_typed(&registry, r, 0).unwrap().as_slice(), &old);
}
assert_eq!(vm.heap.concrete_type(r, &registry), Ok(prometeu_bytecode::registry::TypeId(13)));
let foreign = support::load(&assemble("HALT").unwrap()).unwrap();
assert_eq!(vm.heap.concrete_type(r, foreign.registry()), Err(ValueError::Type));
}
#[test]
fn default_groups_and_roundtrip_all_storage_types_keep_identity_and_owners() {
let mut vm = vm("STRUCT_NEW 9\nSET_GLOBAL 0\nHALT", RuntimeLimits::default());
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
let Value::HeapRef(r) = vm.operand_stack[0] else { panic!() };
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let defaults = [
vec![Value::Int32(0)],
vec![Value::Int64(0)],
vec![Value::Float(0.)],
vec![Value::Boolean(false)],
vec![Value::Null],
vec![Value::Float(0.), Value::Float(0.)],
vec![Value::Int64(0)],
vec![Value::Int64(0), Value::Int64(0), Value::Int64(0)],
vec![Value::Null, Value::Null],
vec![Value::Null],
vec![Value::Null, Value::Null],
vec![Value::Null],
];
for (field, group) in defaults.iter().enumerate() {
assert_eq!(vm.heap.load_typed(&registry, r, field).unwrap().as_slice(), group);
}
// Present Trait implementation zero and shared String/Dynamic/reference values.
let string = Value::String(std::sync::Arc::from("owned"));
for (field, group) in [
(4, vec![string.clone()]),
(8, vec![Value::Int64(4), string]),
(9, vec![Value::HeapRef(r)]),
(10, vec![Value::HeapRef(r), Value::Int64(0)]),
] {
vm.heap.store_typed(&registry, r, field, &group).unwrap();
assert_eq!(vm.heap.load_typed(&registry, r, field).unwrap().as_slice(), group);
}
}
#[test]
fn decoded_stores_and_reads_preserve_complete_native_and_reference_groups() {
for (field, group) in [
(0, vec![Value::Int32(7)]),
(1, vec![Value::Int64(8)]),
(2, vec![Value::Float(1.)]),
(3, vec![Value::Boolean(true)]),
(4, vec![Value::String(std::sync::Arc::from(""))]),
(5, vec![Value::Float(1.), Value::Float(2.)]),
(6, vec![Value::Int64(u32::MAX.into())]),
(7, vec![Value::Int64(1), Value::Int64(2), Value::Int64(3)]),
(8, vec![Value::Null, Value::Null]),
(9, vec![Value::Null]),
(10, vec![Value::Null, Value::Null]),
(11, vec![Value::Null]),
] {
let mut text = "STRUCT_NEW 9\nSET_GLOBAL 0\nGET_GLOBAL 0\n".to_string();
for i in 0..group.len() {
text += &format!("GET_GLOBAL {}\n", i + 1);
}
text += &format!(
"STRUCT_SET type=9, field={field}\nGET_GLOBAL 0\nSTRUCT_GET type=9, field={field}\nHALT"
);
let mut v = vm(&text, RuntimeLimits::default());
v.globals.push(Value::Null).unwrap();
v.globals.extend_from_slice(&group).unwrap();
assert_eq!(
v.run_budget(10_000, &mut Native, &mut HostContext::new(None)).unwrap().reason,
LogicalFrameEndingReason::Halted
);
assert_eq!(v.operand_stack.as_slice(), group);
}
}
#[test]
fn provisional_allocation_and_handle_refusals_publish_nothing() {
for quota in [
RuntimeResource::HandleSlots,
RuntimeResource::AuxiliaryBytes,
RuntimeResource::TemporaryBytes,
] {
let mut v = vm("PUSH_I64 10\nARRAY_NEW 12\nHALT", RuntimeLimits::default());
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
// Test-only accounting state: lower the resource ceiling to current usage
// after boot, without changing any production constructor/check.
let current = v.budget.used(quota);
v.budget.test_lower_limit(quota, current);
let guest = v.budget.used(RuntimeResource::GuestBytes);
let live = v.heap.len();
let allocations = v.heap.allocation_count();
let before = v.cycles;
trap(v.step(&mut Native, &mut HostContext::new(None)), TRAP_RESOURCE_LIMIT);
assert_eq!(v.cycles - before, 28);
assert_eq!(v.heap.len(), live);
assert_eq!(v.heap.allocation_count(), allocations);
assert_eq!(v.operand_stack.as_slice(), &[Value::Int64(10)]);
assert_eq!(v.budget.used(RuntimeResource::GuestBytes), guest);
}
let mut v = vm("PUSH_I64 10\nARRAY_NEW 12\nHALT", RuntimeLimits::default());
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
let guest = v.budget.used(RuntimeResource::GuestBytes);
let guard = crate::typed_storage::refuse_next_allocation();
let failure = v.step(&mut Native, &mut HostContext::new(None));
drop(guard);
let LogicalFrameEndingReason::Trap(t) = failure.unwrap_err() else { panic!() };
assert_eq!(
t.resource.unwrap().reason,
crate::resource_budget::ResourceReason::AllocationFailed
);
assert_eq!(v.budget.used(RuntimeResource::GuestBytes), guest);
assert_eq!(v.operand_stack.as_slice(), &[Value::Int64(10)]);
assert_eq!(v.heap.len(), 1);
}
#[test]
fn rooted_native_owners_boxes_traits_and_cycles_survive_then_reclaim_at_real_safepoints() {
let text = "STRUCT_NEW 9\nSET_GLOBAL 0\nGET_GLOBAL 0\nSTRUCT_GET type=9, field=4\nSET_GLOBAL 9\nPUSH_I64 1\nARRAY_NEW 17\nSET_GLOBAL 1\nGET_GLOBAL 1\nPUSH_I64 0\nGET_GLOBAL 0\nARRAY_SET 17\nGET_GLOBAL 0\nGET_GLOBAL 0\nSTRUCT_SET type=9, field=9\nGET_GLOBAL 0\nGET_GLOBAL 0\nREF_TO_TRAIT source=9, target=10\nSTRUCT_SET type=9, field=10\nGET_GLOBAL 0\nPUSH_F64 f64:0x3ff0000000000000\nPUSH_F64 f64:0x4000000000000000\nDYN_PACK 5\nSTRUCT_SET type=9, field=8\nGET_GLOBAL 0\nGET_GLOBAL 2\nSTRUCT_SET type=9, field=4\nPUSH_I64 1\nARRAY_NEW 14\nSET_GLOBAL 3\nGET_GLOBAL 3\nPUSH_I64 0\nGET_GLOBAL 2\nARRAY_SET 14\nPUSH_I64 1\nARRAY_NEW 15\nSET_GLOBAL 4\nGET_GLOBAL 4\nPUSH_I64 0\nGET_GLOBAL 2\nDYN_PACK 4\nARRAY_SET 15\nFRAME_SYNC\nGET_GLOBAL 9\nSET_GLOBAL 2\nGET_GLOBAL 9\nSET_GLOBAL 3\nFRAME_SYNC\nGET_GLOBAL 9\nSET_GLOBAL 0\nGET_GLOBAL 9\nSET_GLOBAL 1\nGET_GLOBAL 9\nSET_GLOBAL 4\nSTRUCT_NEW 19\nPOP_N 1\nFRAME_SYNC\nHALT";
let mut v = vm(text, RuntimeLimits::default());
v.gc_alloc_threshold = 1;
v.globals.resize(3, Value::Null).unwrap();
v.push(Value::String(std::sync::Arc::from("one content"))).unwrap();
let string = v.pop().unwrap();
v.globals[2] = string;
assert_eq!(
v.run_budget(10_000, &mut Native, &mut HostContext::new(None)).unwrap().reason,
LogicalFrameEndingReason::FrameSync
);
let Value::HeapRef(node) = v.globals[0] else { panic!() };
let registry = v.validated_image.as_ref().unwrap().registry().clone();
assert_eq!(
v.heap.load_typed(&registry, node, 10).unwrap().as_slice(),
&[Value::HeapRef(node), Value::Int64(0)]
);
assert_eq!(v.budget.used(RuntimeResource::StringBytes), 11);
assert_eq!(v.budget.used(RuntimeResource::StringAllocations), 1);
assert_eq!(
v.run_budget(10_000, &mut Native, &mut HostContext::new(None)).unwrap().reason,
LogicalFrameEndingReason::FrameSync
);
assert!(v.heap.is_valid(node));
assert_eq!(v.budget.used(RuntimeResource::StringAllocations), 1);
assert_eq!(
v.run_budget(10_000, &mut Native, &mut HostContext::new(None)).unwrap().reason,
LogicalFrameEndingReason::FrameSync
);
assert!(!v.heap.is_valid(node));
assert_eq!(v.heap.len(), 1);
assert_eq!(v.budget.used(RuntimeResource::StringBytes), 0);
assert_eq!(v.budget.used(RuntimeResource::StringAllocations), 0);
assert_eq!(v.heap.concrete_type(node, &registry), Err(ValueError::InvalidHandle));
}
#[test]
fn exact_struct_weights_and_empty_construction_charge_once() {
for (ty, cost) in [(19, 8), (21, 13)] {
let (v, result) = attempt(&format!("STRUCT_NEW {ty}"), &[], RuntimeLimits::default(), cost);
result.unwrap();
assert!(matches!(v.operand_stack[0], Value::HeapRef(_)));
}
let (v, result) = attempt("ARRAY_NEW 12", &[Value::Int64(0)], RuntimeLimits::default(), 8);
result.unwrap();
assert!(matches!(v.operand_stack[0], Value::HeapRef(_)));
}
#[test]
fn arrays_of_every_builtin_and_reference_view_default_and_roundtrip_by_decoded_ops() {
for (ty, default, value) in [
(11, vec![Value::Int32(0)], vec![Value::Int32(7)]),
(22, vec![Value::Int64(0)], vec![Value::Int64(8)]),
(23, vec![Value::Float(0.)], vec![Value::Float(1.)]),
(24, vec![Value::Boolean(false)], vec![Value::Boolean(true)]),
(14, vec![Value::Null], vec![Value::String(std::sync::Arc::from("shared"))]),
(12, vec![Value::Float(0.), Value::Float(0.)], vec![Value::Float(1.), Value::Float(2.)]),
(25, vec![Value::Int64(0)], vec![Value::Int64(42)]),
(
13,
vec![Value::Int64(0), Value::Int64(0), Value::Int64(0)],
vec![Value::Int64(1), Value::Int64(2), Value::Int64(3)],
),
(15, vec![Value::Null, Value::Null], vec![Value::Int64(4), Value::Null]),
(16, vec![Value::Null, Value::Null], vec![Value::Null, Value::Null]),
(17, vec![Value::Null], vec![Value::Null]),
(18, vec![Value::Null], vec![Value::Null]),
] {
let mut text = format!(
"PUSH_I64 1\nARRAY_NEW {ty}\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I64 0\nARRAY_GET {ty}\nPOP_N {}\nGET_GLOBAL 0\nPUSH_I64 0\n",
value.len()
);
for i in 0..value.len() {
text += &format!("GET_GLOBAL {}\n", i + 1);
}
text += &format!("ARRAY_SET {ty}\nGET_GLOBAL 0\nPUSH_I64 0\nARRAY_GET {ty}\nHALT");
let mut v = vm(&text, RuntimeLimits::default());
v.globals.push(Value::Null).unwrap();
v.globals.extend_from_slice(&value).unwrap();
for _ in 0..6 {
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
assert_eq!(v.operand_stack.as_slice(), default);
assert_eq!(
v.run_budget(10_000, &mut Native, &mut HostContext::new(None)).unwrap().reason,
LogicalFrameEndingReason::Halted
);
assert_eq!(v.operand_stack.as_slice(), value);
}
}
#[test]
fn invalid_stale_wrong_nominal_and_foreign_registry_receivers_are_charged_and_preserved() {
let mut v = vm("GET_GLOBAL 0\nARRAY_LEN 11\nHALT", RuntimeLimits::default());
let registry = v.validated_image.as_ref().unwrap().registry().clone();
let wrong = v
.heap
.allocate_typed_struct(registry.clone(), prometeu_bytecode::registry::TypeId(19))
.unwrap();
let foreign = support::load(&assemble("HALT").unwrap()).unwrap();
let foreign_ref = v
.heap
.allocate_typed_array(
foreign.registry().clone(),
prometeu_bytecode::registry::TypeId(11),
0,
)
.unwrap();
for (value, code) in [
(Value::Int32(0), TRAP_TYPE),
(Value::Null, TRAP_NULL_REFERENCE),
(Value::HeapRef(HeapRef { index: u32::MAX, generation: 1 }), TRAP_INVALID_HANDLE),
(
Value::HeapRef(HeapRef { index: wrong.index, generation: wrong.generation + 1 }),
TRAP_INVALID_HANDLE,
),
(Value::HeapRef(wrong), TRAP_TYPE),
(Value::HeapRef(foreign_ref), TRAP_TYPE),
] {
v.pc = 0;
v.operand_stack.clear();
v.globals.clear();
v.globals.push(value.clone()).unwrap();
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
let before = v.cycles;
trap(v.step(&mut Native, &mut HostContext::new(None)), code);
assert_eq!(v.cycles - before, 3);
assert_eq!(v.operand_stack.as_slice(), &[value]);
}
}
#[test]
fn malformed_trait_and_dynamic_stores_reject_the_whole_group() {
for (ty, group) in [
(16, vec![Value::Null, Value::Int64(0)]),
(16, vec![Value::Int32(0), Value::Null]),
(15, vec![Value::Null, Value::Int32(0)]),
(15, vec![Value::Int64(5), Value::Int32(0)]),
(15, vec![Value::Int64(999), Value::Null]),
] {
let text = format!(
"PUSH_I64 1\nARRAY_NEW {ty}\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I64 0\nGET_GLOBAL 1\nGET_GLOBAL 2\nARRAY_SET {ty}\nHALT"
);
let mut v = vm(&text, RuntimeLimits::default());
v.globals.push(Value::Null).unwrap();
v.globals.extend_from_slice(&group).unwrap();
for _ in 0..7 {
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
let sources = v.operand_stack.as_slice().to_vec();
let before = v.cycles;
trap(v.step(&mut Native, &mut HostContext::new(None)), TRAP_TYPE);
assert_eq!(v.cycles - before, 6);
assert_eq!(v.operand_stack.as_slice(), sources);
let Value::HeapRef(r) = v.globals[0] else { panic!() };
let registry = v.validated_image.as_ref().unwrap().registry();
assert_eq!(
v.heap.load_typed(registry, r, 0).unwrap().as_slice(),
&[Value::Null, Value::Null]
);
}
}
#[test]
fn legacy_verifier_rejects_every_collection_even_when_unreachable() {
for text in [
"STRUCT_NEW 9",
"STRUCT_GET type=9, field=0",
"STRUCT_SET type=9, field=0",
"ARRAY_NEW 11",
"ARRAY_LEN 11",
"ARRAY_GET 11",
"ARRAY_SET 11",
] {
let code = assemble(&format!("HALT\n{text}")).unwrap();
let f =
prometeu_bytecode::FunctionMeta { code_len: code.len() as u32, ..Default::default() };
assert!(matches!(
crate::verifier::Verifier::verify(&code, &[f]),
Err(crate::verifier::VerifierError::RegistryRequired { pc: 2, .. })
));
}
}
#[test]
fn invalid_string_overwrite_keeps_the_previous_native_owner() {
let text = "STRUCT_NEW 9\nSET_GLOBAL 0\nGET_GLOBAL 0\nGET_GLOBAL 1\nSTRUCT_SET type=9, field=4\nGET_GLOBAL 0\nGET_GLOBAL 2\nSTRUCT_SET type=9, field=4\nHALT";
let mut v = vm(text, RuntimeLimits::default());
let text: std::sync::Arc<str> = std::sync::Arc::from("old owner");
v.globals
.extend_from_slice(&[Value::Null, Value::String(text.clone()), Value::Int32(3)])
.unwrap();
for _ in 0..7 {
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
let sources = v.operand_stack.as_slice().to_vec();
let before = v.cycles;
trap(v.step(&mut Native, &mut HostContext::new(None)), TRAP_TYPE);
assert_eq!(v.cycles - before, 5);
assert_eq!(v.operand_stack.as_slice(), sources);
let Value::HeapRef(r) = v.globals[0] else { panic!() };
let registry = v.validated_image.as_ref().unwrap().registry();
let group = v.heap.load_typed(registry, r, 4).unwrap();
let Value::String(stored) = &group.as_slice()[0] else { panic!() };
assert!(std::sync::Arc::ptr_eq(stored, &text));
}
#[test]
fn pixel_get_cost_bounds_and_result_reservation_failures_preserve_sources() {
for lowered in
[None, Some(RuntimeResource::AuxiliaryBytes), Some(RuntimeResource::TemporaryBytes)]
{
let mut v = vm("GET_GLOBAL 0\nGET_GLOBAL 1\nARRAY_GET 13\nHALT", RuntimeLimits::default());
let registry = v.validated_image.as_ref().unwrap().registry().clone();
let r = v
.heap
.allocate_typed_array(registry.clone(), prometeu_bytecode::registry::TypeId(13), 1)
.unwrap();
v.globals
.extend_from_slice(&[
Value::HeapRef(r),
Value::Int64(if lowered.is_none() { 1 } else { 0 }),
])
.unwrap();
for _ in 0..2 {
v.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
if let Some(q) = lowered {
v.budget.test_lower_limit(q, v.budget.used(q));
}
let sources = v.operand_stack.as_slice().to_vec();
let before = v.cycles;
trap(
v.step(&mut Native, &mut HostContext::new(None)),
if lowered.is_none() { TRAP_OOB } else { TRAP_RESOURCE_LIMIT },
);
assert_eq!(v.cycles - before, 6);
assert_eq!(v.operand_stack.as_slice(), sources);
assert_eq!(
v.heap.load_typed(&registry, r, 0).unwrap().as_slice(),
&[Value::Int64(0), Value::Int64(0), Value::Int64(0)]
);
}
}
#[test]
fn incomplete_set_group_does_not_consume_a_frame_local_and_still_charges_static_cost() {
let code = assemble(
"GET_GLOBAL 0\nGET_GLOBAL 1\nGET_GLOBAL 2\nGET_GLOBAL 3\nGET_GLOBAL 4\nARRAY_SET 13\nHALT",
)
.unwrap();
let mut declarations = support::declarations(code.len());
declarations.functions[0].local_slots = 1;
let image = crate::ValidatedProgramImage::load(
&support::bytes_with(&code, declarations),
&mut prometeu_bytecode::load_limits::LoadBudget::new(Default::default()),
NONE,
)
.unwrap();
let mut v = VirtualMachine::from_image(image, RuntimeLimits::default());
v.prepare_boot_call().unwrap();
v.operand_stack[0] = Value::Int64(123);
v.pc = 30;
v.operand_stack
.extend_from_slice(&[Value::Null, Value::Int64(0), Value::Int64(1), Value::Int64(2)])
.unwrap();
let before = v.cycles;
let sources = v.operand_stack.as_slice().to_vec();
trap(v.step(&mut Native, &mut HostContext::new(None)), TRAP_STACK_UNDERFLOW);
assert_eq!(v.cycles - before, 7);
assert_eq!(v.operand_stack.as_slice(), sources);
assert_eq!(v.operand_stack[0], Value::Int64(123));
}
@@ -0,0 +1,134 @@
#[path = "support/collections.rs"]
mod support;
use prometeu_bytecode::{Value, assemble};
use prometeu_hal::HostContext;
use prometeu_vm::{LogicalFrameEndingReason, VirtualMachine, resource_budget::RuntimeLimits};
use support::{Native, load};
fn run(code: &[u8]) -> Vec<Value> {
let mut vm = VirtualMachine::from_image(load(code).unwrap(), RuntimeLimits::default());
vm.prepare_boot_call().unwrap();
let r = vm.run_budget(10_000, &mut Native, &mut HostContext::new(None)).unwrap();
assert_eq!(r.reason, LogicalFrameEndingReason::Halted);
vm.operand_stack_top(32).to_vec()
}
#[test]
fn independent_bytes_execute_default_array_and_len_on_sealed_image() {
let code = [0x14, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0xa3, 0, 11, 0, 0, 0, 0xa4, 0, 11, 0, 0, 0, 1, 0];
assert_eq!(run(&code), [Value::Int64(2)]);
}
#[test]
fn guest_aliases_mutate_same_instance_and_groups_roundtrip_without_boxing() {
let code=assemble("STRUCT_NEW 9\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_F64 f64:0x3ff8000000000000\nPUSH_F64 f64:0x4004000000000000\nSTRUCT_SET type=9, field=5\nGET_GLOBAL 0\nSTRUCT_GET type=9, field=5\nPUSH_I64 2\nARRAY_NEW 17\nSET_GLOBAL 1\nGET_GLOBAL 1\nPUSH_I64 0\nGET_GLOBAL 0\nARRAY_SET 17\nGET_GLOBAL 1\nPUSH_I64 0\nARRAY_GET 17\nPUSH_I32 42\nSTRUCT_SET type=9, field=0\nGET_GLOBAL 0\nSTRUCT_GET type=9, field=0\nGET_GLOBAL 1\nARRAY_LEN 17\nHALT").unwrap();
assert_eq!(
run(&code),
[Value::Int64(2), Value::Int32(42), Value::Float(2.5), Value::Float(1.5)]
);
}
#[test]
fn every_builtin_group_can_be_stored_and_loaded_by_decoded_struct_operations() {
for (field, push, expected) in [
(0, "PUSH_I32 23", vec![Value::Int32(23)]),
(1, "PUSH_I64 23", vec![Value::Int64(23)]),
(2, "PUSH_F64 f64:0x4004000000000000", vec![Value::Float(2.5)]),
(3, "PUSH_BOOL 1", vec![Value::Boolean(true)]),
(4, "GET_GLOBAL 0\nSTRUCT_GET type=9, field=4", vec![Value::Null]),
(
5,
"PUSH_F64 f64:0x3ff8000000000000\nPUSH_F64 f64:0x4004000000000000",
vec![Value::Float(2.5), Value::Float(1.5)],
),
(6, "PUSH_I64 4294967295", vec![Value::Int64(4294967295)]),
(
7,
"PUSH_I64 1\nPUSH_I64 2\nPUSH_I64 3",
vec![Value::Int64(3), Value::Int64(2), Value::Int64(1)],
),
(8, "PUSH_F64 f64:0x3ff8000000000000\nPUSH_F64 f64:0x4004000000000000\nDYN_PACK 5", vec![]),
] {
let code=assemble(&format!("STRUCT_NEW 9\nSET_GLOBAL 0\nGET_GLOBAL 0\n{push}\nSTRUCT_SET type=9, field={field}\nGET_GLOBAL 0\nSTRUCT_GET type=9, field={field}\n{}HALT",if field==8 {"DYN_UNPACK 5\n"}else{""})).unwrap();
let actual = run(&code);
assert_eq!(
actual,
if field == 8 { vec![Value::Float(2.5), Value::Float(1.5)] } else { expected }
);
}
}
#[test]
fn verifier_rejects_proven_types_metadata_and_unreachable_invalid_fields() {
for text in [
"ARRAY_NEW 0\nHALT",
"STRUCT_NEW 11\nHALT",
"HALT\nSTRUCT_GET type=9, field=12",
"PUSH_I32 1\nARRAY_NEW 11\nHALT",
"STRUCT_NEW 19\nSTRUCT_GET type=9, field=0\nHALT",
"STRUCT_NEW 9\nPUSH_BOOL 1\nSTRUCT_SET type=9, field=0\nHALT",
"PUSH_I64 1\nARRAY_NEW 13\nPUSH_F64 f64:0x3ff0000000000000\nARRAY_GET 13\nHALT",
] {
assert!(load(&assemble(text).unwrap()).is_err(), "{text}");
}
}
#[test]
fn empty_instances_have_identity_and_nested_array_references_preserve_aliases() {
let code=assemble("STRUCT_NEW 19\nSTRUCT_NEW 19\nEQ\nPUSH_I64 0\nARRAY_NEW 11\nARRAY_LEN 11\nPUSH_I64 1\nARRAY_NEW 18\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I64 0\nPUSH_I64 2\nARRAY_NEW 11\nARRAY_SET 18\nGET_GLOBAL 0\nPUSH_I64 0\nARRAY_GET 18\nARRAY_LEN 11\nHALT").unwrap();
assert_eq!(run(&code), [Value::Int64(2), Value::Int64(0), Value::Boolean(false)]);
}
#[test]
fn converged_unknown_receiver_join_keeps_runtime_checks_and_valid_branch_executes() {
let text = "PUSH_BOOL 1\nJMP_IF_FALSE 31\nPUSH_I64 1\nARRAY_NEW 11\nJMP 47\nPUSH_I64 1\nARRAY_NEW 14\nARRAY_LEN 11\nHALT";
assert_eq!(run(&assemble(text).unwrap()), [Value::Int64(1)]);
let mut vm = VirtualMachine::from_image(
load(&assemble(&text.replace("PUSH_BOOL 1", "PUSH_BOOL 0")).unwrap()).unwrap(),
RuntimeLimits::default(),
);
vm.prepare_boot_call().unwrap();
let r = vm.run_budget(10_000, &mut Native, &mut HostContext::new(None)).unwrap();
let LogicalFrameEndingReason::Trap(t) = r.reason else { panic!() };
assert_eq!(t.code, prometeu_bytecode::TRAP_TYPE);
assert_eq!(t.opcode, 0xa4);
assert_eq!(t.pc, 47);
}
#[test]
fn verifier_rejects_group_tearing_jumps_into_immediates_and_unequal_height_joins() {
for text in [
"STRUCT_NEW 9\nSTRUCT_GET type=9, field=5\nPOP_N 1\nPUSH_I32 1\nSTRUCT_NEW 9\nSWAP\nSTRUCT_SET type=9, field=5\nHALT",
"JMP 8\nSTRUCT_NEW 9\nHALT",
"PUSH_BOOL 1\nJMP_IF_FALSE 21\nSTRUCT_NEW 9\nJMP 21\nHALT",
] {
assert!(load(&assemble(text).unwrap()).is_err(), "{text}");
}
}
#[test]
fn collection_load_limits_and_analysis_refusals_keep_context_and_refund_scratch() {
use prometeu_bytecode::load_limits::{LoadBudget, LoadCode, LoadLimits, LoadResource};
use prometeu_hal::syscalls::caps::NONE;
use prometeu_vm::{ValidatedProgramImage, VmInitError};
let code = assemble("PUSH_I64 1\nARRAY_NEW 13\nPUSH_I64 0\nARRAY_GET 13\nHALT").unwrap();
let mut d = support::declarations(code.len());
d.functions[0].max_stack_slots = 2;
assert!(load(&code).is_ok());
let bytes = support::bytes_with(&code, d);
let e = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(Default::default()), NONE)
.unwrap_err();
let VmInitError::RegistryLoadFailed(e) = e else { panic!() };
assert_eq!(e.code, LoadCode::InvalidCode);
assert_eq!(e.function, Some(0));
assert_eq!(e.pc, Some(26));
let bytes = support::bytes(&code);
for limits in [
LoadLimits { work: 1, ..Default::default() },
LoadLimits { temporary_bytes: 1, ..Default::default() },
LoadLimits { registry_bytes: 1, ..Default::default() },
] {
let mut budget = LoadBudget::new(limits);
let VmInitError::RegistryLoadFailed(e) =
ValidatedProgramImage::load(&bytes, &mut budget, NONE).unwrap_err()
else {
panic!()
};
assert_eq!(e.code, LoadCode::ResourceLimit);
assert_eq!(budget.used(LoadResource::TemporaryBytes), 0);
assert_eq!(budget.used(LoadResource::RegistryBytes), 0);
}
}
@@ -0,0 +1,99 @@
#![allow(dead_code)]
use prometeu_bytecode::load_limits::LoadBudget;
use prometeu_bytecode::registry::*;
use prometeu_bytecode::registry_codec::PbxModule;
use prometeu_hal::{HostContext, HostReturn, NativeInterface};
use prometeu_vm::ValidatedProgramImage;
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!("no native call expected")
}
}
pub fn declarations(code_len: usize) -> RegistryDeclarations {
let mut types: Vec<_> = [
BuiltinId::INT32,
BuiltinId::INT64,
BuiltinId::FLOAT,
BuiltinId::BOOL,
BuiltinId::STRING,
BuiltinId::VEC2,
BuiltinId::COLOR,
BuiltinId::PIXEL,
BuiltinId::DYNAMIC,
]
.into_iter()
.map(|id| TypeDecl { name: None, kind: TypeKind::Builtin(id) })
.collect();
let field = |id| NamedType { type_id: TypeId(id), name: None };
types.extend([
TypeDecl {
name: Some("Node".into()),
kind: TypeKind::Struct((0..=9).chain([10, 11]).map(field).collect()),
},
TypeDecl { name: None, kind: TypeKind::Trait(vec![]) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(5)) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(7)) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(4)) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(8)) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(10)) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(9)) },
TypeDecl { name: None, kind: TypeKind::Array(TypeId(11)) },
TypeDecl { name: None, kind: TypeKind::Struct(vec![]) },
TypeDecl { name: None, kind: TypeKind::Struct(vec![]) },
]);
types.push(TypeDecl {
name: None,
kind: TypeKind::Struct([0, 5, 10].into_iter().map(field).collect()),
});
for id in [1, 2, 3, 6] {
types.push(TypeDecl { name: None, kind: TypeKind::Array(TypeId(id)) });
}
RegistryDeclarations {
types,
functions: vec![FunctionDecl {
code_len: code_len as u32,
local_slots: 0,
max_stack_slots: 32,
..Default::default()
}],
implementations: vec![ImplementationDecl {
owner: TypeId(9),
trait_id: TypeId(10),
methods: vec![],
}],
}
}
pub fn bytes(code: &[u8]) -> Vec<u8> {
bytes_with(code, declarations(code.len()))
}
pub fn bytes_with(code: &[u8], declarations: RegistryDeclarations) -> Vec<u8> {
let registry =
Registry::resolve(declarations, code.len(), &mut LoadBudget::new(Default::default()))
.unwrap();
PbxModule {
registry: &registry,
code,
constants: &[],
debug: None,
exports: &[],
syscalls: &[],
}
.serialize(&mut LoadBudget::new(Default::default()))
.unwrap()
}
pub fn load(code: &[u8]) -> Result<Arc<ValidatedProgramImage>, prometeu_vm::VmInitError> {
ValidatedProgramImage::load(
&bytes(code),
&mut LoadBudget::new(Default::default()),
prometeu_hal::syscalls::caps::NONE,
)
}