refactor(vm)!: remove publication and logical guard opcodes
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good

Remove INDEX_GUARD, ARRAY_CHECK_LENGTH, STORAGE_PUBLISH and FIELDS_PUBLISH
from decoding, metadata, tooling, verification and execution. Keep ARRAY_LEN
and overlap-safe ARRAY_COPY with complete-group ownership and early charging
of calculable copy work, including refused attempts.

Update specifications, producer handoff, qualification evidence and lessons.
Share collection test support and remove redundant Copy clones for Clippy.

Validation: make ci-domains passed with 1,095 workspace tests, five separately
executed debugger socket tests and all 15 unchanged coverage domain gates.
VM release, resource diagnostics and layer/quality suites also passed.

BREAKING CHANGE: PBX using opcodes 0xA7, 0xA8, 0xAA or 0xAB is rejected,
including unreachable instructions. Consumers must adapt their emission and
collection algorithms or operational guarantees.
This commit is contained in:
2026-10-23 23:37:56 +01:00
parent 69ad1931de
commit dcf6561ea7
27 changed files with 1407 additions and 1013 deletions
@@ -336,22 +336,6 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
emit_u32(parse_u32_any(ops)?, &mut out);
}
"INDEX_GUARD" => {
if !ops.is_empty() {
return Err(AsmError::InvalidOperand(line.into()));
}
emit_u16(CoreOpCode::IndexGuard as u16, &mut out);
}
"STORAGE_PUBLISH" => {
let parts: Vec<_> = ops.split(',').map(str::trim).collect();
if parts.len() != 4 {
return Err(AsmError::InvalidOperand(line.into()));
}
emit_u16(CoreOpCode::StoragePublish as u16, &mut out);
for part in parts {
emit_u32(parse_u32_any(part)?, &mut out);
}
}
"STRUCT_GET" | "STRUCT_SET" => {
let (a, b) = parse_keyvals(ops)?;
let (ty, field) = parse_pair(a, "type", b, "field")?;
@@ -361,18 +345,15 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
emit_u32(ty, &mut out);
emit_u32(field, &mut out);
}
"STRUCT_NEW" | "ARRAY_NEW" | "ARRAY_LEN" | "ARRAY_GET" | "ARRAY_SET"
| "ARRAY_CHECK_LENGTH" | "ARRAY_COPY" | "FIELDS_PUBLISH" => {
"STRUCT_NEW" | "ARRAY_NEW" | "ARRAY_LEN" | "ARRAY_GET" | "ARRAY_SET" | "ARRAY_COPY" => {
if ops.is_empty() {
return Err(AsmError::MissingOperand(line.into()));
}
let op = match mn {
"FIELDS_PUBLISH" => CoreOpCode::FieldsPublish,
"STRUCT_NEW" => CoreOpCode::StructNew,
"ARRAY_NEW" => CoreOpCode::ArrayNew,
"ARRAY_LEN" => CoreOpCode::ArrayLen,
"ARRAY_GET" => CoreOpCode::ArrayGet,
"ARRAY_CHECK_LENGTH" => CoreOpCode::ArrayCheckLength,
"ARRAY_COPY" => CoreOpCode::ArrayCopy,
_ => CoreOpCode::ArraySet,
};
@@ -76,14 +76,6 @@ impl<'a> DecodedInstr<'a> {
Ok(f64::from_le_bytes(self.imm.try_into().unwrap()))
}
/// Four independent u32 operands; widths are resolved through the Registry.
pub fn imm_u32x4(&self) -> Result<[u32; 4], DecodeError> {
self.ensure_len(16)?;
Ok(std::array::from_fn(|i| {
u32::from_le_bytes(self.imm[i * 4..i * 4 + 4].try_into().unwrap())
}))
}
/// Helper for opcodes carrying two u32 values packed in 8 bytes (e.g., ALLOC meta).
#[inline]
pub fn imm_u32x2(&self) -> Result<(u32, u32), DecodeError> {
@@ -72,18 +72,10 @@ fn format_operand(op: CoreOpCode, imm: &[u8]) -> String {
| CoreOpCode::ArrayLen
| CoreOpCode::ArrayGet
| CoreOpCode::ArraySet
| CoreOpCode::ArrayCheckLength
| CoreOpCode::ArrayCopy
| CoreOpCode::FieldsPublish => {
| CoreOpCode::ArrayCopy => {
let v = u32::from_le_bytes(imm.try_into().unwrap());
format!("{}", v)
}
CoreOpCode::StoragePublish => {
let fields: [u32; 4] = std::array::from_fn(|i| {
u32::from_le_bytes(imm[i * 4..i * 4 + 4].try_into().unwrap())
});
format!("{}, {}, {}, {}", fields[0], fields[1], fields[2], fields[3])
}
CoreOpCode::StructGet | CoreOpCode::StructSet => {
let ty = u32::from_le_bytes(imm[..4].try_into().unwrap());
let field = u32::from_le_bytes(imm[4..].try_into().unwrap());
@@ -159,21 +151,3 @@ pub fn disassemble(bytes: &[u8]) -> Result<String, DecodeError> {
}
Ok(out.join("\n"))
}
#[cfg(test)]
mod storage_instruction_tests {
#[test]
fn storage_operands_roundtrip_and_quad_immediates_never_decode_truncated() {
let code = crate::assemble(
"INDEX_GUARD\nARRAY_CHECK_LENGTH 7\nARRAY_COPY 8\nSTORAGE_PUBLISH 8, 9, 0, 1",
)
.unwrap();
let text = super::disassemble(&code).unwrap();
assert_eq!(crate::assemble(&text).unwrap(), code);
let pc = 14;
for end in pc + 2..code.len() {
assert!(crate::decode_next(pc, &code[..end]).is_err());
}
assert_eq!(crate::decode_next(pc, &code).unwrap().imm_u32x4().unwrap(), [8, 9, 0, 1]);
}
}
@@ -205,17 +205,8 @@ pub enum OpCode {
ArrayLen = 0xA4,
ArrayGet = 0xA5,
ArraySet = 0xA6,
/// Signed logical index guard; stack [index:i64, exclusive_limit:i64] -> [].
IndexGuard = 0xA7,
/// Structural Array length check without allocation; TypeId:u32.
ArrayCheckLength = 0xA8,
/// Complete stored groups, overlap-safe; Array TypeId:u32.
ArrayCopy = 0xA9,
/// Move/fill array ranges and two selected Struct fields in one attempt.
/// Array TypeId, Struct TypeId, first field, second field (four u32).
StoragePublish = 0xAA,
/// Atomic full-field writes to schema-selected nullable Struct destinations.
FieldsPublish = 0xAB,
}
impl TryFrom<u16> for OpCode {
@@ -291,11 +282,7 @@ impl TryFrom<u16> for OpCode {
0xA4 => Ok(OpCode::ArrayLen),
0xA5 => Ok(OpCode::ArrayGet),
0xA6 => Ok(OpCode::ArraySet),
0xA7 => Ok(OpCode::IndexGuard),
0xA8 => Ok(OpCode::ArrayCheckLength),
0xA9 => Ok(OpCode::ArrayCopy),
0xAA => Ok(OpCode::StoragePublish),
0xAB => Ok(OpCode::FieldsPublish),
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
}
@@ -375,9 +362,7 @@ impl OpCode {
OpCode::ArrayLen => 3,
OpCode::ArrayGet => 3,
OpCode::ArraySet => 4,
OpCode::IndexGuard | OpCode::ArrayCheckLength => 2,
OpCode::ArrayCopy => 4,
OpCode::StoragePublish | OpCode::FieldsPublish => 6,
}
}
}
@@ -686,27 +686,9 @@ impl OpCodeSpecExt for OpCode {
may_trap: true,
is_safepoint: false,
},
OpCode::IndexGuard => OpcodeSpec {
name: "INDEX_GUARD",
imm_bytes: 0,
pops: Some(2),
pushes: Some(0),
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::ArrayCheckLength
| OpCode::ArrayCopy
| OpCode::StoragePublish
| OpCode::FieldsPublish => OpcodeSpec {
name: match self {
OpCode::ArrayCheckLength => "ARRAY_CHECK_LENGTH",
OpCode::ArrayCopy => "ARRAY_COPY",
OpCode::FieldsPublish => "FIELDS_PUBLISH",
_ => "STORAGE_PUBLISH",
},
imm_bytes: if *self == OpCode::StoragePublish { 16 } else { 4 },
OpCode::ArrayCopy => OpcodeSpec {
name: "ARRAY_COPY",
imm_bytes: 4,
pops: None,
pushes: None,
is_branch: false,
@@ -150,59 +150,11 @@ impl DecodedInstr<'_> {
}
(pops, 1)
}
Op::FieldsPublish => {
let schema = self.imm_u32().map_err(|_| malformed())?;
let (decl, _) = type_info(schema)?;
let TypeKind::Struct(entries) = &decl.kind else {
return Err(bad_category(schema));
};
let mut slots = 0u32;
for entry in entries {
let (owner, layout) = type_info(entry.type_id.0)?;
if !matches!(owner.kind, TypeKind::Struct(_)) {
return Err(bad_category(entry.type_id.0));
}
let fields =
u32::try_from(layout.instance.as_ref().unwrap().initialization_slots)
.map_err(|_| malformed())?;
slots = slots
.checked_add(1)
.and_then(|n| n.checked_add(fields))
.ok_or_else(malformed)?;
}
(slots, 0)
}
Op::ArrayCheckLength | Op::ArrayCopy | Op::StoragePublish => {
let (array, owner, first, second) = if self.opcode == Op::StoragePublish {
let [a, o, f, s] = self.imm_u32x4().map_err(|_| malformed())?;
(a, o, f, s)
} else {
(self.imm_u32().map_err(|_| malformed())?, 0, 0, 0)
};
Op::ArrayCopy => {
let array = self.imm_u32().map_err(|_| malformed())?;
let (_, layout) = type_info(array)?;
let element = layout.array.ok_or_else(|| bad_category(array))?.element_type_id;
let width = registry.type_layout(element).unwrap().storage.slots;
match self.opcode {
Op::ArrayCheckLength => (1, 0),
Op::ArrayCopy => (5, 0),
_ => {
let (_, layout) = type_info(owner)?;
let instance =
layout.instance.as_ref().ok_or_else(|| bad_category(owner))?;
if first == second {
return Err(bad_category(owner).member(second));
}
let mut slots = 8 + width;
for field in [first, second] {
let f = instance
.fields
.get(field as usize)
.ok_or_else(|| bad_category(owner).member(field))?;
slots += registry.type_layout(f.type_id).unwrap().storage.slots;
}
(slots, 0)
}
}
layout.array.ok_or_else(|| bad_category(array))?;
(5, 0)
}
Op::StructNew
| Op::StructGet
@@ -215,3 +215,62 @@ fn collection_effects_and_cached_initialization_width_are_exact() {
);
}
}
#[test]
fn removed_storage_encodings_and_mnemonics_are_unsupported() {
for opcode in [0xa7u16, 0xa8, 0xaa, 0xab] {
assert!(Op::try_from(opcode).is_err());
let bytes = opcode.to_le_bytes();
assert!(
matches!(decode_next(0,&bytes),Err(DecodeError::UnknownOpcode{pc:0,opcode: actual}) if actual == opcode)
);
assert!(disassemble(&bytes).is_err());
}
for text in
["INDEX_GUARD", "ARRAY_CHECK_LENGTH 1", "STORAGE_PUBLISH 1,2,0,1", "FIELDS_PUBLISH 1"]
{
assert!(assemble(text).is_err(), "{text}");
}
}
#[test]
fn range_copy_encoding_effects_and_registry_categories_are_independent_oracles() {
let bytes = [0xa9, 0, 4, 3, 2, 1];
assert_eq!(assemble("ARRAY_COPY 16909060").unwrap(), bytes);
assert_eq!(disassemble(&bytes).unwrap(), "ARRAY_COPY 16909060");
let instruction = decode_next(0, &bytes).unwrap();
assert_eq!(instruction.opcode, Op::ArrayCopy);
assert_eq!(instruction.opcode.cycles(), 4);
let spec = instruction.opcode.spec();
assert_eq!((spec.imm_bytes, spec.pops, spec.pushes), (4, None, None));
assert!(instruction.opcode.requires_registry() && spec.may_trap);
assert!(!spec.is_safepoint && !spec.is_branch && !spec.is_terminator);
for end in 0..6 {
assert!(decode_next(0, &bytes[..end]).is_err());
}
let registry = registry();
let bytes = assemble("ARRAY_COPY 5").unwrap();
assert_eq!(
decode_next(0, &bytes).unwrap().registry_stack_effect(&registry).unwrap(),
Some(RegistryStackEffect { pops: 5, pushes: 0 })
);
for (id, reason) in [
(0, LoadReason::Category),
(4, LoadReason::Category),
(6, LoadReason::Category),
(99, LoadReason::TypeId),
] {
let bytes = assemble(&format!("ARRAY_COPY {id}")).unwrap();
let error = decode_next(0, &bytes).unwrap().registry_stack_effect(&registry).unwrap_err();
assert_eq!(
(error.code, error.reason, error.pc),
(LoadCode::InvalidReference, reason, Some(0))
);
}
for text in ["ARRAY_COPY", "ARRAY_COPY -1", "ARRAY_COPY 4294967296", "ARRAY_COPY 1 2"] {
assert!(assemble(text).is_err());
}
// These are legal immediate bytes, not instruction boundaries.
let bytes = assemble("PUSH_I64 18735214094965159\nHALT").unwrap();
assert!(disassemble(&bytes).is_ok());
}
@@ -87,17 +87,6 @@ fn validate_inner(
},
)?;
}
if instruction.opcode == Op::FieldsPublish {
if let Some(declaration) =
registry.declarations().types.get(instruction.imm_u32().unwrap() as usize)
{
if let prometeu_bytecode::registry::TypeKind::Struct(entries) =
&declaration.kind
{
budget.work(entries.len())?;
}
}
}
instruction
.registry_stack_effect_in(registry, FunctionId(function_id))
.map_err(|e| contextual(e, start + pc))?;
@@ -709,64 +709,15 @@ fn check(
base += registry.type_layout(parameter.type_id).unwrap().storage.slots as usize;
}
}
Op::ArrayNew | Op::ArrayCheckLength => require(working[end - 1], I64, 0, registry, budget)?,
Op::IndexGuard => {
require(working[end - 2], I64, 0, registry, budget)?;
require(working[end - 1], I64, 1, registry, budget)?;
}
Op::FieldsPublish => {
let schema = TypeId(instruction.imm_u32().unwrap());
let effect = instruction.registry_stack_effect(registry)?.unwrap();
let mut at = end - effect.pops as usize;
let TypeKind::Struct(entries) = &registry.declarations().types[schema.0 as usize].kind
else {
unreachable!()
};
for entry in entries {
budget.work(1)?;
check_group(&working[at..], entry.type_id, registry, budget)?;
at += 1;
for field in
&registry.type_layout(entry.type_id).unwrap().instance.as_ref().unwrap().fields
{
budget.work(1)?;
check_group(&working[at..], field.type_id, registry, budget)?;
at += registry.type_layout(field.type_id).unwrap().storage.slots as usize;
}
}
}
Op::ArrayCopy | Op::StoragePublish => {
let [a, o, f, s] = if instruction.opcode == Op::StoragePublish {
instruction.imm_u32x4().unwrap()
} else {
[instruction.imm_u32().unwrap(), 0, 0, 0]
};
let effect = instruction.registry_stack_effect_in(registry, FunctionId(id))?.unwrap();
let base = end - effect.pops as usize;
check_group(&working[base..base + 1], TypeId(a), registry, budget)?;
check_group(&working[base + 2..base + 3], TypeId(a), registry, budget)?;
Op::ArrayNew => require(working[end - 1], I64, 0, registry, budget)?,
Op::ArrayCopy => {
let array = TypeId(instruction.imm_u32().unwrap());
let base = end - 5;
check_group(&working[base..base + 1], array, registry, budget)?;
check_group(&working[base + 2..base + 3], array, registry, budget)?;
for i in [1, 3, 4] {
require(working[base + i], I64, i, registry, budget)?;
}
if instruction.opcode == Op::StoragePublish {
for i in [5, 6] {
require(working[base + i], I64, i, registry, budget)?;
}
let element =
registry.type_layout(TypeId(a)).unwrap().array.unwrap().element_type_id;
let mut at = base + 7;
check_group(&working[at..], element, registry, budget)?;
at += registry.type_layout(element).unwrap().storage.slots as usize;
check_group(&working[at..], TypeId(o), registry, budget)?;
at += 1;
let fields =
&registry.type_layout(TypeId(o)).unwrap().instance.as_ref().unwrap().fields;
for field in [f, s] {
let ty = fields[field as usize].type_id;
check_group(&working[at..], ty, registry, budget)?;
at += registry.type_layout(ty).unwrap().storage.slots as usize;
}
}
}
Op::StructGet | Op::StructSet | Op::ArrayLen | Op::ArrayGet | Op::ArraySet => {
budget.work(3)?;
@@ -1,6 +1,12 @@
use crate::numeric;
use crate::resource_budget::BudgetVec;
mod array_copy;
#[cfg(test)]
mod array_copy_tests;
mod callable;
#[cfg(test)]
#[path = "../tests/support/collections.rs"]
mod collection_test_support;
mod collections;
#[cfg(test)]
mod collections_tests;
@@ -16,9 +22,6 @@ mod random;
mod reference;
mod runtime;
mod stack;
mod storage_publication;
#[cfg(test)]
mod storage_publication_tests;
mod strings;
mod typed;
#[cfg(test)]
@@ -1105,19 +1108,8 @@ impl VirtualMachine {
};
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);
}
OpCode::IndexGuard
| OpCode::ArrayCheckLength
| OpCode::ArrayCopy
| OpCode::StoragePublish => {
let operands = match opcode {
OpCode::StoragePublish => instr.imm_u32x4().unwrap(),
OpCode::IndexGuard => [0; 4],
_ => [instr.imm_u32().unwrap(), 0, 0, 0],
};
return self.execute_storage_publication(opcode, operands, start_pc as u32);
OpCode::ArrayCopy => {
return self.execute_array_copy(instr.imm_u32().unwrap(), start_pc as u32);
}
OpCode::StructNew
| OpCode::StructGet
@@ -0,0 +1,110 @@
//! Complete-group snapshot copy: charge, validate, prepare, then commit.
use super::*;
use crate::value_contract::{ValueError, ValueGroup};
use prometeu_bytecode::registry::TypeId;
fn planned_cost(count: u32, width: u64) -> Option<u64> {
u64::from(count).checked_mul(2)?.checked_mul(width)?.checked_add(4)
}
impl VirtualMachine {
pub(super) fn execute_array_copy(
&mut self,
array_id: u32,
pc: u32,
) -> Result<(), LogicalFrameEndingReason> {
let opcode = OpCode::ArrayCopy;
self.cycles += opcode.cycles();
let image = self.validated_image.clone().expect("validated Array TypeId");
let registry = image.registry();
let array_ty = TypeId(array_id);
let element = registry.type_layout(array_ty).unwrap().array.unwrap().element_type_id;
let width = registry.type_layout(element).unwrap().storage.slots;
if self.temporary_slots() < 5 {
return Err(self.trap(
TRAP_STACK_UNDERFLOW,
opcode as u16,
"Incomplete array copy operands".into(),
pc,
));
}
let base = self.operand_stack.len() - 5;
// Inspect count only to select cost, without changing ordinary fault order.
if let Value::Int64(n) = self.operand_stack[base + 4]
&& let Ok(n) = u32::try_from(n)
{
let cost = planned_cost(n, u64::from(width))
.ok_or_else(|| self.collection_size_trap(opcode, pc, u64::MAX))?;
self.cycles += cost - opcode.cycles();
}
let receiver = |offset: usize| {
let r = match self.operand_stack[base + offset] {
Value::HeapRef(r) => r,
Value::Null => return Err(self.value_trap(ValueError::NullReference, opcode, pc)),
_ => return Err(self.value_trap(ValueError::Type, opcode, pc)),
};
if self.heap.concrete_type(r, registry).map_err(|e| self.value_trap(e, opcode, pc))?
!= array_ty
{
return Err(self.value_trap(ValueError::Type, opcode, pc));
}
Ok(r)
};
let source = receiver(0)?;
let target = receiver(2)?;
let integer = |offset: usize| match self.operand_stack[base + offset] {
Value::Int64(n) => Ok(n),
_ => Err(self.value_trap(ValueError::Type, opcode, pc)),
};
let source_start = integer(1)?;
let target_start = integer(3)?;
let count = integer(4)?;
let range = |r, start: i64| {
let len = self
.heap
.typed_array_len(r, registry)
.map_err(|e| self.value_trap(e, opcode, pc))?;
if start < 0 || count < 0 || start > len as i64 || count > len as i64 - start {
return Err(self.value_trap(ValueError::Bounds, opcode, pc));
}
Ok(start as usize)
};
let source_start = range(source, source_start)?;
let target_start = range(target, target_start)?;
let count = count as usize;
// Operands remain roots; every fallible operation precedes shared writes.
let mut prepared =
BudgetVec::<ValueGroup>::new(&self.budget, RuntimeResource::TemporaryBytes);
prepared.reserve(count).map_err(|e| self.resource_trap(e, opcode, pc))?;
for i in 0..count {
let group = self
.heap
.load_typed(registry, source, source_start + i)
.map_err(|e| self.value_trap(e, opcode, pc))?;
prepared.push(group).expect("complete scratch reservation");
}
// Snapshot captured. No allocation, validation, GC, callback or scheduler.
for (i, group) in prepared.iter().enumerate() {
self.heap.commit_typed(target, target_start + i, group.as_slice());
}
self.operand_stack.truncate(base);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::planned_cost;
#[test]
fn checked_cost_covers_the_full_sum_without_wrap_or_saturation() {
assert_eq!(planned_cost(10, 1), Some(24));
assert_eq!(planned_cost(10, 3), Some(64));
assert_eq!(planned_cost(0, u64::MAX), Some(4));
assert_eq!(planned_cost(u32::MAX, 3), Some(25_769_803_774));
// Synthetic widths exercise defensive overflow, not valid guest layouts.
assert_eq!(planned_cost(1, u64::MAX), None);
assert_eq!(planned_cost(1, u64::MAX / 2), None);
assert_eq!(planned_cost(u32::MAX, u64::MAX), None);
}
}
@@ -0,0 +1,487 @@
use super::collection_test_support as support;
use super::*;
use crate::ValidatedProgramImage;
use prometeu_bytecode::{assemble, registry::TypeId};
use support::Native;
fn machine(instruction: &str, count: usize) -> VirtualMachine {
let mut text = String::new();
for i in 0..count {
text += &format!("GET_GLOBAL {i}\n");
}
text += instruction;
text += "\nHALT";
let mut vm = VirtualMachine::from_image(
support::load(&assemble(&text).unwrap()).unwrap(),
RuntimeLimits::default(),
);
vm.prepare_boot_call().unwrap();
vm
}
fn operands(vm: &mut VirtualMachine, values: &[Value]) {
vm.globals.extend_from_slice(values).unwrap();
for _ in values {
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
}
fn step(vm: &mut VirtualMachine) -> Result<(), LogicalFrameEndingReason> {
vm.step(&mut Native, &mut HostContext::new(None))
}
#[test]
fn raw_copy_preserves_absence_and_box_identity_without_heap_allocations() {
let mut vm = machine("ARRAY_COPY 15", 5);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let a = vm.heap.allocate_typed_array(registry.clone(), TypeId(15), 4).unwrap();
let boxed = vm
.heap
.allocate_dynamic_box(registry.clone(), TypeId(5), &[Value::Float(1.), Value::Float(2.)])
.unwrap();
let present = [Value::Int64(5), Value::HeapRef(boxed)];
vm.heap.store_typed(&registry, a, 0, &present).unwrap();
operands(
&mut vm,
&[Value::HeapRef(a), Value::Int64(0), Value::HeapRef(a), Value::Int64(1), Value::Int64(3)],
);
let before = vm.heap.allocation_count();
vm.budget
.test_lower_limit(RuntimeResource::GuestBytes, vm.budget.used(RuntimeResource::GuestBytes));
step(&mut vm).unwrap();
assert_eq!(vm.heap.allocation_count(), before);
assert_eq!(vm.heap.load_typed(&registry, a, 1).unwrap().as_slice(), present);
for i in [2, 3] {
assert_eq!(
vm.heap.load_typed(&registry, a, i).unwrap().as_slice(),
[Value::Null, Value::Null]
);
}
}
fn pair(ty: u32, len: u32) -> (VirtualMachine, HeapRef, HeapRef) {
let mut vm = machine(&format!("ARRAY_COPY {ty}"), 5);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let source = vm.heap.allocate_typed_array(registry.clone(), TypeId(ty), len).unwrap();
let target = vm.heap.allocate_typed_array(registry, TypeId(ty), len).unwrap();
(vm, source, target)
}
fn copy_inputs(source: HeapRef, target: HeapRef, count: i64) -> [Value; 5] {
[
Value::HeapRef(source),
Value::Int64(0),
Value::HeapRef(target),
Value::Int64(0),
Value::Int64(count),
]
}
fn refused(vm: &mut VirtualMachine, code: u32, cost: u64) {
let inputs = vm.operand_stack.as_slice().to_vec();
let (pc, cycles, temporary, objects) =
(vm.pc, vm.cycles, vm.budget.used(RuntimeResource::TemporaryBytes), vm.heap.len());
let LogicalFrameEndingReason::Trap(info) = step(vm).unwrap_err() else { panic!() };
assert_eq!((info.code, info.opcode, info.pc), (code, 0xa9, pc as u32));
assert_eq!(vm.cycles - cycles, cost);
assert_eq!(vm.operand_stack.as_slice(), inputs);
assert_eq!(vm.budget.used(RuntimeResource::TemporaryBytes), temporary);
assert_eq!(vm.heap.len(), objects);
}
#[test]
fn calculable_work_is_precharged_on_receivers_carriers_and_ranges_in_fault_order() {
for case in 0..20 {
let (mut vm, source, target) = pair(11, 10);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let wrong = vm.heap.allocate_typed_struct(registry.clone(), TypeId(19)).unwrap();
let foreign = support::load(&assemble("HALT").unwrap()).unwrap();
let foreign_ref =
vm.heap.allocate_typed_array(foreign.registry().clone(), TypeId(11), 10).unwrap();
let stale = HeapRef { index: source.index, generation: source.generation + 1 };
let mut inputs = copy_inputs(source, target, 10);
let (offset, value, code) = match case {
0 => (0, Value::Null, TRAP_NULL_REFERENCE),
1 => (2, Value::Null, TRAP_NULL_REFERENCE),
2 => (0, Value::HeapRef(stale), TRAP_INVALID_HANDLE),
3 => (2, Value::HeapRef(stale), TRAP_INVALID_HANDLE),
4 => (0, Value::HeapRef(wrong), TRAP_TYPE),
5 => (2, Value::HeapRef(wrong), TRAP_TYPE),
6 => (0, Value::HeapRef(foreign_ref), TRAP_TYPE),
7 => (2, Value::Int32(0), TRAP_TYPE),
8 => (1, Value::Int32(0), TRAP_TYPE),
9 => (3, Value::Null, TRAP_TYPE),
10 => (1, Value::Int64(-1), TRAP_OOB),
11 => (3, Value::Int64(-1), TRAP_OOB),
12 => (1, Value::Int64(1), TRAP_OOB),
13 => (3, Value::Int64(1), TRAP_OOB),
14 => {
inputs[1] = Value::Int32(0); // Receiver fault precedes offset carrier.
(2, Value::Null, TRAP_NULL_REFERENCE)
}
15 => {
inputs[1] = Value::Int64(-1); // All carriers precede source range.
(3, Value::Int32(0), TRAP_TYPE)
}
16 => (0, Value::Int32(0), TRAP_TYPE),
17 => {
let wrong_array =
vm.heap.allocate_typed_array(registry.clone(), TypeId(22), 10).unwrap();
(2, Value::HeapRef(wrong_array), TRAP_TYPE)
}
18 => (1, Value::Int64(i64::MAX), TRAP_OOB),
_ => (3, Value::Int64(i64::MAX), TRAP_OOB),
};
inputs[offset] = value;
operands(&mut vm, &inputs);
// Quota refusal must not mask earlier faults, even with full cost selected.
vm.budget.test_lower_limit(
RuntimeResource::TemporaryBytes,
vm.budget.used(RuntimeResource::TemporaryBytes),
);
refused(&mut vm, code, 24);
for i in 0..10 {
assert_eq!(
vm.heap.load_typed(&registry, target, i).unwrap().as_slice(),
[Value::Int32(0)]
);
}
}
}
#[test]
fn invalid_count_selects_only_base_without_reordering_ordinary_faults() {
for count in [
Value::Int32(10),
Value::Null,
Value::Int64(-1),
Value::Int64(u32::MAX as i64 + 1),
Value::Int64(i64::MAX),
] {
for bad_receiver in [false, true] {
let (mut vm, source, target) = pair(11, 10);
let mut inputs = copy_inputs(source, target, 0);
inputs[4] = count.clone();
if bad_receiver {
inputs[0] = Value::Null;
}
operands(&mut vm, &inputs);
let code = if bad_receiver {
TRAP_NULL_REFERENCE
} else if matches!(count, Value::Int64(_)) {
TRAP_OOB
} else {
TRAP_TYPE
};
refused(&mut vm, code, 4);
}
}
}
#[test]
fn incomplete_temporary_operands_never_read_frame_locals_for_cost() {
let code = assemble(
"GET_GLOBAL 0\nGET_GLOBAL 1\nGET_GLOBAL 2\nGET_GLOBAL 3\nGET_GLOBAL 4\nARRAY_COPY 11\nHALT",
)
.unwrap();
for available in 0..5 {
let mut declarations = support::declarations(code.len());
declarations.functions[0].local_slots = 5;
let image = ValidatedProgramImage::load(
&support::bytes_with(&code, declarations),
&mut prometeu_bytecode::load_limits::LoadBudget::new(Default::default()),
prometeu_hal::syscalls::caps::NONE,
)
.unwrap();
let mut vm = VirtualMachine::from_image(image, RuntimeLimits::default());
vm.prepare_boot_call().unwrap();
// Internal defense: skip the verified producers, leaving only locals and
// an incomplete temporary group. This is not an admitted bad program.
vm.operand_stack[4] = Value::Int64(10);
vm.operand_stack.extend_from_slice(&vec![Value::Int64(10); available]).unwrap();
vm.pc = 30;
refused(&mut vm, TRAP_STACK_UNDERFLOW, 4);
}
}
#[test]
fn overlap_snapshots_complete_multislot_groups_and_has_no_identity_discount() {
for (source_start, target_start, count) in [(0, 1, 3), (1, 0, 3), (0, 0, 4)] {
for refuse in [false, true] {
let mut vm = machine("ARRAY_COPY 12", 5);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let array = vm.heap.allocate_typed_array(registry.clone(), TypeId(12), 4).unwrap();
for i in 0..4 {
vm.heap
.store_typed(
&registry,
array,
i,
&[Value::Float(i as f64), Value::Float(i as f64 + 10.)],
)
.unwrap();
}
let before: Vec<_> = (0..4)
.map(|i| vm.heap.load_typed(&registry, array, i).unwrap().as_slice().to_vec())
.collect();
operands(
&mut vm,
&[
Value::HeapRef(array),
Value::Int64(source_start),
Value::HeapRef(array),
Value::Int64(target_start),
Value::Int64(count),
],
);
let temporary = vm.budget.used(RuntimeResource::TemporaryBytes);
if refuse {
vm.budget.test_lower_limit(RuntimeResource::TemporaryBytes, temporary);
refused(&mut vm, TRAP_RESOURCE_LIMIT, if count == 3 { 16 } else { 20 });
} else {
let cycles = vm.cycles;
step(&mut vm).unwrap();
assert_eq!(vm.cycles - cycles, if count == 3 { 16 } else { 20 });
assert!(vm.operand_stack.is_empty());
}
for i in 0..4 {
let expected =
if !refuse && i >= target_start as usize && i < (target_start + count) as usize
{
&before[(i as i64 - target_start + source_start) as usize]
} else {
&before[i]
};
assert_eq!(vm.heap.load_typed(&registry, array, i).unwrap().as_slice(), expected);
}
assert_eq!(vm.budget.used(RuntimeResource::TemporaryBytes), temporary);
}
}
}
#[test]
fn scratch_quota_and_allocator_refusals_preserve_all_destinations_and_work() {
for allocation_failure in [false, true] {
let (mut vm, source, target) = pair(11, 10);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
for i in 0..10 {
vm.heap.store_typed(&registry, source, i, &[Value::Int32(i as i32 + 1)]).unwrap();
}
operands(&mut vm, &copy_inputs(source, target, 10));
if allocation_failure {
crate::resource_budget::FAIL_NEXT_VEC_ALLOCATION.with(|fail| fail.set(true));
} else {
vm.budget.test_lower_limit(
RuntimeResource::TemporaryBytes,
vm.budget.used(RuntimeResource::TemporaryBytes),
);
}
let (cycles, temporary) = (vm.cycles, vm.budget.used(RuntimeResource::TemporaryBytes));
let LogicalFrameEndingReason::Trap(info) = step(&mut vm).unwrap_err() else { panic!() };
assert_eq!((info.code, info.opcode, info.pc), (TRAP_RESOURCE_LIMIT, 0xa9, 30));
let resource = info.resource.unwrap();
assert_eq!(resource.resource, RuntimeResource::TemporaryBytes);
assert_eq!(
resource.reason,
if allocation_failure {
crate::resource_budget::ResourceReason::AllocationFailed
} else {
crate::resource_budget::ResourceReason::Limit
}
);
assert_eq!(vm.cycles - cycles, 24);
assert_eq!(vm.budget.used(RuntimeResource::TemporaryBytes), temporary);
assert_eq!(vm.operand_stack.as_slice(), copy_inputs(source, target, 10));
for i in 0..10 {
assert_eq!(
vm.heap.load_typed(&registry, target, i).unwrap().as_slice(),
[Value::Int32(0)]
);
}
}
}
#[test]
fn late_invalid_source_group_releases_partial_preparation_without_any_write() {
let (mut vm, source, target) = pair(17, 10);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let node = vm.heap.allocate_typed_struct(registry.clone(), TypeId(9)).unwrap();
vm.heap.store_typed(&registry, source, 0, &[Value::HeapRef(node)]).unwrap();
// Internal corruption of the last stored handle exercises a late read fault.
vm.heap.commit_typed(
source,
9,
&[Value::HeapRef(HeapRef { index: node.index, generation: node.generation + 1 })],
);
operands(&mut vm, &copy_inputs(source, target, 10));
refused(&mut vm, TRAP_INVALID_HANDLE, 24);
for i in 0..10 {
assert_eq!(vm.heap.load_typed(&registry, target, i).unwrap().as_slice(), [Value::Null]);
}
}
#[test]
fn empty_copy_validates_both_receivers_and_strict_ranges_without_scratch() {
for case in 0..5 {
let (mut vm, source, target) = pair(11, 2);
let mut inputs = copy_inputs(source, target, 0);
inputs[1] = Value::Int64(2);
inputs[3] = Value::Int64(2);
let code = match case {
0 => None,
1 => {
inputs[0] = Value::Null;
Some(TRAP_NULL_REFERENCE)
}
2 => {
inputs[2] = Value::Null;
Some(TRAP_NULL_REFERENCE)
}
3 => {
inputs[1] = Value::Int64(3);
Some(TRAP_OOB)
}
_ => {
inputs[3] = Value::Int64(-1);
Some(TRAP_OOB)
}
};
operands(&mut vm, &inputs);
vm.budget.test_lower_limit(
RuntimeResource::TemporaryBytes,
vm.budget.used(RuntimeResource::TemporaryBytes),
);
if let Some(code) = code {
refused(&mut vm, code, 4);
} else {
let cycles = vm.cycles;
step(&mut vm).unwrap();
assert_eq!(vm.cycles - cycles, 4);
assert!(vm.operand_stack.is_empty());
}
}
}
#[test]
fn zero_budget_and_positive_overshoot_preserve_trap_priority_and_step_count() {
for fail in [false, true] {
let (mut vm, source, target) = pair(11, 10);
operands(&mut vm, &copy_inputs(source, target, 10));
if fail {
vm.budget.test_lower_limit(
RuntimeResource::TemporaryBytes,
vm.budget.used(RuntimeResource::TemporaryBytes),
);
}
let (pc, cycles, inputs) = (vm.pc, vm.cycles, vm.operand_stack.as_slice().to_vec());
let report = vm.run_budget(0, &mut Native, &mut HostContext::new(None)).unwrap();
assert_eq!((report.cycles_used, report.steps_executed), (0, 0));
assert_eq!((vm.pc, vm.cycles), (pc, cycles));
assert_eq!(vm.operand_stack.as_slice(), inputs);
let report = vm.run_budget(1, &mut Native, &mut HostContext::new(None)).unwrap();
assert_eq!((report.cycles_used, report.steps_executed), (24, if fail { 0 } else { 1 }));
if fail {
let LogicalFrameEndingReason::Trap(info) = report.reason else { panic!() };
assert_eq!((info.code, info.opcode, info.pc), (TRAP_RESOURCE_LIMIT, 0xa9, pc as u32));
assert_eq!(vm.operand_stack.as_slice(), inputs);
} else {
assert_eq!(report.reason, LogicalFrameEndingReason::BudgetExhausted);
}
}
}
#[test]
fn copied_groups_preserve_owners_and_references_through_collection_without_guest_growth() {
for ty in [11, 12, 13, 14, 15, 16, 17] {
let (mut vm, source, target) = pair(ty, 1);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let node = vm.heap.allocate_typed_struct(registry.clone(), TypeId(9)).unwrap();
vm.push(Value::String(std::sync::Arc::from("copy owner"))).unwrap();
let string = vm.pop().unwrap();
let group = match ty {
11 => vec![Value::Int32(7)],
12 => vec![Value::Float(1.), Value::Float(2.)],
13 => vec![Value::Int64(1), Value::Int64(2), Value::Int64(3)],
14 => vec![string.clone()],
15 => vec![Value::Int64(4), string.clone()],
16 => vec![Value::HeapRef(node), Value::Int64(0)],
_ => vec![Value::HeapRef(node)],
};
vm.heap.store_typed(&registry, source, 0, &group).unwrap();
operands(&mut vm, &copy_inputs(source, target, 1));
let objects = vm.heap.allocation_count();
let guest = vm.budget.used(RuntimeResource::GuestBytes);
for q in [
RuntimeResource::GuestBytes,
RuntimeResource::HandleSlots,
RuntimeResource::AuxiliaryBytes,
] {
vm.budget.test_lower_limit(q, vm.budget.used(q));
}
let cycles = vm.cycles;
step(&mut vm).unwrap();
assert_eq!(
vm.cycles - cycles,
match ty {
12 | 15 | 16 => 8,
13 => 10,
_ => 6,
}
);
assert_eq!(vm.heap.allocation_count(), objects);
assert_eq!(vm.budget.used(RuntimeResource::GuestBytes), guest);
assert_eq!(vm.heap.load_typed(&registry, target, 0).unwrap().as_slice(), group);
drop(group);
drop(string);
vm.globals.clear();
vm.globals.push(Value::HeapRef(target)).unwrap();
vm.gc_alloc_threshold = 1;
vm.handle_safepoint().unwrap();
assert!(!vm.heap.is_valid(source));
assert!(vm.heap.is_valid(target));
if [16, 17].contains(&ty) {
assert!(vm.heap.is_valid(node));
}
if [14, 15].contains(&ty) {
assert_eq!(vm.budget.used(RuntimeResource::StringAllocations), 1);
}
// Remove all roots and collect using the actual session root traversal.
vm.globals.clear();
vm.last_gc_live_count = 0;
vm.handle_safepoint().unwrap();
assert_eq!(vm.heap.len(), 0);
assert_eq!(vm.budget.used(RuntimeResource::StringAllocations), 0);
}
}
#[test]
fn refused_copy_keeps_source_and_previous_target_native_owners_rooted() {
let (mut vm, source, target) = pair(14, 1);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
for (array, text) in [(source, "candidate owner"), (target, "previous owner")] {
vm.push(Value::String(std::sync::Arc::from(text))).unwrap();
let value = vm.pop().unwrap();
vm.heap.store_typed(&registry, array, 0, &[value]).unwrap();
}
operands(&mut vm, &copy_inputs(source, target, 1));
let temporary = vm.budget.used(RuntimeResource::TemporaryBytes);
vm.budget.test_lower_limit(RuntimeResource::TemporaryBytes, temporary);
refused(&mut vm, TRAP_RESOURCE_LIMIT, 6);
assert_eq!(
vm.heap.load_typed(&registry, source, 0).unwrap().as_slice(),
[Value::String(std::sync::Arc::from("candidate owner"))]
);
assert_eq!(
vm.heap.load_typed(&registry, target, 0).unwrap().as_slice(),
[Value::String(std::sync::Arc::from("previous owner"))]
);
vm.budget.test_lower_limit(
RuntimeResource::TemporaryBytes,
RuntimeLimits::default().get(RuntimeResource::TemporaryBytes),
);
vm.globals.clear(); // Failed operands are now the only session roots.
vm.gc_alloc_threshold = 1;
vm.handle_safepoint().unwrap();
assert!(vm.heap.is_valid(source) && vm.heap.is_valid(target));
assert_eq!(vm.budget.used(RuntimeResource::StringAllocations), 2);
vm.operand_stack.clear();
vm.last_gc_live_count = 0;
vm.handle_safepoint().unwrap();
assert_eq!(vm.heap.len(), 0);
assert_eq!(vm.budget.used(RuntimeResource::StringAllocations), 0);
}
@@ -1,6 +1,5 @@
use super::collection_test_support as support;
use super::*;
#[path = "../../tests/support/collections.rs"]
mod support;
use crate::value_contract::ValueError;
use prometeu_bytecode::assemble;
use support::Native;
@@ -159,7 +159,7 @@ fn inline_faults_preserve_float_bits_owners_and_attempted_cost() {
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();
let mut overflow = HASH_INTRINSICS[2];
overflow.cost_per_byte = u64::MAX;
let cycles = v.cycles;
fault(v.execute_inline_intrinsic(&overflow, 0), TRAP_RESOURCE_LIMIT);
@@ -225,7 +225,7 @@ fn shared_invocation_rejects_bad_outputs_without_consuming_original_string_owner
let count = Arc::strong_count(&content);
let before = usage(&v);
for handler in [missing, wrong, excess] {
let mut meta: IntrinsicMeta = HASH_INTRINSICS[2].clone();
let mut meta: IntrinsicMeta = HASH_INTRINSICS[2];
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);
@@ -1,286 +0,0 @@
//! Generic complete-group range operations. All admission precedes shared writes.
use super::*;
use crate::value_contract::{self, ValueError, ValueGroup};
use prometeu_bytecode::registry::TypeId;
impl VirtualMachine {
pub(super) fn execute_storage_publication(
&mut self,
opcode: OpCode,
operands: [u32; 4],
pc: u32,
) -> Result<(), LogicalFrameEndingReason> {
self.cycles += opcode.cycles();
if opcode == OpCode::IndexGuard {
if self.temporary_slots() < 2 {
return Err(self.trap(
TRAP_STACK_UNDERFLOW,
opcode as u16,
"Incomplete guard operands".into(),
pc,
));
}
let base = self.operand_stack.len() - 2;
match (&self.operand_stack[base], &self.operand_stack[base + 1]) {
(Value::Int64(index), Value::Int64(limit)) if *index >= 0 && index < limit => {}
(Value::Int64(_), Value::Int64(_)) => {
return Err(self.value_trap(ValueError::Bounds, opcode, pc));
}
_ => return Err(self.value_trap(ValueError::Type, opcode, pc)),
}
self.operand_stack.truncate(base);
return Ok(());
}
let image = self.validated_image.clone().ok_or_else(|| {
self.trap(
prometeu_bytecode::TRAP_ILLEGAL_INSTRUCTION,
opcode as u16,
"Storage operation requires a validated Registry".into(),
pc,
)
})?;
let registry = image.registry();
let [array_id, owner_id, first, second] = operands;
let array_ty = TypeId(array_id);
let element = registry.type_layout(array_ty).unwrap().array.unwrap().element_type_id;
let width = registry.type_layout(element).unwrap().storage.slots as usize;
let fields = if opcode == OpCode::StoragePublish {
Some(&registry.type_layout(TypeId(owner_id)).unwrap().instance.as_ref().unwrap().fields)
} else {
None
};
let field_width = |field: u32| {
registry.type_layout(fields.unwrap()[field as usize].type_id).unwrap().storage.slots
as usize
};
let consumed = match opcode {
OpCode::ArrayCheckLength => 1,
OpCode::ArrayCopy => 5,
_ => 8 + width + field_width(first) + field_width(second),
};
if self.temporary_slots() < consumed {
return Err(self.trap(
TRAP_STACK_UNDERFLOW,
opcode as u16,
"Incomplete storage operands".into(),
pc,
));
}
let base = self.operand_stack.len() - consumed;
let integer = |offset: usize| match self.operand_stack[base + offset] {
Value::Int64(n) => Ok(n),
_ => Err(self.value_trap(ValueError::Type, opcode, pc)),
};
if opcode == OpCode::ArrayCheckLength {
let n = integer(0)?;
if n < 0 {
return Err(self.value_trap(ValueError::Bounds, opcode, pc));
}
if u32::try_from(n).is_err() {
return Err(self.collection_size_trap(opcode, pc, n as u64));
}
self.operand_stack.truncate(base);
return Ok(());
}
let receiver = |offset: usize, ty: TypeId| {
let r = match self.operand_stack[base + offset] {
Value::HeapRef(r) => r,
Value::Null => return Err(self.value_trap(ValueError::NullReference, opcode, pc)),
_ => return Err(self.value_trap(ValueError::Type, opcode, pc)),
};
if self.heap.concrete_type(r, registry).map_err(|e| self.value_trap(e, opcode, pc))?
!= ty
{
return Err(self.value_trap(ValueError::Type, opcode, pc));
}
Ok(r)
};
let source = receiver(0, array_ty)?;
let target = receiver(2, array_ty)?;
let source_start = integer(1)?;
let target_start = integer(3)?;
let count = integer(4)?;
let range = |r, start: i64, count: i64| {
let len = self
.heap
.typed_array_len(r, registry)
.map_err(|e| self.value_trap(e, opcode, pc))?;
if start < 0 || count < 0 || start > len as i64 || count > len as i64 - start {
return Err(self.value_trap(ValueError::Bounds, opcode, pc));
}
Ok((start as usize, count as usize))
};
let (source_start, count) = range(source, source_start, count)?;
let (target_start, _) = range(target, target_start, count as i64)?;
let (fill_start, fill_count, owner) = if fields.is_some() {
let (start, count) = range(target, integer(5)?, integer(6)?)?;
let owner = receiver(7 + width, TypeId(owner_id))?;
value_contract::validate(
registry,
&self.heap,
element,
&self.operand_stack[base + 7..base + 7 + width],
)
.map_err(|e| self.value_trap(e, opcode, pc))?;
let mut at = base + 8 + width;
for field in [first, second] {
let ty = fields.unwrap()[field as usize].type_id;
let w = field_width(field);
value_contract::validate(registry, &self.heap, ty, &self.operand_stack[at..at + w])
.map_err(|e| self.value_trap(e, opcode, pc))?;
at += w;
}
(start, count, Some(owner))
} else {
(0, 0, None)
};
let work = (count as u64)
.checked_mul(2)
.and_then(|n| n.checked_add(fill_count as u64))
.and_then(|n| n.checked_mul(width as u64))
.and_then(|n| {
n.checked_add(if fields.is_some() {
(field_width(first) + field_width(second)) as u64
} else {
0
})
})
.ok_or_else(|| self.collection_size_trap(opcode, pc, u64::MAX))?;
self.cycles += work;
// This reservation and all reads/validation can fail. No destination has
// changed yet. The original operands remain roots throughout preparation.
let mut prepared =
BudgetVec::<ValueGroup>::new(&self.budget, RuntimeResource::TemporaryBytes);
prepared.reserve(count).map_err(|e| self.resource_trap(e, opcode, pc))?;
for i in 0..count {
let group = self
.heap
.load_typed(registry, source, source_start + i)
.map_err(|e| self.value_trap(e, opcode, pc))?;
prepared.push(group).expect("complete scratch reservation");
}
// No allocation, GC, callback, scheduler or fallible operation follows.
// Capturing every source group first gives memmove semantics for overlap.
for (i, group) in prepared.iter().enumerate() {
self.heap.commit_typed(target, target_start + i, group.as_slice());
}
if let Some(owner) = owner {
let fill = &self.operand_stack[base + 7..base + 7 + width];
for i in 0..fill_count {
self.heap.commit_typed(target, fill_start + i, fill);
}
let mut at = base + 8 + width;
for field in [first, second] {
let w = field_width(field);
self.heap.commit_typed(owner, field as usize, &self.operand_stack[at..at + w]);
at += w;
}
}
self.operand_stack.truncate(base);
Ok(())
}
}
impl VirtualMachine {
/// A Struct schema lists destination Struct types, without allocating a request.
/// Inputs stay rooted and unconsumed until validation of the entire attempt.
pub(super) fn execute_fields_publication(
&mut self,
schema: u32,
pc: u32,
) -> Result<(), LogicalFrameEndingReason> {
let opcode = OpCode::FieldsPublish;
self.cycles += opcode.cycles();
let image = self.validated_image.clone().expect("validated Registry operation");
let registry = image.registry();
let prometeu_bytecode::registry::TypeKind::Struct(entries) =
&registry.declarations().types[schema as usize].kind
else {
unreachable!()
};
let consumed: usize = entries
.iter()
.map(|entry| {
1 + registry
.type_layout(entry.type_id)
.unwrap()
.instance
.as_ref()
.unwrap()
.fields
.iter()
.map(|f| registry.type_layout(f.type_id).unwrap().storage.slots as usize)
.sum::<usize>()
})
.sum();
if self.temporary_slots() < consumed {
return Err(self.trap(
TRAP_STACK_UNDERFLOW,
opcode as u16,
"Incomplete field publication operands".into(),
pc,
));
}
self.cycles += consumed as u64;
let base = self.operand_stack.len() - consumed;
let mut at = base;
for entry in entries {
match self.operand_stack[at] {
Value::Null => {}
Value::HeapRef(receiver) => {
if self
.heap
.concrete_type(receiver, registry)
.map_err(|e| self.value_trap(e, opcode, pc))?
!= entry.type_id
{
return Err(self.value_trap(ValueError::Type, opcode, pc));
}
}
_ => return Err(self.value_trap(ValueError::Type, opcode, pc)),
}
at += 1;
for field in
&registry.type_layout(entry.type_id).unwrap().instance.as_ref().unwrap().fields
{
let width = registry.type_layout(field.type_id).unwrap().storage.slots as usize;
value_contract::validate(
registry,
&self.heap,
field.type_id,
&self.operand_stack[at..at + width],
)
.map_err(|e| self.value_trap(e, opcode, pc))?;
at += width;
}
}
// No allocation, provenance lookup, validation, callback, GC or scheduler
// boundary follows. Repeated destinations use ordered last-write semantics.
at = base;
for entry in entries {
let receiver = match self.operand_stack[at] {
Value::HeapRef(r) => Some(r),
_ => None,
};
at += 1;
for (index, field) in registry
.type_layout(entry.type_id)
.unwrap()
.instance
.as_ref()
.unwrap()
.fields
.iter()
.enumerate()
{
let width = registry.type_layout(field.type_id).unwrap().storage.slots as usize;
if let Some(receiver) = receiver {
self.heap.commit_typed(receiver, index, &self.operand_stack[at..at + width]);
}
at += width;
}
}
self.operand_stack.truncate(base);
Ok(())
}
}
@@ -1,378 +0,0 @@
use super::*;
#[path = "../../tests/support/collections.rs"]
mod support;
use prometeu_bytecode::{assemble, registry::TypeId};
use support::Native;
fn machine(instruction: &str, count: usize) -> VirtualMachine {
let mut text = String::new();
for i in 0..count {
text += &format!("GET_GLOBAL {i}\n");
}
text += instruction;
text += "\nHALT";
let mut vm = VirtualMachine::from_image(
support::load(&assemble(&text).unwrap()).unwrap(),
RuntimeLimits::default(),
);
vm.prepare_boot_call().unwrap();
vm
}
fn operands(vm: &mut VirtualMachine, values: &[Value]) {
vm.globals.extend_from_slice(values).unwrap();
for _ in values {
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
}
}
fn step(vm: &mut VirtualMachine) -> Result<(), LogicalFrameEndingReason> {
vm.step(&mut Native, &mut HostContext::new(None))
}
fn fault(result: Result<(), LogicalFrameEndingReason>, code: u32) {
let LogicalFrameEndingReason::Trap(t) = result.unwrap_err() else { panic!() };
assert_eq!(t.code, code);
}
#[test]
fn logical_guard_and_length_validation_preserve_exact_faults_and_inputs() {
for (index, limit, valid) in
[(0, 1, true), (1, 1, false), (-1, 3, false), (0, 0, false), (i64::MAX - 1, i64::MAX, true)]
{
let mut vm = machine("INDEX_GUARD", 2);
let values = [Value::Int64(index), Value::Int64(limit)];
operands(&mut vm, &values);
if valid {
step(&mut vm).unwrap();
assert!(vm.operand_stack.is_empty());
} else {
fault(step(&mut vm), TRAP_OOB);
assert_eq!(vm.operand_stack.as_slice(), values);
}
}
for (n, code) in [
(-1, Some(TRAP_OOB)),
(0, None),
(u32::MAX as i64, None),
(u32::MAX as i64 + 1, Some(TRAP_RESOURCE_LIMIT)),
] {
let mut vm = machine("ARRAY_CHECK_LENGTH 15", 1);
operands(&mut vm, &[Value::Int64(n)]);
let before = vm.heap.allocation_count();
if let Some(code) = code {
fault(step(&mut vm), code);
assert_eq!(vm.operand_stack.as_slice(), [Value::Int64(n)]);
} else {
step(&mut vm).unwrap();
assert!(vm.operand_stack.is_empty());
}
assert_eq!(vm.heap.allocation_count(), before);
}
}
#[test]
fn overlapping_publication_preserves_complete_groups_and_publishes_both_fields() {
for quota in [None, Some(RuntimeResource::TemporaryBytes)] {
let mut vm = machine("STORAGE_PUBLISH 12,21,0,1", 13);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let a = vm.heap.allocate_typed_array(registry.clone(), TypeId(12), 4).unwrap();
let owner = vm.heap.allocate_typed_struct(registry.clone(), TypeId(21)).unwrap();
for i in 0..3 {
vm.heap
.store_typed(
&registry,
a,
i,
&[Value::Float(i as f64 + 1.), Value::Float(i as f64 + 10.)],
)
.unwrap();
}
let before: Vec<_> = (0..4)
.map(|i| vm.heap.load_typed(&registry, a, i).unwrap().as_slice().to_vec())
.collect();
let inputs = [
Value::HeapRef(a),
Value::Int64(0),
Value::HeapRef(a),
Value::Int64(1),
Value::Int64(3),
Value::Int64(0),
Value::Int64(1),
Value::Float(9.),
Value::Float(8.),
Value::HeapRef(owner),
Value::Int32(7),
Value::Float(6.),
Value::Float(5.),
];
operands(&mut vm, &inputs);
let old_usage = vm.budget.used(RuntimeResource::TemporaryBytes);
if let Some(q) = quota {
vm.budget.test_lower_limit(q, vm.budget.used(q));
}
if quota.is_some() {
fault(step(&mut vm), TRAP_RESOURCE_LIMIT);
assert_eq!(vm.operand_stack.as_slice(), inputs);
for (i, group) in before.iter().enumerate() {
assert_eq!(vm.heap.load_typed(&registry, a, i).unwrap().as_slice(), group);
}
assert_eq!(
vm.heap.load_typed(&registry, owner, 0).unwrap().as_slice(),
[Value::Int32(0)]
);
assert_eq!(
vm.heap.load_typed(&registry, owner, 1).unwrap().as_slice(),
[Value::Float(0.), Value::Float(0.)]
);
} else {
step(&mut vm).unwrap();
assert!(vm.operand_stack.is_empty());
assert_eq!(
vm.heap.load_typed(&registry, a, 0).unwrap().as_slice(),
[Value::Float(9.), Value::Float(8.)]
);
for i in 1..4 {
assert_eq!(vm.heap.load_typed(&registry, a, i).unwrap().as_slice(), before[i - 1]);
}
assert_eq!(
vm.heap.load_typed(&registry, owner, 0).unwrap().as_slice(),
[Value::Int32(7)]
);
assert_eq!(
vm.heap.load_typed(&registry, owner, 1).unwrap().as_slice(),
[Value::Float(6.), Value::Float(5.)]
);
}
assert_eq!(vm.budget.used(RuntimeResource::TemporaryBytes), old_usage);
}
}
#[test]
fn late_invalid_field_or_range_prevents_every_write() {
for bad_range in [false, true] {
let mut vm = machine("STORAGE_PUBLISH 11,9,0,1", 11);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let a = vm.heap.allocate_typed_array(registry.clone(), TypeId(11), 2).unwrap();
let owner = vm.heap.allocate_typed_struct(registry.clone(), TypeId(9)).unwrap();
vm.heap.store_typed(&registry, a, 0, &[Value::Int32(3)]).unwrap();
let inputs = [
Value::HeapRef(a),
Value::Int64(0),
Value::HeapRef(a),
Value::Int64(1),
Value::Int64(1),
Value::Int64(if bad_range { 2 } else { 0 }),
Value::Int64(1),
Value::Int32(8),
Value::HeapRef(owner),
Value::Int32(4),
if bad_range { Value::Int64(7) } else { Value::Boolean(true) },
];
operands(&mut vm, &inputs);
fault(step(&mut vm), if bad_range { TRAP_OOB } else { TRAP_TYPE });
assert_eq!(vm.operand_stack.as_slice(), inputs);
assert_eq!(vm.heap.load_typed(&registry, a, 0).unwrap().as_slice(), [Value::Int32(3)]);
assert_eq!(vm.heap.load_typed(&registry, a, 1).unwrap().as_slice(), [Value::Int32(0)]);
assert_eq!(vm.heap.load_typed(&registry, owner, 0).unwrap().as_slice(), [Value::Int32(0)]);
}
}
#[test]
fn raw_copy_preserves_absence_and_box_identity_without_heap_allocations() {
let mut vm = machine("ARRAY_COPY 15", 5);
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let a = vm.heap.allocate_typed_array(registry.clone(), TypeId(15), 4).unwrap();
let boxed = vm
.heap
.allocate_dynamic_box(registry.clone(), TypeId(5), &[Value::Float(1.), Value::Float(2.)])
.unwrap();
let present = [Value::Int64(5), Value::HeapRef(boxed)];
vm.heap.store_typed(&registry, a, 0, &present).unwrap();
operands(
&mut vm,
&[Value::HeapRef(a), Value::Int64(0), Value::HeapRef(a), Value::Int64(1), Value::Int64(3)],
);
let before = vm.heap.allocation_count();
vm.budget
.test_lower_limit(RuntimeResource::GuestBytes, vm.budget.used(RuntimeResource::GuestBytes));
step(&mut vm).unwrap();
assert_eq!(vm.heap.allocation_count(), before);
assert_eq!(vm.heap.load_typed(&registry, a, 1).unwrap().as_slice(), present);
for i in [2, 3] {
assert_eq!(
vm.heap.load_typed(&registry, a, i).unwrap().as_slice(),
[Value::Null, Value::Null]
);
}
}
#[test]
fn dead_invalid_operands_and_split_typed_groups_are_rejected() {
for instruction in [
"ARRAY_COPY 9",
"ARRAY_CHECK_LENGTH 99",
"STORAGE_PUBLISH 11,9,0,0",
"STORAGE_PUBLISH 11,9,0,99",
"STORAGE_PUBLISH 11,11,0,1",
] {
assert!(
support::load(&assemble(&format!("HALT\n{instruction}")).unwrap()).is_err(),
"{instruction}"
);
}
assert!(
support::load(&assemble("PUSH_BOOL 1\nPUSH_I64 3\nINDEX_GUARD\nHALT").unwrap()).is_err()
);
}
fn fields_machine() -> VirtualMachine {
use prometeu_bytecode::registry::{NamedType, TypeDecl, TypeKind};
let mut code = String::new();
for i in 0..12 {
code += &format!("GET_GLOBAL {i}\n");
}
code += "FIELDS_PUBLISH 27\nHALT";
let code = assemble(&code).unwrap();
let mut declarations = support::declarations(code.len());
assert_eq!(declarations.types.len(), 26);
let field = |id| NamedType { type_id: TypeId(id), name: None };
declarations.types.push(TypeDecl {
name: None,
kind: TypeKind::Struct([0, 5, 4, 9].into_iter().map(field).collect()),
});
declarations.types.push(TypeDecl {
name: None,
kind: TypeKind::Struct([26, 26].into_iter().map(field).collect()),
});
let image = crate::ValidatedProgramImage::load(
&support::bytes_with(&code, declarations),
&mut prometeu_bytecode::load_limits::LoadBudget::new(Default::default()),
prometeu_hal::syscalls::caps::NONE,
)
.unwrap();
let mut vm = VirtualMachine::from_image(image, RuntimeLimits::default());
vm.prepare_boot_call().unwrap();
vm
}
#[test]
fn fields_publication_is_complete_preserves_native_and_reference_groups_and_needs_no_scratch() {
for alias in [false, true] {
let mut vm = fields_machine();
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let first = vm.heap.allocate_typed_struct(registry.clone(), TypeId(26)).unwrap();
let second = if alias {
first
} else {
vm.heap.allocate_typed_struct(registry.clone(), TypeId(26)).unwrap()
};
let payload = vm.heap.allocate_typed_struct(registry.clone(), TypeId(9)).unwrap();
let text: std::sync::Arc<str> = "owned".into();
let inputs = [
Value::HeapRef(first),
Value::Int32(1),
Value::Float(2.),
Value::Float(3.),
Value::String(text.clone()),
Value::HeapRef(payload),
Value::HeapRef(second),
Value::Int32(42),
Value::Float(20.),
Value::Float(22.),
Value::String(text.clone()),
Value::HeapRef(payload),
];
operands(&mut vm, &inputs);
for resource in [
RuntimeResource::GuestBytes,
RuntimeResource::HandleSlots,
RuntimeResource::TemporaryBytes,
RuntimeResource::AuxiliaryBytes,
] {
vm.budget.test_lower_limit(resource, vm.budget.used(resource));
}
let count = vm.heap.allocation_count();
let cycles = vm.cycles;
step(&mut vm).unwrap();
assert_eq!(vm.cycles - cycles, 18);
assert_eq!(count, vm.heap.allocation_count());
assert!(vm.operand_stack.is_empty());
assert_eq!(
vm.heap.load_typed(&registry, first, 0).unwrap().as_slice(),
[Value::Int32(if alias { 42 } else { 1 })]
);
assert_eq!(
vm.heap.load_typed(&registry, second, 1).unwrap().as_slice(),
[Value::Float(20.), Value::Float(22.)]
);
let native = vm.heap.load_typed(&registry, first, 2).unwrap();
let Value::String(stored) = &native.as_slice()[0] else { panic!() };
assert!(std::sync::Arc::ptr_eq(stored, &text));
assert_eq!(
vm.heap.load_typed(&registry, first, 3).unwrap().as_slice(),
[Value::HeapRef(payload)]
);
}
}
#[test]
fn fields_publication_checks_late_groups_and_skipped_destinations_before_any_write() {
for skipped in [false, true] {
let mut vm = fields_machine();
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let first = vm.heap.allocate_typed_struct(registry.clone(), TypeId(26)).unwrap();
let second = vm.heap.allocate_typed_struct(registry.clone(), TypeId(26)).unwrap();
let inputs = [
Value::HeapRef(first),
Value::Int32(42),
Value::Float(1.),
Value::Float(2.),
Value::Null,
Value::Null,
if skipped { Value::Null } else { Value::HeapRef(second) },
Value::Int32(7),
Value::Float(3.),
Value::Float(4.),
Value::Boolean(true),
Value::Null,
];
operands(&mut vm, &inputs);
fault(step(&mut vm), TRAP_TYPE);
assert_eq!(vm.operand_stack.as_slice(), inputs);
for owner in [first, second] {
assert_eq!(
vm.heap.load_typed(&registry, owner, 0).unwrap().as_slice(),
[Value::Int32(0)]
);
}
}
let mut vm = fields_machine();
let registry = vm.validated_image.as_ref().unwrap().registry().clone();
let first = vm.heap.allocate_typed_struct(registry.clone(), TypeId(26)).unwrap();
let inputs = [
Value::HeapRef(first),
Value::Int32(42),
Value::Float(1.),
Value::Float(2.),
Value::Null,
Value::Null,
Value::Null,
Value::Int32(7),
Value::Float(3.),
Value::Float(4.),
Value::Null,
Value::Null,
];
operands(&mut vm, &inputs);
step(&mut vm).unwrap();
assert_eq!(vm.heap.load_typed(&registry, first, 0).unwrap().as_slice(), [Value::Int32(42)]);
}
#[test]
fn fields_publication_rejects_bad_schemas_dead_operands_and_truncation() {
for text in ["HALT\nFIELDS_PUBLISH 0", "HALT\nFIELDS_PUBLISH 99", "HALT\nFIELDS_PUBLISH 9"] {
assert!(support::load(&assemble(text).unwrap()).is_err(), "{text}");
}
let bytes = assemble("FIELDS_PUBLISH 26").unwrap();
for end in 2..bytes.len() {
assert!(prometeu_bytecode::decode_next(0, &bytes[..end]).is_err());
}
}
@@ -132,3 +132,39 @@ fn collection_load_limits_and_analysis_refusals_keep_context_and_refund_scratch(
assert_eq!(budget.used(LoadResource::RegistryBytes), 0);
}
}
#[test]
fn removed_storage_opcodes_reject_even_in_unreachable_instruction_positions() {
use prometeu_bytecode::load_limits::{LoadCode, LoadReason};
use prometeu_vm::VmInitError;
for opcode in [0xa7u16, 0xa8, 0xaa, 0xab] {
for dead in [false, true] {
let mut code = if dead { vec![1, 0] } else { vec![] };
let pc = code.len() as u32;
code.extend_from_slice(&opcode.to_le_bytes());
let VmInitError::RegistryLoadFailed(error) = load(&code).unwrap_err() else { panic!() };
assert_eq!(error.code, LoadCode::InvalidCode);
assert_eq!(error.reason, LoadReason::UnknownOpcode);
assert_eq!((error.function, error.pc), (Some(0), Some(pc)));
}
}
// The same bytes are accepted as an Int64 immediate, never decoded as opcodes.
let code = [0x14, 0, 0xa7, 0, 0xa8, 0, 0xaa, 0, 0xab, 0, 1, 0];
assert_eq!(
run(&code),
[Value::Int64(i64::from_le_bytes([0xa7, 0, 0xa8, 0, 0xaa, 0, 0xab, 0]))]
);
}
#[test]
fn neutral_pbx_copy_moves_a_range_and_preserves_physical_length() {
let code=assemble("PUSH_I64 2\nARRAY_NEW 11\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I64 0\nPUSH_I32 42\nARRAY_SET 11\nGET_GLOBAL 0\nPUSH_I64 0\nGET_GLOBAL 0\nPUSH_I64 1\nPUSH_I64 1\nARRAY_COPY 11\nGET_GLOBAL 0\nPUSH_I64 1\nARRAY_GET 11\nGET_GLOBAL 0\nARRAY_LEN 11\nHALT").unwrap();
assert_eq!(run(&code), [Value::Int64(2), Value::Int32(42)]);
for text in [
"HALT\nARRAY_COPY 9",
"HALT\nARRAY_COPY 99",
"PUSH_I64 1\nARRAY_NEW 11\nPUSH_I64 0\nPUSH_I64 1\nARRAY_NEW 11\nPUSH_I64 0\nPUSH_BOOL 1\nARRAY_COPY 11\nHALT",
] {
assert!(load(&assemble(text).unwrap()).is_err(), "{text}");
}
}