quality baseline

This commit is contained in:
2026-03-24 13:40:35 +00:00
parent e2a970e69c
commit c7786fa8b0
90 changed files with 3076 additions and 1334 deletions
@@ -1,21 +1,20 @@
use prometeu_hal::syscalls::Syscall;
use crate::fs::{FsBackend, FsState, VirtualFS};
use prometeu_hal::{HardwareBridge, InputSignals};
use prometeu_hal::log::{LogLevel, LogService, LogSource};
use prometeu_hal::telemetry::{CertificationConfig, Certifier, TelemetryFrame};
use std::collections::HashMap;
use std::time::Instant;
use prometeu_bytecode::{Value, TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE};
use prometeu_hal::{expect_bool, expect_int, HostContext, HostReturn, NativeInterface, SyscallId};
use prometeu_bytecode::{TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE, Value};
use prometeu_hal::asset::{BankType, LoadStatus, SlotRef};
use prometeu_hal::button::Button;
use prometeu_hal::cartridge::{AppMode, Cartridge};
use prometeu_hal::color::Color;
use prometeu_hal::log::{LogLevel, LogService, LogSource};
use prometeu_hal::sprite::Sprite;
use prometeu_hal::syscalls::Syscall;
use prometeu_hal::telemetry::{CertificationConfig, Certifier, TelemetryFrame};
use prometeu_hal::tile::Tile;
use prometeu_hal::vm_fault::VmFault;
use prometeu_hal::{HardwareBridge, InputSignals};
use prometeu_hal::{HostContext, HostReturn, NativeInterface, SyscallId, expect_bool, expect_int};
use prometeu_vm::{LogicalFrameEndingReason, VirtualMachine};
use std::collections::HashMap;
use std::time::Instant;
pub struct VirtualMachineRuntime {
/// Host Tick Index: Incremented on every host hardware update (usually 60Hz).
@@ -128,7 +127,12 @@ impl VirtualMachineRuntime {
match self.fs.mount(backend) {
Ok(_) => {
self.fs_state = FsState::Mounted;
self.log(LogLevel::Info, LogSource::Fs, 0, "Filesystem mounted successfully".to_string());
self.log(
LogLevel::Info,
LogSource::Fs,
0,
"Filesystem mounted successfully".to_string(),
);
}
Err(e) => {
let err_msg = format!("Failed to mount filesystem: {:?}", e);
@@ -146,7 +150,12 @@ impl VirtualMachineRuntime {
fn update_fs(&mut self) {
if self.fs_state == FsState::Mounted {
if !self.fs.is_healthy() {
self.log(LogLevel::Error, LogSource::Fs, 0, "Filesystem became unhealthy, unmounting".to_string());
self.log(
LogLevel::Error,
LogSource::Fs,
0,
"Filesystem became unhealthy, unmounting".to_string(),
);
self.unmount_fs();
}
}
@@ -173,7 +182,12 @@ impl VirtualMachineRuntime {
self.current_entrypoint = cartridge.entrypoint.clone();
}
Err(e) => {
self.log(LogLevel::Error, LogSource::Vm, 0, format!("Failed to initialize VM: {:?}", e));
self.log(
LogLevel::Error,
LogSource::Vm,
0,
format!("Failed to initialize VM: {:?}", e),
);
// Fail fast: no program is installed, no app id is switched.
// We don't update current_app_id or other fields.
}
@@ -181,7 +195,11 @@ impl VirtualMachineRuntime {
}
/// Executes a single VM instruction (Debug).
pub fn debug_step_instruction(&mut self, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Option<String> {
pub fn debug_step_instruction(
&mut self,
vm: &mut VirtualMachine,
hw: &mut dyn HardwareBridge,
) -> Option<String> {
let mut ctx = HostContext::new(Some(hw));
match vm.step(self, &mut ctx) {
Ok(_) => None,
@@ -198,7 +216,12 @@ impl VirtualMachineRuntime {
/// This method is responsible for managing the logical frame lifecycle.
/// A single host tick might execute a full logical frame, part of it,
/// or multiple frames depending on the configured slices.
pub fn tick(&mut self, vm: &mut VirtualMachine, signals: &InputSignals, hw: &mut dyn HardwareBridge) -> Option<String> {
pub fn tick(
&mut self,
vm: &mut VirtualMachine,
signals: &InputSignals,
hw: &mut dyn HardwareBridge,
) -> Option<String> {
let start = Instant::now();
self.tick_index += 1;
@@ -228,7 +251,11 @@ impl VirtualMachineRuntime {
// Reset telemetry for the new logical frame
self.telemetry_current = TelemetryFrame {
frame_index: self.logical_frame_index,
cycles_budget: self.certifier.config.cycles_budget_per_frame.unwrap_or(Self::CYCLES_PER_LOGICAL_FRAME),
cycles_budget: self
.certifier
.config
.cycles_budget_per_frame
.unwrap_or(Self::CYCLES_PER_LOGICAL_FRAME),
..Default::default()
};
}
@@ -247,7 +274,8 @@ impl VirtualMachineRuntime {
match run_result {
Ok(run) => {
self.logical_frame_remaining_cycles = self.logical_frame_remaining_cycles.saturating_sub(run.cycles_used);
self.logical_frame_remaining_cycles =
self.logical_frame_remaining_cycles.saturating_sub(run.cycles_used);
// Accumulate metrics for telemetry and certification
self.telemetry_current.cycles_used += run.cycles_used;
@@ -257,7 +285,12 @@ impl VirtualMachineRuntime {
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));
self.log(
LogLevel::Info,
LogSource::Vm,
0xDEB1,
format!("Breakpoint hit at PC 0x{:X}", vm.pc),
);
}
// Handle Panics
@@ -268,18 +301,24 @@ impl VirtualMachineRuntime {
}
// 4. Frame Finalization (FRAME_SYNC reached or Entrypoint returned)
if run.reason == LogicalFrameEndingReason::FrameSync ||
run.reason == 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();
// Finalize frame telemetry
self.telemetry_current.host_cpu_time_us = start.elapsed().as_micros() as u64;
self.telemetry_current.host_cpu_time_us =
start.elapsed().as_micros() as u64;
// Evaluate CAP (Execution Budget Compliance)
let ts_ms = self.boot_time.elapsed().as_millis() as u64;
self.telemetry_current.violations = self.certifier.evaluate(&self.telemetry_current, &mut self.log_service, ts_ms) as u32;
self.telemetry_current.violations = self.certifier.evaluate(
&self.telemetry_current,
&mut self.log_service,
ts_ms,
) as u32;
// Latch telemetry for the Host/Debugger to read.
self.telemetry_last = self.telemetry_current;
@@ -324,7 +363,9 @@ impl VirtualMachineRuntime {
self.telemetry_current.audio_slots_occupied = audio_stats.slots_occupied as u32;
// If the frame ended exactly in this tick, we update the final real time in the latch.
if !self.logical_frame_active && self.telemetry_last.frame_index == self.logical_frame_index.wrapping_sub(1) {
if !self.logical_frame_active
&& self.telemetry_last.frame_index == self.logical_frame_index.wrapping_sub(1)
{
self.telemetry_last.host_cpu_time_us = self.last_frame_cpu_time_us;
self.telemetry_last.cycles_budget = self.telemetry_current.cycles_budget;
self.telemetry_last.gfx_used_bytes = self.telemetry_current.gfx_used_bytes;
@@ -343,7 +384,6 @@ impl VirtualMachineRuntime {
self.logs_written_this_frame.clear();
}
// Helper for syscalls
fn syscall_log_write(&mut self, level_val: i64, tag: u16, msg: String) -> Result<(), VmFault> {
let level = match level_val {
@@ -361,7 +401,12 @@ impl VirtualMachineRuntime {
if count >= Self::MAX_LOGS_PER_FRAME {
if count == Self::MAX_LOGS_PER_FRAME {
self.logs_written_this_frame.insert(app_id, count + 1);
self.log(LogLevel::Warn, LogSource::App { app_id }, 0, "App exceeded log limit per frame".to_string());
self.log(
LogLevel::Warn,
LogSource::App { app_id },
0,
"App exceeded log limit per frame".to_string(),
);
}
return Ok(());
}
@@ -434,11 +479,17 @@ impl NativeInterface for VirtualMachineRuntime {
/// - 0x5000: Logging
///
/// Each syscall returns the number of virtual cycles it consumed.
fn syscall(&mut self, id: SyscallId, args: &[Value], ret: &mut HostReturn, ctx: &mut HostContext) -> Result<(), VmFault> {
fn syscall(
&mut self,
id: SyscallId,
args: &[Value],
ret: &mut HostReturn,
ctx: &mut HostContext,
) -> Result<(), VmFault> {
self.telemetry_current.syscalls += 1;
let syscall = Syscall::from_u32(id).ok_or_else(|| VmFault::Trap(TRAP_INVALID_SYSCALL, format!(
"Unknown syscall: 0x{:08X}", id
)))?;
let syscall = Syscall::from_u32(id).ok_or_else(|| {
VmFault::Trap(TRAP_INVALID_SYSCALL, format!("Unknown syscall: 0x{:08X}", id))
})?;
// Handle hardware-less syscalls first
match syscall {
@@ -457,7 +508,6 @@ impl NativeInterface for VirtualMachineRuntime {
match syscall {
// --- System Syscalls ---
Syscall::SystemHasCart => unreachable!(),
Syscall::SystemRunCart => unreachable!(),
@@ -535,7 +585,10 @@ impl NativeInterface for VirtualMachineRuntime {
}
// gfx.set_sprite(asset_name, id, x, y, tile_id, palette_id, active, flip_x, flip_y, priority)
Syscall::GfxSetSprite => {
let asset_name = match args.get(0).ok_or_else(|| VmFault::Panic("Missing asset_name".into()))? {
let asset_name = match args
.get(0)
.ok_or_else(|| VmFault::Panic("Missing asset_name".into()))?
{
Value::String(s) => s.clone(),
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string asset_name".into())),
};
@@ -549,7 +602,8 @@ impl NativeInterface for VirtualMachineRuntime {
let flip_y = expect_bool(args, 8)?;
let priority = expect_int(args, 9)? as u8;
let bank_id = hw.assets().find_slot_by_name(&asset_name, BankType::TILES).unwrap_or(0);
let bank_id =
hw.assets().find_slot_by_name(&asset_name, BankType::TILES).unwrap_or(0);
if index < 512 {
*hw.gfx_mut().sprite_mut(index) = Sprite {
@@ -569,7 +623,10 @@ impl NativeInterface for VirtualMachineRuntime {
Syscall::GfxDrawText => {
let x = expect_int(args, 0)? as i32;
let y = expect_int(args, 1)? as i32;
let msg = match args.get(2).ok_or_else(|| VmFault::Panic("Missing message".into()))? {
let msg = match args
.get(2)
.ok_or_else(|| VmFault::Panic("Missing message".into()))?
{
Value::String(s) => s.clone(),
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string message".into())),
};
@@ -583,7 +640,10 @@ impl NativeInterface for VirtualMachineRuntime {
Syscall::GfxClear565 => {
let color_val = expect_int(args, 0)? as u32;
if color_val > 0xFFFF {
return Err(VmFault::Trap(TRAP_OOB, "Color value out of bounds (bounded)".into()));
return Err(VmFault::Trap(
TRAP_OOB,
"Color value out of bounds (bounded)".into(),
));
}
let color = Color::from_raw(color_val as u16);
hw.gfx_mut().clear(color);
@@ -655,9 +715,18 @@ impl NativeInterface for VirtualMachineRuntime {
Syscall::InputPadSnapshot => {
let pad = hw.pad();
for btn in [
pad.up(), pad.down(), pad.left(), pad.right(),
pad.a(), pad.b(), pad.x(), pad.y(),
pad.l(), pad.r(), pad.start(), pad.select(),
pad.up(),
pad.down(),
pad.left(),
pad.right(),
pad.a(),
pad.b(),
pad.x(),
pad.y(),
pad.l(),
pad.r(),
pad.start(),
pad.select(),
] {
ret.push_bool(btn.pressed);
ret.push_bool(btn.released);
@@ -783,7 +852,10 @@ impl NativeInterface for VirtualMachineRuntime {
let voice_id = expect_int(args, 1)? as usize;
let volume = expect_int(args, 2)? as u8;
let pan = expect_int(args, 3)? as u8;
let pitch = match args.get(4).ok_or_else(|| VmFault::Panic("Missing pitch".into()))? {
let pitch = match args
.get(4)
.ok_or_else(|| VmFault::Panic("Missing pitch".into()))?
{
Value::Float(f) => *f,
Value::Int32(i) => *i as f64,
Value::Int64(i) => *i as f64,
@@ -791,14 +863,26 @@ impl NativeInterface for VirtualMachineRuntime {
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected number for pitch".into())),
};
hw.audio_mut().play(0, sample_id as u16, voice_id, volume, pan, pitch, 0, prometeu_hal::LoopMode::Off);
hw.audio_mut().play(
0,
sample_id as u16,
voice_id,
volume,
pan,
pitch,
0,
prometeu_hal::LoopMode::Off,
);
ret.push_null();
Ok(())
}
// audio.play(asset_name, sample_id, voice_id, volume, pan, pitch, loop_mode)
Syscall::AudioPlay => {
let asset_name = match args.get(0).ok_or_else(|| VmFault::Panic("Missing asset_name".into()))? {
let asset_name = match args
.get(0)
.ok_or_else(|| VmFault::Panic("Missing asset_name".into()))?
{
Value::String(s) => s.clone(),
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string asset_name".into())),
};
@@ -806,7 +890,10 @@ impl NativeInterface for VirtualMachineRuntime {
let voice_id = expect_int(args, 2)? as usize;
let volume = expect_int(args, 3)? as u8;
let pan = expect_int(args, 4)? as u8;
let pitch = match args.get(5).ok_or_else(|| VmFault::Panic("Missing pitch".into()))? {
let pitch = match args
.get(5)
.ok_or_else(|| VmFault::Panic("Missing pitch".into()))?
{
Value::Float(f) => *f,
Value::Int32(i) => *i as f64,
Value::Int64(i) => *i as f64,
@@ -818,7 +905,8 @@ impl NativeInterface for VirtualMachineRuntime {
_ => prometeu_hal::LoopMode::On,
};
let bank_id = hw.assets().find_slot_by_name(&asset_name, BankType::SOUNDS).unwrap_or(0);
let bank_id =
hw.assets().find_slot_by_name(&asset_name, BankType::SOUNDS).unwrap_or(0);
hw.audio_mut().play(bank_id, sample_id, voice_id, volume, pan, pitch, 0, loop_mode);
ret.push_null();
@@ -846,7 +934,10 @@ impl NativeInterface for VirtualMachineRuntime {
// FS_READ(handle) -> content
Syscall::FsRead => {
let handle = expect_int(args, 0)? as u32;
let path = self.open_files.get(&handle).ok_or_else(|| VmFault::Panic("Invalid handle".into()))?;
let path = self
.open_files
.get(&handle)
.ok_or_else(|| VmFault::Panic("Invalid handle".into()))?;
match self.fs.read_file(path) {
Ok(data) => {
let s = String::from_utf8_lossy(&data).into_owned();
@@ -859,11 +950,17 @@ impl NativeInterface for VirtualMachineRuntime {
// FS_WRITE(handle, content)
Syscall::FsWrite => {
let handle = expect_int(args, 0)? as u32;
let content = match args.get(1).ok_or_else(|| VmFault::Panic("Missing content".into()))? {
let content = match args
.get(1)
.ok_or_else(|| VmFault::Panic("Missing content".into()))?
{
Value::String(s) => s.as_bytes().to_vec(),
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string content".into())),
};
let path = self.open_files.get(&handle).ok_or_else(|| VmFault::Panic("Invalid handle".into()))?;
let path = self
.open_files
.get(&handle)
.ok_or_else(|| VmFault::Panic("Invalid handle".into()))?;
match self.fs.write_file(path, &content) {
Ok(_) => ret.push_bool(true),
Err(_) => ret.push_bool(false),
@@ -919,7 +1016,10 @@ impl NativeInterface for VirtualMachineRuntime {
// LOG_WRITE(level, msg)
Syscall::LogWrite => {
let level = expect_int(args, 0)?;
let msg = match args.get(1).ok_or_else(|| VmFault::Panic("Missing message".into()))? {
let msg = match args
.get(1)
.ok_or_else(|| VmFault::Panic("Missing message".into()))?
{
Value::String(s) => s.clone(),
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string message".into())),
};
@@ -931,7 +1031,10 @@ impl NativeInterface for VirtualMachineRuntime {
Syscall::LogWriteTag => {
let level = expect_int(args, 0)?;
let tag = expect_int(args, 1)? as u16;
let msg = match args.get(2).ok_or_else(|| VmFault::Panic("Missing message".into()))? {
let msg = match args
.get(2)
.ok_or_else(|| VmFault::Panic("Missing message".into()))?
{
Value::String(s) => s.clone(),
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string message".into())),
};
@@ -942,7 +1045,10 @@ impl NativeInterface for VirtualMachineRuntime {
// --- Asset Syscalls ---
Syscall::AssetLoad => {
let asset_id = match args.get(0).ok_or_else(|| VmFault::Panic("Missing asset_id".into()))? {
let asset_id = match args
.get(0)
.ok_or_else(|| VmFault::Panic("Missing asset_id".into()))?
{
Value::String(s) => s.clone(),
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string asset_id".into())),
};
@@ -1018,4 +1124,4 @@ impl NativeInterface for VirtualMachineRuntime {
}
}
}
}
}