implements memcard
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
use super::*;
|
||||
use prometeu_bytecode::{TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE, Value};
|
||||
use crate::services::memcard::{MemcardSlotState, MemcardStatus};
|
||||
use prometeu_hal::asset::{AssetLoadError, AssetOpStatus, BankType, LoadStatus, SlotRef};
|
||||
use prometeu_hal::cartridge::AppMode;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
use prometeu_hal::sprite::Sprite;
|
||||
@@ -346,6 +348,100 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Syscall::MemSlotCount => {
|
||||
if self.current_cartridge_app_mode != AppMode::Game {
|
||||
ret.push_int(MemcardStatus::AccessDenied as i64);
|
||||
ret.push_int(0);
|
||||
return Ok(());
|
||||
}
|
||||
ret.push_int(MemcardStatus::Ok as i64);
|
||||
ret.push_int(self.memcard.slot_count() as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::MemSlotStat => {
|
||||
let slot = expect_slot_index(args, 0)?;
|
||||
if self.current_cartridge_app_mode != AppMode::Game {
|
||||
ret.push_int(MemcardStatus::AccessDenied as i64);
|
||||
ret.push_int(MemcardSlotState::Empty as i64);
|
||||
ret.push_int(0);
|
||||
ret.push_int(0);
|
||||
ret.push_int(0);
|
||||
return Ok(());
|
||||
}
|
||||
let stat = self.memcard.slot_stat(&self.fs, self.current_app_id, slot);
|
||||
let status = if stat.state == MemcardSlotState::Corrupt {
|
||||
MemcardStatus::Corrupt
|
||||
} else {
|
||||
MemcardStatus::Ok
|
||||
};
|
||||
ret.push_int(status as i64);
|
||||
ret.push_int(stat.state as i64);
|
||||
ret.push_int(stat.used_bytes as i64);
|
||||
ret.push_int(stat.generation as i64);
|
||||
ret.push_int(stat.checksum as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::MemSlotRead => {
|
||||
let slot = expect_slot_index(args, 0)?;
|
||||
let offset = expect_non_negative_usize(args, 1, "offset")?;
|
||||
let max_bytes = expect_non_negative_usize(args, 2, "max_bytes")?;
|
||||
if self.current_cartridge_app_mode != AppMode::Game {
|
||||
ret.push_int(MemcardStatus::AccessDenied as i64);
|
||||
ret.push_string(String::new());
|
||||
ret.push_int(0);
|
||||
return Ok(());
|
||||
}
|
||||
let read =
|
||||
self.memcard.slot_read(&self.fs, self.current_app_id, slot, offset, max_bytes);
|
||||
ret.push_int(read.status as i64);
|
||||
ret.push_string(hex_encode(&read.bytes));
|
||||
ret.push_int(read.bytes_read as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::MemSlotWrite => {
|
||||
let slot = expect_slot_index(args, 0)?;
|
||||
let offset = expect_non_negative_usize(args, 1, "offset")?;
|
||||
let payload_hex = expect_string(args, 2, "payload_hex")?;
|
||||
if self.current_cartridge_app_mode != AppMode::Game {
|
||||
ret.push_int(MemcardStatus::AccessDenied as i64);
|
||||
ret.push_int(0);
|
||||
return Ok(());
|
||||
}
|
||||
let payload = hex_decode(&payload_hex)?;
|
||||
let write =
|
||||
self.memcard.slot_write(&self.fs, self.current_app_id, slot, offset, &payload);
|
||||
ret.push_int(write.status as i64);
|
||||
ret.push_int(write.bytes_written as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::MemSlotCommit => {
|
||||
let slot = expect_slot_index(args, 0)?;
|
||||
if self.current_cartridge_app_mode != AppMode::Game {
|
||||
ret.push_int(MemcardStatus::AccessDenied as i64);
|
||||
return Ok(());
|
||||
}
|
||||
let status = {
|
||||
let memcard = &mut self.memcard;
|
||||
let fs = &mut self.fs;
|
||||
memcard.slot_commit(fs, self.current_app_id, slot)
|
||||
};
|
||||
ret.push_int(status as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::MemSlotClear => {
|
||||
let slot = expect_slot_index(args, 0)?;
|
||||
if self.current_cartridge_app_mode != AppMode::Game {
|
||||
ret.push_int(MemcardStatus::AccessDenied as i64);
|
||||
return Ok(());
|
||||
}
|
||||
let status = {
|
||||
let memcard = &mut self.memcard;
|
||||
let fs = &mut self.fs;
|
||||
memcard.slot_clear(fs, self.current_app_id, slot)
|
||||
};
|
||||
ret.push_int(status as i64);
|
||||
Ok(())
|
||||
}
|
||||
Syscall::LogWrite => {
|
||||
self.syscall_log_write(
|
||||
expect_int(args, 0)?,
|
||||
@@ -454,3 +550,56 @@ fn expect_number(args: &[Value], index: usize, field: &str) -> Result<f64, VmFau
|
||||
_ => Err(VmFault::Trap(TRAP_TYPE, format!("Expected number for {}", field))),
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_slot_index(args: &[Value], index: usize) -> Result<u8, VmFault> {
|
||||
let slot = expect_int(args, index)?;
|
||||
if !(0..32).contains(&slot) {
|
||||
return Err(VmFault::Trap(TRAP_OOB, format!("slot index out of bounds: {}", slot)));
|
||||
}
|
||||
Ok(slot as u8)
|
||||
}
|
||||
|
||||
fn expect_non_negative_usize(args: &[Value], index: usize, field: &str) -> Result<usize, VmFault> {
|
||||
let val = expect_int(args, index)?;
|
||||
if val < 0 {
|
||||
return Err(VmFault::Trap(TRAP_OOB, format!("{} must be non-negative", field)));
|
||||
}
|
||||
Ok(val as usize)
|
||||
}
|
||||
|
||||
fn hex_encode(bytes: &[u8]) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for &b in bytes {
|
||||
out.push(HEX[(b >> 4) as usize] as char);
|
||||
out.push(HEX[(b & 0x0f) as usize] as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn hex_decode(s: &str) -> Result<Vec<u8>, VmFault> {
|
||||
fn nibble(c: u8) -> Option<u8> {
|
||||
match c {
|
||||
b'0'..=b'9' => Some(c - b'0'),
|
||||
b'a'..=b'f' => Some(10 + c - b'a'),
|
||||
b'A'..=b'F' => Some(10 + c - b'A'),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = s.as_bytes();
|
||||
if bytes.len() % 2 != 0 {
|
||||
return Err(VmFault::Trap(TRAP_TYPE, "payload_hex must have even length".to_string()));
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() / 2);
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
let hi = nibble(bytes[i])
|
||||
.ok_or_else(|| VmFault::Trap(TRAP_TYPE, "payload_hex contains invalid hex".to_string()))?;
|
||||
let lo = nibble(bytes[i + 1])
|
||||
.ok_or_else(|| VmFault::Trap(TRAP_TYPE, "payload_hex contains invalid hex".to_string()))?;
|
||||
out.push((hi << 4) | lo);
|
||||
i += 2;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ impl VirtualMachineRuntime {
|
||||
last_frame_cpu_time_us: 0,
|
||||
fs: VirtualFS::new(),
|
||||
fs_state: FsState::Unmounted,
|
||||
memcard: MemcardService::new(),
|
||||
open_files: HashMap::new(),
|
||||
next_handle: 1,
|
||||
log_service: LogService::new(4096),
|
||||
@@ -90,6 +91,7 @@ impl VirtualMachineRuntime {
|
||||
|
||||
self.open_files.clear();
|
||||
self.next_handle = 1;
|
||||
self.memcard.clear_all_staging();
|
||||
|
||||
self.current_app_id = 0;
|
||||
self.current_cartridge_title.clear();
|
||||
|
||||
@@ -4,12 +4,52 @@ use prometeu_bytecode::Value;
|
||||
use prometeu_bytecode::assembler::assemble;
|
||||
use prometeu_bytecode::model::{BytecodeModule, ConstantPoolEntry, FunctionMeta, SyscallDecl};
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use crate::fs::{FsBackend, FsEntry, FsError};
|
||||
use prometeu_hal::AudioOpStatus;
|
||||
use prometeu_hal::asset::AssetOpStatus;
|
||||
use prometeu_hal::InputSignals;
|
||||
use prometeu_hal::cartridge::Cartridge;
|
||||
use prometeu_hal::syscalls::caps;
|
||||
use prometeu_vm::VmInitError;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Default)]
|
||||
struct MemFsBackend {
|
||||
files: HashMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl FsBackend for MemFsBackend {
|
||||
fn mount(&mut self) -> Result<(), FsError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unmount(&mut self) {}
|
||||
|
||||
fn list_dir(&self, _path: &str) -> Result<Vec<FsEntry>, FsError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &str) -> Result<Vec<u8>, FsError> {
|
||||
self.files.get(path).cloned().ok_or(FsError::NotFound)
|
||||
}
|
||||
|
||||
fn write_file(&mut self, path: &str, data: &[u8]) -> Result<(), FsError> {
|
||||
self.files.insert(path.to_string(), data.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&mut self, path: &str) -> Result<(), FsError> {
|
||||
self.files.remove(path).map(|_| ()).ok_or(FsError::NotFound)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &str) -> bool {
|
||||
self.files.contains_key(path)
|
||||
}
|
||||
|
||||
fn is_healthy(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn cartridge_with_program(program: Vec<u8>, capabilities: u64) -> Cartridge {
|
||||
Cartridge {
|
||||
@@ -404,3 +444,102 @@ fn tick_gfx_set_sprite_type_mismatch_surfaces_trap_not_panic() {
|
||||
}
|
||||
assert!(matches!(runtime.last_crash_report, Some(CrashReport::VmTrap { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tick_memcard_slot_roundtrip_for_game_profile() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
runtime.mount_fs(Box::new(MemFsBackend::default()));
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hardware = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
let code = assemble(
|
||||
"PUSH_I32 0\nPUSH_I32 0\nPUSH_CONST 0\nHOSTCALL 0\nPOP_N 2\nPUSH_I32 0\nHOSTCALL 1\nPOP_N 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 10\nHOSTCALL 2\nHALT",
|
||||
)
|
||||
.expect("assemble");
|
||||
let program = serialized_single_function_module_with_consts(
|
||||
code,
|
||||
vec![ConstantPoolEntry::String("6869".into())], // "hi" in hex
|
||||
vec![
|
||||
SyscallDecl {
|
||||
module: "mem".into(),
|
||||
name: "slot_write".into(),
|
||||
version: 1,
|
||||
arg_slots: 3,
|
||||
ret_slots: 2,
|
||||
},
|
||||
SyscallDecl {
|
||||
module: "mem".into(),
|
||||
name: "slot_commit".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 1,
|
||||
},
|
||||
SyscallDecl {
|
||||
module: "mem".into(),
|
||||
name: "slot_read".into(),
|
||||
version: 1,
|
||||
arg_slots: 3,
|
||||
ret_slots: 3,
|
||||
},
|
||||
],
|
||||
);
|
||||
let cartridge = Cartridge {
|
||||
app_id: 42,
|
||||
title: "Memcard Game".into(),
|
||||
app_version: "1.0.0".into(),
|
||||
app_mode: AppMode::Game,
|
||||
entrypoint: "".into(),
|
||||
capabilities: caps::FS,
|
||||
program,
|
||||
assets: vec![],
|
||||
asset_table: vec![],
|
||||
preload: vec![],
|
||||
};
|
||||
|
||||
runtime.initialize_vm(&mut vm, &cartridge).expect("runtime must initialize");
|
||||
let report = runtime.tick(&mut vm, &signals, &mut hardware);
|
||||
assert!(report.is_none(), "memcard roundtrip must not crash");
|
||||
assert!(vm.is_halted());
|
||||
assert_eq!(
|
||||
vm.operand_stack_top(3),
|
||||
vec![Value::Int64(2), Value::String("6869".into()), Value::Int64(0)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tick_memcard_access_is_denied_for_non_game_profile() {
|
||||
let mut runtime = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hardware = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
let code = assemble("HOSTCALL 0\nHALT").expect("assemble");
|
||||
let program = serialized_single_function_module(
|
||||
code,
|
||||
vec![SyscallDecl {
|
||||
module: "mem".into(),
|
||||
name: "slot_count".into(),
|
||||
version: 1,
|
||||
arg_slots: 0,
|
||||
ret_slots: 2,
|
||||
}],
|
||||
);
|
||||
let cartridge = Cartridge {
|
||||
app_id: 101,
|
||||
title: "System App".into(),
|
||||
app_version: "1.0.0".into(),
|
||||
app_mode: AppMode::System,
|
||||
entrypoint: "".into(),
|
||||
capabilities: caps::FS,
|
||||
program,
|
||||
assets: vec![],
|
||||
asset_table: vec![],
|
||||
preload: vec![],
|
||||
};
|
||||
|
||||
runtime.initialize_vm(&mut vm, &cartridge).expect("runtime must initialize");
|
||||
let report = runtime.tick(&mut vm, &signals, &mut hardware);
|
||||
assert!(report.is_none(), "non-game memcard call must return status");
|
||||
assert!(vm.is_halted());
|
||||
// top-first: count then status
|
||||
assert_eq!(vm.operand_stack_top(2), vec![Value::Int64(0), Value::Int64(4)]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user