From 2e041266f1b0caa89ef5c0eaa52d863247079ba7 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Fri, 9 Oct 2026 06:35:51 +0100 Subject: [PATCH] fix(vm): enforce return boundaries and amortize budgeted growth 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. --- .../prometeu-bytecode/tests/registry_isa.rs | 26 ++- .../src/registry_verifier/types.rs | 62 ++--- .../prometeu-vm/src/resource_budget.rs | 63 ++++- .../prometeu-vm/src/virtual_machine.rs | 105 ++------- .../src/virtual_machine/callable.rs | 10 +- .../src/virtual_machine/control.rs | 70 ++++++ .../prometeu-vm/src/virtual_machine/loader.rs | 7 +- .../tests/execution_regressions.rs | 218 ++++++++++++++++++ .../02c-program-registry-and-pbx-v1.md | 2 + docs/vm-arch/ISA_CORE.md | 3 +- 10 files changed, 430 insertions(+), 136 deletions(-) create mode 100644 crates/console/prometeu-vm/src/virtual_machine/control.rs create mode 100644 crates/console/prometeu-vm/tests/execution_regressions.rs diff --git a/crates/console/prometeu-bytecode/tests/registry_isa.rs b/crates/console/prometeu-bytecode/tests/registry_isa.rs index f996f67..94d28b8 100644 --- a/crates/console/prometeu-bytecode/tests/registry_isa.rs +++ b/crates/console/prometeu-bytecode/tests/registry_isa.rs @@ -162,18 +162,20 @@ fn collection_literal_encodings_roundtrip_and_reject_every_truncation() { } #[test] fn collection_effects_and_cached_initialization_width_are_exact() { - let mut d = RegistryDeclarations::default(); - d.types = vec![ - TypeDecl { name: None, kind: TypeKind::Builtin(BuiltinId::PIXEL) }, - TypeDecl { - name: None, - kind: TypeKind::Struct(vec![ - NamedType { type_id: TypeId(0), name: None }, - NamedType { type_id: TypeId(1), name: None }, - ]), - }, - TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }, - ]; + let d = RegistryDeclarations { + types: vec![ + TypeDecl { name: None, kind: TypeKind::Builtin(BuiltinId::PIXEL) }, + TypeDecl { + name: None, + kind: TypeKind::Struct(vec![ + NamedType { type_id: TypeId(0), name: None }, + NamedType { type_id: TypeId(1), name: None }, + ]), + }, + TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }, + ], + ..Default::default() + }; let r = Registry::resolve(d, 0, &mut LoadBudget::new(Default::default())).unwrap(); assert_eq!( r.type_layout(TypeId(1)).unwrap().instance.as_ref().unwrap().initialization_slots, diff --git a/crates/console/prometeu-vm/src/registry_verifier/types.rs b/crates/console/prometeu-vm/src/registry_verifier/types.rs index 53b9e9e..8722c85 100644 --- a/crates/console/prometeu-vm/src/registry_verifier/types.rs +++ b/crates/console/prometeu-vm/src/registry_verifier/types.rs @@ -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::(body, budget, at_pc)?; let mut initial = scratch::(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; diff --git a/crates/console/prometeu-vm/src/resource_budget.rs b/crates/console/prometeu-vm/src/resource_budget.rs index be40e95..ccbe29c 100644 --- a/crates/console/prometeu-vm/src/resource_budget.rs +++ b/crates/console/prometeu-vm/src/resource_budget.rs @@ -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::::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::>()); + assert_eq!(budget.used(AuxiliaryBytes), (values.capacity() * size_of::()) 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::::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 BudgetVec { if required <= self.data.capacity() { return Ok(None); } - let bytes = b.bytes::(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, ResourceFailure> { + let b = &self.charge.budget; + let q = self.charge.resource; + let bytes = b.bytes::(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::(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>) { if let Some(mut growth) = growth { diff --git a/crates/console/prometeu-vm/src/virtual_machine.rs b/crates/console/prometeu-vm/src/virtual_machine.rs index 15980b6..9729ef9 100644 --- a/crates/console/prometeu-vm/src/virtual_machine.rs +++ b/crates/console/prometeu-vm/src/virtual_machine.rs @@ -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(()) } } diff --git a/crates/console/prometeu-vm/src/virtual_machine/callable.rs b/crates/console/prometeu-vm/src/virtual_machine/callable.rs index b94ac59..94aa2a0 100644 --- a/crates/console/prometeu-vm/src/virtual_machine/callable.rs +++ b/crates/console/prometeu-vm/src/virtual_machine/callable.rs @@ -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, - 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); } diff --git a/crates/console/prometeu-vm/src/virtual_machine/control.rs b/crates/console/prometeu-vm/src/virtual_machine/control.rs new file mode 100644 index 0000000..5111cf0 --- /dev/null +++ b/crates/console/prometeu-vm/src/virtual_machine/control.rs @@ -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(()) + } +} diff --git a/crates/console/prometeu-vm/src/virtual_machine/loader.rs b/crates/console/prometeu-vm/src/virtual_machine/loader.rs index 886cbf1..f4001f1 100644 --- a/crates/console/prometeu-vm/src/virtual_machine/loader.rs +++ b/crates/console/prometeu-vm/src/virtual_machine/loader.rs @@ -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 diff --git a/crates/console/prometeu-vm/tests/execution_regressions.rs b/crates/console/prometeu-vm/tests/execution_regressions.rs new file mode 100644 index 0000000..2a09a2a --- /dev/null +++ b/crates/console/prometeu-vm/tests/execution_regressions.rs @@ -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)]); + } +} diff --git a/docs/specs/runtime/02c-program-registry-and-pbx-v1.md b/docs/specs/runtime/02c-program-registry-and-pbx-v1.md index 53790ef..00fac6a 100644 --- a/docs/specs/runtime/02c-program-registry-and-pbx-v1.md +++ b/docs/specs/runtime/02c-program-registry-and-pbx-v1.md @@ -144,6 +144,8 @@ Derive P=sum(parameter widths), L=local_slots and R=sum(result widths). A frame RET requires exactly R temporaries, validates ordered types, releases frame owners and returns R slots. Wrong height uses TRAP_BAD_RET_SLOTS; unproved runtime type mismatch uses TRAP_TYPE. Locals begin as Value::Null, not numeric defaults or Uninitialized. Parameter/local slots can be reused after entry; SET_LOCAL updates abstract knowledge. Definite assignment/source variable types remain frontend concerns. Do not introduce silent Int32/Int64, concrete/trait or concrete/Dynamic conversions at boundaries. +A taken branch to the current function's end completes the same return boundary: validate R ordered result slots, release the frame, resume its caller and retain root results before threshold GC. Conditional branches consume their Boolean before checking the returning edge. The verifier checks proven result types on these edges after convergence; Unknown retains runtime validation. No function-end branch may enter adjacent code. Charge the decoded branch once, with no additional RET instruction or charge; direct CALL and RET attempts retain their fixed charges even when runtime validation or resource admission refuses them. + Verifier decodes every function range, validates instruction boundaries/IDs/jump destinations, and analyzes structurally reachable control flow. Track temporary height and local/temporary facts in a finite domain: Unknown, known null, carrier facts and proven semantic/multi-slot groups. Initial parameters follow signatures; other locals start null. GET copies facts; SET replaces. Equal facts survive joins; conflicting facts become Unknown, while unequal heights are rejected. Do not require one permanent local type or infer unbounded unions/branch conditions. Use a bounded worklist to fixed point, reprocessing widened states; decide state-dependent type errors after convergence so visitation order cannot cause rejection. Signature contracts suffice for calls; no interprocedural body inference is required. Partial group mutation invalidates relational facts. Unknown is not proof of compatibility and does not alone reject code: retain complete runtime checks. Type knowledge alone does not eliminate null/generation/bounds checks. CALL_CLOSURE derives ordered parameter/result groups from its expected FnTypeId, including unknown concrete targets; known mismatches reject, unknown values retain runtime checks. Exceeding memory/work budget rejects loading, never skips verification. diff --git a/docs/vm-arch/ISA_CORE.md b/docs/vm-arch/ISA_CORE.md index 4a2340e..d25de19 100644 --- a/docs/vm-arch/ISA_CORE.md +++ b/docs/vm-arch/ISA_CORE.md @@ -51,6 +51,7 @@ Authority rule: - Arithmetic: - `ADD`, `SUB`, `MUL`, `DIV`, `MOD` — binary numeric ops. - `NEG` — unary numeric negation. + - Integer arithmetic wraps at the resulting carrier width. For `DIV`, the signed minimum divided by `-1` returns that minimum; for `MOD`, the same operands return zero. Division or modulo by zero still traps. Mixed Int32/Int64 division promotes to Int64 before the operation. - Comparison and logic: - `EQ`, `NEQ`, `LT`, `LTE`, `GT`, `GTE` — comparisons → `[bool]`. @@ -142,7 +143,7 @@ For exact immediates and stack effects, see `CoreOpCode::spec()` which is the si - Tools MAY optionally annotate it as a safepoint in comments, e.g., `FRAME_SYNC ; safepoint`. - Verification notes: - - The bytecode verifier treats `FRAME_SYNC` as a normal instruction with no stack effect and no control-flow targets. It is permitted before `RET`, between basic blocks, and as the last instruction of a function. Jumps targeting the function end (`pc == end`) remain valid under the end-exclusive rule. + - The bytecode verifier treats `FRAME_SYNC` as a normal instruction with no stack effect and no control-flow targets. It is permitted before `RET` and between basic blocks; a reachable path must still terminate explicitly rather than fall through the function range. Jumps targeting the function end (`pc == end`) remain valid under the end-exclusive rule. A taken end branch completes the current call with the same result-height/type checks, frame release and root-return safepoint as `RET`. It consumes only the decoded branch's cycles, without an additional implicit `RET` charge, and never executes the neighboring function or range gap. ## Registry instruction encodings