This commit is contained in:
2026-03-24 13:40:42 +00:00
parent 78ed7a8253
commit 6950f2bef0
22 changed files with 428 additions and 289 deletions
@@ -37,7 +37,7 @@ pub enum LogicalFrameEndingReason {
Panic(String),
}
pub enum OpError {
pub(crate) enum OpError {
Trap(u32, String),
Panic(String),
}
@@ -61,34 +61,34 @@ pub struct BudgetReport {
pub struct VirtualMachine {
/// Program Counter (PC): The absolute byte offset in ROM for the next instruction.
pub pc: usize,
pc: usize,
/// Operand Stack: The primary workspace for all mathematical and logical operations.
pub operand_stack: Vec<Value>,
operand_stack: Vec<Value>,
/// Call Stack: Manages function call context (return addresses, frame limits).
pub call_stack: Vec<CallFrame>,
call_stack: Vec<CallFrame>,
/// Global Variable Store: Variables that persist for the lifetime of the program.
pub globals: Vec<Value>,
globals: Vec<Value>,
/// The loaded executable (Bytecode + Constant Pool), that is the ROM translated.
pub program: ProgramImage,
program: ProgramImage,
/// Heap Memory: Dynamic allocation pool.
pub heap: Heap,
heap: Heap,
/// Total virtual cycles consumed since the VM started.
pub cycles: u64,
cycles: u64,
/// Stop flag: true if a `HALT` opcode was encountered.
pub halted: bool,
halted: bool,
/// Set of ROM addresses used for software breakpoints in the debugger.
pub breakpoints: std::collections::HashSet<usize>,
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.
pub gc_alloc_threshold: usize,
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`.
pub capabilities: prometeu_hal::syscalls::CapFlags,
capabilities: prometeu_hal::syscalls::CapFlags,
/// Cooperative scheduler: set to true when `YIELD` opcode is executed.
/// The runtime/scheduler should only act on this at safepoints (FRAME_SYNC).
pub yield_requested: bool,
yield_requested: bool,
/// Absolute wake tick requested by the currently running coroutine (when it executes `SLEEP`).
///
/// Canonical rule (authoritative):
@@ -99,13 +99,13 @@ pub struct VirtualMachine {
/// `SLEEP` executes. The scheduler wakes sleeping coroutines when `current_tick >= wake_tick`.
///
/// This definition is deterministic and eliminates off-by-one ambiguity.
pub sleep_requested_until: Option<u64>,
sleep_requested_until: Option<u64>,
/// Logical tick counter advanced at each FRAME_SYNC boundary.
pub current_tick: u64,
current_tick: u64,
/// Cooperative scheduler instance managing ready/sleeping queues.
pub scheduler: Scheduler,
scheduler: Scheduler,
/// Handle to the currently running coroutine (owns the active VM context).
pub current_coro: Option<HeapRef>,
current_coro: Option<HeapRef>,
}
@@ -116,6 +116,34 @@ impl Default for VirtualMachine {
}
impl VirtualMachine {
/// 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) -> Vec<Value> {
let len = self.operand_stack.len();
let start = len.saturating_sub(n);
self.operand_stack[start..].iter().rev().cloned().collect()
}
/// 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); }
/// Creates a new VM instance with the provided bytecode and constants.
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>) -> Self {
Self {
@@ -175,7 +203,7 @@ impl VirtualMachine {
Ok(module) => {
// Run verifier on the module
let max_stacks = Verifier::verify(&module.code, &module.functions)
.map_err(VmInitError::VerificationFailed)?;
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
let mut program = ProgramImage::from(module);
@@ -1457,30 +1485,30 @@ impl VirtualMachine {
self.yield_requested = false;
}
/// Save the currently running VM execution context back into its coroutine object.
/// Must be called only at safepoints.
fn save_current_context_into_coroutine(&mut self) {
if let Some(cur) = self.current_coro {
if let Some(co) = self.heap.coroutine_data_mut(cur) {
co.pc = self.pc;
co.stack = std::mem::take(&mut self.operand_stack);
co.frames = std::mem::take(&mut self.call_stack);
}
}
}
// /// Save the currently running VM execution context back into its coroutine object.
// /// Must be called only at safepoints.
// fn save_current_context_into_coroutine(&mut self) {
// if let Some(cur) = self.current_coro {
// if let Some(co) = self.heap.coroutine_data_mut(cur) {
// co.pc = self.pc;
// co.stack = std::mem::take(&mut self.operand_stack);
// co.frames = std::mem::take(&mut self.call_stack);
// }
// }
// }
/// Load a coroutine context from heap into the VM runtime state.
/// Must be called only at safepoints.
fn load_coroutine_context_into_vm(&mut self, coro: HeapRef) {
if let Some(co) = self.heap.coroutine_data_mut(coro) {
self.pc = co.pc;
self.operand_stack = std::mem::take(&mut co.stack);
self.call_stack = std::mem::take(&mut co.frames);
co.state = CoroutineState::Running;
}
self.current_coro = Some(coro);
self.scheduler.set_current(self.current_coro);
}
// /// Load a coroutine context from heap into the VM runtime state.
// /// Must be called only at safepoints.
// fn load_coroutine_context_into_vm(&mut self, coro: HeapRef) {
// if let Some(co) = self.heap.coroutine_data_mut(coro) {
// self.pc = co.pc;
// self.operand_stack = std::mem::take(&mut co.stack);
// self.call_stack = std::mem::take(&mut co.frames);
// co.state = CoroutineState::Running;
// }
// self.current_coro = Some(coro);
// self.scheduler.set_current(self.current_coro);
// }
pub fn trap(
&self,
@@ -1818,34 +1846,34 @@ mod tests {
assert!(after_first <= before);
assert_eq!(after_second, after_first);
}
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));
}
// 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() {