pr 50
This commit is contained in:
@@ -434,11 +434,22 @@ mod tests {
|
||||
let mut hw = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
|
||||
let rom = prometeu_bytecode::pbc::write_pbc(&prometeu_bytecode::pbc::PbcFile {
|
||||
let rom = prometeu_bytecode::v0::BytecodeModule {
|
||||
version: 0,
|
||||
cp: vec![],
|
||||
rom: vec![0x02, 0x00, 0x00, 0x00, 0x00, 0x00],
|
||||
}).unwrap();
|
||||
const_pool: vec![],
|
||||
functions: vec![prometeu_bytecode::v0::FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 6,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
}],
|
||||
code: vec![0x02, 0x00, 0x00, 0x00, 0x00, 0x00],
|
||||
debug_info: None,
|
||||
exports: vec![prometeu_bytecode::v0::Export { symbol: "main".into(), func_idx: 0 }],
|
||||
imports: vec![],
|
||||
}.serialize();
|
||||
let cartridge = Cartridge {
|
||||
app_id: 1234,
|
||||
title: "test".to_string(),
|
||||
@@ -477,14 +488,25 @@ mod tests {
|
||||
// PUSH_CONST 0 (dummy)
|
||||
// FrameSync (0x80)
|
||||
// JMP 0
|
||||
let rom = prometeu_bytecode::pbc::write_pbc(&prometeu_bytecode::pbc::PbcFile {
|
||||
let rom = prometeu_bytecode::v0::BytecodeModule {
|
||||
version: 0,
|
||||
cp: vec![],
|
||||
rom: vec![
|
||||
const_pool: vec![],
|
||||
functions: vec![prometeu_bytecode::v0::FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 8,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
}],
|
||||
code: vec![
|
||||
0x80, 0x00, // FrameSync (2 bytes opcode)
|
||||
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // JMP 0 (2 bytes opcode + 4 bytes u32)
|
||||
],
|
||||
}).unwrap();
|
||||
debug_info: None,
|
||||
exports: vec![prometeu_bytecode::v0::Export { symbol: "main".into(), func_idx: 0 }],
|
||||
imports: vec![],
|
||||
}.serialize();
|
||||
let cartridge = Cartridge {
|
||||
app_id: 1234,
|
||||
title: "test".to_string(),
|
||||
@@ -680,16 +702,27 @@ mod tests {
|
||||
let signals = InputSignals::default();
|
||||
|
||||
// PushI32 0 (0x17), then Ret (0x51)
|
||||
let rom = prometeu_bytecode::pbc::write_pbc(&prometeu_bytecode::pbc::PbcFile {
|
||||
let rom = prometeu_bytecode::v0::BytecodeModule {
|
||||
version: 0,
|
||||
cp: vec![],
|
||||
rom: vec![
|
||||
const_pool: vec![],
|
||||
functions: vec![prometeu_bytecode::v0::FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 10,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
}],
|
||||
code: vec![
|
||||
0x17, 0x00, // PushI32
|
||||
0x00, 0x00, 0x00, 0x00, // value 0
|
||||
0x11, 0x00, // Pop
|
||||
0x51, 0x00 // Ret
|
||||
],
|
||||
}).unwrap();
|
||||
debug_info: None,
|
||||
exports: vec![prometeu_bytecode::v0::Export { symbol: "main".into(), func_idx: 0 }],
|
||||
imports: vec![],
|
||||
}.serialize();
|
||||
let cartridge = Cartridge {
|
||||
app_id: 1234,
|
||||
title: "test".to_string(),
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::virtual_machine::{ProgramImage, Value};
|
||||
use prometeu_bytecode::v0::{BytecodeModule, DebugInfo};
|
||||
use prometeu_bytecode::pbc::ConstantPoolEntry;
|
||||
use prometeu_bytecode::v0::{BytecodeModule, DebugInfo, ConstantPoolEntry};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -149,6 +148,7 @@ impl Linker {
|
||||
combined_constants,
|
||||
combined_functions,
|
||||
debug_info,
|
||||
exports,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,12 +30,10 @@ pub enum VmFault {
|
||||
pub enum VmInitError {
|
||||
InvalidFormat,
|
||||
UnsupportedFormat,
|
||||
PpbcParseFailed,
|
||||
PbsV0LoadFailed(prometeu_bytecode::v0::LoadError),
|
||||
LinkFailed(LinkError),
|
||||
EntrypointNotFound,
|
||||
VerificationFailed(VerifierError),
|
||||
UnsupportedLegacyCallEncoding,
|
||||
}
|
||||
|
||||
pub struct HostReturn<'a> {
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::virtual_machine::Value;
|
||||
use prometeu_bytecode::v0::{FunctionMeta, DebugInfo};
|
||||
use prometeu_bytecode::abi::TrapInfo;
|
||||
use std::sync::Arc;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ProgramImage {
|
||||
@@ -9,10 +10,11 @@ pub struct ProgramImage {
|
||||
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>, mut functions: Vec<FunctionMeta>, debug_info: Option<DebugInfo>) -> Self {
|
||||
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>, mut functions: Vec<FunctionMeta>, debug_info: Option<DebugInfo>, exports: HashMap<String, u32>) -> Self {
|
||||
if functions.is_empty() && !rom.is_empty() {
|
||||
functions.push(FunctionMeta {
|
||||
code_offset: 0,
|
||||
@@ -25,6 +27,7 @@ impl ProgramImage {
|
||||
constant_pool: Arc::from(constant_pool),
|
||||
functions: Arc::from(functions),
|
||||
debug_info,
|
||||
exports: Arc::new(exports),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ use crate::virtual_machine::scope_frame::ScopeFrame;
|
||||
use crate::virtual_machine::value::Value;
|
||||
use crate::virtual_machine::{NativeInterface, ProgramImage, VmInitError};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
use prometeu_bytecode::pbc::{self, ConstantPoolEntry};
|
||||
use prometeu_bytecode::abi::{TrapInfo, TRAP_OOB, TRAP_DIV_ZERO, TRAP_TYPE, TRAP_INVALID_FUNC, TRAP_BAD_RET_SLOTS};
|
||||
|
||||
/// Reason why the Virtual Machine stopped execution during a specific run.
|
||||
@@ -99,7 +98,7 @@ impl VirtualMachine {
|
||||
call_stack: Vec::new(),
|
||||
scope_stack: Vec::new(),
|
||||
globals: Vec::new(),
|
||||
program: ProgramImage::new(rom, constant_pool, vec![], None),
|
||||
program: ProgramImage::new(rom, constant_pool, vec![], None, std::collections::HashMap::new()),
|
||||
heap: Vec::new(),
|
||||
cycles: 0,
|
||||
halted: false,
|
||||
@@ -122,25 +121,8 @@ impl VirtualMachine {
|
||||
self.cycles = 0;
|
||||
self.halted = true; // execution is impossible until successful load
|
||||
|
||||
// Only recognized formats are loadable.
|
||||
let program = if program_bytes.starts_with(b"PPBC") {
|
||||
// PBC (Prometeu ByteCode) legacy format
|
||||
let pbc_file = pbc::parse_pbc(&program_bytes).map_err(|_| VmInitError::PpbcParseFailed)?;
|
||||
|
||||
// Policy (A): Reject legacy CALL encoding in legacy formats.
|
||||
Self::legacy_reject_call_encoding(&pbc_file.rom)?;
|
||||
|
||||
let cp = pbc_file.cp.into_iter().map(|entry| match entry {
|
||||
ConstantPoolEntry::Int32(v) => Value::Int32(v),
|
||||
ConstantPoolEntry::Int64(v) => Value::Int64(v),
|
||||
ConstantPoolEntry::Float64(v) => Value::Float(v),
|
||||
ConstantPoolEntry::Boolean(v) => Value::Boolean(v),
|
||||
ConstantPoolEntry::String(v) => Value::String(v),
|
||||
ConstantPoolEntry::Null => Value::Null,
|
||||
}).collect();
|
||||
ProgramImage::new(pbc_file.rom, cp, vec![], None)
|
||||
} else if program_bytes.starts_with(b"PBS\0") {
|
||||
// PBS v0 industrial format
|
||||
// Only recognized format is loadable: PBS v0 industrial format
|
||||
let program = if program_bytes.starts_with(b"PBS\0") {
|
||||
match prometeu_bytecode::v0::BytecodeLoader::load(&program_bytes) {
|
||||
Ok(module) => {
|
||||
// Link module(s)
|
||||
@@ -148,18 +130,9 @@ impl VirtualMachine {
|
||||
.map_err(VmInitError::LinkFailed)?;
|
||||
|
||||
// Run verifier on the linked program
|
||||
// Note: Verifier currently expects code and functions separately.
|
||||
// We need to ensure it works with the linked program.
|
||||
let max_stacks = crate::virtual_machine::verifier::Verifier::verify(&linked_program.rom, &linked_program.functions)
|
||||
.map_err(VmInitError::VerificationFailed)?;
|
||||
|
||||
// Apply verified max_stack_slots
|
||||
// Since linked_program.functions is an Arc<[FunctionMeta]>, we need to get a mutable copy if we want to update it.
|
||||
// Or we update it before creating the ProgramImage.
|
||||
|
||||
// Actually, let's look at how we can update max_stack_slots.
|
||||
// ProgramImage holds Arc<[FunctionMeta]>.
|
||||
|
||||
let mut functions = linked_program.functions.as_ref().to_vec();
|
||||
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
|
||||
func.max_stack_slots = max_stack;
|
||||
@@ -177,15 +150,21 @@ impl VirtualMachine {
|
||||
return Err(VmInitError::InvalidFormat);
|
||||
};
|
||||
|
||||
// Resolve the entrypoint. Currently supports numeric addresses or empty (defaults to 0).
|
||||
// Resolve the entrypoint. Currently supports numeric addresses, symbolic exports, or empty (defaults to 0).
|
||||
let pc = if entrypoint.is_empty() {
|
||||
0
|
||||
} else {
|
||||
let addr = entrypoint.parse::<usize>().map_err(|_| VmInitError::EntrypointNotFound)?;
|
||||
} else if let Ok(addr) = entrypoint.parse::<usize>() {
|
||||
if addr >= program.rom.len() && (addr > 0 || !program.rom.is_empty()) {
|
||||
return Err(VmInitError::EntrypointNotFound);
|
||||
}
|
||||
addr
|
||||
} else {
|
||||
// Try to resolve symbol name via ProgramImage exports
|
||||
if let Some(&func_idx) = program.exports.get(entrypoint) {
|
||||
program.functions[func_idx as usize].code_offset as usize
|
||||
} else {
|
||||
return Err(VmInitError::EntrypointNotFound);
|
||||
}
|
||||
};
|
||||
|
||||
// Finalize initialization by applying the new program and PC.
|
||||
@@ -199,16 +178,17 @@ impl VirtualMachine {
|
||||
/// Prepares the VM to execute a specific entrypoint by setting the PC and
|
||||
/// pushing an initial call frame.
|
||||
pub fn prepare_call(&mut self, entrypoint: &str) {
|
||||
let addr = if let Ok(addr) = entrypoint.parse::<usize>() {
|
||||
addr
|
||||
let (addr, func_idx) = if let Ok(addr) = entrypoint.parse::<usize>() {
|
||||
let idx = self.program.functions.iter().position(|f| {
|
||||
addr >= f.code_offset as usize && addr < (f.code_offset + f.code_len) as usize
|
||||
}).unwrap_or(0);
|
||||
(addr, idx)
|
||||
} else if let Some(&func_idx) = self.program.exports.get(entrypoint) {
|
||||
(self.program.functions[func_idx as usize].code_offset as usize, func_idx as usize)
|
||||
} else {
|
||||
0
|
||||
(0, 0)
|
||||
};
|
||||
|
||||
let func_idx = self.program.functions.iter().position(|f| {
|
||||
addr >= f.code_offset as usize && addr < (f.code_offset + f.code_len) as usize
|
||||
}).unwrap_or(0);
|
||||
|
||||
self.pc = addr;
|
||||
self.halted = false;
|
||||
|
||||
@@ -222,7 +202,8 @@ impl VirtualMachine {
|
||||
// Entrypoint also needs locals allocated.
|
||||
// For the sentinel frame, stack_base is always 0.
|
||||
if let Some(func) = self.program.functions.get(func_idx) {
|
||||
for _ in 0..func.local_slots {
|
||||
let total_slots = func.param_slots as u32 + func.local_slots as u32;
|
||||
for _ in 0..total_slots {
|
||||
self.operand_stack.push(Value::Null);
|
||||
}
|
||||
}
|
||||
@@ -234,18 +215,6 @@ impl VirtualMachine {
|
||||
});
|
||||
}
|
||||
|
||||
fn legacy_reject_call_encoding(rom: &[u8]) -> Result<(), VmInitError> {
|
||||
let mut pc = 0usize;
|
||||
while pc < rom.len() {
|
||||
let instr = crate::virtual_machine::bytecode::decoder::decode_at(rom, pc)
|
||||
.map_err(|_| VmInitError::PpbcParseFailed)?;
|
||||
if instr.opcode == OpCode::Call {
|
||||
return Err(VmInitError::UnsupportedLegacyCallEncoding);
|
||||
}
|
||||
pc = instr.next_pc;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for VirtualMachine {
|
||||
@@ -1212,7 +1181,7 @@ mod tests {
|
||||
];
|
||||
|
||||
let mut vm = VirtualMachine {
|
||||
program: ProgramImage::new(rom, vec![], functions, None),
|
||||
program: ProgramImage::new(rom, vec![], functions, None, std::collections::HashMap::new()),
|
||||
..Default::default()
|
||||
};
|
||||
vm.prepare_call("0");
|
||||
@@ -1257,7 +1226,7 @@ mod tests {
|
||||
];
|
||||
|
||||
let mut vm = VirtualMachine {
|
||||
program: ProgramImage::new(rom, vec![], functions, None),
|
||||
program: ProgramImage::new(rom, vec![], functions, None, std::collections::HashMap::new()),
|
||||
..Default::default()
|
||||
};
|
||||
vm.prepare_call("0");
|
||||
@@ -1296,7 +1265,7 @@ mod tests {
|
||||
];
|
||||
|
||||
let mut vm2 = VirtualMachine {
|
||||
program: ProgramImage::new(rom2, vec![], functions2, None),
|
||||
program: ProgramImage::new(rom2, vec![], functions2, None, std::collections::HashMap::new()),
|
||||
..Default::default()
|
||||
};
|
||||
vm2.prepare_call("0");
|
||||
@@ -1405,7 +1374,7 @@ mod tests {
|
||||
];
|
||||
|
||||
let mut vm = VirtualMachine {
|
||||
program: ProgramImage::new(rom, vec![], functions, None),
|
||||
program: ProgramImage::new(rom, vec![], functions, None, std::collections::HashMap::new()),
|
||||
..Default::default()
|
||||
};
|
||||
vm.prepare_call("0");
|
||||
@@ -1927,53 +1896,6 @@ mod tests {
|
||||
assert_eq!(vm.cycles, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_policy_a_reject_legacy_call() {
|
||||
let mut vm = VirtualMachine::default();
|
||||
|
||||
// PBC Header (PPBC)
|
||||
let mut pbc = b"PPBC".to_vec();
|
||||
pbc.extend_from_slice(&0u16.to_le_bytes()); // Version
|
||||
pbc.extend_from_slice(&0u16.to_le_bytes()); // Flags
|
||||
pbc.extend_from_slice(&0u32.to_le_bytes()); // CP count
|
||||
pbc.extend_from_slice(&4u32.to_le_bytes()); // ROM size
|
||||
|
||||
// ROM: CALL (2 bytes) + 4-byte immediate (from OpcodeSpec)
|
||||
// Wait, OpcodeSpec says CALL imm_bytes is 4.
|
||||
pbc.extend_from_slice(&(OpCode::Call as u16).to_le_bytes());
|
||||
pbc.extend_from_slice(&[0, 0, 0, 0]);
|
||||
// Update ROM size to 6
|
||||
pbc[12..16].copy_from_slice(&6u32.to_le_bytes());
|
||||
|
||||
let res = vm.initialize(pbc, "");
|
||||
assert_eq!(res, Err(VmInitError::UnsupportedLegacyCallEncoding));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_policy_a_permit_call_pattern_in_immediate() {
|
||||
let mut vm = VirtualMachine::default();
|
||||
|
||||
// PBC Header (PPBC)
|
||||
let mut pbc = b"PPBC".to_vec();
|
||||
pbc.extend_from_slice(&0u16.to_le_bytes()); // Version
|
||||
pbc.extend_from_slice(&0u16.to_le_bytes()); // Flags
|
||||
pbc.extend_from_slice(&0u32.to_le_bytes()); // CP count
|
||||
|
||||
// ROM: PUSH_I64 with a value that contains OpCode::Call bytes
|
||||
let mut rom = Vec::new();
|
||||
rom.extend_from_slice(&(OpCode::PushI64 as u16).to_le_bytes());
|
||||
let call_val = OpCode::Call as u16;
|
||||
let mut val_bytes = [0u8; 8];
|
||||
val_bytes[0..2].copy_from_slice(&call_val.to_le_bytes());
|
||||
rom.extend_from_slice(&val_bytes);
|
||||
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
|
||||
|
||||
pbc.extend_from_slice(&(rom.len() as u32).to_le_bytes()); // ROM size
|
||||
pbc.extend_from_slice(&rom);
|
||||
|
||||
let res = vm.initialize(pbc, "");
|
||||
assert!(res.is_ok(), "Should NOT fail if Call pattern is in immediate: {:?}", res);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calling_convention_add() {
|
||||
@@ -2505,7 +2427,7 @@ mod tests {
|
||||
function_names: vec![(0, "main".to_string())],
|
||||
};
|
||||
|
||||
let program = ProgramImage::new(rom, vec![], vec![], Some(debug_info));
|
||||
let program = ProgramImage::new(rom, vec![], vec![], Some(debug_info), std::collections::HashMap::new());
|
||||
let mut vm = VirtualMachine {
|
||||
program,
|
||||
..Default::default()
|
||||
@@ -2552,7 +2474,7 @@ mod tests {
|
||||
..Default::default()
|
||||
}];
|
||||
|
||||
let program = ProgramImage::new(rom, vec![], functions, Some(debug_info));
|
||||
let program = ProgramImage::new(rom, vec![], functions, Some(debug_info), std::collections::HashMap::new());
|
||||
let mut vm = VirtualMachine {
|
||||
program,
|
||||
..Default::default()
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
use prometeu_core::virtual_machine::{VirtualMachine, LogicalFrameEndingReason};
|
||||
use prometeu_core::hardware::HardwareBridge;
|
||||
use prometeu_core::Hardware;
|
||||
use prometeu_core::virtual_machine::NativeInterface;
|
||||
use prometeu_core::virtual_machine::Value;
|
||||
use prometeu_core::virtual_machine::HostReturn;
|
||||
use std::path::Path;
|
||||
use std::fs;
|
||||
|
||||
struct MockNative;
|
||||
impl NativeInterface for MockNative {
|
||||
fn syscall(&mut self, id: u32, _args: &[Value], ret: &mut HostReturn, _hw: &mut dyn HardwareBridge) -> Result<(), prometeu_core::virtual_machine::VmFault> {
|
||||
if id == 0x2010 { // InputPadSnapshot
|
||||
for _ in 0..48 {
|
||||
ret.push_bool(false);
|
||||
}
|
||||
} else if id == 0x2011 { // InputTouchSnapshot
|
||||
for _ in 0..6 {
|
||||
ret.push_int(0);
|
||||
}
|
||||
} else {
|
||||
// Push one result for others that might expect it
|
||||
// Based on results_count() in syscalls.rs, most return 1 except GfxClear565 (0)
|
||||
if id != 0x1010 {
|
||||
ret.push_null();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_canonical_cartridge_heartbeat() {
|
||||
let mut pbc_path = Path::new("../../test-cartridges/canonical/golden/program.pbc").to_path_buf();
|
||||
if !pbc_path.exists() {
|
||||
pbc_path = Path::new("test-cartridges/canonical/golden/program.pbc").to_path_buf();
|
||||
}
|
||||
|
||||
let pbc_bytes = fs::read(pbc_path).expect("Failed to read canonical PBC. Did you run the generation test?");
|
||||
|
||||
let mut vm = VirtualMachine::new(vec![], vec![]);
|
||||
vm.initialize(pbc_bytes, "frame").expect("Failed to initialize VM with canonical cartridge");
|
||||
vm.prepare_call("frame");
|
||||
|
||||
let mut native = MockNative;
|
||||
let mut hw = Hardware::new();
|
||||
|
||||
// Run for a reasonable budget
|
||||
let report = vm.run_budget(1000, &mut native, &mut hw).expect("VM failed to run");
|
||||
|
||||
// Acceptance criteria:
|
||||
// 1. No traps
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => panic!("VM trapped: {:?}", trap),
|
||||
LogicalFrameEndingReason::Panic(msg) => panic!("VM panicked: {}", msg),
|
||||
LogicalFrameEndingReason::Halted => {},
|
||||
LogicalFrameEndingReason::EndOfRom => {},
|
||||
LogicalFrameEndingReason::FrameSync => {},
|
||||
LogicalFrameEndingReason::BudgetExhausted => {},
|
||||
LogicalFrameEndingReason::Breakpoint => {},
|
||||
}
|
||||
|
||||
// 2. Deterministic output state (if any)
|
||||
// In our frame(), z should be 30.
|
||||
// Local 2 in frame() should be 30.
|
||||
// Let's check the stack or locals if possible.
|
||||
|
||||
// The VM should have finished 'frame'.
|
||||
// Since 'frame' returns void, the stack should be empty (or have the return value if any, but it's void).
|
||||
assert_eq!(vm.operand_stack.len(), 0, "Stack should be empty after frame() execution");
|
||||
|
||||
println!("Heartbeat test passed!");
|
||||
}
|
||||
Reference in New Issue
Block a user