fix(vm): enforce return boundaries and amortize budgeted growth
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
Validate and complete function-end branches through the shared return path. Handle integer DIV/MOD overflow with wrapping and charge CALL/RET refusals exactly once. Amortize budgeted vector growth with exact-capacity fallback at quota limits. Add execution and accounting regressions, clarify ISA contracts, and include existing lint cleanups.
This commit is contained in:
@@ -26,6 +26,12 @@ enum Fact {
|
||||
Dynamic { part: u32, origin: u64 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct FunctionScope {
|
||||
id: u32,
|
||||
locals: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn validate_registry_types(
|
||||
code: &[u8],
|
||||
registry: &Registry,
|
||||
@@ -62,6 +68,7 @@ fn analyze(
|
||||
let function = ®istry.declarations().functions[id as usize];
|
||||
let layout = registry.function_layout(FunctionId(id)).unwrap();
|
||||
let locals = layout.parameter_slots as usize + function.local_slots as usize;
|
||||
let scope = FunctionScope { id, locals };
|
||||
let mut blocks = basic_blocks::<Fact>(body, budget, at_pc)?;
|
||||
let mut initial = scratch::<Fact>(locals, budget)?;
|
||||
budget.work(locals)?;
|
||||
@@ -101,16 +108,7 @@ fn analyze(
|
||||
while pc < end {
|
||||
*at_pc = pc;
|
||||
let instruction = metered_decode(pc, body, budget)?;
|
||||
transfer(
|
||||
&instruction,
|
||||
&mut working,
|
||||
locals,
|
||||
&mut height,
|
||||
registry,
|
||||
constants,
|
||||
id,
|
||||
budget,
|
||||
)?;
|
||||
transfer(&instruction, &mut working, scope, &mut height, registry, constants, budget)?;
|
||||
let spec = instruction.opcode.spec();
|
||||
if spec.is_branch {
|
||||
let target = instruction.imm_u32().unwrap() as usize;
|
||||
@@ -158,16 +156,14 @@ fn analyze(
|
||||
*at_pc = pc;
|
||||
let instruction = metered_decode(pc, body, budget)?;
|
||||
check(&instruction, &working, locals, height, registry, id, budget)?;
|
||||
transfer(
|
||||
&instruction,
|
||||
&mut working,
|
||||
locals,
|
||||
&mut height,
|
||||
registry,
|
||||
constants,
|
||||
id,
|
||||
budget,
|
||||
)?;
|
||||
transfer(&instruction, &mut working, scope, &mut height, registry, constants, budget)?;
|
||||
if instruction.opcode.spec().is_branch
|
||||
&& instruction.imm_u32().unwrap() as usize == body.len()
|
||||
{
|
||||
// The taken edge returns after consuming a conditional operand.
|
||||
// Check only stabilized facts, just as for an explicit RET.
|
||||
check_results(&working[locals..locals + height], registry, id, budget)?;
|
||||
}
|
||||
if instruction.opcode.spec().is_terminator {
|
||||
break;
|
||||
}
|
||||
@@ -256,13 +252,13 @@ fn invalidate(
|
||||
fn transfer(
|
||||
instruction: &prometeu_bytecode::DecodedInstr<'_>,
|
||||
working: &mut [Fact],
|
||||
locals: usize,
|
||||
scope: FunctionScope,
|
||||
height: &mut usize,
|
||||
registry: &Registry,
|
||||
constants: &[Constant],
|
||||
id: u32,
|
||||
budget: &mut LoadBudget,
|
||||
) -> Result<(), E> {
|
||||
let FunctionScope { id, locals } = scope;
|
||||
budget.work(1)?;
|
||||
let opcode = instruction.opcode;
|
||||
let spec = opcode.spec();
|
||||
@@ -670,12 +666,7 @@ fn check(
|
||||
}
|
||||
}
|
||||
Op::Ret => {
|
||||
let mut base = locals;
|
||||
for ty in ®istry.declarations().functions[id as usize].signature.results {
|
||||
check_group(&working[base..], *ty, registry, budget)?;
|
||||
budget.work(1)?;
|
||||
base += registry.type_layout(*ty).unwrap().storage.slots as usize;
|
||||
}
|
||||
check_results(&working[locals..end], registry, id, budget)?;
|
||||
}
|
||||
Op::MakeClosure => {
|
||||
let target = instruction.imm_u32x2().unwrap().0;
|
||||
@@ -830,5 +821,20 @@ fn check(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_results(
|
||||
values: &[Fact],
|
||||
registry: &Registry,
|
||||
id: u32,
|
||||
budget: &mut LoadBudget,
|
||||
) -> Result<(), E> {
|
||||
let mut base = 0;
|
||||
for ty in ®istry.declarations().functions[id as usize].signature.results {
|
||||
check_group(&values[base..], *ty, registry, budget)?;
|
||||
budget.work(1)?;
|
||||
base += registry.type_layout(*ty).unwrap().storage.slots as usize;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -253,6 +253,47 @@ mod tests {
|
||||
assert_eq!(budget.used(AuxiliaryBytes), 8);
|
||||
assert_eq!(queue.pop(), Some(11));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_growth_moves_a_linear_number_of_elements() {
|
||||
let budget = RuntimeBudget::default();
|
||||
let mut values = BudgetVec::<u64>::new(&budget, AuxiliaryBytes);
|
||||
let mut moved = 0;
|
||||
let count = 16_000;
|
||||
for value in 0..count {
|
||||
let capacity = values.capacity();
|
||||
values.push(value as u64).unwrap();
|
||||
if values.capacity() != capacity {
|
||||
moved += value;
|
||||
}
|
||||
}
|
||||
assert!(moved < 2 * count, "moved {moved} elements for {count} pushes");
|
||||
assert_eq!(values.as_slice(), (0..count as u64).collect::<Vec<_>>());
|
||||
assert_eq!(budget.used(AuxiliaryBytes), (values.capacity() * size_of::<u64>()) as u64);
|
||||
assert_eq!(budget.used(TemporaryBytes), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn growth_falls_back_to_exact_capacity_at_shared_and_coexistence_limits() {
|
||||
for resource in [AuxiliaryBytes, TemporaryBytes] {
|
||||
let limit = if resource == TemporaryBytes { 72 } else { 40 };
|
||||
let budget =
|
||||
RuntimeBudget::new(RuntimeLimits::default().lowered(resource, limit).unwrap());
|
||||
let mut values = BudgetVec::<u64>::new(&budget, resource);
|
||||
for value in 0..5 {
|
||||
values.push(value).unwrap();
|
||||
}
|
||||
assert_eq!(values.as_slice(), &[0, 1, 2, 3, 4]);
|
||||
assert_eq!(values.capacity(), 5);
|
||||
assert_eq!(budget.used(resource), 40);
|
||||
assert!(values.push(5).is_err());
|
||||
assert_eq!(values.as_slice(), &[0, 1, 2, 3, 4]);
|
||||
assert_eq!(budget.used(resource), 40);
|
||||
drop(values);
|
||||
assert_eq!(budget.used(resource), 0);
|
||||
assert_eq!(budget.used(TemporaryBytes), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Contiguous execution storage. The capacity reservation travels with the buffer
|
||||
@@ -280,20 +321,34 @@ impl<T> BudgetVec<T> {
|
||||
if required <= self.data.capacity() {
|
||||
return Ok(None);
|
||||
}
|
||||
let bytes = b.bytes::<T>(required, q)?;
|
||||
// Amortize incremental growth while keeping exact admission available
|
||||
// when spare capacity would exceed a shared or temporary quota.
|
||||
let preferred = required.max(self.data.capacity().saturating_mul(2));
|
||||
if preferred > required
|
||||
&& let Ok(growth) = self.prepare_capacity(preferred)
|
||||
{
|
||||
return Ok(Some(growth));
|
||||
}
|
||||
self.prepare_capacity(required).map(Some)
|
||||
}
|
||||
|
||||
fn prepare_capacity(&self, capacity: usize) -> Result<VecGrowth<T>, ResourceFailure> {
|
||||
let b = &self.charge.budget;
|
||||
let q = self.charge.resource;
|
||||
let bytes = b.bytes::<T>(capacity, q)?;
|
||||
let mut extra = b.reserve(q, bytes - self.charge.amount)?;
|
||||
let temporary = b.reserve(RuntimeResource::TemporaryBytes, self.charge.amount)?;
|
||||
let mut candidate = Vec::new();
|
||||
candidate
|
||||
.try_reserve_exact(required)
|
||||
.try_reserve_exact(capacity)
|
||||
.map_err(|_| b.failure(q, ResourceReason::AllocationFailed, bytes))?;
|
||||
extra.resize(b.bytes::<T>(candidate.capacity(), q)? - self.charge.amount)?;
|
||||
Ok(Some(VecGrowth {
|
||||
Ok(VecGrowth {
|
||||
candidate,
|
||||
extra,
|
||||
_temporary: temporary,
|
||||
old_capacity: self.data.capacity(),
|
||||
}))
|
||||
})
|
||||
}
|
||||
pub(crate) fn commit_growth(&mut self, growth: Option<VecGrowth<T>>) {
|
||||
if let Some(mut growth) = growth {
|
||||
|
||||
@@ -3,6 +3,7 @@ mod callable;
|
||||
mod collections;
|
||||
#[cfg(test)]
|
||||
mod collections_tests;
|
||||
mod control;
|
||||
mod dynamic;
|
||||
mod gc;
|
||||
mod loader;
|
||||
@@ -266,6 +267,15 @@ impl VirtualMachine {
|
||||
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();
|
||||
}
|
||||
|
||||
// Execute
|
||||
match opcode {
|
||||
OpCode::Nop => {}
|
||||
@@ -277,12 +287,7 @@ impl VirtualMachine {
|
||||
.imm_u32()
|
||||
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
|
||||
as usize;
|
||||
let func_start = self
|
||||
.call_stack
|
||||
.last()
|
||||
.map(|f| self.program.functions[f.func_idx].code_offset as usize)
|
||||
.unwrap_or(0);
|
||||
self.pc = func_start + target;
|
||||
self.jump_to(target, opcode, start_pc as u32)?;
|
||||
}
|
||||
OpCode::JmpIfFalse => {
|
||||
let target = instr
|
||||
@@ -293,12 +298,7 @@ impl VirtualMachine {
|
||||
self.pop_trap(opcode, start_pc as u32, "JMP_IF_FALSE requires one operand")?;
|
||||
match val {
|
||||
Value::Boolean(false) => {
|
||||
let func_start = self
|
||||
.call_stack
|
||||
.last()
|
||||
.map(|f| self.program.functions[f.func_idx].code_offset as usize)
|
||||
.unwrap_or(0);
|
||||
self.pc = func_start + target;
|
||||
self.jump_to(target, opcode, start_pc as u32)?;
|
||||
}
|
||||
Value::Boolean(true) => {}
|
||||
_ => {
|
||||
@@ -320,12 +320,7 @@ impl VirtualMachine {
|
||||
self.pop_trap(opcode, start_pc as u32, "JMP_IF_TRUE requires one operand")?;
|
||||
match val {
|
||||
Value::Boolean(true) => {
|
||||
let func_start = self
|
||||
.call_stack
|
||||
.last()
|
||||
.map(|f| self.program.functions[f.func_idx].code_offset as usize)
|
||||
.unwrap_or(0);
|
||||
self.pc = func_start + target;
|
||||
self.jump_to(target, opcode, start_pc as u32)?;
|
||||
}
|
||||
Value::Boolean(false) => {}
|
||||
_ => {
|
||||
@@ -491,7 +486,7 @@ impl VirtualMachine {
|
||||
"Integer division by zero".into(),
|
||||
));
|
||||
}
|
||||
Ok(Value::Int32(a / b))
|
||||
Ok(Value::Int32(a.wrapping_div(b)))
|
||||
}
|
||||
(Value::Int64(a), Value::Int64(b)) => {
|
||||
if b == 0 {
|
||||
@@ -500,7 +495,7 @@ impl VirtualMachine {
|
||||
"Integer division by zero".into(),
|
||||
));
|
||||
}
|
||||
Ok(Value::Int64(a / b))
|
||||
Ok(Value::Int64(a.wrapping_div(b)))
|
||||
}
|
||||
(Value::Int32(a), Value::Int64(b)) => {
|
||||
if b == 0 {
|
||||
@@ -509,7 +504,7 @@ impl VirtualMachine {
|
||||
"Integer division by zero".into(),
|
||||
));
|
||||
}
|
||||
Ok(Value::Int64(a as i64 / b))
|
||||
Ok(Value::Int64((a as i64).wrapping_div(b)))
|
||||
}
|
||||
(Value::Int64(a), Value::Int32(b)) => {
|
||||
if b == 0 {
|
||||
@@ -518,7 +513,7 @@ impl VirtualMachine {
|
||||
"Integer division by zero".into(),
|
||||
));
|
||||
}
|
||||
Ok(Value::Int64(a / b as i64))
|
||||
Ok(Value::Int64(a.wrapping_div(b as i64)))
|
||||
}
|
||||
(Value::Float(a), Value::Float(b)) => {
|
||||
if b == 0.0 {
|
||||
@@ -557,13 +552,13 @@ impl VirtualMachine {
|
||||
if b == 0 {
|
||||
return Err(OpError::Trap(TRAP_DIV_ZERO, "Integer modulo by zero".into()));
|
||||
}
|
||||
Ok(Value::Int32(a % b))
|
||||
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 % b))
|
||||
Ok(Value::Int64(a.wrapping_rem(b)))
|
||||
}
|
||||
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for MOD".into())),
|
||||
})?,
|
||||
@@ -841,61 +836,7 @@ impl VirtualMachine {
|
||||
.map_err(|error| self.resource_trap(error, opcode, start_pc as u32))?;
|
||||
self.pc = callee_offset as usize;
|
||||
}
|
||||
OpCode::Ret => {
|
||||
let frame = self.call_stack.last().cloned().ok_or_else(|| {
|
||||
self.trap(
|
||||
TRAP_STACK_UNDERFLOW,
|
||||
opcode as u16,
|
||||
"RET with empty call stack".into(),
|
||||
start_pc as u32,
|
||||
)
|
||||
})?;
|
||||
let func = &self.program.functions[frame.func_idx];
|
||||
let return_slots = func.return_slots as usize;
|
||||
|
||||
let current_height = self.operand_stack.len();
|
||||
let expected_height = frame.stack_base
|
||||
+ func.param_slots as usize
|
||||
+ func.local_slots as usize
|
||||
+ return_slots;
|
||||
|
||||
if current_height != expected_height {
|
||||
return Err(self.trap(TRAP_BAD_RET_SLOTS, opcode as u16, format!(
|
||||
"Incorrect stack height at RET in func {}: expected {} slots (stack_base={} + params={} + locals={} + returns={}), got {}",
|
||||
frame.func_idx, expected_height, frame.stack_base, func.param_slots, func.local_slots, return_slots, current_height
|
||||
), start_pc as u32));
|
||||
}
|
||||
|
||||
self.check_signature_group(
|
||||
frame.func_idx,
|
||||
true,
|
||||
&self.operand_stack[current_height - return_slots..],
|
||||
)
|
||||
.map_err(|(_, error)| self.value_trap(error, opcode, start_pc as u32))?;
|
||||
|
||||
// Copy return values (preserving order: pop return_slots values, then reverse to push back)
|
||||
let mut return_vals = BudgetVec::new(&self.budget, RuntimeResource::TemporaryBytes);
|
||||
return_vals
|
||||
.reserve(return_slots)
|
||||
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
||||
for _ in 0..return_slots {
|
||||
return_vals
|
||||
.push(self.pop().map_err(LogicalFrameEndingReason::Panic)?)
|
||||
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
||||
}
|
||||
return_vals.reverse();
|
||||
|
||||
self.call_stack.pop();
|
||||
self.operand_stack.truncate(frame.stack_base);
|
||||
for val in return_vals.drain(..) {
|
||||
self.push_trap(val, opcode, start_pc as u32)?;
|
||||
}
|
||||
self.pc = frame.return_pc as usize;
|
||||
if self.call_stack.is_empty() {
|
||||
self.handle_safepoint()
|
||||
.map_err(|e| self.resource_trap(e, opcode, start_pc as u32))?;
|
||||
}
|
||||
}
|
||||
OpCode::Ret => self.finish_return(opcode, start_pc as u32)?,
|
||||
OpCode::Syscall => {
|
||||
let pc_at_syscall = start_pc as u32;
|
||||
let id = instr
|
||||
@@ -1131,8 +1072,10 @@ impl VirtualMachine {
|
||||
}
|
||||
}
|
||||
|
||||
// Apply the instruction cost to the cycle counter
|
||||
self.cycles += opcode.cycles();
|
||||
// Control attempts were already charged before validation.
|
||||
if !charged_control {
|
||||
self.cycles += opcode.cycles();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ impl VirtualMachine {
|
||||
let base = end - p - 1;
|
||||
self.check_signature_group(target, false, &self.operand_stack[base..end - 1])
|
||||
.map_err(|(_, e)| self.value_trap(e, op, pc))?;
|
||||
self.install_callable_frame(target, base, Some(closure), 1, false, op, pc)?;
|
||||
self.install_callable_frame(target, base, Some(closure), false, op, pc)?;
|
||||
}
|
||||
OpCode::CallTrait => {
|
||||
let TypeKind::Trait(methods) = ®istry
|
||||
@@ -200,7 +200,7 @@ impl VirtualMachine {
|
||||
op,
|
||||
pc,
|
||||
)?;
|
||||
self.install_callable_frame(target, base, None, 1, true, op, pc)?;
|
||||
self.install_callable_frame(target, base, None, true, op, pc)?;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
@@ -253,7 +253,6 @@ impl VirtualMachine {
|
||||
target: usize,
|
||||
base: usize,
|
||||
closure: Option<HeapRef>,
|
||||
discard: usize,
|
||||
receiver_last: bool,
|
||||
op: OpCode,
|
||||
pc: u32,
|
||||
@@ -264,13 +263,14 @@ impl VirtualMachine {
|
||||
let code = function.code_offset as usize;
|
||||
let stack_growth = self
|
||||
.operand_stack
|
||||
.prepare_growth(locals.saturating_sub(discard))
|
||||
.prepare_growth(locals.saturating_sub(1))
|
||||
.map_err(|e| self.resource_trap(e, op, pc))?;
|
||||
let frame_growth =
|
||||
self.call_stack.prepare_growth(1).map_err(|e| self.resource_trap(e, op, pc))?;
|
||||
self.operand_stack.commit_growth(stack_growth);
|
||||
self.call_stack.commit_growth(frame_growth);
|
||||
self.operand_stack.truncate(self.operand_stack.len() - discard);
|
||||
// Both call forms discard one carrier: Fn or ImplementationId.
|
||||
self.operand_stack.truncate(self.operand_stack.len() - 1);
|
||||
if receiver_last {
|
||||
self.operand_stack[base..].rotate_right(1);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Function-local branches and validated return boundaries share one completion path.
|
||||
use super::*;
|
||||
|
||||
impl VirtualMachine {
|
||||
pub(super) fn jump_to(
|
||||
&mut self,
|
||||
target: usize,
|
||||
opcode: OpCode,
|
||||
pc: u32,
|
||||
) -> Result<(), LogicalFrameEndingReason> {
|
||||
let function = self.call_stack.last().map(|f| &self.program.functions[f.func_idx]);
|
||||
if self.validated_image.is_some() && function.is_some_and(|f| target == f.code_len as usize)
|
||||
{
|
||||
return self.finish_return(opcode, pc);
|
||||
}
|
||||
self.pc = function.map_or(0, |f| f.code_offset as usize) + target;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn finish_return(
|
||||
&mut self,
|
||||
opcode: OpCode,
|
||||
pc: u32,
|
||||
) -> Result<(), LogicalFrameEndingReason> {
|
||||
let frame = self.call_stack.last().cloned().ok_or_else(|| {
|
||||
self.trap(TRAP_STACK_UNDERFLOW, opcode as u16, "RET with empty call stack".into(), pc)
|
||||
})?;
|
||||
let func = &self.program.functions[frame.func_idx];
|
||||
let return_slots = func.return_slots as usize;
|
||||
|
||||
let current_height = self.operand_stack.len();
|
||||
let expected_height =
|
||||
frame.stack_base + func.param_slots as usize + func.local_slots as usize + return_slots;
|
||||
|
||||
if current_height != expected_height {
|
||||
return Err(self.trap(TRAP_BAD_RET_SLOTS, opcode as u16, format!(
|
||||
"Incorrect stack height at RET in func {}: expected {} slots (stack_base={} + params={} + locals={} + returns={}), got {}",
|
||||
frame.func_idx, expected_height, frame.stack_base, func.param_slots, func.local_slots, return_slots, current_height
|
||||
), pc));
|
||||
}
|
||||
|
||||
self.check_signature_group(
|
||||
frame.func_idx,
|
||||
true,
|
||||
&self.operand_stack[current_height - return_slots..],
|
||||
)
|
||||
.map_err(|(_, error)| self.value_trap(error, opcode, pc))?;
|
||||
|
||||
// Copy return values (preserving order: pop return_slots values, then reverse to push back)
|
||||
let mut return_vals = BudgetVec::new(&self.budget, RuntimeResource::TemporaryBytes);
|
||||
return_vals.reserve(return_slots).map_err(|e| self.resource_trap(e, opcode, pc))?;
|
||||
for _ in 0..return_slots {
|
||||
return_vals
|
||||
.push(self.pop().map_err(LogicalFrameEndingReason::Panic)?)
|
||||
.map_err(|e| self.resource_trap(e, opcode, pc))?;
|
||||
}
|
||||
return_vals.reverse();
|
||||
|
||||
self.call_stack.pop();
|
||||
self.operand_stack.truncate(frame.stack_base);
|
||||
for val in return_vals.drain(..) {
|
||||
self.push_trap(val, opcode, pc)?;
|
||||
}
|
||||
self.pc = frame.return_pc as usize;
|
||||
if self.call_stack.is_empty() {
|
||||
self.handle_safepoint().map_err(|e| self.resource_trap(e, opcode, pc))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -59,11 +59,8 @@ impl VirtualMachine {
|
||||
if self.validated_image.is_none() {
|
||||
return Err(VmInitError::EntrypointNotFound);
|
||||
}
|
||||
if self.validated_image.is_some() {
|
||||
if self
|
||||
.validated_image
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
if let Some(image) = &self.validated_image {
|
||||
if image
|
||||
.registry()
|
||||
.declarations()
|
||||
.functions
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
mod support {
|
||||
pub mod callables;
|
||||
}
|
||||
|
||||
use prometeu_bytecode::{Value, assemble, load_limits::*, registry::*};
|
||||
use prometeu_hal::{HostContext, syscalls::caps};
|
||||
use prometeu_test_support::program::{TestProgram, int64_signature};
|
||||
use prometeu_vm::{
|
||||
LogicalFrameEndingReason, ValidatedProgramImage, VirtualMachine, VmInitError,
|
||||
resource_budget::{RuntimeLimits, RuntimeResource},
|
||||
};
|
||||
use support::callables::{Native, image, run, sig, vm};
|
||||
|
||||
#[test]
|
||||
fn root_end_branch_returns_without_executing_neighbor_or_retaining_locals() {
|
||||
let mut machine =
|
||||
vm(&[("PUSH_I32 42\nJMP 12", sig(&[], &[0]), vec![]), ("HALT", sig(&[], &[]), vec![])]);
|
||||
let report = run(&mut machine, 100);
|
||||
assert_eq!(report.reason, LogicalFrameEndingReason::EndOfRom);
|
||||
assert_eq!(report.cycles_used, 4); // PUSH_I32 + JMP; no decoded RET.
|
||||
assert!(machine.call_stack_is_empty());
|
||||
assert_eq!(machine.operand_stack_top(10), vec![Value::Int32(42)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_branch_returns_to_caller_from_direct_closure_and_trait_calls() {
|
||||
let mut direct = vm(&[
|
||||
("CALL 1\nPUSH_I32 1\nADD\nRET", sig(&[], &[0]), vec![]),
|
||||
("PUSH_I32 41\nJMP 12", sig(&[], &[0]), vec![]),
|
||||
("HALT", sig(&[], &[]), vec![]),
|
||||
]);
|
||||
let mut closure = vm(&[
|
||||
("PUSH_I32 42\nMAKE_CLOSURE fn=1,type=4\nCALL_CLOSURE 4\nRET", sig(&[], &[0]), vec![]),
|
||||
("GET_CAPTURE 0\nJMP 12", sig(&[], &[0]), vec![TypeId(0)]),
|
||||
("HALT", sig(&[], &[]), vec![]),
|
||||
]);
|
||||
let trait_image = image(
|
||||
&[
|
||||
(
|
||||
"STRUCT_NEW 5\nREF_TO_TRAIT source=5,target=7\nCALL_TRAIT type=7,method=0\nRET",
|
||||
sig(&[], &[0]),
|
||||
vec![],
|
||||
),
|
||||
("PUSH_I32 42\nJMP 12", sig(&[5], &[0]), vec![]),
|
||||
("HALT", sig(&[], &[]), vec![]),
|
||||
],
|
||||
vec![ImplementationDecl {
|
||||
owner: TypeId(5),
|
||||
trait_id: TypeId(7),
|
||||
methods: vec![FunctionId(1)],
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
let mut trait_call = VirtualMachine::from_image(trait_image, Default::default());
|
||||
trait_call.prepare_boot_call().unwrap();
|
||||
for machine in [&mut direct, &mut closure, &mut trait_call] {
|
||||
assert_eq!(run(machine, 1000).reason, LogicalFrameEndingReason::EndOfRom);
|
||||
assert!(machine.call_stack_is_empty());
|
||||
assert_eq!(machine.operand_stack_top(10), vec![Value::Int32(42)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_end_branches_return_only_on_the_taken_edge() {
|
||||
for (op, taken) in [("JMP_IF_TRUE", true), ("JMP_IF_FALSE", false)] {
|
||||
for condition in [false, true] {
|
||||
let source = format!(
|
||||
"PUSH_I32 42\nPUSH_BOOL {}\n{op} 25\nPOP\nPUSH_I32 99\nRET",
|
||||
u8::from(condition)
|
||||
);
|
||||
let mut machine =
|
||||
vm(&[(&source, sig(&[], &[0]), vec![]), ("HALT", sig(&[], &[]), vec![])]);
|
||||
assert_eq!(run(&mut machine, 100).reason, LogicalFrameEndingReason::EndOfRom);
|
||||
assert!(machine.call_stack_is_empty());
|
||||
let expected = if condition == taken { 42 } else { 99 };
|
||||
assert_eq!(machine.operand_stack_top(10), vec![Value::Int32(expected)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_branch_preserves_multislot_results_and_frame_continuation() {
|
||||
let mut machine = vm(&[
|
||||
("CALL 1\nRET", sig(&[], &[2]), vec![]),
|
||||
(
|
||||
"FRAME_SYNC\nPUSH_F64 f64:0x3ff0000000000000\nPUSH_F64 f64:0x4000000000000000\nJMP 28",
|
||||
sig(&[], &[2]),
|
||||
vec![],
|
||||
),
|
||||
("HALT", sig(&[], &[]), vec![]),
|
||||
]);
|
||||
assert_eq!(run(&mut machine, 100).reason, LogicalFrameEndingReason::FrameSync);
|
||||
assert!(!machine.call_stack_is_empty());
|
||||
assert_eq!(run(&mut machine, 100).reason, LogicalFrameEndingReason::EndOfRom);
|
||||
assert!(machine.call_stack_is_empty());
|
||||
assert_eq!(machine.operand_stack_top(10), vec![Value::Float(2.), Value::Float(1.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_end_branch_roots_closure_result_before_safepoint_collection() {
|
||||
let mut source = "MAKE_CLOSURE fn=1,type=4\nPOP\n".repeat(1030);
|
||||
source.push_str("PUSH_I32 42\nMAKE_CLOSURE fn=2,type=4\n");
|
||||
let end = assemble(&source).unwrap().len() + 6;
|
||||
source.push_str(&format!("JMP {end}"));
|
||||
let mut machine = vm(&[
|
||||
(&source, sig(&[], &[4]), vec![]),
|
||||
("PUSH_I32 0\nRET", sig(&[], &[0]), vec![]),
|
||||
("GET_CAPTURE 0\nRET", sig(&[], &[0]), vec![TypeId(0)]),
|
||||
]);
|
||||
assert_eq!(run(&mut machine, 100_000).reason, LogicalFrameEndingReason::EndOfRom);
|
||||
assert!(machine.call_stack_is_empty());
|
||||
assert_eq!(machine.heap().len(), 1);
|
||||
let snapshot = machine.operand_stack_top(10);
|
||||
assert_eq!(snapshot.len(), 1);
|
||||
let Value::HeapRef(owner) = snapshot[0] else { panic!("expected closure result") };
|
||||
assert!(machine.heap().is_valid(owner));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_branches_reject_proven_bad_results_at_load() {
|
||||
for source in [
|
||||
"PUSH_BOOL 1\nJMP 9",
|
||||
"PUSH_BOOL 1\nPUSH_BOOL 1\nJMP_IF_TRUE 22\nPOP\nPUSH_I32 42\nRET",
|
||||
"PUSH_BOOL 1\nPUSH_BOOL 0\nJMP_IF_FALSE 22\nPOP\nPUSH_I32 42\nRET",
|
||||
] {
|
||||
assert!(matches!(
|
||||
image(&[(source, sig(&[], &[0]), vec![])], vec![]),
|
||||
Err(VmInitError::RegistryLoadFailed(e))
|
||||
if e.code == LoadCode::InvalidCode && e.reason == LoadReason::TypeMismatch
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_branch_checks_unknown_results_without_releasing_frame() {
|
||||
let mut machine = vm(&[
|
||||
("PUSH_BOOL 1\nSET_GLOBAL 0\nCALL 1\nRET", sig(&[], &[0]), vec![]),
|
||||
("GET_GLOBAL 0\nJMP 12", sig(&[], &[0]), vec![]),
|
||||
]);
|
||||
let report = run(&mut machine, 100);
|
||||
assert!(matches!(report.reason, LogicalFrameEndingReason::Trap(t)
|
||||
if t.code == prometeu_bytecode::TRAP_TYPE && t.opcode == 0x02 && t.pc == 23));
|
||||
assert!(!machine.call_stack_is_empty());
|
||||
assert_eq!(machine.operand_stack_top(1), vec![Value::Boolean(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_call_depth_refusal_is_charged_once_and_zero_budget_is_inert() {
|
||||
let image = image(&[("CALL 0\nRET", sig(&[], &[]), vec![])], vec![]).unwrap();
|
||||
let limits = RuntimeLimits::default().lowered(RuntimeResource::CallDepth, 1).unwrap();
|
||||
let mut machine = VirtualMachine::from_image(image, limits);
|
||||
machine.prepare_boot_call().unwrap();
|
||||
let pc = machine.pc();
|
||||
let zero = run(&mut machine, 0);
|
||||
assert_eq!((zero.cycles_used, zero.steps_executed), (0, 0));
|
||||
assert_eq!(machine.pc(), pc);
|
||||
let failed = run(&mut machine, 1);
|
||||
assert_eq!((failed.cycles_used, failed.steps_executed), (5, 0));
|
||||
assert!(matches!(failed.reason, LogicalFrameEndingReason::Trap(t)
|
||||
if t.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT && t.pc == pc as u32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_return_type_refusal_is_charged_once() {
|
||||
let mut machine = vm(&[("GET_GLOBAL 0\nRET", sig(&[], &[1]), vec![])]);
|
||||
assert_eq!(run(&mut machine, 1).steps_executed, 1);
|
||||
let report = run(&mut machine, 1);
|
||||
assert_eq!((report.cycles_used, report.steps_executed), (4, 0));
|
||||
assert!(matches!(report.reason, LogicalFrameEndingReason::Trap(t)
|
||||
if t.code == prometeu_bytecode::TRAP_TYPE && t.pc == 6));
|
||||
assert!(!machine.call_stack_is_empty());
|
||||
assert_eq!(machine.operand_stack_top(1), vec![Value::Int32(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_division_and_remainder_overflow_wrap_without_host_panic() {
|
||||
for (push, minimum, type_id) in [("PUSH_I32", i32::MIN as i64, 1), ("PUSH_I64", i64::MIN, 0)] {
|
||||
for (op, expected) in [("DIV", minimum), ("MOD", 0)] {
|
||||
let code = assemble(&format!("{push} {minimum}\n{push} -1\n{op}\nRET")).unwrap();
|
||||
let program = TestProgram::single(
|
||||
code,
|
||||
Signature { parameters: vec![], results: vec![TypeId(type_id)] },
|
||||
0,
|
||||
2,
|
||||
);
|
||||
let image = ValidatedProgramImage::load(
|
||||
&program.serialize(),
|
||||
&mut LoadBudget::new(Default::default()),
|
||||
caps::NONE,
|
||||
)
|
||||
.unwrap();
|
||||
let mut machine = VirtualMachine::from_image(image, Default::default());
|
||||
machine.prepare_boot_call().unwrap();
|
||||
assert_eq!(run(&mut machine, 100).reason, LogicalFrameEndingReason::EndOfRom);
|
||||
let value =
|
||||
if type_id == 1 { Value::Int32(expected as i32) } else { Value::Int64(expected) };
|
||||
assert_eq!(machine.operand_stack_top(1), vec![value]);
|
||||
}
|
||||
}
|
||||
// Promotion must happen before division: the Int32 minimum fits in Int64.
|
||||
for (source, expected) in [
|
||||
("PUSH_I32 -2147483648\nPUSH_I64 -1\nDIV\nRET", 2_147_483_648),
|
||||
("PUSH_I64 -9223372036854775808\nPUSH_I32 -1\nDIV\nRET", i64::MIN),
|
||||
] {
|
||||
let program = TestProgram::single(assemble(source).unwrap(), int64_signature(0, 1), 0, 2);
|
||||
let image = ValidatedProgramImage::load(
|
||||
&program.serialize(),
|
||||
&mut LoadBudget::new(Default::default()),
|
||||
caps::NONE,
|
||||
)
|
||||
.unwrap();
|
||||
let mut machine = VirtualMachine::from_image(image, Default::default());
|
||||
machine.prepare_boot_call().unwrap();
|
||||
let report = machine.run_budget(100, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(report.reason, LogicalFrameEndingReason::EndOfRom);
|
||||
assert_eq!(machine.operand_stack_top(1), vec![Value::Int64(expected)]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user