pr 00.2
This commit is contained in:
@@ -7,6 +7,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
prometeu-vm = { path = "../prometeu-vm" }
|
||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||
prometeu-abi = { path = "../prometeu-abi" }
|
||||
prometeu-hardware-contract = { path = "../prometeu-hardware-contract" }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use prometeu_vm::VirtualMachine;
|
||||
use crate::firmware::boot_target::BootTarget;
|
||||
use crate::firmware::firmware_state::{FirmwareState, LoadCartridgeStep, ResetStep};
|
||||
use crate::firmware::prometeu_context::PrometeuContext;
|
||||
@@ -5,7 +6,6 @@ use crate::hardware::{HardwareBridge, InputSignals};
|
||||
use crate::model::Cartridge;
|
||||
use crate::prometeu_hub::PrometeuHub;
|
||||
use crate::prometeu_os::PrometeuOS;
|
||||
use crate::virtual_machine::VirtualMachine;
|
||||
|
||||
use crate::telemetry::CertificationConfig;
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use prometeu_vm::VirtualMachine;
|
||||
use crate::firmware::boot_target::BootTarget;
|
||||
use crate::hardware::{HardwareBridge, InputSignals};
|
||||
use crate::prometeu_hub::PrometeuHub;
|
||||
use crate::prometeu_os::PrometeuOS;
|
||||
use crate::virtual_machine::VirtualMachine;
|
||||
|
||||
pub struct PrometeuContext<'a> {
|
||||
pub vm: &'a mut VirtualMachine,
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
//! The "Source of Truth" for the console's behavior lives here.
|
||||
|
||||
pub mod hardware;
|
||||
pub mod virtual_machine;
|
||||
pub mod firmware;
|
||||
pub mod fs;
|
||||
pub mod prometeu_os;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
mod prometeu_os;
|
||||
|
||||
use crate::virtual_machine::NativeInterface;
|
||||
pub use prometeu_os::PrometeuOS;
|
||||
|
||||
@@ -3,12 +3,12 @@ use crate::fs::{FsBackend, FsState, VirtualFS};
|
||||
use crate::hardware::{HardwareBridge, InputSignals};
|
||||
use crate::log::{LogLevel, LogService, LogSource};
|
||||
use crate::model::{BankType, Cartridge, Color};
|
||||
use crate::prometeu_os::NativeInterface;
|
||||
use crate::telemetry::{CertificationConfig, Certifier, TelemetryFrame};
|
||||
use crate::virtual_machine::{HostContext, HostReturn, SyscallId, Value, VirtualMachine, VmFault};
|
||||
use std::collections::HashMap;
|
||||
use std::time::Instant;
|
||||
use prometeu_hardware_contract::{expect_bool, expect_int};
|
||||
use prometeu_abi::virtual_machine::{Value, VmFault};
|
||||
use prometeu_hardware_contract::{expect_bool, expect_int, HostContext, HostReturn, NativeInterface, SyscallId};
|
||||
use prometeu_vm::{LogicalFrameEndingReason, VirtualMachine};
|
||||
|
||||
/// PrometeuOS (POS): The central system firmware and resource manager.
|
||||
///
|
||||
@@ -251,22 +251,22 @@ impl PrometeuOS {
|
||||
self.telemetry_current.vm_steps += run.steps_executed;
|
||||
|
||||
// Handle Breakpoints
|
||||
if run.reason == crate::virtual_machine::LogicalFrameEndingReason::Breakpoint {
|
||||
if run.reason == LogicalFrameEndingReason::Breakpoint {
|
||||
self.paused = true;
|
||||
self.debug_step_request = false;
|
||||
self.log(LogLevel::Info, LogSource::Vm, 0xDEB1, format!("Breakpoint hit at PC 0x{:X}", vm.pc));
|
||||
}
|
||||
|
||||
// Handle Panics
|
||||
if let crate::virtual_machine::LogicalFrameEndingReason::Panic(err) = run.reason {
|
||||
if let LogicalFrameEndingReason::Panic(err) = run.reason {
|
||||
let err_msg = format!("PVM Fault: \"{}\"", err);
|
||||
self.log(LogLevel::Error, LogSource::Vm, 0, err_msg.clone());
|
||||
return Some(err_msg);
|
||||
}
|
||||
|
||||
// 4. Frame Finalization (FRAME_SYNC reached or Entrypoint returned)
|
||||
if run.reason == crate::virtual_machine::LogicalFrameEndingReason::FrameSync ||
|
||||
run.reason == crate::virtual_machine::LogicalFrameEndingReason::EndOfRom {
|
||||
if run.reason == LogicalFrameEndingReason::FrameSync ||
|
||||
run.reason == LogicalFrameEndingReason::EndOfRom {
|
||||
// All drawing commands for this frame are now complete.
|
||||
// Finalize the framebuffer.
|
||||
hw.gfx_mut().render_all();
|
||||
@@ -415,10 +415,11 @@ impl PrometeuOS {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use prometeu_abi::virtual_machine::Value;
|
||||
use prometeu_hardware_contract::HostReturn;
|
||||
use super::*;
|
||||
use crate::hardware::InputSignals;
|
||||
use crate::model::{AppMode, Cartridge};
|
||||
use crate::virtual_machine::{Value, VirtualMachine};
|
||||
use crate::Hardware;
|
||||
|
||||
fn call_syscall(os: &mut PrometeuOS, id: u32, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Result<(), VmFault> {
|
||||
@@ -768,7 +769,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_gfx_clear565_syscall() {
|
||||
let mut hw = crate::Hardware::new();
|
||||
let mut hw = Hardware::new();
|
||||
let mut os = PrometeuOS::new(None);
|
||||
let mut stack = Vec::new();
|
||||
|
||||
@@ -795,7 +796,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_input_snapshots_syscalls() {
|
||||
let mut hw = crate::Hardware::new();
|
||||
let mut hw = Hardware::new();
|
||||
let mut os = PrometeuOS::new(None);
|
||||
|
||||
// Pad snapshot
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
use crate::virtual_machine::opcode_spec::{OpCodeSpecExt, OpcodeSpec};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DecodeError {
|
||||
TruncatedOpcode { pc: usize },
|
||||
UnknownOpcode { pc: usize, opcode: u16 },
|
||||
TruncatedImmediate { pc: usize, opcode: OpCode, need: usize, have: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DecodedInstr<'a> {
|
||||
pub opcode: OpCode,
|
||||
pub spec: OpcodeSpec,
|
||||
pub imm: &'a [u8],
|
||||
pub next_pc: usize,
|
||||
}
|
||||
|
||||
pub fn decode_at(rom: &[u8], pc: usize) -> Result<DecodedInstr<'_>, DecodeError> {
|
||||
if pc + 2 > rom.len() {
|
||||
return Err(DecodeError::TruncatedOpcode { pc });
|
||||
}
|
||||
let opcode_val = u16::from_le_bytes([rom[pc], rom[pc+1]]);
|
||||
let opcode = OpCode::try_from(opcode_val).map_err(|_| DecodeError::UnknownOpcode { pc, opcode: opcode_val })?;
|
||||
let spec = opcode.spec();
|
||||
|
||||
let imm_start = pc + 2;
|
||||
let imm_end = imm_start + spec.imm_bytes as usize;
|
||||
|
||||
if imm_end > rom.len() {
|
||||
return Err(DecodeError::TruncatedImmediate {
|
||||
pc,
|
||||
opcode,
|
||||
need: spec.imm_bytes as usize,
|
||||
have: rom.len().saturating_sub(imm_start)
|
||||
});
|
||||
}
|
||||
|
||||
let imm = &rom[imm_start..imm_end];
|
||||
|
||||
Ok(DecodedInstr {
|
||||
opcode,
|
||||
spec,
|
||||
imm,
|
||||
next_pc: imm_end,
|
||||
})
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
pub mod decoder;
|
||||
@@ -1,5 +0,0 @@
|
||||
pub struct CallFrame {
|
||||
pub return_pc: u32,
|
||||
pub stack_base: usize,
|
||||
pub func_idx: usize,
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
use crate::virtual_machine::call_frame::CallFrame;
|
||||
use prometeu_bytecode::abi::{TrapInfo, TRAP_INVALID_LOCAL};
|
||||
use prometeu_bytecode::FunctionMeta;
|
||||
|
||||
/// Computes the absolute stack index for the start of the current frame's locals (including args).
|
||||
pub fn local_base(frame: &CallFrame) -> usize {
|
||||
frame.stack_base
|
||||
}
|
||||
|
||||
/// Computes the absolute stack index for a given local slot.
|
||||
pub fn local_index(frame: &CallFrame, slot: u32) -> usize {
|
||||
frame.stack_base + slot as usize
|
||||
}
|
||||
|
||||
/// Validates that a local slot index is within the valid range for the function.
|
||||
/// Range: 0 <= slot < (param_slots + local_slots)
|
||||
pub fn check_local_slot(meta: &FunctionMeta, slot: u32, opcode: u16, pc: u32) -> Result<(), TrapInfo> {
|
||||
let limit = meta.param_slots as u32 + meta.local_slots as u32;
|
||||
if slot < limit {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(TrapInfo {
|
||||
code: TRAP_INVALID_LOCAL,
|
||||
opcode,
|
||||
message: format!("Local slot {} out of bounds for function (limit {})", slot, limit),
|
||||
pc,
|
||||
span: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
mod virtual_machine;
|
||||
mod call_frame;
|
||||
mod scope_frame;
|
||||
mod program;
|
||||
pub mod local_addressing;
|
||||
pub mod opcode_spec;
|
||||
pub mod bytecode;
|
||||
pub mod verifier;
|
||||
|
||||
pub use program::ProgramImage;
|
||||
pub use prometeu_abi::virtual_machine::{Value, VmFault};
|
||||
pub use prometeu_bytecode::abi::TrapInfo;
|
||||
pub use prometeu_bytecode::opcode::OpCode;
|
||||
pub use prometeu_hardware_contract::{
|
||||
HostContext, HostReturn, NativeInterface, SyscallId,
|
||||
};
|
||||
pub type VmInitError = prometeu_abi::virtual_machine::VmInitError<VerifierError>;
|
||||
pub use verifier::VerifierError;
|
||||
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
|
||||
@@ -1,84 +0,0 @@
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
|
||||
/// Specification for a single OpCode.
|
||||
/// All JMP/JMP_IF_* immediate are u32 absolute offsets from function start.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct OpcodeSpec {
|
||||
pub name: &'static str,
|
||||
pub imm_bytes: u8, // immediate payload size (decode)
|
||||
pub pops: u16, // slots popped
|
||||
pub pushes: u16, // slots pushed
|
||||
pub is_branch: bool, // has a control-flow target
|
||||
pub is_terminator: bool, // ends basic block: JMP/RET/TRAP/HALT
|
||||
pub may_trap: bool, // runtime trap possible
|
||||
}
|
||||
|
||||
pub trait OpCodeSpecExt {
|
||||
fn spec(&self) -> OpcodeSpec;
|
||||
}
|
||||
|
||||
impl OpCodeSpecExt for OpCode {
|
||||
fn spec(&self) -> OpcodeSpec {
|
||||
match self {
|
||||
OpCode::Nop => OpcodeSpec { name: "NOP", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Halt => OpcodeSpec { name: "HALT", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: true, may_trap: false },
|
||||
OpCode::Jmp => OpcodeSpec { name: "JMP", imm_bytes: 4, pops: 0, pushes: 0, is_branch: true, is_terminator: true, may_trap: false },
|
||||
OpCode::JmpIfFalse => OpcodeSpec { name: "JMP_IF_FALSE", imm_bytes: 4, pops: 1, pushes: 0, is_branch: true, is_terminator: false, may_trap: true },
|
||||
OpCode::JmpIfTrue => OpcodeSpec { name: "JMP_IF_TRUE", imm_bytes: 4, pops: 1, pushes: 0, is_branch: true, is_terminator: false, may_trap: true },
|
||||
OpCode::Trap => OpcodeSpec { name: "TRAP", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: true, may_trap: true },
|
||||
OpCode::PushConst => OpcodeSpec { name: "PUSH_CONST", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Pop => OpcodeSpec { name: "POP", imm_bytes: 0, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PopN => OpcodeSpec { name: "POP_N", imm_bytes: 4, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Dup => OpcodeSpec { name: "DUP", imm_bytes: 0, pops: 1, pushes: 2, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Swap => OpcodeSpec { name: "SWAP", imm_bytes: 0, pops: 2, pushes: 2, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushI64 => OpcodeSpec { name: "PUSH_I64", imm_bytes: 8, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushF64 => OpcodeSpec { name: "PUSH_F64", imm_bytes: 8, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushBool => OpcodeSpec { name: "PUSH_BOOL", imm_bytes: 1, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushI32 => OpcodeSpec { name: "PUSH_I32", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushBounded => OpcodeSpec { name: "PUSH_BOUNDED", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Add => OpcodeSpec { name: "ADD", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Sub => OpcodeSpec { name: "SUB", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Mul => OpcodeSpec { name: "MUL", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Div => OpcodeSpec { name: "DIV", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Mod => OpcodeSpec { name: "MOD", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::BoundToInt => OpcodeSpec { name: "BOUND_TO_INT", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::IntToBoundChecked => OpcodeSpec { name: "INT_TO_BOUND_CHECKED", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Eq => OpcodeSpec { name: "EQ", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Neq => OpcodeSpec { name: "NEQ", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Lt => OpcodeSpec { name: "LT", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Gt => OpcodeSpec { name: "GT", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::And => OpcodeSpec { name: "AND", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Or => OpcodeSpec { name: "OR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Not => OpcodeSpec { name: "NOT", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::BitAnd => OpcodeSpec { name: "BIT_AND", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::BitOr => OpcodeSpec { name: "BIT_OR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::BitXor => OpcodeSpec { name: "BIT_XOR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Shl => OpcodeSpec { name: "SHL", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Shr => OpcodeSpec { name: "SHR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Lte => OpcodeSpec { name: "LTE", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Gte => OpcodeSpec { name: "GTE", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Neg => OpcodeSpec { name: "NEG", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::GetGlobal => OpcodeSpec { name: "GET_GLOBAL", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::SetGlobal => OpcodeSpec { name: "SET_GLOBAL", imm_bytes: 4, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::GetLocal => OpcodeSpec { name: "GET_LOCAL", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::SetLocal => OpcodeSpec { name: "SET_LOCAL", imm_bytes: 4, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Call => OpcodeSpec { name: "CALL", imm_bytes: 4, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Ret => OpcodeSpec { name: "RET", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: true, may_trap: false },
|
||||
OpCode::PushScope => OpcodeSpec { name: "PUSH_SCOPE", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PopScope => OpcodeSpec { name: "POP_SCOPE", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Alloc => OpcodeSpec { name: "ALLOC", imm_bytes: 8, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateLoad => OpcodeSpec { name: "GATE_LOAD", imm_bytes: 4, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateStore => OpcodeSpec { name: "GATE_STORE", imm_bytes: 4, pops: 2, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateBeginPeek => OpcodeSpec { name: "GATE_BEGIN_PEEK", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateEndPeek => OpcodeSpec { name: "GATE_END_PEEK", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateBeginBorrow => OpcodeSpec { name: "GATE_BEGIN_BORROW", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateEndBorrow => OpcodeSpec { name: "GATE_END_BORROW", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateBeginMutate => OpcodeSpec { name: "GATE_BEGIN_MUTATE", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateEndMutate => OpcodeSpec { name: "GATE_END_MUTATE", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateRetain => OpcodeSpec { name: "GATE_RETAIN", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateRelease => OpcodeSpec { name: "GATE_RELEASE", imm_bytes: 0, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Syscall => OpcodeSpec { name: "SYSCALL", imm_bytes: 4, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::FrameSync => OpcodeSpec { name: "FRAME_SYNC", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
use crate::virtual_machine::Value;
|
||||
use prometeu_bytecode::abi::TrapInfo;
|
||||
use prometeu_bytecode::{BytecodeModule, ConstantPoolEntry, DebugInfo, Export, FunctionMeta};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Represents a fully linked, executable PBS program image.
|
||||
///
|
||||
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
||||
/// produced by the compiler. All linking, relocation, and symbol resolution
|
||||
/// MUST be performed by the compiler before this image is created.
|
||||
///
|
||||
/// The runtime (VM) assumes this image is authoritative and performs no
|
||||
/// additional linking or fixups.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ProgramImage {
|
||||
pub rom: Arc<[u8]>,
|
||||
pub constant_pool: Arc<[Value]>,
|
||||
pub functions: Arc<[FunctionMeta]>,
|
||||
pub debug_info: Option<DebugInfo>,
|
||||
pub exports: Arc<HashMap<String, u32>>,
|
||||
}
|
||||
|
||||
impl ProgramImage {
|
||||
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>, functions: Vec<FunctionMeta>, debug_info: Option<DebugInfo>, exports: HashMap<String, u32>) -> Self {
|
||||
Self {
|
||||
rom: Arc::from(rom),
|
||||
constant_pool: Arc::from(constant_pool),
|
||||
functions: Arc::from(functions),
|
||||
debug_info,
|
||||
exports: Arc::new(exports),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_trap(&self, code: u32, opcode: u16, mut message: String, pc: u32) -> TrapInfo {
|
||||
let span = self.debug_info.as_ref().and_then(|di| {
|
||||
di.pc_to_span.iter().find(|(p, _)| *p == pc).map(|(_, s)| s.clone())
|
||||
});
|
||||
|
||||
if let Some(func_idx) = self.find_function_index(pc) {
|
||||
if let Some(func_name) = self.get_function_name(func_idx) {
|
||||
message = format!("{} (in function {})", message, func_name);
|
||||
}
|
||||
}
|
||||
|
||||
TrapInfo {
|
||||
code,
|
||||
opcode,
|
||||
message,
|
||||
pc,
|
||||
span,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_function_index(&self, pc: u32) -> Option<usize> {
|
||||
self.functions.iter().position(|f| {
|
||||
pc >= f.code_offset && pc < (f.code_offset + f.code_len)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_function_name(&self, func_idx: usize) -> Option<&str> {
|
||||
self.debug_info.as_ref()
|
||||
.and_then(|di| di.function_names.iter().find(|(idx, _)| *idx as usize == func_idx))
|
||||
.map(|(_, name)| name.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BytecodeModule> for ProgramImage {
|
||||
fn from(module: BytecodeModule) -> Self {
|
||||
let constant_pool: Vec<Value> = module.const_pool.iter().map(|entry| {
|
||||
match entry {
|
||||
ConstantPoolEntry::Null => Value::Null,
|
||||
ConstantPoolEntry::Int64(v) => Value::Int64(*v),
|
||||
ConstantPoolEntry::Float64(v) => Value::Float(*v),
|
||||
ConstantPoolEntry::Boolean(v) => Value::Boolean(*v),
|
||||
ConstantPoolEntry::String(v) => Value::String(v.clone()),
|
||||
ConstantPoolEntry::Int32(v) => Value::Int32(*v),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
let mut exports = HashMap::new();
|
||||
for export in module.exports {
|
||||
exports.insert(export.symbol, export.func_idx);
|
||||
}
|
||||
|
||||
ProgramImage::new(
|
||||
module.code,
|
||||
constant_pool,
|
||||
module.functions,
|
||||
module.debug_info,
|
||||
exports,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProgramImage> for BytecodeModule {
|
||||
fn from(program: ProgramImage) -> Self {
|
||||
let const_pool = program.constant_pool.iter().map(|v| match v {
|
||||
Value::Null => ConstantPoolEntry::Null,
|
||||
Value::Int64(v) => ConstantPoolEntry::Int64(*v),
|
||||
Value::Float(v) => ConstantPoolEntry::Float64(*v),
|
||||
Value::Boolean(v) => ConstantPoolEntry::Boolean(*v),
|
||||
Value::String(v) => ConstantPoolEntry::String(v.clone()),
|
||||
Value::Int32(v) => ConstantPoolEntry::Int32(*v),
|
||||
Value::Bounded(v) => ConstantPoolEntry::Int32(*v as i32),
|
||||
Value::Gate(_) => ConstantPoolEntry::Null,
|
||||
}).collect();
|
||||
|
||||
let exports = program.exports.iter().map(|(symbol, &func_idx)| Export {
|
||||
symbol: symbol.clone(),
|
||||
func_idx,
|
||||
}).collect();
|
||||
|
||||
BytecodeModule {
|
||||
version: 0,
|
||||
const_pool,
|
||||
functions: program.functions.as_ref().to_vec(),
|
||||
code: program.rom.as_ref().to_vec(),
|
||||
debug_info: program.debug_info.clone(),
|
||||
exports,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
pub struct ScopeFrame {
|
||||
pub scope_stack_base: usize,
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Represents any piece of data that can be stored on the VM stack or in globals.
|
||||
///
|
||||
/// The PVM is "dynamically typed" at the bytecode level, meaning a single
|
||||
/// `Value` enum can hold different primitive types. The VM performs
|
||||
/// automatic type promotion (e.g., adding an Int32 to a Float64 results
|
||||
/// in a Float64) to ensure mathematical correctness.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Value {
|
||||
/// 32-bit signed integer. Used for most loop counters and indices.
|
||||
Int32(i32),
|
||||
/// 64-bit signed integer. Used for large numbers and timestamps.
|
||||
Int64(i64),
|
||||
/// 64-bit double precision float. Used for physics and complex math.
|
||||
Float(f64),
|
||||
/// Boolean value (true/false).
|
||||
Boolean(bool),
|
||||
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
|
||||
String(String),
|
||||
/// Bounded 16-bit-ish integer.
|
||||
Bounded(u32),
|
||||
/// A pointer to an object on the heap.
|
||||
Gate(usize),
|
||||
/// Represents the absence of a value (equivalent to `null` or `undefined`).
|
||||
Null,
|
||||
}
|
||||
|
||||
impl PartialEq for Value {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Value::Int32(a), Value::Int32(b)) => a == b,
|
||||
(Value::Int64(a), Value::Int64(b)) => a == b,
|
||||
(Value::Int32(a), Value::Int64(b)) => *a as i64 == *b,
|
||||
(Value::Int64(a), Value::Int32(b)) => *a == *b as i64,
|
||||
(Value::Float(a), Value::Float(b)) => a == b,
|
||||
(Value::Int32(a), Value::Float(b)) => *a as f64 == *b,
|
||||
(Value::Float(a), Value::Int32(b)) => *a == *b as f64,
|
||||
(Value::Int64(a), Value::Float(b)) => *a as f64 == *b,
|
||||
(Value::Float(a), Value::Int64(b)) => *a == *b as f64,
|
||||
(Value::Boolean(a), Value::Boolean(b)) => a == b,
|
||||
(Value::String(a), Value::String(b)) => a == b,
|
||||
(Value::Bounded(a), Value::Bounded(b)) => a == b,
|
||||
(Value::Gate(a), Value::Gate(b)) => a == b,
|
||||
(Value::Null, Value::Null) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Value {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
match (self, other) {
|
||||
(Value::Int32(a), Value::Int32(b)) => a.partial_cmp(b),
|
||||
(Value::Int64(a), Value::Int64(b)) => a.partial_cmp(b),
|
||||
(Value::Int32(a), Value::Int64(b)) => (*a as i64).partial_cmp(b),
|
||||
(Value::Int64(a), Value::Int32(b)) => a.partial_cmp(&(*b as i64)),
|
||||
(Value::Float(a), Value::Float(b)) => a.partial_cmp(b),
|
||||
(Value::Bounded(a), Value::Bounded(b)) => a.partial_cmp(b),
|
||||
(Value::Int32(a), Value::Float(b)) => (*a as f64).partial_cmp(b),
|
||||
(Value::Float(a), Value::Int32(b)) => a.partial_cmp(&(*b as f64)),
|
||||
(Value::Int64(a), Value::Float(b)) => (*a as f64).partial_cmp(b),
|
||||
(Value::Float(a), Value::Int64(b)) => a.partial_cmp(&(*b as f64)),
|
||||
(Value::Boolean(a), Value::Boolean(b)) => a.partial_cmp(b),
|
||||
(Value::String(a), Value::String(b)) => a.partial_cmp(b),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn as_float(&self) -> Option<f64> {
|
||||
match self {
|
||||
Value::Int32(i) => Some(*i as f64),
|
||||
Value::Int64(i) => Some(*i as f64),
|
||||
Value::Float(f) => Some(*f),
|
||||
Value::Bounded(b) => Some(*b as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_integer(&self) -> Option<i64> {
|
||||
match self {
|
||||
Value::Int32(i) => Some(*i as i64),
|
||||
Value::Int64(i) => Some(*i),
|
||||
Value::Float(f) => Some(*f as i64),
|
||||
Value::Bounded(b) => Some(*b as i64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
Value::Int32(i) => i.to_string(),
|
||||
Value::Int64(i) => i.to_string(),
|
||||
Value::Float(f) => f.to_string(),
|
||||
Value::Bounded(b) => format!("{}b", b),
|
||||
Value::Boolean(b) => b.to_string(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Gate(r) => format!("[Gate {}]", r),
|
||||
Value::Null => "null".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn test_value_equality() {
|
||||
assert_eq!(Value::Int32(10), Value::Int32(10));
|
||||
assert_eq!(Value::Int64(10), Value::Int64(10));
|
||||
assert_eq!(Value::Int32(10), Value::Int64(10));
|
||||
assert_eq!(Value::Int64(10), Value::Int32(10));
|
||||
assert_eq!(Value::Float(10.5), Value::Float(10.5));
|
||||
assert_eq!(Value::Int32(10), Value::Float(10.0));
|
||||
assert_eq!(Value::Float(10.0), Value::Int32(10));
|
||||
assert_eq!(Value::Int64(10), Value::Float(10.0));
|
||||
assert_eq!(Value::Float(10.0), Value::Int64(10));
|
||||
assert_ne!(Value::Int32(10), Value::Int32(11));
|
||||
assert_ne!(Value::Int64(10), Value::Int64(11));
|
||||
assert_ne!(Value::Int32(10), Value::Int64(11));
|
||||
assert_ne!(Value::Int32(10), Value::Float(10.1));
|
||||
assert_eq!(Value::Boolean(true), Value::Boolean(true));
|
||||
assert_ne!(Value::Boolean(true), Value::Boolean(false));
|
||||
assert_eq!(Value::String("oi".into()), Value::String("oi".into()));
|
||||
assert_eq!(Value::Null, Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_value_conversions() {
|
||||
let v_int32 = Value::Int32(42);
|
||||
assert_eq!(v_int32.as_float(), Some(42.0));
|
||||
assert_eq!(v_int32.as_integer(), Some(42));
|
||||
|
||||
let v_int64 = Value::Int64(42);
|
||||
assert_eq!(v_int64.as_float(), Some(42.0));
|
||||
assert_eq!(v_int64.as_integer(), Some(42));
|
||||
|
||||
let v_float = Value::Float(42.7);
|
||||
assert_eq!(v_float.as_float(), Some(42.7));
|
||||
assert_eq!(v_float.as_integer(), Some(42));
|
||||
|
||||
let v_bool = Value::Boolean(true);
|
||||
assert_eq!(v_bool.as_float(), None);
|
||||
assert_eq!(v_bool.as_integer(), None);
|
||||
}
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
use crate::abi::syscalls::Syscall;
|
||||
use crate::virtual_machine::bytecode::decoder::{decode_at, DecodeError};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
use prometeu_bytecode::FunctionMeta;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum VerifierError {
|
||||
UnknownOpcode { pc: usize, opcode: u16 },
|
||||
TruncatedOpcode { pc: usize },
|
||||
TruncatedImmediate { pc: usize, opcode: OpCode, need: usize, have: usize },
|
||||
InvalidJumpTarget { pc: usize, target: usize },
|
||||
JumpToMidInstruction { pc: usize, target: usize },
|
||||
StackUnderflow { pc: usize, opcode: OpCode },
|
||||
StackMismatchJoin { pc: usize, target: usize, height_in: u16, height_target: u16 },
|
||||
BadRetStackHeight { pc: usize, height: u16, expected: u16 },
|
||||
FunctionOutOfBounds { func_idx: usize, start: usize, end: usize, code_len: usize },
|
||||
InvalidSyscallId { pc: usize, id: u32 },
|
||||
TrailingBytes { func_idx: usize, at_pc: usize },
|
||||
InvalidFuncId { pc: usize, id: u32 },
|
||||
}
|
||||
|
||||
pub struct Verifier;
|
||||
|
||||
impl Verifier {
|
||||
pub fn verify(code: &[u8], functions: &[FunctionMeta]) -> Result<Vec<u16>, VerifierError> {
|
||||
let mut max_stacks = Vec::with_capacity(functions.len());
|
||||
for (i, func) in functions.iter().enumerate() {
|
||||
max_stacks.push(Self::verify_function(code, func, i, functions)?);
|
||||
}
|
||||
Ok(max_stacks)
|
||||
}
|
||||
|
||||
fn verify_function(code: &[u8], func: &FunctionMeta, func_idx: usize, all_functions: &[FunctionMeta]) -> Result<u16, VerifierError> {
|
||||
let func_start = func.code_offset as usize;
|
||||
let func_end = func_start + func.code_len as usize;
|
||||
|
||||
if func_start > code.len() || func_end > code.len() || func_start > func_end {
|
||||
return Err(VerifierError::FunctionOutOfBounds {
|
||||
func_idx,
|
||||
start: func_start,
|
||||
end: func_end,
|
||||
code_len: code.len(),
|
||||
});
|
||||
}
|
||||
|
||||
let func_code = &code[func_start..func_end];
|
||||
|
||||
// First pass: find all valid instruction boundaries
|
||||
let mut valid_pc = HashSet::new();
|
||||
let mut pc = 0;
|
||||
while pc < func_code.len() {
|
||||
valid_pc.insert(pc);
|
||||
let instr = decode_at(func_code, pc).map_err(|e| match e {
|
||||
DecodeError::UnknownOpcode { pc: _, opcode } =>
|
||||
VerifierError::UnknownOpcode { pc: func_start + pc, opcode },
|
||||
DecodeError::TruncatedOpcode { pc: _ } =>
|
||||
VerifierError::TruncatedOpcode { pc: func_start + pc },
|
||||
DecodeError::TruncatedImmediate { pc: _, opcode, need, have } =>
|
||||
VerifierError::TruncatedImmediate { pc: func_start + pc, opcode, need, have },
|
||||
})?;
|
||||
pc = instr.next_pc;
|
||||
}
|
||||
|
||||
if pc != func_code.len() {
|
||||
return Err(VerifierError::TrailingBytes { func_idx, at_pc: func_start + pc });
|
||||
}
|
||||
|
||||
let mut stack_height_in: HashMap<usize, u16> = HashMap::new();
|
||||
let mut worklist = VecDeque::new();
|
||||
let mut max_stack: u16 = 0;
|
||||
|
||||
// Start from function entry
|
||||
stack_height_in.insert(0, 0);
|
||||
worklist.push_back(0);
|
||||
|
||||
while let Some(pc) = worklist.pop_front() {
|
||||
let in_height = *stack_height_in.get(&pc).unwrap();
|
||||
let instr = decode_at(func_code, pc).unwrap(); // Guaranteed to succeed due to first pass
|
||||
let spec = instr.spec;
|
||||
|
||||
// Resolve dynamic pops/pushes
|
||||
let (pops, pushes) = match instr.opcode {
|
||||
OpCode::PopN => {
|
||||
let n = u32::from_le_bytes(instr.imm[0..4].try_into().unwrap()) as u16;
|
||||
(n, 0)
|
||||
}
|
||||
OpCode::Call => {
|
||||
let func_id = u32::from_le_bytes(instr.imm[0..4].try_into().unwrap());
|
||||
let callee = all_functions.get(func_id as usize).ok_or_else(|| {
|
||||
VerifierError::InvalidFuncId { pc: func_start + pc, id: func_id }
|
||||
})?;
|
||||
(callee.param_slots, callee.return_slots)
|
||||
}
|
||||
OpCode::Ret => {
|
||||
(func.return_slots, 0)
|
||||
}
|
||||
OpCode::Syscall => {
|
||||
let id = u32::from_le_bytes(instr.imm[0..4].try_into().unwrap());
|
||||
let syscall = Syscall::from_u32(id).ok_or_else(|| {
|
||||
VerifierError::InvalidSyscallId { pc: func_start + pc, id }
|
||||
})?;
|
||||
(syscall.args_count() as u16, syscall.results_count() as u16)
|
||||
}
|
||||
_ => (spec.pops, spec.pushes),
|
||||
};
|
||||
|
||||
if in_height < pops {
|
||||
return Err(VerifierError::StackUnderflow { pc: func_start + pc, opcode: instr.opcode });
|
||||
}
|
||||
|
||||
let out_height = in_height - pops + pushes;
|
||||
max_stack = max_stack.max(out_height);
|
||||
|
||||
if instr.opcode == OpCode::Ret {
|
||||
if in_height != func.return_slots {
|
||||
return Err(VerifierError::BadRetStackHeight { pc: func_start + pc, height: in_height, expected: func.return_slots });
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate to successors
|
||||
if spec.is_branch {
|
||||
let target = u32::from_le_bytes(instr.imm[0..4].try_into().unwrap()) as usize;
|
||||
|
||||
if target >= func.code_len as usize {
|
||||
return Err(VerifierError::InvalidJumpTarget { pc: func_start + pc, target: func_start + target });
|
||||
}
|
||||
if !valid_pc.contains(&target) {
|
||||
return Err(VerifierError::JumpToMidInstruction { pc: func_start + pc, target: func_start + target });
|
||||
}
|
||||
|
||||
if let Some(&existing_height) = stack_height_in.get(&target) {
|
||||
if existing_height != out_height {
|
||||
return Err(VerifierError::StackMismatchJoin { pc: func_start + pc, target: func_start + target, height_in: out_height, height_target: existing_height });
|
||||
}
|
||||
} else {
|
||||
stack_height_in.insert(target, out_height);
|
||||
worklist.push_back(target);
|
||||
}
|
||||
}
|
||||
|
||||
if !spec.is_terminator {
|
||||
let next_pc = instr.next_pc;
|
||||
if next_pc < func.code_len as usize {
|
||||
if let Some(&existing_height) = stack_height_in.get(&next_pc) {
|
||||
if existing_height != out_height {
|
||||
return Err(VerifierError::StackMismatchJoin { pc: func_start + pc, target: func_start + next_pc, height_in: out_height, height_target: existing_height });
|
||||
}
|
||||
} else {
|
||||
stack_height_in.insert(next_pc, out_height);
|
||||
worklist.push_back(next_pc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(max_stack)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_verifier_underflow() {
|
||||
// OpCode::Add (2 bytes)
|
||||
let code = vec![OpCode::Add as u8, 0x00];
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 2,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::StackUnderflow { pc: 0, opcode: OpCode::Add }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_dup_underflow() {
|
||||
let code = vec![(OpCode::Dup as u16).to_le_bytes()[0], (OpCode::Dup as u16).to_le_bytes()[1]];
|
||||
let functions = vec![FunctionMeta { code_offset: 0, code_len: 2, ..Default::default() }];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::StackUnderflow { pc: 0, opcode: OpCode::Dup }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_invalid_jmp_target() {
|
||||
// Jmp (2 bytes) + 100u32 (4 bytes)
|
||||
let mut code = vec![OpCode::Jmp as u8, 0x00];
|
||||
code.extend_from_slice(&100u32.to_le_bytes());
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 6,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::InvalidJumpTarget { pc: 0, target: 100 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_jmp_to_mid_instr() {
|
||||
// PushI32 (2 bytes) + 42u32 (4 bytes)
|
||||
// Jmp 1 (middle of PushI32)
|
||||
let mut code = vec![OpCode::PushI32 as u8, 0x00];
|
||||
code.extend_from_slice(&42u32.to_le_bytes());
|
||||
code.push(OpCode::Jmp as u8);
|
||||
code.push(0x00);
|
||||
code.extend_from_slice(&1u32.to_le_bytes());
|
||||
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 12,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::JumpToMidInstruction { pc: 6, target: 1 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_truncation_opcode() {
|
||||
let code = vec![OpCode::PushI32 as u8]; // Truncated u16 opcode
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 1,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::TruncatedOpcode { pc: 0 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_truncation_immediate() {
|
||||
let mut code = vec![OpCode::PushI32 as u8, 0x00];
|
||||
code.push(0x42); // Only 1 byte of 4-byte immediate
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 3,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::TruncatedImmediate { pc: 0, opcode: OpCode::PushI32, need: 4, have: 1 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_stack_mismatch_join() {
|
||||
// Let's make it reachable:
|
||||
// 0: PushBool true
|
||||
// 3: JmpIfTrue 15
|
||||
// 9: Jmp 27
|
||||
// 15: PushI32 1
|
||||
// 21: Jmp 27
|
||||
// 27: Nop
|
||||
|
||||
let mut code = Vec::new();
|
||||
code.push(OpCode::PushBool as u8); code.push(0x00); code.push(1); // 0: PushBool (3 bytes)
|
||||
code.push(OpCode::JmpIfTrue as u8); code.push(0x00); code.extend_from_slice(&15u32.to_le_bytes()); // 3: JmpIfTrue (6 bytes)
|
||||
code.push(OpCode::Jmp as u8); code.push(0x00); code.extend_from_slice(&27u32.to_le_bytes()); // 9: Jmp (6 bytes)
|
||||
code.push(OpCode::PushI32 as u8); code.push(0x00); code.extend_from_slice(&1u32.to_le_bytes()); // 15: PushI32 (6 bytes)
|
||||
code.push(OpCode::Jmp as u8); code.push(0x00); code.extend_from_slice(&27u32.to_le_bytes()); // 21: Jmp (6 bytes)
|
||||
code.push(OpCode::Nop as u8); code.push(0x00); // 27: Nop (2 bytes)
|
||||
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 29,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
// Path 0->3->9->27: height 1-1+0 = 0.
|
||||
// Path 0->3->15->21->27: height 1-1+1 = 1.
|
||||
// Mismatch at 27: 0 vs 1.
|
||||
|
||||
assert_eq!(res, Err(VerifierError::StackMismatchJoin { pc: 21, target: 27, height_in: 1, height_target: 0 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_bad_ret_height() {
|
||||
// PushI32 1 (6 bytes)
|
||||
// Ret (2 bytes)
|
||||
let mut code = vec![OpCode::PushI32 as u8, 0x00];
|
||||
code.extend_from_slice(&1u32.to_le_bytes());
|
||||
code.push(OpCode::Ret as u8);
|
||||
code.push(0x00);
|
||||
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 8,
|
||||
return_slots: 0, // Expected 0, but got 1
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::BadRetStackHeight { pc: 6, height: 1, expected: 0 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_max_stack() {
|
||||
// PushI32 1
|
||||
// PushI32 2
|
||||
// Add
|
||||
// Ret
|
||||
let mut code = Vec::new();
|
||||
code.push(OpCode::PushI32 as u8); code.push(0x00); code.extend_from_slice(&1u32.to_le_bytes());
|
||||
code.push(OpCode::PushI32 as u8); code.push(0x00); code.extend_from_slice(&2u32.to_le_bytes());
|
||||
code.push(OpCode::Add as u8); code.push(0x00);
|
||||
code.push(OpCode::Ret as u8); code.push(0x00);
|
||||
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 16,
|
||||
return_slots: 1,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions).unwrap();
|
||||
assert_eq!(res[0], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verifier_invalid_syscall_id() {
|
||||
let mut code = Vec::new();
|
||||
code.push(OpCode::Syscall as u8); code.push(0x00);
|
||||
code.extend_from_slice(&0xDEADBEEFu32.to_le_bytes()); // Unknown ID
|
||||
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 6,
|
||||
..Default::default()
|
||||
}];
|
||||
let res = Verifier::verify(&code, &functions);
|
||||
assert_eq!(res, Err(VerifierError::InvalidSyscallId { pc: 0, id: 0xDEADBEEF }));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,14 +1,13 @@
|
||||
use prometeu_core::virtual_machine::HostReturn;
|
||||
use prometeu_core::virtual_machine::NativeInterface;
|
||||
use prometeu_core::virtual_machine::Value;
|
||||
use prometeu_core::virtual_machine::{HostContext, LogicalFrameEndingReason, VirtualMachine};
|
||||
use prometeu_core::Hardware;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use prometeu_abi::virtual_machine::{Value, VmFault};
|
||||
use prometeu_hardware_contract::{HostContext, HostReturn, NativeInterface};
|
||||
use prometeu_vm::{LogicalFrameEndingReason, VirtualMachine};
|
||||
|
||||
struct MockNative;
|
||||
impl NativeInterface for MockNative {
|
||||
fn syscall(&mut self, id: u32, _args: &[Value], ret: &mut HostReturn, _ctx: &mut HostContext) -> Result<(), prometeu_core::virtual_machine::VmFault> {
|
||||
fn syscall(&mut self, id: u32, _args: &[Value], ret: &mut HostReturn, _ctx: &mut HostContext) -> Result<(), VmFault> {
|
||||
if id == 0x2010 { // InputPadSnapshot
|
||||
for _ in 0..48 {
|
||||
ret.push_bool(false);
|
||||
|
||||
Reference in New Issue
Block a user