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.
3928 lines
151 KiB
Rust
3928 lines
151 KiB
Rust
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;
|
|
mod control;
|
|
mod dynamic;
|
|
mod gc;
|
|
mod identity;
|
|
mod intrinsic;
|
|
mod lifecycle;
|
|
mod loader;
|
|
mod native_arrays;
|
|
mod random;
|
|
mod reference;
|
|
mod runtime;
|
|
mod stack;
|
|
mod strings;
|
|
mod typed;
|
|
#[cfg(test)]
|
|
mod typed_tests;
|
|
|
|
use crate::call_frame::CallFrame;
|
|
use crate::heap::Heap;
|
|
use crate::lookup_intrinsic_by_id;
|
|
use crate::resource_budget::{ResourceFailure, RuntimeBudget, RuntimeLimits, RuntimeResource};
|
|
use crate::roots::{RootVisitor, visit_value_for_roots};
|
|
use crate::vm_init_error::VmInitError;
|
|
use crate::{HostContext, NativeInterface};
|
|
use prometeu_bytecode::HeapRef;
|
|
use prometeu_bytecode::ProgramImage;
|
|
use prometeu_bytecode::Value;
|
|
#[cfg(test)]
|
|
use prometeu_bytecode::decode_next;
|
|
use prometeu_bytecode::isa::core::CoreOpCode as OpCode;
|
|
#[cfg(test)]
|
|
use prometeu_bytecode::registry::FunctionDecl;
|
|
use prometeu_bytecode::{
|
|
TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT, TRAP_INVALID_FUNC, TRAP_INVALID_HANDLE,
|
|
TRAP_INVALID_INTRINSIC, TRAP_INVALID_SYSCALL, TRAP_NULL_REFERENCE, TRAP_OOB,
|
|
TRAP_RESOURCE_LIMIT, TRAP_STACK_UNDERFLOW, TRAP_TYPE, TRAP_UNAVAILABLE, TrapInfo,
|
|
};
|
|
use prometeu_hal::syscalls::caps::NONE;
|
|
use prometeu_hal::vm_fault::VmFault;
|
|
#[cfg(test)]
|
|
use prometeu_test_support::program::{TestProgram, int64_signature};
|
|
|
|
/// Reason why the Virtual Machine stopped execution during a specific run.
|
|
/// This allows the system to decide if it should continue execution in the next tick
|
|
/// or if the frame is finalized.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum LogicalFrameEndingReason {
|
|
/// Execution reached a `FRAME_SYNC` instruction, marking the end of the logical frame.
|
|
FrameSync,
|
|
/// The outer lifecycle callback returned; gameplay has not resumed.
|
|
LifecycleComplete,
|
|
/// The cycle budget for the current host tick was exhausted before reaching `FRAME_SYNC`.
|
|
BudgetExhausted,
|
|
/// A `HALT` instruction was executed, terminating the program.
|
|
Halted,
|
|
/// The Program Counter (PC) reached the end of the available bytecode.
|
|
EndOfRom,
|
|
/// Execution hit a registered breakpoint.
|
|
Breakpoint,
|
|
/// A runtime trap occurred (e.g., out-of-bounds access).
|
|
Trap(TrapInfo),
|
|
/// A fatal error occurred that cannot be recovered (e.g., stack underflow).
|
|
Panic(String),
|
|
}
|
|
|
|
pub(crate) enum OpError {
|
|
Trap(u32, String),
|
|
}
|
|
|
|
impl From<crate::numeric::NumericError> for OpError {
|
|
fn from(error: crate::numeric::NumericError) -> Self {
|
|
Self::Trap(error.code, format!("Numeric operation failed: {error:?}"))
|
|
}
|
|
}
|
|
|
|
impl From<TrapInfo> for LogicalFrameEndingReason {
|
|
fn from(info: TrapInfo) -> Self {
|
|
LogicalFrameEndingReason::Trap(info)
|
|
}
|
|
}
|
|
|
|
/// A report detailing the results of an execution slice (run_budget).
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct BudgetReport {
|
|
/// Total virtual cycles consumed during this run.
|
|
pub cycles_used: u64,
|
|
/// Number of VM instructions executed.
|
|
pub steps_executed: u32,
|
|
/// The reason why this execution slice ended.
|
|
pub reason: LogicalFrameEndingReason,
|
|
}
|
|
|
|
pub struct VirtualMachine {
|
|
/// Program Counter (PC): The absolute byte offset in ROM for the next instruction.
|
|
pc: usize,
|
|
/// Operand Stack: The primary workspace for all mathematical and logical operations.
|
|
operand_stack: BudgetVec<Value>,
|
|
/// Call Stack: Manages function call context (return addresses, frame limits).
|
|
call_stack: BudgetVec<CallFrame>,
|
|
/// Global Variable Store: Variables that persist for the lifetime of the program.
|
|
globals: BudgetVec<Value>,
|
|
/// The loaded executable (Bytecode + Constant Pool), that is the ROM translated.
|
|
program: ProgramImage,
|
|
validated_image: Option<std::sync::Arc<crate::ValidatedProgramImage>>,
|
|
strings: Option<crate::string_ledger::StringLedger>,
|
|
/// Heap Memory: Dynamic allocation pool.
|
|
heap: Heap,
|
|
/// Total virtual cycles consumed since the VM started.
|
|
cycles: u64,
|
|
/// Stop flag: true if a `HALT` opcode was encountered.
|
|
halted: bool,
|
|
lifecycle: Option<lifecycle::LifecycleCall>,
|
|
lifecycle_failure: Option<LogicalFrameEndingReason>,
|
|
memcard_boot_started: bool,
|
|
memcard_boot_result: Option<i32>,
|
|
memcard_boot_required: bool,
|
|
/// Set of ROM addresses used for software breakpoints in the debugger.
|
|
breakpoints: std::collections::HashSet<usize>,
|
|
/// GC: number of newly allocated live objects threshold to trigger a collection at safepoint.
|
|
/// The GC only runs at safepoints (e.g., FRAME_SYNC). 0 disables automatic GC.
|
|
gc_alloc_threshold: usize,
|
|
/// GC: snapshot of live objects count after the last collection (or VM init).
|
|
last_gc_live_count: usize,
|
|
/// Capability flags granted to the currently running program/cart.
|
|
/// Syscalls are capability-gated using `prometeu_hal::syscalls::SyscallMeta::caps`.
|
|
capabilities: prometeu_hal::syscalls::CapFlags,
|
|
budget: RuntimeBudget,
|
|
#[cfg(feature = "resource-diagnostics")]
|
|
gc_diagnostics: crate::resource_diagnostics::GcDiagnostics,
|
|
#[cfg(feature = "resource-diagnostics")]
|
|
peak_call_depth: usize,
|
|
}
|
|
|
|
impl Default for VirtualMachine {
|
|
fn default() -> Self {
|
|
Self::empty(RuntimeLimits::default())
|
|
}
|
|
}
|
|
|
|
impl VirtualMachine {
|
|
#[cfg(feature = "resource-diagnostics")]
|
|
pub fn resource_observer(&self) -> RuntimeBudget {
|
|
self.budget.clone()
|
|
}
|
|
|
|
#[cfg(feature = "resource-diagnostics")]
|
|
pub fn resource_snapshot(&self) -> crate::resource_diagnostics::ResourceSnapshot {
|
|
let (free_handles, retired_handles) = self.heap.diagnostic_handles();
|
|
crate::resource_diagnostics::ResourceSnapshot {
|
|
budget: self.budget.diagnostic_snapshot(),
|
|
live_objects: self.heap.len(),
|
|
free_handles,
|
|
retired_handles,
|
|
tracked_strings: self.strings.as_ref().map_or(0, |s| s.tracked_allocations()),
|
|
call_depth: self.call_stack.len(),
|
|
peak_call_depth: self.peak_call_depth.max(self.call_stack.len()),
|
|
cycles: self.cycles,
|
|
gc: self.gc_diagnostics.clone(),
|
|
}
|
|
}
|
|
/// Returns the current program counter.
|
|
pub fn pc(&self) -> usize {
|
|
self.pc
|
|
}
|
|
|
|
/// Returns true if there are no active call frames.
|
|
pub fn call_stack_is_empty(&self) -> bool {
|
|
self.call_stack.is_empty()
|
|
}
|
|
|
|
/// Returns up to `n` values from the top of the operand stack (top-first order).
|
|
pub fn operand_stack_top(&self, n: usize) -> prometeu_hal::ValueSnapshot {
|
|
let len = self.operand_stack.len();
|
|
let start = len.saturating_sub(n);
|
|
let values: Vec<_> = self.operand_stack[start..].iter().rev().cloned().collect();
|
|
let mut owners = [None, None];
|
|
for value in &values {
|
|
if let Value::String(content) = value {
|
|
if let Some(image) = &self.validated_image
|
|
&& owners[0].is_none()
|
|
&& image.retains_string(content)
|
|
{
|
|
owners[0] = Some(image.string_retention());
|
|
}
|
|
if let Some(strings) = &self.strings
|
|
&& owners[1].is_none()
|
|
&& strings.retains(content)
|
|
{
|
|
owners[1] = Some(strings.retention());
|
|
}
|
|
}
|
|
}
|
|
prometeu_hal::ValueSnapshot::with_owners(values, owners)
|
|
}
|
|
|
|
/// Returns a reference to the VM's heap.
|
|
pub fn heap(&self) -> &Heap {
|
|
&self.heap
|
|
}
|
|
|
|
/// Returns true if the VM has executed a HALT and is not currently running.
|
|
pub fn is_halted(&self) -> bool {
|
|
self.halted
|
|
}
|
|
|
|
/// Adds a software breakpoint at the given PC.
|
|
pub fn insert_breakpoint(&mut self, pc: usize) {
|
|
let _ = self.breakpoints.insert(pc);
|
|
}
|
|
|
|
/// Removes a software breakpoint at the given PC, if present.
|
|
pub fn remove_breakpoint(&mut self, pc: usize) {
|
|
let _ = self.breakpoints.remove(&pc);
|
|
}
|
|
|
|
/// Returns the list of currently configured breakpoints.
|
|
pub fn breakpoints_list(&self) -> Vec<usize> {
|
|
self.breakpoints.iter().cloned().collect()
|
|
}
|
|
|
|
// Test-only helpers for internal unit tests within this crate.
|
|
#[cfg(test)]
|
|
pub(crate) fn push_operand_for_test(&mut self, v: Value) {
|
|
self.operand_stack.push(v).unwrap();
|
|
}
|
|
/// Creates a new VM instance with the provided bytecode and constants.
|
|
#[cfg(test)]
|
|
pub(crate) fn fault_session(rom: Vec<u8>, constant_pool: Vec<Value>) -> Self {
|
|
Self::fault_session_with_limits(rom, constant_pool, RuntimeLimits::default())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) fn fault_session_with_limits(
|
|
rom: Vec<u8>,
|
|
constant_pool: Vec<Value>,
|
|
limits: RuntimeLimits,
|
|
) -> Self {
|
|
let mut vm = Self::empty(limits);
|
|
vm.program = ProgramImage {
|
|
rom: rom.into(),
|
|
constant_pool: constant_pool.into(),
|
|
..Default::default()
|
|
};
|
|
vm.halted = false;
|
|
vm
|
|
}
|
|
|
|
fn empty(limits: RuntimeLimits) -> Self {
|
|
let budget = RuntimeBudget::new(limits);
|
|
Self {
|
|
pc: 0,
|
|
operand_stack: BudgetVec::new(&budget, RuntimeResource::AuxiliaryBytes),
|
|
call_stack: BudgetVec::new(&budget, RuntimeResource::AuxiliaryBytes),
|
|
globals: BudgetVec::new(&budget, RuntimeResource::AuxiliaryBytes),
|
|
program: ProgramImage::default(),
|
|
validated_image: None,
|
|
strings: None,
|
|
heap: Heap::with_budget(&budget),
|
|
cycles: 0,
|
|
halted: true,
|
|
lifecycle: None,
|
|
memcard_boot_started: false,
|
|
memcard_boot_result: None,
|
|
memcard_boot_required: false,
|
|
lifecycle_failure: None,
|
|
breakpoints: std::collections::HashSet::new(),
|
|
gc_alloc_threshold: 1024, // conservative default; tests may override
|
|
last_gc_live_count: 0,
|
|
capabilities: NONE,
|
|
budget,
|
|
#[cfg(feature = "resource-diagnostics")]
|
|
gc_diagnostics: Default::default(),
|
|
#[cfg(feature = "resource-diagnostics")]
|
|
peak_call_depth: 0,
|
|
}
|
|
}
|
|
|
|
/// Sessions share validated code, constants, debug and Registry ownership.
|
|
/// Entry setup validates supplied groups before publishing an active frame.
|
|
pub fn from_image(
|
|
image: std::sync::Arc<crate::ValidatedProgramImage>,
|
|
limits: RuntimeLimits,
|
|
) -> Self {
|
|
let mut vm = Self::empty(limits);
|
|
vm.program = image.execution.clone();
|
|
vm.capabilities = image.capabilities();
|
|
vm.validated_image = Some(image);
|
|
vm.halted = true;
|
|
vm
|
|
}
|
|
|
|
/// Executes a single instruction at the current Program Counter (PC).
|
|
///
|
|
/// This follows the classic CPU cycle:
|
|
/// 1. Fetch: Read the opcode from memory.
|
|
/// 2. Decode: Identify what operation to perform.
|
|
/// 3. Execute: Perform the operation, updating stacks, memory, or calling peripherals.
|
|
fn step_inner(
|
|
&mut self,
|
|
native: &mut dyn NativeInterface,
|
|
ctx: &mut HostContext,
|
|
) -> Result<(), LogicalFrameEndingReason> {
|
|
if self.halted || self.pc >= self.program.rom.len() {
|
|
return Ok(());
|
|
}
|
|
|
|
let start_pc = self.pc;
|
|
|
|
// Fetch & Decode
|
|
let instr = prometeu_bytecode::decode_next(self.pc, &self.program.rom)
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
|
|
let opcode = instr.opcode;
|
|
self.pc = instr.next_pc;
|
|
|
|
// Call/return and branch attempts pay once before any runtime refusal.
|
|
let charged_control = matches!(
|
|
opcode,
|
|
OpCode::Call | OpCode::Ret | OpCode::Jmp | OpCode::JmpIfTrue | OpCode::JmpIfFalse
|
|
);
|
|
if charged_control {
|
|
self.cycles += opcode.cycles();
|
|
}
|
|
|
|
let charged_math = if opcode == OpCode::Intrinsic {
|
|
lookup_intrinsic_by_id(instr.imm_u32().unwrap()).filter(|m| {
|
|
matches!(m.implementation, crate::IntrinsicImplementation::Host(_))
|
|
&& (m.owner == "vec2" || m.owner == "mathf" || m.owner.starts_with("math."))
|
|
})
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(meta) = charged_math {
|
|
self.cycles += meta.cost_cycles;
|
|
}
|
|
// Execute
|
|
match opcode {
|
|
OpCode::Nop => {}
|
|
OpCode::Halt => {
|
|
self.halted = true;
|
|
}
|
|
OpCode::Jmp => {
|
|
let target = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
|
as usize;
|
|
self.jump_to(target, opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::JmpIfFalse => {
|
|
let target = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
|
as usize;
|
|
let val =
|
|
self.pop_trap(opcode, start_pc as u32, "JMP_IF_FALSE requires one operand")?;
|
|
match val {
|
|
Value::Boolean(false) => {
|
|
self.jump_to(target, opcode, start_pc as u32)?;
|
|
}
|
|
Value::Boolean(true) => {}
|
|
_ => {
|
|
return Err(self.trap(
|
|
TRAP_TYPE,
|
|
opcode as u16,
|
|
format!("Expected boolean for JMP_IF_FALSE, got {:?}", val),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
}
|
|
}
|
|
OpCode::JmpIfTrue => {
|
|
let target = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
|
as usize;
|
|
let val =
|
|
self.pop_trap(opcode, start_pc as u32, "JMP_IF_TRUE requires one operand")?;
|
|
match val {
|
|
Value::Boolean(true) => {
|
|
self.jump_to(target, opcode, start_pc as u32)?;
|
|
}
|
|
Value::Boolean(false) => {}
|
|
_ => {
|
|
return Err(self.trap(
|
|
TRAP_TYPE,
|
|
opcode as u16,
|
|
format!("Expected boolean for JMP_IF_TRUE, got {:?}", val),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
}
|
|
}
|
|
OpCode::Trap => {
|
|
// TRAP is guest-visible ISA, distinct from debugger breakpoints.
|
|
self.cycles += OpCode::Trap.cycles();
|
|
return Err(self.trap(
|
|
TRAP_EXPLICIT,
|
|
opcode as u16,
|
|
"Program requested trap".into(),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
OpCode::Spawn | OpCode::Yield | OpCode::Sleep => {
|
|
return Err(self.trap(
|
|
TRAP_TYPE,
|
|
opcode as u16,
|
|
"Retired coroutine opcode".into(),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
OpCode::Hostcall => {
|
|
return Err(self.trap(
|
|
TRAP_INVALID_SYSCALL,
|
|
opcode as u16,
|
|
"Unpatched HOSTCALL".into(),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
OpCode::MakeClosure | OpCode::CallClosure | OpCode::GetCapture | OpCode::CallTrait => {
|
|
let (first, second) = if matches!(opcode, OpCode::MakeClosure | OpCode::CallTrait) {
|
|
instr.imm_u32x2().unwrap()
|
|
} else {
|
|
(instr.imm_u32().unwrap(), 0)
|
|
};
|
|
return self.execute_callable(opcode, first, second, start_pc as u32);
|
|
}
|
|
OpCode::PushConst => {
|
|
let idx = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
|
as usize;
|
|
let val = self.program.constant_pool.get(idx).cloned().ok_or_else(|| {
|
|
self.trap(
|
|
TRAP_OOB,
|
|
opcode as u16,
|
|
format!("Invalid constant index {}", idx),
|
|
start_pc as u32,
|
|
)
|
|
})?;
|
|
self.push_trap(val, opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::PushI64 => {
|
|
let val = instr
|
|
.imm_i64()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
self.push_trap(Value::Int64(val), opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::PushI32 => {
|
|
let val = instr
|
|
.imm_i32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
self.push_trap(Value::Int32(val), opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::PushF64 => {
|
|
let val = instr
|
|
.imm_f64()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
self.push_trap(Value::Float(val), opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::PushBool => {
|
|
let val = instr
|
|
.imm_u8()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
self.push_trap(Value::Boolean(val != 0), opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::Pop => {
|
|
self.pop_trap(opcode, start_pc as u32, "POP requires one operand")?;
|
|
}
|
|
OpCode::PopN => {
|
|
let n = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
for _ in 0..n {
|
|
self.pop_trap(opcode, start_pc as u32, "POPN operand stack underflow")?;
|
|
}
|
|
}
|
|
OpCode::Dup => {
|
|
let val =
|
|
self.peek_trap(opcode, start_pc as u32, "DUP requires one operand")?.clone();
|
|
self.push_trap(val, opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::Swap => {
|
|
let a = self.pop_trap(opcode, start_pc as u32, "SWAP requires two operands")?;
|
|
let b = self.pop_trap(opcode, start_pc as u32, "SWAP requires two operands")?;
|
|
self.push_trap(a, opcode, start_pc as u32)?;
|
|
self.push_trap(b, opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::Add => {
|
|
let len = self.operand_stack.len();
|
|
if self.temporary_slots() >= 2
|
|
&& (matches!(self.operand_stack[len - 2], Value::String(_))
|
|
|| matches!(self.operand_stack[len - 1], Value::String(_)))
|
|
{
|
|
self.execute_string_add(opcode, start_pc as u32)?;
|
|
} else {
|
|
self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::opcode_binary(opcode, &a, &b).map_err(|e| {
|
|
if e.code == TRAP_TYPE {
|
|
OpError::Trap(
|
|
TRAP_TYPE,
|
|
format!(
|
|
"Invalid types for {}",
|
|
format!("{opcode:?}").to_uppercase()
|
|
),
|
|
)
|
|
} else {
|
|
OpError::from(e)
|
|
}
|
|
})
|
|
})?;
|
|
}
|
|
}
|
|
OpCode::Sub | OpCode::Mul | OpCode::Div => {
|
|
self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::opcode_binary(opcode, &a, &b).map_err(|e| {
|
|
if e.code == TRAP_TYPE {
|
|
OpError::Trap(
|
|
TRAP_TYPE,
|
|
format!(
|
|
"Invalid types for {}",
|
|
format!("{opcode:?}").to_uppercase()
|
|
),
|
|
)
|
|
} else {
|
|
OpError::from(e)
|
|
}
|
|
})
|
|
})?
|
|
}
|
|
OpCode::Mod => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Int32(a), Value::Int32(b)) => {
|
|
if b == 0 {
|
|
return Err(OpError::Trap(TRAP_DIV_ZERO, "Integer modulo by zero".into()));
|
|
}
|
|
Ok(Value::Int32(a.wrapping_rem(b)))
|
|
}
|
|
(Value::Int64(a), Value::Int64(b)) => {
|
|
if b == 0 {
|
|
return Err(OpError::Trap(TRAP_DIV_ZERO, "Integer modulo by zero".into()));
|
|
}
|
|
Ok(Value::Int64(a.wrapping_rem(b)))
|
|
}
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for MOD".into())),
|
|
})?,
|
|
OpCode::Eq => self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::equal_values(&a, &b).map(Value::Boolean).map_err(OpError::from)
|
|
})?,
|
|
OpCode::Neq => self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::equal_values(&a, &b).map(|v| Value::Boolean(!v)).map_err(OpError::from)
|
|
})?,
|
|
OpCode::Lt => self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::compare_values(&a, &b)
|
|
.map_err(OpError::from)?
|
|
.map(|o| Value::Boolean(o == std::cmp::Ordering::Less))
|
|
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for LT".into()))
|
|
})?,
|
|
OpCode::Gt => self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::compare_values(&a, &b)
|
|
.map_err(OpError::from)?
|
|
.map(|o| Value::Boolean(o == std::cmp::Ordering::Greater))
|
|
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for GT".into()))
|
|
})?,
|
|
OpCode::Lte => self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::compare_values(&a, &b)
|
|
.map_err(OpError::from)?
|
|
.map(|o| Value::Boolean(o != std::cmp::Ordering::Greater))
|
|
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for LTE".into()))
|
|
})?,
|
|
OpCode::Gte => self.binary_op(opcode, start_pc as u32, |a, b| {
|
|
numeric::compare_values(&a, &b)
|
|
.map_err(OpError::from)?
|
|
.map(|o| Value::Boolean(o != std::cmp::Ordering::Less))
|
|
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for GTE".into()))
|
|
})?,
|
|
OpCode::And => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Boolean(a), Value::Boolean(b)) => Ok(Value::Boolean(a && b)),
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for AND".into())),
|
|
})?,
|
|
OpCode::Or => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Boolean(a), Value::Boolean(b)) => Ok(Value::Boolean(a || b)),
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for OR".into())),
|
|
})?,
|
|
OpCode::Not => {
|
|
let val = self.pop_trap(opcode, start_pc as u32, "NOT requires one operand")?;
|
|
if let Value::Boolean(b) = val {
|
|
self.push_trap(Value::Boolean(!b), opcode, start_pc as u32)?;
|
|
} else {
|
|
return Err(self.trap(
|
|
TRAP_TYPE,
|
|
opcode as u16,
|
|
"Invalid type for NOT".into(),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
}
|
|
OpCode::BitAnd => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a & b)),
|
|
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a & b)),
|
|
(Value::Int32(a), Value::Int64(b)) => Ok(Value::Int64((a as i64) & b)),
|
|
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a & (b as i64))),
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for BitAnd".into())),
|
|
})?,
|
|
OpCode::BitOr => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a | b)),
|
|
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a | b)),
|
|
(Value::Int32(a), Value::Int64(b)) => Ok(Value::Int64((a as i64) | b)),
|
|
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a | (b as i64))),
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for BitOr".into())),
|
|
})?,
|
|
OpCode::BitXor => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a ^ b)),
|
|
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a ^ b)),
|
|
(Value::Int32(a), Value::Int64(b)) => Ok(Value::Int64((a as i64) ^ b)),
|
|
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a ^ (b as i64))),
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for BitXor".into())),
|
|
})?,
|
|
OpCode::Shl => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_shl(b as u32))),
|
|
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_shl(b as u32))),
|
|
(Value::Int32(a), Value::Int64(b)) => {
|
|
Ok(Value::Int64((a as i64).wrapping_shl(b as u32)))
|
|
}
|
|
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a.wrapping_shl(b as u32))),
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for Shl".into())),
|
|
})?,
|
|
OpCode::Shr => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
|
|
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_shr(b as u32))),
|
|
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_shr(b as u32))),
|
|
(Value::Int32(a), Value::Int64(b)) => {
|
|
Ok(Value::Int64((a as i64).wrapping_shr(b as u32)))
|
|
}
|
|
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a.wrapping_shr(b as u32))),
|
|
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for Shr".into())),
|
|
})?,
|
|
OpCode::Neg => {
|
|
let val = self.pop_trap(opcode, start_pc as u32, "NEG requires one operand")?;
|
|
match val {
|
|
Value::Int32(a) => {
|
|
self.push_trap(Value::Int32(a.wrapping_neg()), opcode, start_pc as u32)?
|
|
}
|
|
Value::Int64(a) => {
|
|
self.push_trap(Value::Int64(a.wrapping_neg()), opcode, start_pc as u32)?
|
|
}
|
|
Value::Float(a) => {
|
|
let result = numeric::neg(a).map_err(|e| {
|
|
self.trap(e.code, opcode as u16, format!("NEG: {e:?}"), start_pc as u32)
|
|
})?;
|
|
self.push_trap(Value::Float(result), opcode, start_pc as u32)?;
|
|
}
|
|
_ => {
|
|
return Err(self.trap(
|
|
TRAP_TYPE,
|
|
opcode as u16,
|
|
"Invalid type for Neg".into(),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
}
|
|
}
|
|
OpCode::GetGlobal => {
|
|
let idx = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
|
as usize;
|
|
if idx >= self.globals.len() {
|
|
self.globals
|
|
.resize(
|
|
idx.checked_add(1).ok_or_else(|| {
|
|
self.resource_trap(
|
|
self.budget.failure(
|
|
RuntimeResource::AuxiliaryBytes,
|
|
crate::resource_budget::ResourceReason::SizeOverflow,
|
|
u64::MAX,
|
|
),
|
|
opcode,
|
|
start_pc as u32,
|
|
)
|
|
})?,
|
|
Value::Int32(0),
|
|
)
|
|
.map_err(|error| self.resource_trap(error, opcode, start_pc as u32))?;
|
|
}
|
|
let val = self.globals[idx].clone();
|
|
self.push_trap(val, opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::SetGlobal => {
|
|
let idx = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
|
as usize;
|
|
let val =
|
|
self.pop_trap(opcode, start_pc as u32, "SET_GLOBAL requires one operand")?;
|
|
if idx >= self.globals.len() {
|
|
self.globals
|
|
.resize(
|
|
idx.checked_add(1).ok_or_else(|| {
|
|
self.resource_trap(
|
|
self.budget.failure(
|
|
RuntimeResource::AuxiliaryBytes,
|
|
crate::resource_budget::ResourceReason::SizeOverflow,
|
|
u64::MAX,
|
|
),
|
|
opcode,
|
|
start_pc as u32,
|
|
)
|
|
})?,
|
|
Value::Int32(0),
|
|
)
|
|
.map_err(|error| self.resource_trap(error, opcode, start_pc as u32))?;
|
|
}
|
|
self.globals[idx] = val;
|
|
}
|
|
OpCode::GetLocal => {
|
|
let slot = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
let frame = self.call_stack.last().ok_or_else(|| {
|
|
LogicalFrameEndingReason::Panic("No active call frame".into())
|
|
})?;
|
|
let func = &self.program.functions[frame.func_idx];
|
|
|
|
crate::local_addressing::check_local_slot(
|
|
func,
|
|
slot,
|
|
opcode as u16,
|
|
start_pc as u32,
|
|
)
|
|
.map_err(|trap_info| {
|
|
self.trap(trap_info.code, trap_info.opcode, trap_info.message, trap_info.pc)
|
|
})?;
|
|
|
|
let stack_idx = crate::local_addressing::local_index(frame, slot);
|
|
let val = self.operand_stack.get(stack_idx).cloned().ok_or_else(|| {
|
|
LogicalFrameEndingReason::Panic(
|
|
"Internal error: validated local slot not found in stack".into(),
|
|
)
|
|
})?;
|
|
self.push_trap(val, opcode, start_pc as u32)?;
|
|
}
|
|
OpCode::SetLocal => {
|
|
let slot = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
let val =
|
|
self.pop_trap(opcode, start_pc as u32, "SET_LOCAL requires one operand")?;
|
|
let frame = self.call_stack.last().ok_or_else(|| {
|
|
LogicalFrameEndingReason::Panic("No active call frame".into())
|
|
})?;
|
|
let func = &self.program.functions[frame.func_idx];
|
|
|
|
crate::local_addressing::check_local_slot(
|
|
func,
|
|
slot,
|
|
opcode as u16,
|
|
start_pc as u32,
|
|
)
|
|
.map_err(|trap_info| {
|
|
self.trap(trap_info.code, trap_info.opcode, trap_info.message, trap_info.pc)
|
|
})?;
|
|
|
|
let stack_idx = crate::local_addressing::local_index(frame, slot);
|
|
self.operand_stack[stack_idx] = val;
|
|
}
|
|
OpCode::Call => {
|
|
self.check_call_depth()
|
|
.map_err(|error| self.resource_trap(error, opcode, start_pc as u32))?;
|
|
let func_id = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
|
as usize;
|
|
let callee = self.program.functions.get(func_id).ok_or_else(|| {
|
|
self.trap(
|
|
TRAP_INVALID_FUNC,
|
|
opcode as u16,
|
|
format!("Invalid func_id {}", func_id),
|
|
start_pc as u32,
|
|
)
|
|
})?;
|
|
|
|
if self.temporary_slots() < callee.param_slots as usize {
|
|
return Err(self.trap(
|
|
TRAP_STACK_UNDERFLOW,
|
|
opcode as u16,
|
|
format!(
|
|
"Stack underflow during CALL to func {}: expected at least {} arguments, got {}",
|
|
func_id,
|
|
callee.param_slots,
|
|
self.operand_stack.len()
|
|
),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
|
|
let stack_base = self.operand_stack.len() - callee.param_slots as usize;
|
|
|
|
self.check_signature_group(func_id, false, &self.operand_stack[stack_base..])
|
|
.map_err(|(_, error)| self.value_trap(error, opcode, start_pc as u32))?;
|
|
|
|
let callee_local_slots = callee.local_slots;
|
|
let callee_offset = callee.code_offset;
|
|
let stack_growth = self
|
|
.operand_stack
|
|
.prepare_growth(callee_local_slots as usize)
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
let frame_growth = self
|
|
.call_stack
|
|
.prepare_growth(1)
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
self.operand_stack.commit_growth(stack_growth);
|
|
self.call_stack.commit_growth(frame_growth);
|
|
// Allocate and zero-init local_slots
|
|
for _ in 0..callee_local_slots {
|
|
self.operand_stack
|
|
.push(Value::Null)
|
|
.map_err(|error| self.resource_trap(error, opcode, start_pc as u32))?;
|
|
}
|
|
|
|
self.call_stack
|
|
.push(CallFrame {
|
|
return_pc: self.pc as u32,
|
|
stack_base,
|
|
func_idx: func_id,
|
|
closure: None,
|
|
})
|
|
.map_err(|error| self.resource_trap(error, opcode, start_pc as u32))?;
|
|
self.pc = callee_offset as usize;
|
|
}
|
|
OpCode::Ret => self.finish_return(opcode, start_pc as u32)?,
|
|
OpCode::Syscall => {
|
|
let pc_at_syscall = start_pc as u32;
|
|
let id = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
let syscall = prometeu_hal::syscalls::Syscall::from_u32(id).ok_or_else(|| {
|
|
self.trap(
|
|
TRAP_INVALID_SYSCALL,
|
|
OpCode::Syscall as u16,
|
|
format!("Unknown syscall: 0x{:08X}", id),
|
|
pc_at_syscall,
|
|
)
|
|
})?;
|
|
|
|
// Capability check before any side effects or argument consumption.
|
|
let meta = prometeu_hal::syscalls::meta_for(syscall);
|
|
if (self.capabilities & meta.caps) != meta.caps {
|
|
return Err(self.trap(
|
|
TRAP_INVALID_SYSCALL,
|
|
OpCode::Syscall as u16,
|
|
format!(
|
|
"Missing capability for syscall {} (required=0x{:X})",
|
|
syscall.name(),
|
|
meta.caps
|
|
),
|
|
pc_at_syscall,
|
|
));
|
|
}
|
|
|
|
let args_count = syscall.args_count();
|
|
|
|
let mut args = BudgetVec::new(&self.budget, RuntimeResource::TemporaryBytes);
|
|
args.reserve(args_count)
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
for _ in 0..args_count {
|
|
let v = self.pop().map_err(|_e| {
|
|
self.trap(
|
|
TRAP_STACK_UNDERFLOW,
|
|
OpCode::Syscall as u16,
|
|
"Syscall argument stack underflow".to_string(),
|
|
pc_at_syscall,
|
|
)
|
|
})?;
|
|
args.push(v).map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
}
|
|
args.reverse();
|
|
|
|
let stack_height_before = self.operand_stack.len();
|
|
self.operand_stack
|
|
.reserve(syscall.results_count())
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
let mut arrays = native_arrays::SessionArrays {
|
|
heap: &mut self.heap,
|
|
registry: self.validated_image.as_ref().map(|image| image.registry().as_ref()),
|
|
work: 0,
|
|
};
|
|
let mut strings = strings::SessionStringAllocator {
|
|
ledger: &mut self.strings,
|
|
budget: self.budget.clone(),
|
|
};
|
|
let mut ret = crate::HostReturn::new(
|
|
self.operand_stack.native_result_buffer(),
|
|
syscall.results_count(),
|
|
&mut strings,
|
|
)
|
|
.with_arrays(&mut arrays);
|
|
let native_result = native.syscall(id, &args, &mut ret, ctx);
|
|
let return_overflow = ret.overflowed();
|
|
let return_failure = ret.failure().cloned();
|
|
self.cycles += arrays.work;
|
|
let native_result = return_failure.map(Err).unwrap_or(native_result);
|
|
if native_result.is_err() {
|
|
self.operand_stack.truncate(stack_height_before);
|
|
}
|
|
native_result.map_err(|fault| match fault {
|
|
VmFault::ResourceLimit(resource) => {
|
|
self.resource_trap(resource, opcode, pc_at_syscall)
|
|
}
|
|
VmFault::Trap(code, msg) => {
|
|
self.trap(code, OpCode::Syscall as u16, msg, pc_at_syscall)
|
|
}
|
|
VmFault::Panic(msg) => LogicalFrameEndingReason::Panic(msg),
|
|
VmFault::Unavailable => {
|
|
LogicalFrameEndingReason::Panic("Host feature unavailable".into())
|
|
}
|
|
})?;
|
|
|
|
let stack_height_after = self.operand_stack.len();
|
|
let results_pushed = stack_height_after - stack_height_before;
|
|
if return_overflow || results_pushed != syscall.results_count() {
|
|
return Err(LogicalFrameEndingReason::Panic(format!(
|
|
"Syscall {} (0x{:08X}) results mismatch: expected {}, got {} (overflow={})",
|
|
syscall.name(),
|
|
id,
|
|
syscall.results_count(),
|
|
results_pushed,
|
|
return_overflow
|
|
)));
|
|
}
|
|
if syscall == prometeu_hal::syscalls::Syscall::MemBootstrap {
|
|
let context = self.pop_integer().map_err(LogicalFrameEndingReason::Panic)?;
|
|
if !self.begin_memcard_boot(context).map_err(|e| {
|
|
LogicalFrameEndingReason::Panic(format!("Invalid memcard bootstrap: {e:?}"))
|
|
})? {
|
|
return Err(LogicalFrameEndingReason::Panic(
|
|
"Missing memcard boot binding".into(),
|
|
));
|
|
}
|
|
}
|
|
}
|
|
OpCode::Intrinsic => {
|
|
let pc_at_intrinsic = start_pc as u32;
|
|
let id = instr
|
|
.imm_u32()
|
|
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
|
let intrinsic = lookup_intrinsic_by_id(id).ok_or_else(|| {
|
|
self.trap(
|
|
TRAP_INVALID_INTRINSIC,
|
|
OpCode::Intrinsic as u16,
|
|
format!("Unknown intrinsic: 0x{:08X}", id),
|
|
pc_at_intrinsic,
|
|
)
|
|
})?;
|
|
|
|
if matches!(
|
|
intrinsic.implementation,
|
|
crate::IntrinsicImplementation::BorrowedInline(_)
|
|
) {
|
|
return self.execute_inline_intrinsic(intrinsic, pc_at_intrinsic);
|
|
}
|
|
if matches!(intrinsic.implementation, crate::IntrinsicImplementation::VmOwned) {
|
|
return self.execute_random(intrinsic, pc_at_intrinsic);
|
|
}
|
|
|
|
let args_count = intrinsic.arg_slots();
|
|
let mut args = BudgetVec::new(&self.budget, RuntimeResource::TemporaryBytes);
|
|
args.reserve(args_count)
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
for _ in 0..args_count {
|
|
let value = self.pop().map_err(|_e| {
|
|
self.trap(
|
|
TRAP_STACK_UNDERFLOW,
|
|
OpCode::Intrinsic as u16,
|
|
"Intrinsic argument stack underflow".to_string(),
|
|
pc_at_intrinsic,
|
|
)
|
|
})?;
|
|
args.push(value).map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
}
|
|
args.reverse();
|
|
|
|
let _result_storage = self
|
|
.budget
|
|
.reserve(
|
|
RuntimeResource::TemporaryBytes,
|
|
self.budget
|
|
.bytes::<Value>(intrinsic.ret_slots(), RuntimeResource::TemporaryBytes)
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?,
|
|
)
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
self.operand_stack
|
|
.reserve(intrinsic.ret_slots())
|
|
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
|
let results = intrinsic
|
|
.validate_argument_values(&args)
|
|
.and_then(|()| {
|
|
(intrinsic.implementation.host_callback().expect("host intrinsic"))(
|
|
&args, ctx,
|
|
)
|
|
})
|
|
.map_err(|err| match err {
|
|
crate::IntrinsicExecutionError::ArityMismatch { expected, got } => self
|
|
.trap(
|
|
TRAP_INVALID_INTRINSIC,
|
|
OpCode::Intrinsic as u16,
|
|
format!(
|
|
"Intrinsic {}.{} argument mismatch: expected {}, got {}",
|
|
intrinsic.owner, intrinsic.name, expected, got
|
|
),
|
|
pc_at_intrinsic,
|
|
),
|
|
crate::IntrinsicExecutionError::TypeMismatch { index, expected } => self
|
|
.trap(
|
|
TRAP_TYPE,
|
|
OpCode::Intrinsic as u16,
|
|
format!(
|
|
"Intrinsic {}.{} argument {} type mismatch: expected {:?}",
|
|
intrinsic.owner, intrinsic.name, index, expected
|
|
),
|
|
pc_at_intrinsic,
|
|
),
|
|
crate::IntrinsicExecutionError::Numeric(error) => self.trap(
|
|
error.code,
|
|
opcode as u16,
|
|
format!(
|
|
"Intrinsic {}.{}: {:?}",
|
|
intrinsic.owner, intrinsic.name, error
|
|
),
|
|
pc_at_intrinsic,
|
|
),
|
|
crate::IntrinsicExecutionError::HardwareUnavailable => self.trap(
|
|
TRAP_UNAVAILABLE,
|
|
OpCode::Intrinsic as u16,
|
|
format!(
|
|
"Input query {}.{} unavailable",
|
|
intrinsic.owner, intrinsic.name
|
|
),
|
|
pc_at_intrinsic,
|
|
),
|
|
})?;
|
|
|
|
intrinsic.validate_result_values(&results).map_err(|err| match err {
|
|
crate::IntrinsicExecutionError::ArityMismatch { expected, got } => self.trap(
|
|
TRAP_INVALID_INTRINSIC,
|
|
OpCode::Intrinsic as u16,
|
|
format!(
|
|
"Intrinsic {}.{} results mismatch: expected {}, got {}",
|
|
intrinsic.owner, intrinsic.name, expected, got
|
|
),
|
|
pc_at_intrinsic,
|
|
),
|
|
crate::IntrinsicExecutionError::TypeMismatch { index, expected } => self.trap(
|
|
TRAP_INVALID_INTRINSIC,
|
|
OpCode::Intrinsic as u16,
|
|
format!(
|
|
"Intrinsic {}.{} result {} type mismatch: expected {:?}",
|
|
intrinsic.owner, intrinsic.name, index, expected
|
|
),
|
|
pc_at_intrinsic,
|
|
),
|
|
crate::IntrinsicExecutionError::Numeric(error) => self.trap(
|
|
error.code,
|
|
opcode as u16,
|
|
format!(
|
|
"Intrinsic {}.{} result: {:?}",
|
|
intrinsic.owner, intrinsic.name, error
|
|
),
|
|
pc_at_intrinsic,
|
|
),
|
|
crate::IntrinsicExecutionError::HardwareUnavailable => self.trap(
|
|
TRAP_UNAVAILABLE,
|
|
OpCode::Intrinsic as u16,
|
|
format!("Input query {}.{} unavailable", intrinsic.owner, intrinsic.name),
|
|
pc_at_intrinsic,
|
|
),
|
|
})?;
|
|
|
|
for value in results {
|
|
self.push_trap(value, opcode, start_pc as u32)?;
|
|
}
|
|
}
|
|
OpCode::DynPack | OpCode::DynUnpack | OpCode::DynCanUnpack => {
|
|
self.cycles += opcode.cycles();
|
|
let target = instr.imm_u32().unwrap();
|
|
return self.execute_dynamic(opcode, target, start_pc as u32);
|
|
}
|
|
OpCode::RefIsExact | OpCode::RefImplements | OpCode::RefToTrait | OpCode::RefCast => {
|
|
self.cycles += opcode.cycles();
|
|
let (source, target) = instr.imm_u32x2().unwrap();
|
|
return self.execute_reference(opcode, source, target, start_pc as u32);
|
|
}
|
|
OpCode::RefIdentityHash | OpCode::RefIdentityEq => {
|
|
let (left, right) = if opcode == OpCode::RefIdentityHash {
|
|
(instr.imm_u32().unwrap(), None)
|
|
} else {
|
|
let (left, right) = instr.imm_u32x2().unwrap();
|
|
(left, Some(right))
|
|
};
|
|
return self.execute_identity(opcode, left, right, start_pc as u32);
|
|
}
|
|
OpCode::ArrayCopy => {
|
|
return self.execute_array_copy(instr.imm_u32().unwrap(), 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 => {
|
|
if self.memcard_boot_required && self.memcard_boot_result != Some(0) {
|
|
return Err(LogicalFrameEndingReason::Panic(
|
|
"Frame entered before memcard bootstrap admission".into(),
|
|
));
|
|
}
|
|
if self.lifecycle.is_some() {
|
|
return Err(self.trap(
|
|
TRAP_TYPE,
|
|
opcode as u16,
|
|
"FRAME_SYNC is forbidden in lifecycle hooks".into(),
|
|
start_pc as u32,
|
|
));
|
|
}
|
|
// Marks the logical end of a frame: consume cycles and signal to the driver
|
|
self.cycles += OpCode::FrameSync.cycles();
|
|
self.handle_safepoint()
|
|
.map_err(|error| self.resource_trap(error, opcode, start_pc as u32))?;
|
|
return Err(LogicalFrameEndingReason::FrameSync);
|
|
}
|
|
}
|
|
|
|
// Control attempts were already charged before validation.
|
|
if !charged_control && charged_math.is_none() {
|
|
self.cycles += opcode.cycles();
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::sync::Arc;
|
|
|
|
fn fault_cache(
|
|
rom: Vec<u8>,
|
|
constant_pool: Vec<Value>,
|
|
functions: Vec<ExecutionFunction>,
|
|
debug_info: Option<prometeu_bytecode::model::DebugInfo>,
|
|
exports: std::collections::HashMap<String, u32>,
|
|
) -> ProgramImage {
|
|
ProgramImage {
|
|
rom: rom.into(),
|
|
constant_pool: constant_pool.into(),
|
|
functions: functions.into(),
|
|
debug_info: debug_info.map(Arc::new),
|
|
exports: Arc::new(exports),
|
|
}
|
|
}
|
|
fn entry_auxiliary_bytes() -> u64 {
|
|
(size_of::<CallFrame>()) as u64
|
|
}
|
|
|
|
fn scalar_signature(p: usize, r: usize, result: u32) -> prometeu_bytecode::registry::Signature {
|
|
use prometeu_bytecode::registry::*;
|
|
Signature {
|
|
parameters: vec![NamedType { type_id: TypeId(1), name: None }; p],
|
|
results: vec![TypeId(result); r],
|
|
}
|
|
}
|
|
fn typed_test_vm(
|
|
mut code: Vec<u8>,
|
|
constants: Vec<Value>,
|
|
mut functions: Vec<FunctionDecl>,
|
|
) -> VirtualMachine {
|
|
// Test producer emits final syscall identities as canonical HOSTCALL declarations.
|
|
let mut syscalls = vec![];
|
|
let mut at = 0;
|
|
while at < code.len() {
|
|
let instruction = prometeu_bytecode::decode_next(at, &code).unwrap();
|
|
let next_pc = instruction.next_pc;
|
|
if instruction.opcode == OpCode::Syscall {
|
|
let syscall =
|
|
prometeu_hal::syscalls::Syscall::from_u32(instruction.imm_u32().unwrap())
|
|
.unwrap();
|
|
let meta = prometeu_hal::syscalls::meta_for(syscall);
|
|
let index = syscalls.len() as u32;
|
|
syscalls.push(SyscallDecl {
|
|
module: meta.module.into(),
|
|
name: meta.name.into(),
|
|
version: meta.version,
|
|
arg_slots: meta.arg_slots as u16,
|
|
ret_slots: meta.ret_slots,
|
|
});
|
|
code[at..at + 2].copy_from_slice(&(OpCode::Hostcall as u16).to_le_bytes());
|
|
code[at + 2..at + 6].copy_from_slice(&index.to_le_bytes());
|
|
}
|
|
at = next_pc;
|
|
}
|
|
let end = code.len() as u32;
|
|
for i in 0..functions.len() {
|
|
functions[i].code_len =
|
|
functions.get(i + 1).map_or(end, |f| f.code_offset) - functions[i].code_offset;
|
|
}
|
|
let const_pool = constants
|
|
.into_iter()
|
|
.map(|v| match v {
|
|
Value::Null => prometeu_bytecode::model::ConstantPoolEntry::Null,
|
|
Value::Int32(n) => prometeu_bytecode::model::ConstantPoolEntry::Int32(n),
|
|
Value::Int64(n) => prometeu_bytecode::model::ConstantPoolEntry::Int64(n),
|
|
Value::Float(n) => prometeu_bytecode::model::ConstantPoolEntry::Float64(n),
|
|
Value::Boolean(n) => prometeu_bytecode::model::ConstantPoolEntry::Boolean(n),
|
|
Value::String(n) => {
|
|
prometeu_bytecode::model::ConstantPoolEntry::String(n.to_string())
|
|
}
|
|
_ => panic!("non-constant fixture"),
|
|
})
|
|
.collect();
|
|
let bytes =
|
|
TestProgram { code, functions, const_pool, syscalls, ..Default::default() }.serialize();
|
|
let image = crate::ValidatedProgramImage::load(
|
|
&bytes,
|
|
&mut prometeu_bytecode::load_limits::LoadBudget::new(Default::default()),
|
|
prometeu_hal::syscalls::caps::ALL,
|
|
)
|
|
.unwrap();
|
|
let mut vm = VirtualMachine::from_image(image, RuntimeLimits::default());
|
|
vm.prepare_boot_call().unwrap();
|
|
vm
|
|
}
|
|
fn new_test_vm(mut code: Vec<u8>, constant_pool: Vec<Value>) -> VirtualMachine {
|
|
// Explicit scalar fixture entry; append HALT to instruction fragments.
|
|
code.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
typed_test_vm(
|
|
code,
|
|
constant_pool,
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
max_stack_slots: 256,
|
|
..Default::default()
|
|
}],
|
|
)
|
|
}
|
|
fn limited_session(code: Vec<u8>, limits: RuntimeLimits) -> VirtualMachine {
|
|
let v = new_test_vm(code, vec![]);
|
|
VirtualMachine::from_image(v.validated_image.unwrap(), limits)
|
|
}
|
|
fn fault_vm(rom: Vec<u8>, constant_pool: Vec<Value>) -> VirtualMachine {
|
|
let rom_len = rom.len() as u32;
|
|
let mut vm = VirtualMachine::fault_session(rom, constant_pool);
|
|
vm.program.functions = std::sync::Arc::from(vec![prometeu_bytecode::ExecutionFunction {
|
|
code_offset: 0,
|
|
code_len: rom_len,
|
|
..Default::default()
|
|
}]);
|
|
// Ensure tests start with a properly initialized entry context at func 0
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
vm
|
|
}
|
|
use crate::HostReturn;
|
|
use prometeu_bytecode::model::SyscallDecl;
|
|
use prometeu_bytecode::{
|
|
ExecutionFunction, TRAP_EXPLICIT, TRAP_INVALID_LOCAL, TRAP_OOB, TRAP_STACK_UNDERFLOW,
|
|
TRAP_TYPE, assemble, disassemble,
|
|
};
|
|
use prometeu_hal::expect_int;
|
|
|
|
struct MockNative;
|
|
impl NativeInterface for MockNative {
|
|
fn syscall(
|
|
&mut self,
|
|
_id: u32,
|
|
_args: &[Value],
|
|
_ret: &mut HostReturn,
|
|
_ctx: &mut HostContext,
|
|
) -> Result<(), VmFault> {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn serialized_single_function_module(code: Vec<u8>, syscalls: Vec<SyscallDecl>) -> Vec<u8> {
|
|
TestProgram {
|
|
const_pool: vec![],
|
|
functions: vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
code_len: code.len() as u32,
|
|
|
|
signature: int64_signature(0, 0),
|
|
captures: vec![],
|
|
name: None,
|
|
local_slots: 0,
|
|
max_stack_slots: 256,
|
|
}],
|
|
code,
|
|
debug_info: None,
|
|
exports: vec![],
|
|
syscalls,
|
|
}
|
|
.serialize()
|
|
}
|
|
|
|
fn serialized_single_hostcall_module(syscall: SyscallDecl) -> Vec<u8> {
|
|
let mut source = String::new();
|
|
for _ in 0..syscall.arg_slots {
|
|
source.push_str("PUSH_I32 0\n");
|
|
}
|
|
source.push_str("HOSTCALL 0\nHALT");
|
|
let code = assemble(&source).expect("assemble");
|
|
serialized_single_function_module(code, vec![syscall])
|
|
}
|
|
|
|
#[test]
|
|
fn test_deterministic_pc_and_tick_trace_across_runs() {
|
|
// Program:
|
|
// PUSH_I32 1; YIELD; FrameSync;
|
|
// PUSH_I32 2; YIELD; FrameSync;
|
|
// PUSH_I32 3; FrameSync; HALT
|
|
// We collect (pc, tick, stack_height) after each run_budget slice and
|
|
// compare two independent VMs initialized from the same ROM.
|
|
let mut rom = Vec::new();
|
|
// PUSH 1
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1i32.to_le_bytes());
|
|
// YIELD + FrameSync
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
// PUSH 2
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&2i32.to_le_bytes());
|
|
// YIELD + FrameSync
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
// PUSH 3 + FrameSync + HALT
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&3i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm1 = new_test_vm(rom.clone(), vec![]);
|
|
let mut vm2 = new_test_vm(rom.clone(), vec![]);
|
|
|
|
let mut native = MockNative;
|
|
let mut ctx1 = HostContext::new(None);
|
|
let mut ctx2 = HostContext::new(None);
|
|
|
|
let mut trace1 = Vec::new();
|
|
let mut trace2 = Vec::new();
|
|
|
|
// Run both VMs in lockstep slices until both halt
|
|
for _ in 0..10 {
|
|
if !vm1.halted {
|
|
let rep = vm1.run_budget(4, &mut native, &mut ctx1).expect("vm1 ok");
|
|
trace1.push((
|
|
vm1.pc,
|
|
vm1.cycles,
|
|
vm1.operand_stack.len(),
|
|
format!("{:?}", rep.reason),
|
|
));
|
|
}
|
|
if !vm2.halted {
|
|
let rep = vm2.run_budget(4, &mut native, &mut ctx2).expect("vm2 ok");
|
|
trace2.push((
|
|
vm2.pc,
|
|
vm2.cycles,
|
|
vm2.operand_stack.len(),
|
|
format!("{:?}", rep.reason),
|
|
));
|
|
}
|
|
if vm1.halted && vm2.halted {
|
|
break;
|
|
}
|
|
}
|
|
|
|
assert!(vm1.halted && vm2.halted, "Both VMs should reach HALT deterministically");
|
|
assert_eq!(trace1, trace2, "Per-slice traces must be identical across runs");
|
|
// Also verify final stack content deterministic
|
|
assert_eq!(vm1.pop().unwrap(), Value::Int32(3));
|
|
assert_eq!(vm1.pop().unwrap(), Value::Int32(2));
|
|
assert_eq!(vm1.pop().unwrap(), Value::Int32(1));
|
|
assert!(vm1.operand_stack.is_empty());
|
|
assert_eq!(vm2.pop().unwrap(), Value::Int32(3));
|
|
assert_eq!(vm2.pop().unwrap(), Value::Int32(2));
|
|
assert_eq!(vm2.pop().unwrap(), Value::Int32(1));
|
|
assert!(vm2.operand_stack.is_empty());
|
|
}
|
|
|
|
// fn test_arithmetic_chain() {
|
|
// let mut native = MockNative;
|
|
// let mut ctx = HostContext::new(None);
|
|
//
|
|
// // (10 + 20) * 2 / 5 % 4 = 12 * 2 / 5 % 4 = 60 / 5 % 4 = 12 % 4 = 0
|
|
// // wait: (10 + 20) = 30. 30 * 2 = 60. 60 / 5 = 12. 12 % 4 = 0.
|
|
// let mut rom = Vec::new();
|
|
// rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&10i32.to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&20i32.to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::Add as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&2i32.to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::Mul as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&5i32.to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::Div as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&4i32.to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::Mod as u16).to_le_bytes());
|
|
// rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
//
|
|
// let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
// vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
//
|
|
// assert_eq!(vm.pop().unwrap(), Value::Int32(0));
|
|
// }
|
|
|
|
#[test]
|
|
fn test_div_by_zero_trap() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&10i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Div as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_DIV_ZERO);
|
|
assert_eq!(trap.opcode, OpCode::Div as u16);
|
|
}
|
|
_ => panic!("Expected Trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_comparisons_polymorphic() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// 10 < 20.5 (true)
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&10i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushF64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&20.5f64.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Lt as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.pop().unwrap(), Value::Boolean(true));
|
|
}
|
|
|
|
#[test]
|
|
fn test_push_i64_immediate() {
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i64.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.peek().unwrap(), &Value::Int64(42));
|
|
}
|
|
|
|
#[test]
|
|
fn test_push_f64_immediate() {
|
|
let value = 3.125f64;
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushF64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&value.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.peek().unwrap(), &Value::Float(value));
|
|
}
|
|
|
|
#[test]
|
|
fn test_push_bool_immediate() {
|
|
let mut rom = Vec::new();
|
|
// True
|
|
rom.extend_from_slice(&(OpCode::PushBool as u16).to_le_bytes());
|
|
rom.push(1);
|
|
// False
|
|
rom.extend_from_slice(&(OpCode::PushBool as u16).to_le_bytes());
|
|
rom.push(0);
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.step(&mut native, &mut ctx).unwrap(); // Push true
|
|
assert_eq!(vm.peek().unwrap(), &Value::Boolean(true));
|
|
vm.step(&mut native, &mut ctx).unwrap(); // Push false
|
|
assert_eq!(vm.peek().unwrap(), &Value::Boolean(false));
|
|
}
|
|
|
|
#[test]
|
|
fn test_push_const_string() {
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushConst as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let cp = vec![Value::String("hello".into())];
|
|
let mut vm = new_test_vm(rom, cp);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.peek().unwrap(), &Value::String("hello".into()));
|
|
}
|
|
|
|
#[test]
|
|
fn test_shared_string_clone_reuses_materialized_payload() {
|
|
let mut vm = VirtualMachine::default();
|
|
let payload: Arc<str> = "shared-global".into();
|
|
vm.globals.push(Value::String(payload.clone())).unwrap();
|
|
|
|
let cloned = vm.globals[0].clone();
|
|
match cloned {
|
|
Value::String(cloned_payload) => assert!(Arc::ptr_eq(&payload, &cloned_payload)),
|
|
other => panic!("expected string clone from globals, got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_push_const_invalid_index_traps_oob() {
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushConst as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_OOB);
|
|
assert_eq!(trap.opcode, OpCode::PushConst as u16);
|
|
assert!(trap.message.contains("Invalid constant index"));
|
|
}
|
|
other => panic!("Expected Trap(OOB), got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_call_ret_scope_separation() {
|
|
let mut rom = Vec::new();
|
|
|
|
// entrypoint:
|
|
// PUSH_I64 10
|
|
// CALL func_id 1
|
|
// HALT
|
|
rom.extend_from_slice(&(OpCode::PushI64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&10i64.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes()); // func_id 1
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let func_addr = rom.len();
|
|
|
|
// func:
|
|
// PUSH_I64 20
|
|
// GET_LOCAL 0 -- should be 10 (arg)
|
|
// ADD -- 10 + 20 = 30
|
|
// SET_LOCAL 0 -- store result in local 0 (the arg slot)
|
|
// GET_LOCAL 0 -- read 30 back
|
|
// RET
|
|
rom.extend_from_slice(&(OpCode::PushI64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&20i64.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::GetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Add as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::SetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::GetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom,
|
|
vec![],
|
|
vec![
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
max_stack_slots: 256,
|
|
..Default::default()
|
|
},
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: func_addr as u32,
|
|
signature: int64_signature(1, 1),
|
|
max_stack_slots: 256,
|
|
..Default::default()
|
|
},
|
|
],
|
|
);
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// Run until Halt
|
|
let mut steps = 0;
|
|
while !vm.halted && steps < 100 {
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
steps += 1;
|
|
}
|
|
|
|
assert!(vm.halted);
|
|
assert_eq!(vm.pop_integer().unwrap(), 30);
|
|
assert_eq!(vm.operand_stack.len(), 0);
|
|
assert_eq!(vm.call_stack.len(), 1);
|
|
// Scope frames removed: no scope stack to assert on
|
|
}
|
|
|
|
#[test]
|
|
fn test_ret_mandatory_value() {
|
|
let mut rom = Vec::new();
|
|
// entrypoint: CALL func_id 1; HALT
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes()); // func_id 1
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let func_addr = rom.len();
|
|
// func: RET (SEM VALOR ANTES)
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let functions = vec![
|
|
ExecutionFunction { code_offset: 0, code_len: func_addr as u32, ..Default::default() },
|
|
ExecutionFunction {
|
|
code_offset: func_addr as u32,
|
|
code_len: (rom.len() - func_addr) as u32,
|
|
param_slots: 0,
|
|
return_slots: 1,
|
|
..Default::default()
|
|
},
|
|
];
|
|
|
|
let mut vm = VirtualMachine {
|
|
program: fault_cache(rom, vec![], functions, None, std::collections::HashMap::new()),
|
|
..Default::default()
|
|
};
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.step(&mut native, &mut ctx).unwrap(); // CALL
|
|
let res = vm.step(&mut native, &mut ctx); // RET -> should fail
|
|
assert!(res.is_err());
|
|
match res.unwrap_err() {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_BAD_RET_SLOTS);
|
|
}
|
|
_ => panic!("Expected Trap(TRAP_BAD_RET_SLOTS)"),
|
|
}
|
|
|
|
// Agora com valor de retorno
|
|
let mut rom2 = Vec::new();
|
|
rom2.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom2.extend_from_slice(&1u32.to_le_bytes());
|
|
rom2.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
let func_addr2 = rom2.len();
|
|
rom2.extend_from_slice(&(OpCode::PushI64 as u16).to_le_bytes());
|
|
rom2.extend_from_slice(&123i64.to_le_bytes());
|
|
rom2.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let mut vm2 = typed_test_vm(
|
|
rom2,
|
|
vec![],
|
|
vec![
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
max_stack_slots: 256,
|
|
..Default::default()
|
|
},
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: func_addr2 as u32,
|
|
signature: int64_signature(0, 1),
|
|
max_stack_slots: 256,
|
|
..Default::default()
|
|
},
|
|
],
|
|
);
|
|
vm2.prepare_call("0").expect("prepare entry call");
|
|
vm2.step(&mut native, &mut ctx).unwrap(); // CALL
|
|
vm2.step(&mut native, &mut ctx).unwrap(); // PUSH_I64
|
|
vm2.step(&mut native, &mut ctx).unwrap(); // RET
|
|
|
|
assert_eq!(vm2.operand_stack.len(), 1);
|
|
assert_eq!(vm2.pop().unwrap(), Value::Int64(123));
|
|
}
|
|
|
|
// Scope tests removed under PR-2.1 (scope frames eliminated)
|
|
|
|
#[test]
|
|
fn test_push_i32() {
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.peek().unwrap(), &Value::Int32(42));
|
|
}
|
|
|
|
#[test]
|
|
fn test_bitwise_promotion() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// i32 & i32 -> i32
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0xF0i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0x0Fi32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::BitAnd as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.pop().unwrap(), Value::Int32(0));
|
|
|
|
// i32 | i64 -> i64
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0xF0i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0x0Fi64.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::BitOr as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.pop().unwrap(), Value::Int64(0xFF));
|
|
}
|
|
|
|
#[test]
|
|
fn test_comparisons_lte_gte() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// 10 <= 20 (true)
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&10i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&20i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Lte as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.pop().unwrap(), Value::Boolean(true));
|
|
|
|
// 20 >= 20 (true)
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&20i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&20i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Gte as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.pop().unwrap(), Value::Boolean(true));
|
|
}
|
|
|
|
#[test]
|
|
fn test_negation() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Neg as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.pop().unwrap(), Value::Int32(-42));
|
|
}
|
|
|
|
#[test]
|
|
fn test_jmp_if_true() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// Corrected Calculations:
|
|
// 0-1: PushBool
|
|
// 2: 1 (u8)
|
|
// 3-4: JmpIfTrue
|
|
// 5-8: addr (u32)
|
|
// 9-10: Halt (Offset 9)
|
|
// 11-12: PushI32 (Offset 11)
|
|
// 13-16: 100 (i32)
|
|
// 17-18: Halt
|
|
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushBool as u16).to_le_bytes());
|
|
rom.push(1);
|
|
rom.extend_from_slice(&(OpCode::JmpIfTrue as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(11u32).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes()); // Offset 9
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes()); // Offset 11
|
|
rom.extend_from_slice(&100i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.step(&mut native, &mut ctx).unwrap(); // PushBool
|
|
vm.step(&mut native, &mut ctx).unwrap(); // JmpIfTrue
|
|
assert_eq!(vm.pc, 11);
|
|
vm.step(&mut native, &mut ctx).unwrap(); // PushI32
|
|
assert_eq!(vm.pop().unwrap(), Value::Int32(100));
|
|
}
|
|
|
|
#[test]
|
|
fn test_trap_opcode() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Trap as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_EXPLICIT);
|
|
assert_eq!(trap.opcode, OpCode::Trap as u16);
|
|
assert_eq!(trap.pc, 6);
|
|
assert!(trap.message.contains("Program requested trap"));
|
|
}
|
|
other => panic!("Expected Trap(TRAP_EXPLICIT), got {:?}", other),
|
|
}
|
|
assert_eq!(vm.pc, 8); // PushI32 (6 bytes) + Trap (2 bytes)
|
|
assert_eq!(vm.peek().unwrap(), &Value::Int32(42));
|
|
}
|
|
|
|
#[test]
|
|
fn test_debugger_breakpoint_remains_distinct_from_trap_opcode() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Trap as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom, vec![]);
|
|
vm.insert_breakpoint(6);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::Breakpoint);
|
|
assert_eq!(vm.pc, 6);
|
|
assert_eq!(vm.peek().unwrap(), &Value::Int32(42));
|
|
}
|
|
|
|
#[test]
|
|
fn test_pop_n_opcode() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&2i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&3i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PopN as u16).to_le_bytes());
|
|
rom.extend_from_slice(&2u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
assert_eq!(vm.pop().unwrap(), Value::Int32(1));
|
|
assert!(vm.pop().is_err()); // Stack should be empty
|
|
}
|
|
|
|
#[test]
|
|
fn test_entry_point_ret_with_prepare_call() {
|
|
// PushI32 0 (0x17), then Ret (0x51)
|
|
let rom = vec![
|
|
0x17, 0x00, // PushI32
|
|
0x00, 0x00, 0x00, 0x00, // value 0
|
|
0x11, 0x00, // Pop
|
|
0x51, 0x00, // Ret
|
|
];
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
}],
|
|
);
|
|
|
|
let mut ctx = HostContext::new(None);
|
|
struct TestNative;
|
|
impl NativeInterface for TestNative {
|
|
fn syscall(
|
|
&mut self,
|
|
_id: u32,
|
|
_args: &[Value],
|
|
_ret: &mut HostReturn,
|
|
_ctx: &mut HostContext,
|
|
) -> Result<(), VmFault> {
|
|
Ok(())
|
|
}
|
|
}
|
|
let mut native = TestNative;
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let result = vm.run_budget(100, &mut native, &mut ctx).expect("VM run failed");
|
|
assert_eq!(result.reason, LogicalFrameEndingReason::EndOfRom);
|
|
}
|
|
|
|
#[test]
|
|
fn test_syscall_abi_multi_slot_return() {
|
|
let rom = vec![
|
|
0x70, 0x00, // Syscall + Reserved
|
|
0x01, 0x00, 0x00, 0x00, // Syscall ID 1
|
|
];
|
|
|
|
struct MultiReturnNative;
|
|
impl NativeInterface for MultiReturnNative {
|
|
fn syscall(
|
|
&mut self,
|
|
_id: u32,
|
|
_args: &[Value],
|
|
ret: &mut HostReturn,
|
|
_ctx: &mut HostContext,
|
|
) -> Result<(), VmFault> {
|
|
ret.push_bool(true);
|
|
ret.push_int(42);
|
|
ret.push_int(255);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let mut native = MultiReturnNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
// Ensure we have SYSTEM capability so we pass capability gate
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::SYSTEM);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
// Under PR5, VM enforces return-slot count based on SyscallMeta during syscall
|
|
// execution. A mismatch yields a Panic with a descriptive message.
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Panic(msg) => {
|
|
assert!(msg.contains("results mismatch"));
|
|
}
|
|
_ => panic!("Expected Panic with results mismatch, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_syscall_abi_void_return() {
|
|
let rom = vec![
|
|
0x70, 0x00, // Syscall + Reserved
|
|
0x01, 0x00, 0x00, 0x00, // Syscall ID 1
|
|
];
|
|
|
|
struct VoidReturnNative;
|
|
impl NativeInterface for VoidReturnNative {
|
|
fn syscall(
|
|
&mut self,
|
|
_id: u32,
|
|
_args: &[Value],
|
|
_ret: &mut HostReturn,
|
|
_ctx: &mut HostContext,
|
|
) -> Result<(), VmFault> {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let mut native = VoidReturnNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
vm.operand_stack.push(Value::Int32(100)).unwrap();
|
|
vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
assert_eq!(vm.pop().unwrap(), Value::Int32(100));
|
|
assert!(vm.operand_stack.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn test_syscall_arg_type_mismatch_trap() {
|
|
// GfxClear (0x1001) takes 1 argument
|
|
let rom = vec![
|
|
0x16, 0x00, // PushBool + Reserved
|
|
0x01, // value 1 (true)
|
|
0x70, 0x00, // Syscall + Reserved
|
|
0x01, 0x10, 0x00, 0x00, // Syscall ID 0x1001
|
|
];
|
|
|
|
struct ArgCheckNative;
|
|
impl NativeInterface for ArgCheckNative {
|
|
fn syscall(
|
|
&mut self,
|
|
_id: u32,
|
|
args: &[Value],
|
|
_ret: &mut HostReturn,
|
|
_ctx: &mut HostContext,
|
|
) -> Result<(), VmFault> {
|
|
expect_int(args, 0)?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
let mut native = ArgCheckNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
// Ensure we have GFX capability so we reach type checking inside native handler
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_TYPE);
|
|
assert_eq!(trap.opcode, OpCode::Syscall as u16);
|
|
}
|
|
_ => panic!("Expected Trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_add_invalid_types_traps_type() {
|
|
let rom = assemble("PUSH_I32 1\nPUSH_BOOL 1\nADD\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_TYPE);
|
|
assert_eq!(trap.opcode, OpCode::Add as u16);
|
|
assert!(trap.message.contains("Invalid types for ADD"));
|
|
}
|
|
other => panic!("Expected Trap(TYPE), got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_add_stack_underflow_traps() {
|
|
let rom = assemble("PUSH_I32 1\nADD\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_STACK_UNDERFLOW);
|
|
assert_eq!(trap.opcode, OpCode::Add as u16);
|
|
assert!(trap.message.contains("requires two operands"));
|
|
}
|
|
other => panic!("Expected Trap(STACK_UNDERFLOW), got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_and_invalid_types_traps_type() {
|
|
let rom = assemble("PUSH_I32 1\nPUSH_BOOL 1\nAND\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_TYPE);
|
|
assert_eq!(trap.opcode, OpCode::And as u16);
|
|
assert!(trap.message.contains("Invalid types for AND"));
|
|
}
|
|
other => panic!("Expected Trap(TYPE), got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_not_invalid_type_traps_type() {
|
|
let rom = assemble("PUSH_I32 1\nNOT\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_TYPE);
|
|
assert_eq!(trap.opcode, OpCode::Not as u16);
|
|
assert!(trap.message.contains("Invalid type for NOT"));
|
|
}
|
|
other => panic!("Expected Trap(TYPE), got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_neg_invalid_type_traps_type() {
|
|
let rom = assemble("PUSH_BOOL 1\nNEG\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_TYPE);
|
|
assert_eq!(trap.opcode, OpCode::Neg as u16);
|
|
assert!(trap.message.contains("Invalid type for Neg"));
|
|
}
|
|
other => panic!("Expected Trap(TYPE), got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_pop_underflow_traps() {
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::Pop as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_STACK_UNDERFLOW);
|
|
assert_eq!(trap.opcode, OpCode::Pop as u16);
|
|
assert!(trap.message.contains("POP requires one operand"));
|
|
}
|
|
other => panic!("Expected Trap(STACK_UNDERFLOW), got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_invalid_syscall_trap() {
|
|
let rom = vec![
|
|
0x70, 0x00, // Syscall + Reserved
|
|
0xEF, 0xBE, 0xAD, 0xDE, // 0xDEADBEEF
|
|
];
|
|
let mut vm = fault_vm(rom.clone(), vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
// Grant GFX capability so arg underflow is checked (capability gate is first)
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_INVALID_SYSCALL);
|
|
assert_eq!(trap.opcode, OpCode::Syscall as u16);
|
|
assert!(trap.message.contains("Unknown syscall"));
|
|
assert_eq!(trap.pc, 0);
|
|
}
|
|
_ => panic!("Expected Trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_intrinsic_vec2_dot_executes_without_syscalls() {
|
|
let mut rom = Vec::new();
|
|
for value in [1.0f64, 2.0, 3.0, 4.0] {
|
|
rom.extend_from_slice(&(OpCode::PushF64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&value.to_bits().to_le_bytes());
|
|
}
|
|
rom.extend_from_slice(&(OpCode::Intrinsic as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0x1000u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
let mut vm = new_test_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert!(matches!(report.reason, LogicalFrameEndingReason::Halted));
|
|
assert_eq!(vm.operand_stack, vec![Value::Float(11.0)]);
|
|
}
|
|
|
|
#[test]
|
|
fn test_intrinsic_vec2_length_executes_without_syscalls() {
|
|
let mut rom = Vec::new();
|
|
for value in [3.0f64, 4.0] {
|
|
rom.extend_from_slice(&(OpCode::PushF64 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&value.to_bits().to_le_bytes());
|
|
}
|
|
rom.extend_from_slice(&(OpCode::Intrinsic as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0x1001u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
let mut vm = new_test_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert!(matches!(report.reason, LogicalFrameEndingReason::Halted));
|
|
assert_eq!(vm.operand_stack, vec![Value::Float(5.0)]);
|
|
}
|
|
|
|
#[test]
|
|
fn test_removed_input_endpoint_is_an_unknown_intrinsic() {
|
|
let rom = assemble("INTRINSIC 0x2000\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert!(
|
|
matches!(report.reason, LogicalFrameEndingReason::Trap(trap) if trap.code == TRAP_INVALID_INTRINSIC)
|
|
);
|
|
assert!(vm.operand_stack.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn test_intrinsic_input_touch_x_requires_hardware_context() {
|
|
let rom = assemble("INTRINSIC 0x2134\nHALT").expect("assemble");
|
|
let mut vm = new_test_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_UNAVAILABLE);
|
|
assert_eq!(trap.pc, 0);
|
|
assert_eq!(trap.opcode, OpCode::Intrinsic as u16);
|
|
}
|
|
other => panic!("Expected unavailable input trap, got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_invalid_intrinsic_trap_is_distinct_from_syscall() {
|
|
let rom = assemble("INTRINSIC 0xDEADBEEF\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_INVALID_INTRINSIC);
|
|
assert_eq!(trap.opcode, OpCode::Intrinsic as u16);
|
|
assert!(trap.message.contains("Unknown intrinsic"));
|
|
}
|
|
_ => panic!("Expected intrinsic trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_intrinsic_argument_underflow_trap() {
|
|
let rom = assemble("PUSH_I32 1\nINTRINSIC 0x1000\nHALT").expect("assemble");
|
|
let mut vm = fault_vm(rom, vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_STACK_UNDERFLOW);
|
|
assert_eq!(trap.opcode, OpCode::Intrinsic as u16);
|
|
assert!(trap.message.contains("Intrinsic argument stack underflow"));
|
|
}
|
|
_ => panic!("Expected intrinsic underflow trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_syscall_arg_underflow_trap() {
|
|
// GfxClear (0x1001) expects 1 arg
|
|
let rom = vec![
|
|
0x70, 0x00, // Syscall + Reserved
|
|
0x01, 0x10, 0x00, 0x00, // Syscall ID 0x1001
|
|
];
|
|
let mut vm = fault_vm(rom.clone(), vec![]);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
// Grant GFX capability so arg underflow is checked (capability gate is first)
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_STACK_UNDERFLOW);
|
|
assert_eq!(trap.opcode, OpCode::Syscall as u16);
|
|
assert!(trap.message.contains("underflow"));
|
|
assert_eq!(trap.pc, 0);
|
|
}
|
|
_ => panic!("Expected Trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_syscall_missing_capability_trap() {
|
|
// Program: directly call GfxClear (0x1001). We check caps before args, so no underflow.
|
|
let mut rom = vec![
|
|
0x70, 0x00, // Syscall + Reserved
|
|
0x01, 0x10, 0x00, 0x00, // Syscall ID 0x1001 (LE)
|
|
];
|
|
|
|
// Seal a valid invocation; then explicitly corrupt installed capabilities.
|
|
let mut prefix = assemble("PUSH_I64 0").unwrap();
|
|
prefix.append(&mut rom);
|
|
let mut vm = new_test_vm(prefix, vec![]);
|
|
// Remove all capabilities
|
|
vm.set_capabilities(0);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_INVALID_SYSCALL);
|
|
assert_eq!(trap.opcode, OpCode::Syscall as u16);
|
|
assert!(trap.message.contains("Missing capability"));
|
|
assert_eq!(trap.pc, 10);
|
|
}
|
|
other => panic!("Expected Trap, got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_syscall_with_capability_success() {
|
|
// Program: push arg 0; call GfxClear (0x1001)
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Syscall as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0x1001u32.to_le_bytes()); // GfxClear
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
// Grant only GFX capability
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
// Any non-trap outcome is considered success here
|
|
if let LogicalFrameEndingReason::Trap(trap) = report.reason {
|
|
panic!("Unexpected trap: {:?}", trap);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_syscall_results_count_mismatch_panic() {
|
|
// GfxClear (0x1001) expects 0 results
|
|
let rom = vec![
|
|
0x17, 0x00, // PushI32
|
|
0x00, 0x00, 0x00, 0x00, // value 0
|
|
0x70, 0x00, // Syscall + Reserved
|
|
0x01, 0x10, 0x00, 0x00, // Syscall ID 0x1001
|
|
];
|
|
|
|
struct BadNative;
|
|
impl NativeInterface for BadNative {
|
|
fn syscall(
|
|
&mut self,
|
|
_id: u32,
|
|
_args: &[Value],
|
|
ret: &mut HostReturn,
|
|
_ctx: &mut HostContext,
|
|
) -> Result<(), VmFault> {
|
|
// Wrong: GfxClear is void but we push something
|
|
ret.push_int(42);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
let mut vm = new_test_vm(rom.clone(), vec![]);
|
|
// Grant GFX capability so results mismatch path is exercised
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
let mut native = BadNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Panic(msg) => assert!(msg.contains("results mismatch")),
|
|
_ => panic!("Expected Panic, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_status_first_syscall_results_count_mismatch_panic() {
|
|
// ComposerBindScene (0x1101) expects 1 result.
|
|
let code = assemble("PUSH_I32 0\nSYSCALL 0x1101").expect("assemble");
|
|
|
|
struct BadNativeNoReturn;
|
|
impl NativeInterface for BadNativeNoReturn {
|
|
fn syscall(
|
|
&mut self,
|
|
_id: u32,
|
|
_args: &[Value],
|
|
_ret: &mut HostReturn,
|
|
_ctx: &mut HostContext,
|
|
) -> Result<(), VmFault> {
|
|
// Wrong: status-first syscall must return one status slot.
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
let mut vm = new_test_vm(code, vec![]);
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
let mut native = BadNativeNoReturn;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).expect("run");
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Panic(msg) => assert!(msg.contains("results mismatch")),
|
|
other => panic!("Expected Panic, got {:?}", other),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_hardening_invalid_magic() {
|
|
let mut vm = VirtualMachine::default();
|
|
let res = vm.initialize(vec![0, 0, 0, 0]);
|
|
assert!(matches!(res, Err(VmInitError::RegistryLoadFailed(_))));
|
|
// VM should remain empty
|
|
assert_eq!(vm.program.rom.len(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_hardening_unsupported_version() {
|
|
let mut vm = VirtualMachine::default();
|
|
let mut header = vec![0u8; 32];
|
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
|
header[4..6].copy_from_slice(&1u16.to_le_bytes()); // unsupported version
|
|
|
|
let res = vm.initialize(header);
|
|
assert!(
|
|
matches!(res,Err(VmInitError::RegistryLoadFailed(e)) if e.reason == prometeu_bytecode::load_limits::LoadReason::Version)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_hardening_malformed_pbx_v0() {
|
|
let mut vm = VirtualMachine::default();
|
|
let mut header = vec![0u8; 32];
|
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
|
header[4..6].copy_from_slice(&0u16.to_le_bytes());
|
|
header[8..12].copy_from_slice(&1u32.to_le_bytes()); // missing directory
|
|
|
|
let res = vm.initialize(header);
|
|
match res {
|
|
Err(VmInitError::RegistryLoadFailed(_)) => {}
|
|
_ => panic!("Expected PBX v0 load failure UnexpectedEof, got {:?}", res),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_hardening_boot_protocol_entrypoint_not_found() {
|
|
let mut vm = VirtualMachine::default();
|
|
let header = TestProgram {
|
|
const_pool: vec![],
|
|
functions: vec![],
|
|
code: vec![],
|
|
debug_info: None,
|
|
exports: vec![],
|
|
syscalls: vec![],
|
|
}
|
|
.serialize();
|
|
|
|
let res = vm.initialize(header);
|
|
assert!(matches!(res, Err(VmInitError::RegistryLoadFailed(_))));
|
|
|
|
// VM state should not be updated
|
|
assert_eq!(vm.pc, 0);
|
|
assert_eq!(vm.program.rom.len(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_hardening_successful_init() {
|
|
let mut vm = VirtualMachine { pc: 123, ..Default::default() };
|
|
let code = assemble("HALT").expect("assemble");
|
|
|
|
let header = TestProgram {
|
|
const_pool: vec![],
|
|
functions: vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
code_len: code.len() as u32,
|
|
|
|
signature: int64_signature(0, 0),
|
|
captures: vec![],
|
|
name: None,
|
|
local_slots: 0,
|
|
max_stack_slots: 256,
|
|
}],
|
|
code,
|
|
debug_info: None,
|
|
exports: vec![],
|
|
syscalls: vec![],
|
|
}
|
|
.serialize();
|
|
|
|
let res = vm.initialize(header);
|
|
assert!(res.is_ok());
|
|
assert_eq!(vm.pc, 0);
|
|
assert_eq!(vm.program.rom.len(), 2);
|
|
assert_eq!(vm.cycles, 0);
|
|
|
|
vm.prepare_boot_call().expect("prepare entry call");
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).expect("run loaded PBX");
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
|
assert!(vm.is_halted());
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_rewrites_hostcall_before_verification() {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
|
|
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
|
|
let bytes = serialized_single_function_module(
|
|
code,
|
|
vec![SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "clear".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
}],
|
|
);
|
|
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert!(res.is_ok(), "patched hostcall should initialize");
|
|
|
|
let text = disassemble(&vm.program.rom).expect("disassemble patched rom");
|
|
assert!(text.contains("SYSCALL 0x1001"));
|
|
assert!(!text.contains("HOSTCALL"));
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_rejects_hostcall_index_out_of_bounds() {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
|
|
let code = assemble("HOSTCALL 1\nHALT").expect("assemble");
|
|
let bytes = serialized_single_function_module(
|
|
code,
|
|
vec![SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "clear".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
}],
|
|
);
|
|
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert_eq!(
|
|
res,
|
|
Err(VmInitError::LoaderPatchFailed(
|
|
crate::vm_init_error::LoaderPatchError::HostcallIndexOutOfBounds {
|
|
pc: 0,
|
|
sysc_index: 1,
|
|
syscalls_len: 1,
|
|
},
|
|
))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_rejects_unused_syscall_decl() {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
|
|
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
|
|
let bytes = serialized_single_function_module(
|
|
code,
|
|
vec![
|
|
SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "clear".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
},
|
|
SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "draw_text".into(),
|
|
version: 1,
|
|
arg_slots: 4,
|
|
ret_slots: 0,
|
|
},
|
|
],
|
|
);
|
|
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert_eq!(
|
|
res,
|
|
Err(VmInitError::LoaderPatchFailed(
|
|
crate::vm_init_error::LoaderPatchError::UnusedSyscallDecl {
|
|
sysc_index: 1,
|
|
module: "gfx2d".into(),
|
|
name: "draw_text".into(),
|
|
version: 1,
|
|
},
|
|
))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_rejects_raw_syscall_in_preload_artifact() {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
|
|
let code = assemble("PUSH_I32 0\nSYSCALL 0x1001\nHALT").expect("assemble");
|
|
let bytes = serialized_single_function_module(
|
|
code,
|
|
vec![SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "clear".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
}],
|
|
);
|
|
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert_eq!(
|
|
res,
|
|
Err(VmInitError::LoaderPatchFailed(
|
|
crate::vm_init_error::LoaderPatchError::RawSyscallInPreloadArtifact {
|
|
pc: 6,
|
|
syscall_id: 0x1001,
|
|
},
|
|
))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_propagates_resolution_failure() {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
|
|
let code = assemble("HOSTCALL 0\nHALT").expect("assemble");
|
|
let bytes = serialized_single_function_module(
|
|
code,
|
|
vec![SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "missing".into(),
|
|
version: 1,
|
|
arg_slots: 0,
|
|
ret_slots: 0,
|
|
}],
|
|
);
|
|
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert_eq!(
|
|
res,
|
|
Err(VmInitError::LoaderPatchFailed(
|
|
crate::vm_init_error::LoaderPatchError::ResolveFailed(
|
|
prometeu_hal::syscalls::DeclaredLoadError::UnknownSyscall {
|
|
module: "gfx2d".into(),
|
|
name: "missing".into(),
|
|
version: 1,
|
|
},
|
|
),
|
|
))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_propagates_missing_capability() {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::NONE);
|
|
|
|
let code = assemble("HOSTCALL 0\nHALT").expect("assemble");
|
|
let bytes = serialized_single_function_module(
|
|
code,
|
|
vec![SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "clear".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
}],
|
|
);
|
|
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert_eq!(
|
|
res,
|
|
Err(VmInitError::LoaderPatchFailed(
|
|
crate::vm_init_error::LoaderPatchError::ResolveFailed(
|
|
prometeu_hal::syscalls::DeclaredLoadError::MissingCapability {
|
|
required: prometeu_hal::syscalls::caps::GFX2D,
|
|
provided: prometeu_hal::syscalls::caps::NONE,
|
|
module: "gfx2d".into(),
|
|
name: "clear".into(),
|
|
version: 1,
|
|
},
|
|
),
|
|
))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_propagates_abi_mismatch() {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::GFX);
|
|
|
|
let code = assemble("HOSTCALL 0\nHALT").expect("assemble");
|
|
let bytes = serialized_single_function_module(
|
|
code,
|
|
vec![SyscallDecl {
|
|
module: "gfx2d".into(),
|
|
name: "draw_line".into(),
|
|
version: 1,
|
|
arg_slots: 4,
|
|
ret_slots: 0,
|
|
}],
|
|
);
|
|
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert_eq!(
|
|
res,
|
|
Err(VmInitError::LoaderPatchFailed(
|
|
crate::vm_init_error::LoaderPatchError::ResolveFailed(
|
|
prometeu_hal::syscalls::DeclaredLoadError::AbiMismatch {
|
|
module: "gfx2d".into(),
|
|
name: "draw_line".into(),
|
|
version: 1,
|
|
declared_arg_slots: 4,
|
|
declared_ret_slots: 0,
|
|
expected_arg_slots: 5,
|
|
expected_ret_slots: 0,
|
|
},
|
|
),
|
|
))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_accepts_status_first_signatures() {
|
|
let cases = vec![
|
|
SyscallDecl {
|
|
module: "composer".into(),
|
|
name: "bind_scene".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 1,
|
|
},
|
|
SyscallDecl {
|
|
module: "composer".into(),
|
|
name: "unbind_scene".into(),
|
|
version: 1,
|
|
arg_slots: 0,
|
|
ret_slots: 1,
|
|
},
|
|
SyscallDecl {
|
|
module: "composer".into(),
|
|
name: "emit_sprite".into(),
|
|
version: 1,
|
|
arg_slots: 9,
|
|
ret_slots: 1,
|
|
},
|
|
SyscallDecl {
|
|
module: "audio".into(),
|
|
name: "play_sample".into(),
|
|
version: 1,
|
|
arg_slots: 5,
|
|
ret_slots: 1,
|
|
},
|
|
SyscallDecl {
|
|
module: "audio".into(),
|
|
name: "play".into(),
|
|
version: 1,
|
|
arg_slots: 7,
|
|
ret_slots: 1,
|
|
},
|
|
SyscallDecl {
|
|
module: "asset".into(),
|
|
name: "load".into(),
|
|
version: 1,
|
|
arg_slots: 2,
|
|
ret_slots: 2,
|
|
},
|
|
SyscallDecl {
|
|
module: "asset".into(),
|
|
name: "commit".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 1,
|
|
},
|
|
SyscallDecl {
|
|
module: "asset".into(),
|
|
name: "cancel".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 1,
|
|
},
|
|
];
|
|
|
|
for syscall in cases {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::ALL);
|
|
let bytes = serialized_single_hostcall_module(syscall);
|
|
let res = vm.initialize(bytes);
|
|
assert!(res.is_ok(), "status-first signature must be accepted: {:?}", res);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_patching_rejects_legacy_status_first_ret_slots() {
|
|
let cases = vec![
|
|
SyscallDecl {
|
|
module: "composer".into(),
|
|
name: "bind_scene".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
},
|
|
SyscallDecl {
|
|
module: "audio".into(),
|
|
name: "play_sample".into(),
|
|
version: 1,
|
|
arg_slots: 5,
|
|
ret_slots: 0,
|
|
},
|
|
SyscallDecl {
|
|
module: "audio".into(),
|
|
name: "play".into(),
|
|
version: 1,
|
|
arg_slots: 7,
|
|
ret_slots: 0,
|
|
},
|
|
SyscallDecl {
|
|
module: "asset".into(),
|
|
name: "load".into(),
|
|
version: 1,
|
|
arg_slots: 2,
|
|
ret_slots: 1,
|
|
},
|
|
SyscallDecl {
|
|
module: "asset".into(),
|
|
name: "commit".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
},
|
|
SyscallDecl {
|
|
module: "asset".into(),
|
|
name: "cancel".into(),
|
|
version: 1,
|
|
arg_slots: 1,
|
|
ret_slots: 0,
|
|
},
|
|
];
|
|
|
|
for syscall in cases {
|
|
let mut vm = VirtualMachine::default();
|
|
vm.set_capabilities(prometeu_hal::syscalls::caps::ALL);
|
|
let bytes = serialized_single_hostcall_module(syscall.clone());
|
|
let err = vm.initialize(bytes).expect_err("legacy ABI must be rejected");
|
|
match err {
|
|
VmInitError::LoaderPatchFailed(
|
|
crate::vm_init_error::LoaderPatchError::ResolveFailed(
|
|
prometeu_hal::syscalls::DeclaredLoadError::AbiMismatch {
|
|
module,
|
|
name,
|
|
version,
|
|
declared_arg_slots,
|
|
declared_ret_slots,
|
|
expected_arg_slots,
|
|
expected_ret_slots,
|
|
},
|
|
),
|
|
) => {
|
|
assert_eq!(module, syscall.module);
|
|
assert_eq!(name, syscall.name);
|
|
assert_eq!(version, syscall.version);
|
|
assert_eq!(declared_arg_slots, syscall.arg_slots);
|
|
assert_eq!(declared_ret_slots, syscall.ret_slots);
|
|
|
|
assert_eq!(expected_arg_slots, declared_arg_slots);
|
|
assert_ne!(expected_ret_slots, declared_ret_slots);
|
|
}
|
|
other => panic!("expected ABI mismatch, got {:?}", other),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_hardening_missing_sysc_section() {
|
|
let mut vm = VirtualMachine::default();
|
|
let base = serialized_single_function_module(assemble("HALT").unwrap(), vec![]);
|
|
// Deliberately malformed envelope: remove one directory record and relocate payloads.
|
|
let mut header = base;
|
|
let count = u32::from_le_bytes(header[8..12].try_into().unwrap()) as usize;
|
|
let index = (0..count)
|
|
.find(|i| u32::from_le_bytes(header[32 + 12 * i..36 + 12 * i].try_into().unwrap()) == 5)
|
|
.unwrap();
|
|
header.drain(32 + 12 * index..44 + 12 * index);
|
|
header[8..12].copy_from_slice(&((count - 1) as u32).to_le_bytes());
|
|
for i in 0..count - 1 {
|
|
let pos = 36 + 12 * i;
|
|
let offset = u32::from_le_bytes(header[pos..pos + 4].try_into().unwrap()) - 12;
|
|
header[pos..pos + 4].copy_from_slice(&offset.to_le_bytes());
|
|
}
|
|
let res = vm.initialize(header);
|
|
|
|
assert!(
|
|
matches!(res,Err(VmInitError::RegistryLoadFailed(e)) if e.reason==prometeu_bytecode::load_limits::LoadReason::MissingSection && e.section==Some(5))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_loader_hardening_duplicate_sysc_identity() {
|
|
let mut vm = VirtualMachine::default();
|
|
|
|
use prometeu_bytecode::registry_codec::{PbxEnvelope, SectionData, encode_envelope};
|
|
let base = serialized_single_function_module(
|
|
assemble("HOSTCALL 0\nHALT").unwrap(),
|
|
vec![SyscallDecl {
|
|
module: "system".into(),
|
|
name: "has_cart".into(),
|
|
version: 1,
|
|
arg_slots: 0,
|
|
ret_slots: 1,
|
|
}],
|
|
);
|
|
let mut budget = prometeu_bytecode::load_limits::LoadBudget::new(Default::default());
|
|
let envelope = PbxEnvelope::parse(&base, &mut budget).unwrap();
|
|
let syscall = envelope.section(5).unwrap().bytes;
|
|
let mut duplicate = 2u32.to_le_bytes().to_vec();
|
|
duplicate.extend_from_slice(&syscall[4..]);
|
|
duplicate.extend_from_slice(&syscall[4..]);
|
|
let sections: Vec<_> = (0..9)
|
|
.filter_map(|kind| {
|
|
envelope.section(kind).map(|section| SectionData {
|
|
kind,
|
|
bytes: if kind == 5 { &duplicate } else { section.bytes },
|
|
})
|
|
})
|
|
.collect();
|
|
let bytes = encode_envelope(§ions, &mut budget).unwrap();
|
|
let res = vm.initialize(bytes);
|
|
|
|
assert!(
|
|
matches!(res,Err(VmInitError::RegistryLoadFailed(e)) if e.reason==prometeu_bytecode::load_limits::LoadReason::DuplicateSyscall)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_calling_convention_add() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// F0 (entry):
|
|
// PUSH_I32 10
|
|
// PUSH_I32 20
|
|
// CALL 1 (add)
|
|
// HALT
|
|
// F1 (add):
|
|
// GET_LOCAL 0 (a)
|
|
// GET_LOCAL 1 (b)
|
|
// ADD
|
|
// RET (1 slot)
|
|
|
|
let mut rom = Vec::new();
|
|
// F0
|
|
let f0_start = 0;
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&10i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&20i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
// F1
|
|
let f1_start = rom.len() as u32;
|
|
rom.extend_from_slice(&(OpCode::GetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::GetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Add as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f0_start as u32,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
},
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f1_start,
|
|
|
|
signature: scalar_signature(2, 1, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
},
|
|
],
|
|
);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
|
assert_eq!(vm.operand_stack.last().unwrap(), &Value::Int32(30));
|
|
}
|
|
|
|
#[test]
|
|
fn test_calling_convention_multi_slot_return() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// F0:
|
|
// CALL 1
|
|
// HALT
|
|
// F1:
|
|
// PUSH_I32 100
|
|
// PUSH_I32 200
|
|
// RET (2 slots)
|
|
|
|
let mut rom = Vec::new();
|
|
// F0
|
|
let f0_start = 0;
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
// F1
|
|
let f1_start = rom.len() as u32;
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&100i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&200i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f0_start as u32,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
},
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f1_start,
|
|
|
|
signature: scalar_signature(0, 2, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
},
|
|
],
|
|
);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
|
// Stack should be [100, 200]
|
|
assert_eq!(vm.operand_stack.len(), 2);
|
|
assert_eq!(vm.operand_stack[0], Value::Int32(100));
|
|
assert_eq!(vm.operand_stack[1], Value::Int32(200));
|
|
}
|
|
|
|
#[test]
|
|
fn test_calling_convention_void_call() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// F0:
|
|
// PUSH_I32 42
|
|
// CALL 1
|
|
// HALT
|
|
// F1:
|
|
// POP
|
|
// RET (0 slots)
|
|
|
|
let mut rom = Vec::new();
|
|
let f0_start = 0;
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let f1_start = rom.len() as u32;
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f0_start as u32,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
},
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f1_start,
|
|
|
|
signature: scalar_signature(1, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
},
|
|
],
|
|
);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
|
assert_eq!(vm.operand_stack.len(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_trap_invalid_func() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// CALL 99 (invalid)
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&99u32.to_le_bytes());
|
|
|
|
let mut vm = fault_vm(rom.clone(), vec![]);
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_INVALID_FUNC);
|
|
assert_eq!(trap.opcode, OpCode::Call as u16);
|
|
}
|
|
_ => panic!("Expected Trap(TRAP_INVALID_FUNC), got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_trap_bad_ret_slots() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// F0: CALL 1; HALT
|
|
// F1: PUSH_I32 42; RET (expected 0 slots)
|
|
|
|
let mut rom = Vec::new();
|
|
let f0_start = 0;
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
let f0_len = rom.len() - f0_start;
|
|
|
|
let f1_start = rom.len() as u32;
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
let f1_len = rom.len() as u32 - f1_start;
|
|
|
|
let mut vm = fault_vm(rom.clone(), vec![]);
|
|
vm.program.functions = std::sync::Arc::from(vec![
|
|
ExecutionFunction {
|
|
code_offset: f0_start as u32,
|
|
code_len: f0_len as u32,
|
|
..Default::default()
|
|
},
|
|
ExecutionFunction {
|
|
code_offset: f1_start,
|
|
code_len: f1_len,
|
|
param_slots: 0,
|
|
return_slots: 0, // ERROR: function pushes 42 but returns 0
|
|
..Default::default()
|
|
},
|
|
]);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_BAD_RET_SLOTS);
|
|
assert_eq!(trap.opcode, OpCode::Ret as u16);
|
|
assert!(trap.message.contains("Incorrect stack height"));
|
|
}
|
|
_ => panic!("Expected Trap(TRAP_BAD_RET_SLOTS), got {:?}", report.reason),
|
|
}
|
|
}
|
|
#[test]
|
|
fn test_locals_round_trip() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// PUSH_I32 42
|
|
// SET_LOCAL 0
|
|
// PUSH_I32 0 (garbage)
|
|
// GET_LOCAL 0
|
|
// RET (1 slot)
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::SetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Pop as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::GetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
local_slots: 1,
|
|
|
|
signature: scalar_signature(0, 1, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
}],
|
|
);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::EndOfRom);
|
|
// RET pops return values and pushes them back on the caller stack (which is the sentinel frame's stack here).
|
|
assert_eq!(vm.operand_stack, vec![Value::Int32(42)]);
|
|
}
|
|
|
|
#[test]
|
|
fn test_locals_per_call_isolation() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// Function 0 (entry):
|
|
// CALL 1
|
|
// POP
|
|
// CALL 1
|
|
// HALT
|
|
// Function 1:
|
|
// GET_LOCAL 0 (should be Null initially)
|
|
// PUSH_I32 42
|
|
// SET_LOCAL 0
|
|
// RET (1 slot: the initial Null)
|
|
|
|
let mut rom = Vec::new();
|
|
// F0
|
|
let f0_start = 0;
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Pop as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
// F1
|
|
let f1_start = rom.len() as u32;
|
|
rom.extend_from_slice(&(OpCode::GetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::SetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&0u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Ret as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f0_start as u32,
|
|
|
|
signature: scalar_signature(0, 0, 4),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
},
|
|
FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: f1_start,
|
|
local_slots: 1,
|
|
|
|
signature: scalar_signature(0, 1, 4),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
},
|
|
],
|
|
);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
|
|
|
// The last value on stack is the return of the second CALL 1,
|
|
// which should be Value::Null because locals are zero-initialized on each call.
|
|
assert_eq!(vm.operand_stack.last().unwrap(), &Value::Null);
|
|
}
|
|
|
|
#[test]
|
|
fn test_invalid_local_index_traps() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// Function with 0 params, 1 local.
|
|
// GET_LOCAL 1 (OOB)
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::GetLocal as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = fault_vm(rom.clone(), vec![]);
|
|
vm.program.functions = std::sync::Arc::from(vec![ExecutionFunction {
|
|
code_offset: 0,
|
|
code_len: 8,
|
|
local_slots: 1,
|
|
..Default::default()
|
|
}]);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_INVALID_LOCAL);
|
|
assert_eq!(trap.opcode, OpCode::GetLocal as u16);
|
|
assert!(trap.message.contains("out of bounds"));
|
|
}
|
|
_ => panic!("Expected Trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_nested_if() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// if (true) {
|
|
// if (false) {
|
|
// PUSH 1
|
|
// } else {
|
|
// PUSH 2
|
|
// }
|
|
// } else {
|
|
// PUSH 3
|
|
// }
|
|
// HALT
|
|
let mut rom = Vec::new();
|
|
// 0: PUSH_BOOL true
|
|
rom.extend_from_slice(&(OpCode::PushBool as u16).to_le_bytes());
|
|
rom.push(1);
|
|
// 3: JMP_IF_FALSE -> ELSE1 (offset 42)
|
|
rom.extend_from_slice(&(OpCode::JmpIfFalse as u16).to_le_bytes());
|
|
rom.extend_from_slice(&42u32.to_le_bytes());
|
|
|
|
// INNER IF:
|
|
// 9: PUSH_BOOL false
|
|
rom.extend_from_slice(&(OpCode::PushBool as u16).to_le_bytes());
|
|
rom.push(0);
|
|
// 12: JMP_IF_FALSE -> ELSE2 (offset 30)
|
|
rom.extend_from_slice(&(OpCode::JmpIfFalse as u16).to_le_bytes());
|
|
rom.extend_from_slice(&30u32.to_le_bytes());
|
|
// 18: PUSH_I32 1
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1i32.to_le_bytes());
|
|
// 24: JMP -> END (offset 48)
|
|
rom.extend_from_slice(&(OpCode::Jmp as u16).to_le_bytes());
|
|
rom.extend_from_slice(&48u32.to_le_bytes());
|
|
|
|
// ELSE2:
|
|
// 30: PUSH_I32 2
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&2i32.to_le_bytes());
|
|
// 36: JMP -> END (offset 48)
|
|
rom.extend_from_slice(&(OpCode::Jmp as u16).to_le_bytes());
|
|
rom.extend_from_slice(&48u32.to_le_bytes());
|
|
|
|
// ELSE1:
|
|
// 42: PUSH_I32 3
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&3i32.to_le_bytes());
|
|
|
|
// END:
|
|
// 48: HALT
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
}],
|
|
);
|
|
// We need to set up the function meta for absolute jumps to work correctly
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
|
|
vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.pop().unwrap(), Value::Int32(2));
|
|
}
|
|
|
|
#[test]
|
|
fn test_if_with_empty_branches() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// PUSH_BOOL true
|
|
// JMP_IF_FALSE -> ELSE (offset 15)
|
|
// // Empty then
|
|
// JMP -> END (offset 15)
|
|
// ELSE:
|
|
// // Empty else
|
|
// END:
|
|
// HALT
|
|
let mut rom = Vec::new();
|
|
// 0-2: PUSH_BOOL true
|
|
rom.extend_from_slice(&(OpCode::PushBool as u16).to_le_bytes());
|
|
rom.push(1);
|
|
// 3-8: JMP_IF_FALSE -> 15
|
|
rom.extend_from_slice(&(OpCode::JmpIfFalse as u16).to_le_bytes());
|
|
rom.extend_from_slice(&15u32.to_le_bytes());
|
|
// 9-14: JMP -> 15
|
|
rom.extend_from_slice(&(OpCode::Jmp as u16).to_le_bytes());
|
|
rom.extend_from_slice(&15u32.to_le_bytes());
|
|
// 15-16: HALT
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
}],
|
|
);
|
|
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
|
assert_eq!(vm.operand_stack.len(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_jmp_if_non_boolean_trap() {
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// PUSH_I32 1
|
|
// JMP_IF_TRUE 9
|
|
// HALT
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
|
rom.extend_from_slice(&1i32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::JmpIfTrue as u16).to_le_bytes());
|
|
rom.extend_from_slice(&9u32.to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = fault_vm(rom.clone(), vec![]);
|
|
vm.program.functions = std::sync::Arc::from(vec![ExecutionFunction {
|
|
code_offset: 0,
|
|
code_len: 14,
|
|
..Default::default()
|
|
}]);
|
|
vm.prepare_call("0").expect("prepare entry call");
|
|
|
|
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
|
match report.reason {
|
|
LogicalFrameEndingReason::Trap(trap) => {
|
|
assert_eq!(trap.code, TRAP_TYPE);
|
|
assert_eq!(trap.opcode, OpCode::JmpIfTrue as u16);
|
|
assert!(trap.message.contains("Expected boolean"));
|
|
}
|
|
_ => panic!("Expected Trap, got {:?}", report.reason),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_gc_triggers_only_at_frame_sync() {
|
|
#[cfg(test)]
|
|
use crate::object::ObjectKind;
|
|
|
|
// ROM: NOP; FRAME_SYNC; HALT
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::Nop as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
}],
|
|
);
|
|
|
|
// Set a very low threshold to trigger GC as soon as we hit FRAME_SYNC
|
|
vm.gc_alloc_threshold = 1;
|
|
|
|
// Allocate an unreachable object (no roots referencing it)
|
|
let _orphan = vm.heap.allocate_object(ObjectKind::Bytes, &[1, 2, 3]).unwrap();
|
|
// Entry preparation allocates no heap object.
|
|
assert_eq!(vm.heap.len(), 1);
|
|
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// Step 1: NOP — should not run GC
|
|
vm.step(&mut native, &mut ctx).unwrap();
|
|
assert_eq!(vm.heap.len(), 1, "GC must not run except at safepoints");
|
|
|
|
// Step 2: FRAME_SYNC — GC should run and reclaim the unreachable object
|
|
match vm.step(&mut native, &mut ctx) {
|
|
Err(LogicalFrameEndingReason::FrameSync) => {}
|
|
other => panic!("Expected FrameSync, got {:?}", other),
|
|
}
|
|
// No execution object remains
|
|
assert_eq!(vm.heap.len(), 0, "Unreachable object must be reclaimed at FRAME_SYNC");
|
|
}
|
|
|
|
#[test]
|
|
fn test_gc_keeps_roots_and_collects_unreachable_at_frame_sync() {
|
|
#[cfg(test)]
|
|
use crate::object::ObjectKind;
|
|
|
|
// ROM: FRAME_SYNC; FRAME_SYNC; HALT
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
}],
|
|
);
|
|
|
|
vm.gc_alloc_threshold = 1;
|
|
|
|
// Allocate two objects; make one a root by placing it on the operand stack
|
|
let rooted = vm.heap.allocate_object(ObjectKind::Bytes, &[9, 9]).unwrap();
|
|
let unreachable = vm.heap.allocate_object(ObjectKind::Bytes, &[8, 8, 8]).unwrap();
|
|
// Entry preparation allocates no heap object.
|
|
assert_eq!(vm.heap.len(), 2);
|
|
vm.operand_stack.push(Value::HeapRef(rooted)).unwrap();
|
|
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// Execute FRAME_SYNC: should trigger GC
|
|
match vm.step(&mut native, &mut ctx) {
|
|
Err(LogicalFrameEndingReason::FrameSync) => {}
|
|
other => panic!("Expected FrameSync, got {:?}", other),
|
|
}
|
|
|
|
// Rooted survives and unreachable is collected
|
|
assert_eq!(vm.heap.len(), 1);
|
|
assert!(vm.heap.is_valid(rooted));
|
|
assert!(!vm.heap.is_valid(unreachable));
|
|
}
|
|
|
|
#[test]
|
|
fn test_gc_simple_allocation_collection_cycle() {
|
|
#[cfg(test)]
|
|
use crate::object::ObjectKind;
|
|
|
|
// ROM: FRAME_SYNC; FRAME_SYNC; HALT
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
}],
|
|
);
|
|
|
|
// Make GC trigger on any allocation delta
|
|
vm.gc_alloc_threshold = 1;
|
|
|
|
// Cycle 1: allocate one unreachable object
|
|
let _h1 = vm.heap.allocate_object(ObjectKind::Bytes, &[1]).unwrap();
|
|
// Entry preparation allocates no heap object.
|
|
assert_eq!(vm.heap.len(), 1);
|
|
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// FRAME_SYNC should collect it (first FRAME_SYNC)
|
|
match vm.step(&mut native, &mut ctx) {
|
|
Err(LogicalFrameEndingReason::FrameSync) => {}
|
|
other => panic!("Expected FrameSync, got {:?}", other),
|
|
}
|
|
// No execution object remains
|
|
assert_eq!(vm.heap.len(), 0);
|
|
|
|
// Cycle 2: allocate again and collect again deterministically
|
|
let _h2 = vm.heap.allocate_object(ObjectKind::Bytes, &[2]).unwrap();
|
|
assert_eq!(vm.heap.len(), 1);
|
|
// Second FRAME_SYNC should also be reached deterministically
|
|
match vm.step(&mut native, &mut ctx) {
|
|
Err(LogicalFrameEndingReason::FrameSync) => {}
|
|
other => panic!("Expected FrameSync, got {:?}", other),
|
|
}
|
|
assert_eq!(vm.heap.len(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_gc_many_short_lived_objects_stress() {
|
|
#[cfg(test)]
|
|
use crate::object::ObjectKind;
|
|
|
|
// ROM: FRAME_SYNC; HALT
|
|
let mut rom = Vec::new();
|
|
rom.extend_from_slice(&(OpCode::FrameSync as u16).to_le_bytes());
|
|
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
|
|
|
let mut vm = typed_test_vm(
|
|
rom.clone(),
|
|
vec![],
|
|
vec![FunctionDecl {
|
|
lifecycle_role: Default::default(),
|
|
code_offset: 0,
|
|
|
|
signature: scalar_signature(0, 0, 1),
|
|
captures: vec![],
|
|
name: None,
|
|
code_len: 0,
|
|
max_stack_slots: 256,
|
|
local_slots: 0,
|
|
}],
|
|
);
|
|
|
|
// Deterministic: trigger collection when any growth since last sweep occurs
|
|
vm.gc_alloc_threshold = 1;
|
|
|
|
// Allocate many small, unreferenced objects
|
|
let count = 2048usize; // stress but still quick
|
|
for i in 0..count {
|
|
let byte = (i & 0xFF) as u8;
|
|
let _ = vm.heap.allocate_object(ObjectKind::Bytes, &[byte]).unwrap();
|
|
}
|
|
// Entry preparation allocates no heap object.
|
|
assert_eq!(vm.heap.len(), count);
|
|
|
|
let mut native = MockNative;
|
|
let mut ctx = HostContext::new(None);
|
|
|
|
// Single FRAME_SYNC should reclaim all since there are no roots
|
|
match vm.step(&mut native, &mut ctx) {
|
|
Err(LogicalFrameEndingReason::FrameSync) => {}
|
|
other => panic!("Expected FrameSync, got {:?}", other),
|
|
}
|
|
|
|
assert_eq!(vm.heap.len(), 0, "All short-lived objects must be reclaimed deterministically");
|
|
}
|
|
|
|
#[test]
|
|
fn call_depth_includes_entry_and_traps_before_frame_growth() {
|
|
for limit in [1, 3, 1024] {
|
|
let limits =
|
|
RuntimeLimits::default().lowered(RuntimeResource::CallDepth, limit).unwrap();
|
|
let mut vm = limited_session(assemble("CALL 0").unwrap(), limits);
|
|
vm.prepare_call("0").unwrap();
|
|
let report =
|
|
vm.run_budget(100_000, &mut MockNative, &mut HostContext::new(None)).unwrap();
|
|
assert!(matches!(report.reason, LogicalFrameEndingReason::Trap(trap)
|
|
if trap.code == TRAP_RESOURCE_LIMIT && trap.pc == 0 && trap.opcode == OpCode::Call as u16));
|
|
assert_eq!(vm.call_stack.len(), limit as usize);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn entry_depth_zero_returns_typed_setup_failure_without_allocating() {
|
|
let limits = RuntimeLimits::default().lowered(RuntimeResource::CallDepth, 0).unwrap();
|
|
let mut vm = limited_session(assemble("HALT").unwrap(), limits);
|
|
let error = vm.prepare_boot_call().unwrap_err();
|
|
let VmInitError::RuntimeResourceLimit(error) = error else { panic!("{error:?}") };
|
|
assert_eq!(
|
|
(error.resource, error.requested, error.limit),
|
|
(RuntimeResource::CallDepth, 1, 0)
|
|
);
|
|
assert!(vm.call_stack.is_empty());
|
|
assert_eq!(vm.heap.len(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn operand_globals_and_frames_share_one_auxiliary_limit() {
|
|
let frame = entry_auxiliary_bytes();
|
|
let slot = size_of::<Value>() as u64;
|
|
for (source, extra, expected_pc, expected_op) in [
|
|
("PUSH_I32 1\nPUSH_I32 2", slot, 6, OpCode::PushI32),
|
|
("GET_GLOBAL 0\nGET_GLOBAL 1", 2 * slot, 6, OpCode::GetGlobal),
|
|
("GET_GLOBAL 4294967295", 0, 0, OpCode::GetGlobal),
|
|
("CALL 0", 0, 0, OpCode::Call),
|
|
] {
|
|
let limits = RuntimeLimits::default()
|
|
.lowered(RuntimeResource::AuxiliaryBytes, frame + extra)
|
|
.unwrap();
|
|
let code = assemble(source).unwrap();
|
|
let mut vm = limited_session(code.clone(), limits);
|
|
vm.prepare_boot_call().unwrap();
|
|
let report = vm.run_budget(100, &mut MockNative, &mut HostContext::new(None)).unwrap();
|
|
assert!(
|
|
matches!(report.reason, LogicalFrameEndingReason::Trap(trap)
|
|
if trap.code == TRAP_RESOURCE_LIMIT && trap.pc == expected_pc && trap.opcode == expected_op as u16),
|
|
"{source}"
|
|
);
|
|
assert!(vm.budget.used(RuntimeResource::AuxiliaryBytes) <= frame + extra);
|
|
assert_eq!(vm.budget.used(RuntimeResource::TemporaryBytes), 0);
|
|
assert_eq!(vm.call_stack.len(), 1);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn gc_scratch_failure_traps_before_sweep_and_preserves_roots() {
|
|
let limits = RuntimeLimits::default().lowered(RuntimeResource::TemporaryBytes, 0).unwrap();
|
|
let mut vm = limited_session(assemble("FRAME_SYNC").unwrap(), limits);
|
|
vm.prepare_boot_call().unwrap();
|
|
vm.gc_alloc_threshold = 1;
|
|
let current = vm.heap.alloc_closure(0, &[]).unwrap();
|
|
vm.globals.push(Value::HeapRef(current)).unwrap();
|
|
let guest = vm.budget.used(RuntimeResource::GuestBytes);
|
|
let report = vm.run_budget(100, &mut MockNative, &mut HostContext::new(None)).unwrap();
|
|
assert!(matches!(report.reason, LogicalFrameEndingReason::Trap(trap)
|
|
if trap.code == TRAP_RESOURCE_LIMIT && trap.pc == 0 && trap.opcode == OpCode::FrameSync as u16));
|
|
assert!(vm.heap.is_valid(current));
|
|
assert!(!vm.heap.header(current).unwrap().is_marked());
|
|
assert_eq!(vm.budget.used(RuntimeResource::GuestBytes), guest);
|
|
assert_eq!(vm.budget.used(RuntimeResource::TemporaryBytes), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn entry_preparation_needs_no_guest_heap_quota() {
|
|
let limits = RuntimeLimits::default().lowered(RuntimeResource::GuestBytes, 0).unwrap();
|
|
let mut vm = limited_session(assemble("HALT").unwrap(), limits);
|
|
vm.prepare_boot_call().unwrap();
|
|
assert_eq!(vm.call_stack.len(), 1);
|
|
assert_eq!(vm.heap.len(), 0);
|
|
assert_eq!(vm.budget.used(RuntimeResource::GuestBytes), 0);
|
|
assert_eq!(vm.budget.used(RuntimeResource::HandleSlots), 0);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "virtual_machine/callable_tests.rs"]
|
|
mod callable_tests;
|
|
|
|
#[cfg(feature = "resource-diagnostics")]
|
|
pub mod string_provenance_qualification;
|
|
|
|
#[cfg(test)]
|
|
#[path = "virtual_machine/identity_tests.rs"]
|
|
mod identity_tests;
|