break monster VM into small pieces :D
This commit is contained in:
@@ -0,0 +1,546 @@
|
||||
use super::*;
|
||||
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::color::Color;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_hal::sprite::Sprite;
|
||||
use prometeu_hal::syscalls::Syscall;
|
||||
use prometeu_hal::tile::Tile;
|
||||
use prometeu_hal::vm_fault::VmFault;
|
||||
use prometeu_hal::{HostContext, HostReturn, NativeInterface, SyscallId, expect_bool, expect_int};
|
||||
|
||||
impl VirtualMachineRuntime {
|
||||
fn syscall_log_write(&mut self, level_val: i64, tag: u16, msg: String) -> Result<(), VmFault> {
|
||||
let level = match level_val {
|
||||
0 => LogLevel::Trace,
|
||||
1 => LogLevel::Debug,
|
||||
2 => LogLevel::Info,
|
||||
3 => LogLevel::Warn,
|
||||
4 => LogLevel::Error,
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, format!("Invalid log level: {}", level_val))),
|
||||
};
|
||||
|
||||
let app_id = self.current_app_id;
|
||||
let count = *self.logs_written_this_frame.get(&app_id).unwrap_or(&0);
|
||||
|
||||
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(),
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.logs_written_this_frame.insert(app_id, count + 1);
|
||||
|
||||
let mut final_msg = msg;
|
||||
if final_msg.len() > Self::MAX_LOG_LEN {
|
||||
final_msg.truncate(Self::MAX_LOG_LEN);
|
||||
}
|
||||
|
||||
self.log(level, LogSource::App { app_id }, tag, final_msg);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn get_color(&self, value: i64) -> Color {
|
||||
Color::from_raw(value as u16)
|
||||
}
|
||||
|
||||
pub(crate) fn get_button<'a>(
|
||||
&self,
|
||||
id: u32,
|
||||
hw: &'a dyn prometeu_hal::HardwareBridge,
|
||||
) -> Option<&'a Button> {
|
||||
let pad = hw.pad();
|
||||
match id {
|
||||
0 => Some(pad.up()),
|
||||
1 => Some(pad.down()),
|
||||
2 => Some(pad.left()),
|
||||
3 => Some(pad.right()),
|
||||
4 => Some(pad.a()),
|
||||
5 => Some(pad.b()),
|
||||
6 => Some(pad.x()),
|
||||
7 => Some(pad.y()),
|
||||
8 => Some(pad.l()),
|
||||
9 => Some(pad.r()),
|
||||
10 => Some(pad.start()),
|
||||
11 => Some(pad.select()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_button_down(
|
||||
&self,
|
||||
id: u32,
|
||||
hw: &mut dyn prometeu_hal::HardwareBridge,
|
||||
) -> bool {
|
||||
match id {
|
||||
0 => hw.pad().up().down,
|
||||
1 => hw.pad().down().down,
|
||||
2 => hw.pad().left().down,
|
||||
3 => hw.pad().right().down,
|
||||
4 => hw.pad().a().down,
|
||||
5 => hw.pad().b().down,
|
||||
6 => hw.pad().x().down,
|
||||
7 => hw.pad().y().down,
|
||||
8 => hw.pad().l().down,
|
||||
9 => hw.pad().r().down,
|
||||
10 => hw.pad().start().down,
|
||||
11 => hw.pad().select().down,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeInterface for VirtualMachineRuntime {
|
||||
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))
|
||||
})?;
|
||||
|
||||
match syscall {
|
||||
Syscall::SystemHasCart => {
|
||||
ret.push_bool(true);
|
||||
return Ok(());
|
||||
}
|
||||
Syscall::SystemRunCart => return Ok(()),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let hw = ctx.require_hw()?;
|
||||
|
||||
match syscall {
|
||||
Syscall::SystemHasCart => unreachable!(),
|
||||
Syscall::SystemRunCart => unreachable!(),
|
||||
Syscall::GfxClear => {
|
||||
let color = self.get_color(expect_int(args, 0)?);
|
||||
hw.gfx_mut().clear(color);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::GfxFillRect => {
|
||||
let x = expect_int(args, 0)? as i32;
|
||||
let y = expect_int(args, 1)? as i32;
|
||||
let w = expect_int(args, 2)? as i32;
|
||||
let h = expect_int(args, 3)? as i32;
|
||||
let color = self.get_color(expect_int(args, 4)?);
|
||||
hw.gfx_mut().fill_rect(x, y, w, h, color);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::GfxDrawLine => {
|
||||
let x1 = expect_int(args, 0)? as i32;
|
||||
let y1 = expect_int(args, 1)? as i32;
|
||||
let x2 = expect_int(args, 2)? as i32;
|
||||
let y2 = expect_int(args, 3)? as i32;
|
||||
let color = self.get_color(expect_int(args, 4)?);
|
||||
hw.gfx_mut().draw_line(x1, y1, x2, y2, color);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::GfxDrawCircle => {
|
||||
let x = expect_int(args, 0)? as i32;
|
||||
let y = expect_int(args, 1)? as i32;
|
||||
let r = expect_int(args, 2)? as i32;
|
||||
let color = self.get_color(expect_int(args, 3)?);
|
||||
hw.gfx_mut().draw_circle(x, y, r, color);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::GfxDrawDisc => {
|
||||
let x = expect_int(args, 0)? as i32;
|
||||
let y = expect_int(args, 1)? as i32;
|
||||
let r = expect_int(args, 2)? as i32;
|
||||
let border_color = self.get_color(expect_int(args, 3)?);
|
||||
let fill_color = self.get_color(expect_int(args, 4)?);
|
||||
hw.gfx_mut().draw_disc(x, y, r, border_color, fill_color);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::GfxDrawSquare => {
|
||||
let x = expect_int(args, 0)? as i32;
|
||||
let y = expect_int(args, 1)? as i32;
|
||||
let w = expect_int(args, 2)? as i32;
|
||||
let h = expect_int(args, 3)? as i32;
|
||||
let border_color = self.get_color(expect_int(args, 4)?);
|
||||
let fill_color = self.get_color(expect_int(args, 5)?);
|
||||
hw.gfx_mut().draw_square(x, y, w, h, border_color, fill_color);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::GfxSetSprite => {
|
||||
let asset_name = match args
|
||||
.first()
|
||||
.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())),
|
||||
};
|
||||
let index = expect_int(args, 1)? as usize;
|
||||
let x = expect_int(args, 2)? as i32;
|
||||
let y = expect_int(args, 3)? as i32;
|
||||
let tile_id = expect_int(args, 4)? as u16;
|
||||
let palette_id = expect_int(args, 5)? as u8;
|
||||
let active = expect_bool(args, 6)?;
|
||||
let flip_x = expect_bool(args, 7)?;
|
||||
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);
|
||||
|
||||
if index < 512 {
|
||||
*hw.gfx_mut().sprite_mut(index) = Sprite {
|
||||
tile: Tile { id: tile_id, flip_x: false, flip_y: false, palette_id },
|
||||
x,
|
||||
y,
|
||||
bank_id,
|
||||
active,
|
||||
flip_x,
|
||||
flip_y,
|
||||
priority,
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
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()))?
|
||||
{
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string message".into())),
|
||||
};
|
||||
let color = self.get_color(expect_int(args, 3)?);
|
||||
hw.gfx_mut().draw_text(x, y, &msg, color);
|
||||
Ok(())
|
||||
}
|
||||
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".into()));
|
||||
}
|
||||
hw.gfx_mut().clear(Color::from_raw(color_val as u16));
|
||||
Ok(())
|
||||
}
|
||||
Syscall::InputGetPad => {
|
||||
ret.push_bool(self.is_button_down(expect_int(args, 0)? as u32, hw));
|
||||
Ok(())
|
||||
}
|
||||
Syscall::InputGetPadPressed => {
|
||||
let val = self
|
||||
.get_button(expect_int(args, 0)? as u32, hw)
|
||||
.map(|b| b.pressed)
|
||||
.unwrap_or(false);
|
||||
ret.push_bool(val);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::InputGetPadReleased => {
|
||||
let val = self
|
||||
.get_button(expect_int(args, 0)? as u32, hw)
|
||||
.map(|b| b.released)
|
||||
.unwrap_or(false);
|
||||
ret.push_bool(val);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::InputGetPadHold => {
|
||||
let val = self
|
||||
.get_button(expect_int(args, 0)? as u32, hw)
|
||||
.map(|b| b.hold_frames)
|
||||
.unwrap_or(0);
|
||||
ret.push_int(val as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::TouchGetX => {
|
||||
ret.push_int(hw.touch().x() as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::TouchGetY => {
|
||||
ret.push_int(hw.touch().y() as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::TouchIsDown => {
|
||||
ret.push_bool(hw.touch().f().down);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::TouchIsPressed => {
|
||||
ret.push_bool(hw.touch().f().pressed);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::TouchIsReleased => {
|
||||
ret.push_bool(hw.touch().f().released);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::TouchGetHold => {
|
||||
ret.push_int(hw.touch().f().hold_frames as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::TouchGetFinger => {
|
||||
let btn = hw.touch().f();
|
||||
ret.push_bool(btn.pressed);
|
||||
ret.push_bool(btn.released);
|
||||
ret.push_bool(btn.down);
|
||||
ret.push_int(btn.hold_frames as i64);
|
||||
Ok(())
|
||||
}
|
||||
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(),
|
||||
] {
|
||||
ret.push_bool(btn.pressed);
|
||||
ret.push_bool(btn.released);
|
||||
ret.push_bool(btn.down);
|
||||
ret.push_int(btn.hold_frames as i64);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Syscall::InputTouchSnapshot => {
|
||||
let touch = hw.touch();
|
||||
ret.push_bool(touch.f().pressed);
|
||||
ret.push_bool(touch.f().released);
|
||||
ret.push_bool(touch.f().down);
|
||||
ret.push_int(touch.f().hold_frames as i64);
|
||||
ret.push_int(touch.x() as i64);
|
||||
ret.push_int(touch.y() as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::PadGetUp => push_button(ret, hw.pad().up()),
|
||||
Syscall::PadGetDown => push_button(ret, hw.pad().down()),
|
||||
Syscall::PadGetLeft => push_button(ret, hw.pad().left()),
|
||||
Syscall::PadGetRight => push_button(ret, hw.pad().right()),
|
||||
Syscall::PadGetA => push_button(ret, hw.pad().a()),
|
||||
Syscall::PadGetB => push_button(ret, hw.pad().b()),
|
||||
Syscall::PadGetX => push_button(ret, hw.pad().x()),
|
||||
Syscall::PadGetY => push_button(ret, hw.pad().y()),
|
||||
Syscall::PadGetL => push_button(ret, hw.pad().l()),
|
||||
Syscall::PadGetR => push_button(ret, hw.pad().r()),
|
||||
Syscall::PadGetStart => push_button(ret, hw.pad().start()),
|
||||
Syscall::PadGetSelect => push_button(ret, hw.pad().select()),
|
||||
Syscall::AudioPlaySample => {
|
||||
let sample_id = expect_int(args, 0)? as u32;
|
||||
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 = expect_number(args, 4, "pitch")?;
|
||||
|
||||
hw.audio_mut().play(
|
||||
0,
|
||||
sample_id as u16,
|
||||
voice_id,
|
||||
volume,
|
||||
pan,
|
||||
pitch,
|
||||
0,
|
||||
prometeu_hal::LoopMode::Off,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::AudioPlay => {
|
||||
let asset_name = match args
|
||||
.first()
|
||||
.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())),
|
||||
};
|
||||
let sample_id = expect_int(args, 1)? as u16;
|
||||
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 = expect_number(args, 5, "pitch")?;
|
||||
let loop_mode = match expect_int(args, 6)? {
|
||||
0 => prometeu_hal::LoopMode::Off,
|
||||
_ => prometeu_hal::LoopMode::On,
|
||||
};
|
||||
|
||||
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);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::FsOpen => {
|
||||
let path = expect_string(args, 0, "path")?;
|
||||
if self.fs_state != FsState::Mounted {
|
||||
ret.push_int(-1);
|
||||
return Ok(());
|
||||
}
|
||||
let handle = self.next_handle;
|
||||
self.open_files.insert(handle, path);
|
||||
self.next_handle += 1;
|
||||
ret.push_int(handle as i64);
|
||||
Ok(())
|
||||
}
|
||||
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()))?;
|
||||
match self.fs.read_file(path) {
|
||||
Ok(data) => ret.push_string(String::from_utf8_lossy(&data).into_owned()),
|
||||
Err(_) => ret.push_null(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Syscall::FsWrite => {
|
||||
let handle = expect_int(args, 0)? as u32;
|
||||
let content = expect_string(args, 1, "content")?.into_bytes();
|
||||
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),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Syscall::FsClose => {
|
||||
self.open_files.remove(&(expect_int(args, 0)? as u32));
|
||||
Ok(())
|
||||
}
|
||||
Syscall::FsListDir => {
|
||||
let path = expect_string(args, 0, "path")?;
|
||||
match self.fs.list_dir(&path) {
|
||||
Ok(entries) => {
|
||||
let names: Vec<String> = entries.into_iter().map(|e| e.name).collect();
|
||||
ret.push_string(names.join(";"));
|
||||
}
|
||||
Err(_) => ret.push_null(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Syscall::FsExists => {
|
||||
ret.push_bool(self.fs.exists(&expect_string(args, 0, "path")?));
|
||||
Ok(())
|
||||
}
|
||||
Syscall::FsDelete => {
|
||||
match self.fs.delete(&expect_string(args, 0, "path")?) {
|
||||
Ok(_) => ret.push_bool(true),
|
||||
Err(_) => ret.push_bool(false),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Syscall::LogWrite => {
|
||||
self.syscall_log_write(
|
||||
expect_int(args, 0)?,
|
||||
0,
|
||||
expect_string(args, 1, "message")?,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
Syscall::LogWriteTag => {
|
||||
self.syscall_log_write(
|
||||
expect_int(args, 0)?,
|
||||
expect_int(args, 1)? as u16,
|
||||
expect_string(args, 2, "message")?,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
Syscall::AssetLoad => {
|
||||
let asset_id = expect_string(args, 0, "asset_id")?;
|
||||
let asset_type = match expect_int(args, 1)? as u32 {
|
||||
0 => BankType::TILES,
|
||||
1 => BankType::SOUNDS,
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
};
|
||||
let slot = SlotRef { asset_type, index: expect_int(args, 2)? as usize };
|
||||
|
||||
match hw.assets().load(&asset_id, slot) {
|
||||
Ok(handle) => {
|
||||
ret.push_int(handle as i64);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(VmFault::Panic(e)),
|
||||
}
|
||||
}
|
||||
Syscall::AssetStatus => {
|
||||
let status_val = match hw.assets().status(expect_int(args, 0)? as u32) {
|
||||
LoadStatus::PENDING => 0,
|
||||
LoadStatus::LOADING => 1,
|
||||
LoadStatus::READY => 2,
|
||||
LoadStatus::COMMITTED => 3,
|
||||
LoadStatus::CANCELED => 4,
|
||||
LoadStatus::ERROR => 5,
|
||||
};
|
||||
ret.push_int(status_val);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::AssetCommit => {
|
||||
hw.assets().commit(expect_int(args, 0)? as u32);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::AssetCancel => {
|
||||
hw.assets().cancel(expect_int(args, 0)? as u32);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::BankInfo => {
|
||||
let asset_type = match expect_int(args, 0)? as u32 {
|
||||
0 => BankType::TILES,
|
||||
1 => BankType::SOUNDS,
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
};
|
||||
let json =
|
||||
serde_json::to_string(&hw.assets().bank_info(asset_type)).unwrap_or_default();
|
||||
ret.push_string(json);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::BankSlotInfo => {
|
||||
let asset_type = match expect_int(args, 0)? as u32 {
|
||||
0 => BankType::TILES,
|
||||
1 => BankType::SOUNDS,
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
};
|
||||
let slot = SlotRef { asset_type, index: expect_int(args, 1)? as usize };
|
||||
let json = serde_json::to_string(&hw.assets().slot_info(slot)).unwrap_or_default();
|
||||
ret.push_string(json);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_button(ret: &mut HostReturn, button: &Button) -> Result<(), VmFault> {
|
||||
ret.push_bool(button.pressed);
|
||||
ret.push_bool(button.released);
|
||||
ret.push_bool(button.down);
|
||||
ret.push_int(button.hold_frames as i64);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expect_string(args: &[Value], index: usize, field: &str) -> Result<String, VmFault> {
|
||||
match args.get(index).ok_or_else(|| VmFault::Panic(format!("Missing {}", field)))? {
|
||||
Value::String(value) => Ok(value.clone()),
|
||||
_ => Err(VmFault::Trap(TRAP_TYPE, format!("Expected string {}", field))),
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_number(args: &[Value], index: usize, field: &str) -> Result<f64, VmFault> {
|
||||
match args.get(index).ok_or_else(|| VmFault::Panic(format!("Missing {}", field)))? {
|
||||
Value::Float(f) => Ok(*f),
|
||||
Value::Int32(i) => Ok(*i as f64),
|
||||
Value::Int64(i) => Ok(*i as f64),
|
||||
_ => Err(VmFault::Trap(TRAP_TYPE, format!("Expected number for {}", field))),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
use super::*;
|
||||
use crate::CrashReport;
|
||||
use crate::fs::FsBackend;
|
||||
use prometeu_hal::cartridge::Cartridge;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
|
||||
impl VirtualMachineRuntime {
|
||||
pub fn new(cap_config: Option<CertificationConfig>) -> Self {
|
||||
let boot_time = Instant::now();
|
||||
let mut os = Self {
|
||||
tick_index: 0,
|
||||
logical_frame_index: 0,
|
||||
logical_frame_active: false,
|
||||
logical_frame_remaining_cycles: 0,
|
||||
last_frame_cpu_time_us: 0,
|
||||
fs: VirtualFS::new(),
|
||||
fs_state: FsState::Unmounted,
|
||||
open_files: HashMap::new(),
|
||||
next_handle: 1,
|
||||
log_service: LogService::new(4096),
|
||||
current_app_id: 0,
|
||||
current_cartridge_title: String::new(),
|
||||
current_cartridge_app_version: String::new(),
|
||||
current_cartridge_app_mode: AppMode::Game,
|
||||
current_entrypoint: String::new(),
|
||||
logs_written_this_frame: HashMap::new(),
|
||||
telemetry_current: TelemetryFrame::default(),
|
||||
telemetry_last: TelemetryFrame::default(),
|
||||
last_crash_report: None,
|
||||
certifier: Certifier::new(cap_config.unwrap_or_default()),
|
||||
paused: false,
|
||||
debug_step_request: false,
|
||||
needs_prepare_entry_call: false,
|
||||
boot_time,
|
||||
};
|
||||
|
||||
os.log(LogLevel::Info, LogSource::Pos, 0, "PrometeuOS starting...".to_string());
|
||||
|
||||
os
|
||||
}
|
||||
|
||||
pub fn log(&mut self, level: LogLevel, source: LogSource, tag: u16, msg: String) {
|
||||
let ts_ms = self.boot_time.elapsed().as_millis() as u64;
|
||||
let frame = self.logical_frame_index;
|
||||
self.log_service.log(ts_ms, frame, level, source, tag, msg);
|
||||
}
|
||||
|
||||
pub fn mount_fs(&mut self, backend: Box<dyn FsBackend>) {
|
||||
self.log(LogLevel::Info, LogSource::Fs, 0, "Attempting to mount filesystem".to_string());
|
||||
match self.fs.mount(backend) {
|
||||
Ok(_) => {
|
||||
self.fs_state = FsState::Mounted;
|
||||
self.log(
|
||||
LogLevel::Info,
|
||||
LogSource::Fs,
|
||||
0,
|
||||
"Filesystem mounted successfully".to_string(),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
let err_msg = format!("Failed to mount filesystem: {:?}", e);
|
||||
self.log(LogLevel::Error, LogSource::Fs, 0, err_msg);
|
||||
self.fs_state = FsState::Error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unmount_fs(&mut self) {
|
||||
self.fs.unmount();
|
||||
self.fs_state = FsState::Unmounted;
|
||||
}
|
||||
|
||||
pub(crate) fn update_fs(&mut self) {
|
||||
if self.fs_state == FsState::Mounted && !self.fs.is_healthy() {
|
||||
self.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Fs,
|
||||
0,
|
||||
"Filesystem became unhealthy, unmounting".to_string(),
|
||||
);
|
||||
self.unmount_fs();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear_cartridge_state(&mut self) {
|
||||
self.logical_frame_index = 0;
|
||||
self.logical_frame_active = false;
|
||||
self.logical_frame_remaining_cycles = 0;
|
||||
self.last_frame_cpu_time_us = 0;
|
||||
|
||||
self.open_files.clear();
|
||||
self.next_handle = 1;
|
||||
|
||||
self.current_app_id = 0;
|
||||
self.current_cartridge_title.clear();
|
||||
self.current_cartridge_app_version.clear();
|
||||
self.current_cartridge_app_mode = AppMode::Game;
|
||||
self.current_entrypoint.clear();
|
||||
self.logs_written_this_frame.clear();
|
||||
|
||||
self.telemetry_current = TelemetryFrame::default();
|
||||
self.telemetry_last = TelemetryFrame::default();
|
||||
self.last_crash_report = None;
|
||||
|
||||
self.paused = false;
|
||||
self.debug_step_request = false;
|
||||
self.needs_prepare_entry_call = false;
|
||||
}
|
||||
|
||||
pub fn reset(&mut self, vm: &mut VirtualMachine) {
|
||||
*vm = VirtualMachine::default();
|
||||
self.clear_cartridge_state();
|
||||
}
|
||||
|
||||
pub fn initialize_vm(
|
||||
&mut self,
|
||||
vm: &mut VirtualMachine,
|
||||
cartridge: &Cartridge,
|
||||
) -> Result<(), CrashReport> {
|
||||
self.clear_cartridge_state();
|
||||
vm.set_capabilities(cartridge.capabilities);
|
||||
|
||||
match vm.initialize(cartridge.program.clone(), &cartridge.entrypoint) {
|
||||
Ok(_) => {
|
||||
self.current_app_id = cartridge.app_id;
|
||||
self.current_cartridge_title = cartridge.title.clone();
|
||||
self.current_cartridge_app_version = cartridge.app_version.clone();
|
||||
self.current_cartridge_app_mode = cartridge.app_mode;
|
||||
self.current_entrypoint = cartridge.entrypoint.clone();
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
let report = CrashReport::VmInit { error: e };
|
||||
self.last_crash_report = Some(report.clone());
|
||||
self.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Vm,
|
||||
report.log_tag(),
|
||||
format!("Failed to initialize VM: {}", report),
|
||||
);
|
||||
Err(report)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use super::*;
|
||||
use prometeu_bytecode::TRAP_TYPE;
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_bytecode::assembler::assemble;
|
||||
use prometeu_bytecode::model::{BytecodeModule, FunctionMeta, SyscallDecl};
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use prometeu_hal::InputSignals;
|
||||
use prometeu_hal::cartridge::Cartridge;
|
||||
use prometeu_hal::syscalls::caps;
|
||||
use prometeu_vm::VmInitError;
|
||||
|
||||
fn cartridge_with_program(program: Vec<u8>, capabilities: u64) -> Cartridge {
|
||||
Cartridge {
|
||||
app_id: 42,
|
||||
title: "Test Cart".into(),
|
||||
app_version: "1.0.0".into(),
|
||||
app_mode: AppMode::Game,
|
||||
entrypoint: "".into(),
|
||||
capabilities,
|
||||
program,
|
||||
assets: vec![],
|
||||
asset_table: vec![],
|
||||
preload: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn serialized_single_function_module(code: Vec<u8>, syscalls: Vec<SyscallDecl>) -> Vec<u8> {
|
||||
BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
..Default::default()
|
||||
}],
|
||||
code,
|
||||
debug_info: None,
|
||||
exports: vec![],
|
||||
syscalls,
|
||||
}
|
||||
.serialize()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_vm_applies_cartridge_capabilities_before_loader_resolution() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
|
||||
let program = serialized_single_function_module(
|
||||
code,
|
||||
vec![SyscallDecl {
|
||||
module: "gfx".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}],
|
||||
);
|
||||
let cartridge = cartridge_with_program(program, caps::NONE);
|
||||
|
||||
let res = runtime.initialize_vm(&mut vm, &cartridge);
|
||||
|
||||
assert!(matches!(res, Err(CrashReport::VmInit { error: VmInitError::LoaderPatchFailed(_) })));
|
||||
assert_eq!(runtime.current_app_id, 0);
|
||||
assert_eq!(vm.pc(), 0);
|
||||
assert_eq!(vm.operand_stack_top(1), Vec::<Value>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_vm_succeeds_when_cartridge_capabilities_cover_hostcalls() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
|
||||
let program = serialized_single_function_module(
|
||||
code,
|
||||
vec![SyscallDecl {
|
||||
module: "gfx".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}],
|
||||
);
|
||||
let cartridge = cartridge_with_program(program, caps::GFX);
|
||||
|
||||
let res = runtime.initialize_vm(&mut vm, &cartridge);
|
||||
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(runtime.current_app_id, 42);
|
||||
assert!(!vm.is_halted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tick_returns_error_when_vm_ends_slice_with_trap() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hardware = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
let code = assemble("PUSH_BOOL 1\nHOSTCALL 0\nHALT").expect("assemble");
|
||||
let program = serialized_single_function_module(
|
||||
code,
|
||||
vec![SyscallDecl {
|
||||
module: "gfx".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}],
|
||||
);
|
||||
let cartridge = cartridge_with_program(program, caps::GFX);
|
||||
|
||||
runtime.initialize_vm(&mut vm, &cartridge).expect("runtime must initialize");
|
||||
|
||||
let report =
|
||||
runtime.tick(&mut vm, &signals, &mut hardware).expect("trap must surface as runtime error");
|
||||
|
||||
match report {
|
||||
CrashReport::VmTrap { trap } => {
|
||||
assert_eq!(trap.code, TRAP_TYPE);
|
||||
assert!(trap.message.contains("Expected integer at index 0"));
|
||||
}
|
||||
other => panic!("expected VmTrap crash report, got {:?}", other),
|
||||
}
|
||||
assert!(matches!(runtime.last_crash_report, Some(CrashReport::VmTrap { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tick_returns_panic_report_distinct_from_trap() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::new(assemble("HOSTCALL 0\nHALT").expect("assemble"), vec![]);
|
||||
let mut hardware = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
|
||||
let report = runtime
|
||||
.tick(&mut vm, &signals, &mut hardware)
|
||||
.expect("panic must surface as runtime error");
|
||||
|
||||
match report {
|
||||
CrashReport::VmPanic { message, pc } => {
|
||||
assert!(message.contains("HOSTCALL 0 reached execution without loader patching"));
|
||||
assert!(pc.is_some());
|
||||
}
|
||||
other => panic!("expected VmPanic crash report, got {:?}", other),
|
||||
}
|
||||
assert!(matches!(runtime.last_crash_report, Some(CrashReport::VmPanic { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_vm_success_clears_previous_crash_report() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
runtime.last_crash_report = Some(CrashReport::VmPanic { message: "stale".into(), pc: Some(1) });
|
||||
|
||||
let mut vm = VirtualMachine::default();
|
||||
let code = assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble");
|
||||
let program = serialized_single_function_module(
|
||||
code,
|
||||
vec![SyscallDecl {
|
||||
module: "gfx".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}],
|
||||
);
|
||||
let cartridge = cartridge_with_program(program, caps::GFX);
|
||||
|
||||
runtime.initialize_vm(&mut vm, &cartridge).expect("runtime must initialize");
|
||||
assert!(runtime.last_crash_report.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_cartridge_scoped_runtime_state() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
|
||||
runtime.tick_index = 77;
|
||||
runtime.logical_frame_index = 12;
|
||||
runtime.logical_frame_active = true;
|
||||
runtime.logical_frame_remaining_cycles = 345;
|
||||
runtime.last_frame_cpu_time_us = 678;
|
||||
runtime.fs_state = FsState::Mounted;
|
||||
runtime.open_files.insert(7, "/save.dat".into());
|
||||
runtime.next_handle = 9;
|
||||
runtime.current_app_id = 42;
|
||||
runtime.current_cartridge_title = "Cart".into();
|
||||
runtime.current_cartridge_app_version = "1.2.3".into();
|
||||
runtime.current_cartridge_app_mode = AppMode::System;
|
||||
runtime.current_entrypoint = "main".into();
|
||||
runtime.logs_written_this_frame.insert(42, 3);
|
||||
runtime.telemetry_current.frame_index = 8;
|
||||
runtime.telemetry_current.cycles_used = 99;
|
||||
runtime.telemetry_last.frame_index = 7;
|
||||
runtime.telemetry_last.completed_logical_frames = 2;
|
||||
runtime.last_crash_report =
|
||||
Some(CrashReport::VmPanic { message: "stale".into(), pc: Some(55) });
|
||||
runtime.paused = true;
|
||||
runtime.debug_step_request = true;
|
||||
runtime.needs_prepare_entry_call = true;
|
||||
|
||||
runtime.reset(&mut vm);
|
||||
|
||||
assert_eq!(runtime.tick_index, 77);
|
||||
assert_eq!(runtime.fs_state, FsState::Mounted);
|
||||
assert_eq!(runtime.logical_frame_index, 0);
|
||||
assert!(!runtime.logical_frame_active);
|
||||
assert_eq!(runtime.logical_frame_remaining_cycles, 0);
|
||||
assert_eq!(runtime.last_frame_cpu_time_us, 0);
|
||||
assert!(runtime.open_files.is_empty());
|
||||
assert_eq!(runtime.next_handle, 1);
|
||||
assert_eq!(runtime.current_app_id, 0);
|
||||
assert!(runtime.current_cartridge_title.is_empty());
|
||||
assert!(runtime.current_cartridge_app_version.is_empty());
|
||||
assert_eq!(runtime.current_cartridge_app_mode, AppMode::Game);
|
||||
assert!(runtime.current_entrypoint.is_empty());
|
||||
assert!(runtime.logs_written_this_frame.is_empty());
|
||||
assert_eq!(runtime.telemetry_current.frame_index, 0);
|
||||
assert_eq!(runtime.telemetry_current.cycles_used, 0);
|
||||
assert_eq!(runtime.telemetry_last.frame_index, 0);
|
||||
assert_eq!(runtime.telemetry_last.completed_logical_frames, 0);
|
||||
assert!(runtime.last_crash_report.is_none());
|
||||
assert!(!runtime.paused);
|
||||
assert!(!runtime.debug_step_request);
|
||||
assert!(!runtime.needs_prepare_entry_call);
|
||||
assert_eq!(vm.pc(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_vm_failure_clears_previous_identity_and_handles() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
|
||||
let good_program = serialized_single_function_module(
|
||||
assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble"),
|
||||
vec![SyscallDecl {
|
||||
module: "gfx".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}],
|
||||
);
|
||||
let good_cartridge = cartridge_with_program(good_program, caps::GFX);
|
||||
runtime.initialize_vm(&mut vm, &good_cartridge).expect("runtime must initialize");
|
||||
|
||||
runtime.open_files.insert(5, "/save.dat".into());
|
||||
runtime.next_handle = 6;
|
||||
runtime.paused = true;
|
||||
runtime.debug_step_request = true;
|
||||
runtime.telemetry_current.cycles_used = 123;
|
||||
|
||||
let bad_program = serialized_single_function_module(
|
||||
assemble("PUSH_I32 0\nHOSTCALL 0\nHALT").expect("assemble"),
|
||||
vec![SyscallDecl {
|
||||
module: "gfx".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}],
|
||||
);
|
||||
let bad_cartridge = cartridge_with_program(bad_program, caps::NONE);
|
||||
|
||||
let res = runtime.initialize_vm(&mut vm, &bad_cartridge);
|
||||
|
||||
assert!(matches!(res, Err(CrashReport::VmInit { error: VmInitError::LoaderPatchFailed(_) })));
|
||||
assert_eq!(runtime.current_app_id, 0);
|
||||
assert!(runtime.current_cartridge_title.is_empty());
|
||||
assert!(runtime.current_cartridge_app_version.is_empty());
|
||||
assert_eq!(runtime.current_cartridge_app_mode, AppMode::Game);
|
||||
assert!(runtime.current_entrypoint.is_empty());
|
||||
assert!(runtime.open_files.is_empty());
|
||||
assert_eq!(runtime.next_handle, 1);
|
||||
assert!(!runtime.paused);
|
||||
assert!(!runtime.debug_step_request);
|
||||
assert_eq!(runtime.telemetry_current.cycles_used, 0);
|
||||
assert!(matches!(runtime.last_crash_report, Some(CrashReport::VmInit { .. })));
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
use super::*;
|
||||
use crate::CrashReport;
|
||||
use prometeu_hal::asset::BankType;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_hal::{HardwareBridge, HostContext, InputSignals};
|
||||
use prometeu_vm::LogicalFrameEndingReason;
|
||||
|
||||
impl VirtualMachineRuntime {
|
||||
pub fn debug_step_instruction(
|
||||
&mut self,
|
||||
vm: &mut VirtualMachine,
|
||||
hw: &mut dyn HardwareBridge,
|
||||
) -> Option<CrashReport> {
|
||||
let mut ctx = HostContext::new(Some(hw));
|
||||
match vm.step(self, &mut ctx) {
|
||||
Ok(_) => None,
|
||||
Err(e) => {
|
||||
let report = match e {
|
||||
LogicalFrameEndingReason::Trap(trap) => CrashReport::VmTrap { trap },
|
||||
LogicalFrameEndingReason::Panic(message) => {
|
||||
CrashReport::VmPanic { message, pc: Some(vm.pc() as u32) }
|
||||
}
|
||||
other => CrashReport::VmPanic {
|
||||
message: format!("Unexpected fault during step: {:?}", other),
|
||||
pc: Some(vm.pc() as u32),
|
||||
},
|
||||
};
|
||||
self.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Vm,
|
||||
report.log_tag(),
|
||||
format!("PVM Fault during Step: {}", report),
|
||||
);
|
||||
self.last_crash_report = Some(report.clone());
|
||||
Some(report)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tick(
|
||||
&mut self,
|
||||
vm: &mut VirtualMachine,
|
||||
signals: &InputSignals,
|
||||
hw: &mut dyn HardwareBridge,
|
||||
) -> Option<CrashReport> {
|
||||
let start = Instant::now();
|
||||
self.tick_index += 1;
|
||||
|
||||
if self.paused && !self.debug_step_request {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.update_fs();
|
||||
|
||||
if !self.logical_frame_active {
|
||||
self.logical_frame_active = true;
|
||||
self.logical_frame_remaining_cycles = Self::CYCLES_PER_LOGICAL_FRAME;
|
||||
self.begin_logical_frame(signals, hw);
|
||||
|
||||
if self.needs_prepare_entry_call || vm.call_stack_is_empty() {
|
||||
vm.prepare_call(&self.current_entrypoint);
|
||||
self.needs_prepare_entry_call = false;
|
||||
}
|
||||
|
||||
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),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
let budget = std::cmp::min(Self::SLICE_PER_TICK, self.logical_frame_remaining_cycles);
|
||||
|
||||
if budget > 0 {
|
||||
let run_result = {
|
||||
let mut ctx = HostContext::new(Some(hw));
|
||||
vm.run_budget(budget, self, &mut ctx)
|
||||
};
|
||||
|
||||
match run_result {
|
||||
Ok(run) => {
|
||||
self.logical_frame_remaining_cycles =
|
||||
self.logical_frame_remaining_cycles.saturating_sub(run.cycles_used);
|
||||
self.telemetry_current.cycles_used += run.cycles_used;
|
||||
self.telemetry_current.vm_steps += run.steps_executed;
|
||||
|
||||
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()),
|
||||
);
|
||||
}
|
||||
|
||||
if let LogicalFrameEndingReason::Panic(err) = run.reason {
|
||||
let report =
|
||||
CrashReport::VmPanic { message: err, pc: Some(vm.pc() as u32) };
|
||||
self.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Vm,
|
||||
report.log_tag(),
|
||||
report.summary(),
|
||||
);
|
||||
self.last_crash_report = Some(report.clone());
|
||||
return Some(report);
|
||||
}
|
||||
|
||||
if let LogicalFrameEndingReason::Trap(trap) = &run.reason {
|
||||
let report = CrashReport::VmTrap { trap: trap.clone() };
|
||||
self.log(
|
||||
LogLevel::Error,
|
||||
LogSource::Vm,
|
||||
report.log_tag(),
|
||||
report.summary(),
|
||||
);
|
||||
self.last_crash_report = Some(report.clone());
|
||||
return Some(report);
|
||||
}
|
||||
|
||||
if run.reason == LogicalFrameEndingReason::FrameSync
|
||||
|| run.reason == LogicalFrameEndingReason::EndOfRom
|
||||
{
|
||||
hw.gfx_mut().render_all();
|
||||
self.telemetry_current.host_cpu_time_us =
|
||||
start.elapsed().as_micros() as u64;
|
||||
|
||||
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.completed_logical_frames += 1;
|
||||
self.telemetry_last = self.telemetry_current;
|
||||
|
||||
self.logical_frame_index += 1;
|
||||
self.logical_frame_active = false;
|
||||
self.logical_frame_remaining_cycles = 0;
|
||||
|
||||
if run.reason == LogicalFrameEndingReason::FrameSync {
|
||||
self.needs_prepare_entry_call = true;
|
||||
}
|
||||
|
||||
if self.debug_step_request {
|
||||
self.paused = true;
|
||||
self.debug_step_request = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let report = CrashReport::VmPanic { message: e, pc: Some(vm.pc() as u32) };
|
||||
self.log(LogLevel::Error, LogSource::Vm, report.log_tag(), report.summary());
|
||||
self.last_crash_report = Some(report.clone());
|
||||
return Some(report);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.last_frame_cpu_time_us = start.elapsed().as_micros() as u64;
|
||||
|
||||
let gfx_stats = hw.assets().bank_info(BankType::TILES);
|
||||
self.telemetry_current.gfx_used_bytes = gfx_stats.used_bytes;
|
||||
self.telemetry_current.gfx_inflight_bytes = gfx_stats.inflight_bytes;
|
||||
self.telemetry_current.gfx_slots_occupied = gfx_stats.slots_occupied as u32;
|
||||
|
||||
let audio_stats = hw.assets().bank_info(BankType::SOUNDS);
|
||||
self.telemetry_current.audio_used_bytes = audio_stats.used_bytes;
|
||||
self.telemetry_current.audio_inflight_bytes = audio_stats.inflight_bytes;
|
||||
self.telemetry_current.audio_slots_occupied = audio_stats.slots_occupied as u32;
|
||||
|
||||
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;
|
||||
self.telemetry_last.gfx_inflight_bytes = self.telemetry_current.gfx_inflight_bytes;
|
||||
self.telemetry_last.gfx_slots_occupied = self.telemetry_current.gfx_slots_occupied;
|
||||
self.telemetry_last.audio_used_bytes = self.telemetry_current.audio_used_bytes;
|
||||
self.telemetry_last.audio_inflight_bytes = self.telemetry_current.audio_inflight_bytes;
|
||||
self.telemetry_last.audio_slots_occupied = self.telemetry_current.audio_slots_occupied;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn begin_logical_frame(
|
||||
&mut self,
|
||||
_signals: &InputSignals,
|
||||
hw: &mut dyn HardwareBridge,
|
||||
) {
|
||||
hw.audio_mut().clear_commands();
|
||||
self.logs_written_this_frame.clear();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user