//! Guest mem ABI. Only bounded copies cross the VM/native ownership boundary. use super::{ MemcardService, image::Error, session::{Mode, RequestReason, RequestState}, }; use prometeu_bytecode::{HeapRef, TRAP_OOB, TRAP_TYPE, Value}; use prometeu_hal::{HostReturn, expect_int, syscalls::Syscall, vm_fault::VmFault}; use std::time::Instant; fn index(args: &[Value], n: usize) -> Result { usize::try_from(expect_int(args, n)?) .map_err(|_| VmFault::Trap(TRAP_OOB, "Negative memcard range".into())) } fn opaque(args: &[Value], n: usize) -> Result { u64::try_from(expect_int(args, n)?) .map_err(|_| VmFault::Trap(TRAP_OOB, "Negative memcard identity".into())) } fn handle(args: &[Value], n: usize) -> Result { match args.get(n) { Some(Value::HeapRef(h)) => Ok(*h), _ => Err(VmFault::Trap(TRAP_TYPE, "Expected Array".into())), } } fn text(args: &[Value], n: usize) -> Result<&str, VmFault> { match args.get(n) { Some(Value::String(s)) => Ok(s), _ => Err(VmFault::Trap(TRAP_TYPE, "Expected String".into())), } } pub fn status(e: Error) -> i64 { use prometeu_hal::memcard::MemcardIoError as I; match e { Error::NoSpace | Error::Io(I::NoSpace) => 3, Error::AccessDenied | Error::IdentityMismatch | Error::Io(I::AccessDenied | I::AlreadyExists) => 4, Error::Corrupt => 5, Error::Indeterminate | Error::Io(I::Indeterminate) => 6, Error::Io(I::Unavailable) => 7, Error::InvalidState | Error::Canceled => 8, Error::Busy | Error::Io(I::Busy) => 9, Error::ReadOnly | Error::CounterExhausted | Error::Io(I::ReadOnly) => 10, Error::InvalidRange | Error::Io(I::InvalidRange) => 11, Error::Unsupported | Error::Io(I::Unsupported) => 12, Error::Io(I::IoError) => 13, Error::OutOfMemory => 16, } } fn error(ret: &mut HostReturn, syscall: Syscall, e: Error) { ret.push_int(status(e)); for _ in 1..syscall.results_count() { ret.push_null(); } } impl MemcardService { pub fn guest( &mut self, syscall: Syscall, args: &[Value], ret: &mut HostReturn, app_id: u32, timestamp: u64, game_profile: bool, ) -> Result<(), VmFault> { let authorized = game_profile && self.session.app_id() == Some(app_id); if syscall == Syscall::MemBootstrap { if !authorized || !self.session.is_boot_active() { return Err(VmFault::Trap( TRAP_TYPE, "Memcard snapshot is not admitted for bootstrap".into(), )); } ret.push_int(self.session.context() as i64); return Ok(()); } let context = opaque(args, 0)?; if !authorized || context != self.session.context() { error(ret, syscall, Error::AccessDenied); return Ok(()); } match syscall { Syscall::MemSlotCount => { ret.push_int(0); ret.push_int(self.session.count() as i64); } Syscall::MemSlotStat => match self.session.descriptor(context, index(args, 1)?) { Ok((d, used, dirty)) => { ret.push_int(0); ret.push_int(i64::from(used > 0)); ret.push_int(used as i64); ret.push_int(d.generation as i64); ret.push_int(d.update_at as i64); ret.push_int(d.crc as i64); ret.push_bool(dirty); } Err(e) => error(ret, syscall, e), }, Syscall::MemSlotRead | Syscall::MemSlotWrite => { let local = index(args, 1)?; let offset = index(args, 2)?; let array = handle(args, 3)?; let array_offset = index(args, 4)?; let count = index(args, 5)?; if count > 4096 { return Err(VmFault::Trap( TRAP_OOB, "Memcard transfer exceeds 4096 bytes".into(), )); } if let Err(e) = self.session.descriptor(context, local) { error(ret, syscall, e); return Ok(()); } if offset.checked_add(count).is_none_or(|end| end > 65536) { error(ret, syscall, Error::InvalidRange); return Ok(()); } ret.byte_arrays()?.validate(array, array_offset, count)?; let mut bytes = [0; 4096]; if syscall == Syscall::MemSlotRead { match self.session.read(context, local, offset, &mut bytes[..count]) { Ok(n) => { ret.byte_arrays()?.write(array, array_offset, &bytes[..n])?; ret.push_int(0); ret.push_int(n as i64) } Err(e) => error(ret, syscall, e), } } else { ret.byte_arrays()?.read(array, array_offset, &mut bytes[..count])?; match self.session.write(context, local, offset, &bytes[..count]) { Ok(()) => { ret.push_int(0); ret.push_int(count as i64) } Err(e) => error(ret, syscall, e), } } } Syscall::MemSlotCommit => { match self.session.commit( context, index(args, 1)?, timestamp, Instant::now(), &self.lane, ) { Ok(id) => { ret.push_int(0); ret.push_int(id as i64) } Err(e) => error(ret, syscall, e), } } Syscall::MemSlotClear => match self.session.clear(context, index(args, 1)?) { Ok(()) => ret.push_int(0), Err(e) => error(ret, syscall, e), }, Syscall::MemQuery => match self.session.query(context, opaque(args, 1)?) { Ok(r) => { ret.push_int(0); ret.push_int(match r.state { RequestState::Pending => 0, RequestState::Success => 1, RequestState::Failure => 2, RequestState::Indeterminate => 3, RequestState::MemoryOnly => 4, }); ret.push_int(match r.reason { RequestReason::None => 0, RequestReason::Storage(e) => status(e), RequestReason::Timeout | RequestReason::RestartRequired => 15, }); } Err(e) => error(ret, syscall, e), }, Syscall::MemRelease => match self.session.release_request(context, opaque(args, 1)?) { Ok(()) => ret.push_int(0), Err(e) => error(ret, syscall, e), }, Syscall::MemInfo => { ret.push_int(0); ret.push_int(i64::from(self.session.mode() == Some(Mode::MemoryOnly))); ret.push_bool(self.session.is_new()); let (recovered, degraded, blocked) = self.session.health(); ret.push_bool(recovered); ret.push_bool(degraded); ret.push_bool(blocked); } Syscall::MemMetadata => match self.session.presentation(context) { Ok(Some(g)) => { ret.push_int(0); ret.push_string(&g.title)?; ret.push_int(g.data_format_version as i64); ret.push_int(g.created_at as i64) } Ok(None) => { ret.push_int(0); ret.push_string("")?; ret.push_int(0); ret.push_int(timestamp as i64) } Err(e) => error(ret, syscall, e), }, Syscall::MemPresentation => { let title = text(args, 1)?; let version = u32::try_from(index(args, 2)?) .map_err(|_| VmFault::Trap(TRAP_OOB, "Invalid dataFormatVersion".into()))?; let frames = u8::try_from(index(args, 3)?) .map_err(|_| VmFault::Trap(TRAP_OOB, "Invalid icon frames".into()))?; let duration = u16::try_from(index(args, 4)?) .map_err(|_| VmFault::Trap(TRAP_OOB, "Invalid icon duration".into()))?; let array = handle(args, 5)?; let offset = index(args, 6)?; let count = index(args, 7)?; if count > 2096 || title.len() > 128 { error(ret, syscall, Error::InvalidRange); return Ok(()); } let mut bytes = [0; 2096]; ret.byte_arrays()?.read(array, offset, &mut bytes[..count])?; match self.session.set_presentation( context, title, version, frames, duration, &bytes[..count], timestamp, ) { Ok(()) => ret.push_int(0), Err(e) => error(ret, syscall, e), } } Syscall::MemDiagnostic => { let message = text(args, 1)?; if message.len() > 1024 { error(ret, syscall, Error::InvalidRange) } else { self.diagnostic.clear(); self.diagnostic.push_str(message); ret.push_int(0) } } Syscall::MemPublishPresentation => { match self.session.publish_presentation(context, &self.lane, Instant::now()) { Ok(id) => { ret.push_int(0); ret.push_int(id as i64) } Err(e) => error(ret, syscall, e), } } _ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid memcard operation".into())), } Ok(()) } }