harden deterministic headless runtime control
This commit is contained in:
@@ -11,9 +11,9 @@ mod program_image;
|
||||
mod value;
|
||||
|
||||
pub use abi::{
|
||||
TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT, TRAP_ILLEGAL_INSTRUCTION,
|
||||
TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_OOB,
|
||||
TRAP_STACK_UNDERFLOW, TRAP_TYPE,
|
||||
SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT,
|
||||
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL,
|
||||
TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_STACK_UNDERFLOW, TRAP_TYPE,
|
||||
};
|
||||
pub use assembler::{assemble, AsmError};
|
||||
pub use decoder::{decode_next, DecodeError};
|
||||
|
||||
@@ -159,6 +159,15 @@ impl<'a> VmFacade<'a> {
|
||||
self.os.vm_runtime.debug_step_request = true;
|
||||
}
|
||||
|
||||
pub fn clear_debug_step_request(&mut self) {
|
||||
if let Some(session) = self.active_session_mut() {
|
||||
session.runtime.debug_step_request = false;
|
||||
return;
|
||||
}
|
||||
|
||||
self.os.vm_runtime.debug_step_request = false;
|
||||
}
|
||||
|
||||
pub fn debug_step_requested(&self) -> bool {
|
||||
self.active_session()
|
||||
.map(|session| session.runtime.debug_step_request)
|
||||
|
||||
@@ -65,7 +65,7 @@ pub struct VirtualMachineRuntime {
|
||||
|
||||
impl VirtualMachineRuntime {
|
||||
pub const CYCLES_PER_LOGICAL_FRAME: u64 = 1_500_000;
|
||||
pub const SLICE_PER_TICK: u64 = 1_500_000;
|
||||
pub const SLICE_PER_TICK: u64 = 250_000;
|
||||
pub const MAX_LOG_LEN: usize = 256;
|
||||
pub const MAX_LOGS_PER_FRAME: u32 = 10;
|
||||
|
||||
|
||||
@@ -76,6 +76,9 @@ impl VirtualMachineRuntime {
|
||||
vm: &mut VirtualMachine,
|
||||
platform: &mut dyn RuntimePlatform,
|
||||
) -> Option<CrashReport> {
|
||||
if vm.call_stack_is_empty() {
|
||||
vm.prepare_boot_call();
|
||||
}
|
||||
let step_result = {
|
||||
let mut ctx = HostContext::new_platform(Some(platform));
|
||||
let mut fs = VirtualFS::new();
|
||||
@@ -96,18 +99,28 @@ impl VirtualMachineRuntime {
|
||||
};
|
||||
|
||||
match step_result {
|
||||
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),
|
||||
},
|
||||
};
|
||||
Ok(())
|
||||
| Err(
|
||||
LogicalFrameEndingReason::FrameSync
|
||||
| LogicalFrameEndingReason::BudgetExhausted
|
||||
| LogicalFrameEndingReason::Halted
|
||||
| LogicalFrameEndingReason::EndOfRom
|
||||
| LogicalFrameEndingReason::Breakpoint,
|
||||
) => None,
|
||||
Err(LogicalFrameEndingReason::Trap(trap)) => {
|
||||
let report = CrashReport::VmTrap { trap };
|
||||
self.log(
|
||||
log_service,
|
||||
LogLevel::Error,
|
||||
LogSource::Vm,
|
||||
report.log_tag(),
|
||||
format!("PVM Fault during Step: {}", report),
|
||||
);
|
||||
self.last_crash_report = Some(report.clone());
|
||||
Some(report)
|
||||
}
|
||||
Err(LogicalFrameEndingReason::Panic(message)) => {
|
||||
let report = CrashReport::VmPanic { message, pc: Some(vm.pc() as u32) };
|
||||
self.log(
|
||||
log_service,
|
||||
LogLevel::Error,
|
||||
|
||||
@@ -2,20 +2,19 @@ use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_drivers::MemoryBanks;
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use prometeu_drivers::{LocalFramebufferRenderBackend, MemoryBanks};
|
||||
use prometeu_firmware::firmware_state::{AppCrashesStep, ResetStep};
|
||||
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
|
||||
use prometeu_hal::{
|
||||
AssetBridge, AudioBridge, FrameId, Game2DFrameComposer, InputPlatform, InputSignals,
|
||||
OwnedRgba8888Frame, RenderBackend, RenderSubmission, RenderSubmissionSink, RenderSubmitError,
|
||||
RenderWorkerError, RuntimePlatform, TelemetryPlatform,
|
||||
RuntimePlatform, TelemetryPlatform,
|
||||
};
|
||||
use prometeu_system::{CrashReport, LatestRenderFrameStore, RenderWorkerConfig};
|
||||
use prometeu_system::{CrashReport, LatestRenderFrameStore};
|
||||
|
||||
const BOOT_TICK_LIMIT: usize = 64;
|
||||
const LOGICAL_FRAME_TICK_LIMIT: usize = 100_000;
|
||||
const FRAME_PUBLISH_SPINS: usize = 10_000;
|
||||
|
||||
/// One published logical frame plus the automation counter.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -30,26 +29,65 @@ pub struct HostState {
|
||||
pub pc: usize,
|
||||
pub stack_top: Vec<Value>,
|
||||
pub frame_index: u64,
|
||||
pub tick_index: u64,
|
||||
pub app_id: u32,
|
||||
pub status: HostExecutionStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HostExecutionStatus {
|
||||
Running,
|
||||
Paused,
|
||||
Terminated,
|
||||
Faulted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AdvanceFrameOutcome {
|
||||
FrameCompleted { logical_frame_index: u64, frame_id: FrameId },
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AdvanceFramesStop {
|
||||
Completed,
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdvanceFramesOutcome {
|
||||
pub requested: u64,
|
||||
pub completed: u64,
|
||||
pub stop: AdvanceFramesStop,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HostError {
|
||||
BootFailed(String),
|
||||
AlreadyBooted,
|
||||
BootFailed { reason: String, report: Option<CrashReport> },
|
||||
InvalidState { operation: &'static str, status: HostExecutionStatus },
|
||||
LogicalFrameDidNotClose,
|
||||
FrameNotPublished,
|
||||
RenderWorker(RenderWorkerError),
|
||||
FrameNotPublished { previous: Option<FrameId> },
|
||||
NoFrameAvailable,
|
||||
}
|
||||
|
||||
impl fmt::Display for HostError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::BootFailed(reason) => write!(f, "boot failed: {reason}"),
|
||||
Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"),
|
||||
Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"),
|
||||
Self::InvalidState { operation, status } => {
|
||||
write!(f, "{operation} is invalid while execution is {status:?}")
|
||||
}
|
||||
Self::LogicalFrameDidNotClose => {
|
||||
write!(f, "logical frame did not reach FrameSync, end of ROM, or a fault")
|
||||
}
|
||||
Self::FrameNotPublished => write!(f, "logical frame closed without a published frame"),
|
||||
Self::RenderWorker(error) => write!(f, "render worker failed: {error:?}"),
|
||||
Self::FrameNotPublished { .. } => {
|
||||
write!(f, "logical frame closed without its canonical published frame")
|
||||
}
|
||||
Self::NoFrameAvailable => write!(f, "no completed frame is available for capture"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,8 +99,14 @@ pub struct HeadlessHost {
|
||||
firmware: Firmware,
|
||||
platform: HeadlessPlatform,
|
||||
signals: InputSignals,
|
||||
/// Frame id observed before the logical frame that `capture_frame` should return.
|
||||
previous_frame_id: Option<FrameId>,
|
||||
boot_attempted: bool,
|
||||
last_completed_frame: Option<CompletedFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct CompletedFrame {
|
||||
logical_frame_index: u64,
|
||||
frame_id: FrameId,
|
||||
}
|
||||
|
||||
struct HeadlessPlatform {
|
||||
@@ -79,7 +123,8 @@ impl HeadlessHost {
|
||||
firmware: Firmware::new(None),
|
||||
platform: HeadlessPlatform { hardware, store },
|
||||
signals: InputSignals::default(),
|
||||
previous_frame_id: None,
|
||||
boot_attempted: false,
|
||||
last_completed_frame: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,26 +133,30 @@ impl HeadlessHost {
|
||||
/// The transition into `GameRunning` is the last tick. The first game
|
||||
/// logical frame stays available for [`Self::advance_frame`].
|
||||
pub fn boot(&mut self, path: impl Into<String>) -> Result<(), HostError> {
|
||||
if self.boot_attempted {
|
||||
return Err(HostError::AlreadyBooted);
|
||||
}
|
||||
self.boot_attempted = true;
|
||||
let path = path.into();
|
||||
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
|
||||
self.ensure_worker()?;
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for _ in 0..BOOT_TICK_LIMIT {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||
let detail = self
|
||||
.get_fault()
|
||||
.map(|report| report.summary())
|
||||
let report = self.get_fault();
|
||||
let reason = report
|
||||
.as_ref()
|
||||
.map(CrashReport::summary)
|
||||
.unwrap_or_else(|| "cartridge crashed during boot".to_string());
|
||||
return Err(HostError::BootFailed(detail));
|
||||
return Err(HostError::BootFailed { reason, report });
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
|
||||
return Err(HostError::BootFailed("cartridge did not load".to_string()));
|
||||
return Err(HostError::BootFailed {
|
||||
reason: "cartridge did not load".to_string(),
|
||||
report: None,
|
||||
});
|
||||
}
|
||||
self.tick_once();
|
||||
}
|
||||
@@ -115,7 +164,10 @@ impl HeadlessHost {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(HostError::BootFailed("boot did not reach the game".to_string()))
|
||||
Err(HostError::BootFailed {
|
||||
reason: "boot did not reach the game".to_string(),
|
||||
report: self.get_fault(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,51 +178,101 @@ impl HeadlessHost {
|
||||
&self.signals,
|
||||
&mut self.platform,
|
||||
);
|
||||
self.previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id);
|
||||
self.platform.store = LatestRenderFrameStore::default();
|
||||
self.boot_attempted = false;
|
||||
self.last_completed_frame = None;
|
||||
}
|
||||
|
||||
pub fn pause(&mut self) {
|
||||
pub fn pause(&mut self) -> Result<(), HostError> {
|
||||
self.require_active("pause")?;
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn resume(&mut self) {
|
||||
pub fn resume(&mut self) -> Result<(), HostError> {
|
||||
self.require_active("resume")?;
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute one VM instruction. This does not close a logical frame.
|
||||
pub fn step(&mut self) -> Option<CrashReport> {
|
||||
pub fn step(&mut self) -> Result<Option<CrashReport>, HostError> {
|
||||
self.require_active("step")?;
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
let report = self.firmware.os.vm().debug_step_active_session(&mut self.platform);
|
||||
self.platform.hardware.audio.clear_commands();
|
||||
report
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub fn advance_frame(&mut self) -> Result<(), HostError> {
|
||||
pub fn advance_frame(&mut self) -> Result<AdvanceFrameOutcome, HostError> {
|
||||
if let Some(report) = self.get_fault() {
|
||||
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||
}
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(AdvanceFrameOutcome::Terminated);
|
||||
}
|
||||
|
||||
let start = self.firmware.os.vm().logical_frame_index();
|
||||
self.previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id);
|
||||
let previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id);
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
|
||||
for _ in 0..LOGICAL_FRAME_TICK_LIMIT {
|
||||
self.tick_once();
|
||||
if self.fault_is_visible() {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
return Ok(());
|
||||
if let Some(report) = self.get_fault() {
|
||||
self.finish_frame_step();
|
||||
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||
}
|
||||
if self.firmware.os.vm().logical_frame_index() > start {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
return Ok(());
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(AdvanceFrameOutcome::Terminated);
|
||||
}
|
||||
|
||||
let logical_frame_index = self.firmware.os.vm().logical_frame_index();
|
||||
if logical_frame_index > start {
|
||||
self.finish_frame_step();
|
||||
let frame = self
|
||||
.platform
|
||||
.store
|
||||
.latest_frame()
|
||||
.ok_or(HostError::FrameNotPublished { previous: previous_frame_id })?;
|
||||
if Some(frame.frame_id) == previous_frame_id {
|
||||
return Err(HostError::FrameNotPublished { previous: previous_frame_id });
|
||||
}
|
||||
self.last_completed_frame =
|
||||
Some(CompletedFrame { logical_frame_index, frame_id: frame.frame_id });
|
||||
return Ok(AdvanceFrameOutcome::FrameCompleted {
|
||||
logical_frame_index,
|
||||
frame_id: frame.frame_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
self.finish_frame_step();
|
||||
Err(HostError::LogicalFrameDidNotClose)
|
||||
}
|
||||
|
||||
pub fn advance_frames(&mut self, count: u64) -> Result<(), HostError> {
|
||||
pub fn advance_frames(&mut self, count: u64) -> Result<AdvanceFramesOutcome, HostError> {
|
||||
let mut completed = 0;
|
||||
for _ in 0..count {
|
||||
self.advance_frame()?;
|
||||
match self.advance_frame()? {
|
||||
AdvanceFrameOutcome::FrameCompleted { .. } => completed += 1,
|
||||
AdvanceFrameOutcome::Faulted(report) => {
|
||||
return Ok(AdvanceFramesOutcome {
|
||||
requested: count,
|
||||
completed,
|
||||
stop: AdvanceFramesStop::Faulted(report),
|
||||
});
|
||||
}
|
||||
AdvanceFrameOutcome::Terminated => {
|
||||
return Ok(AdvanceFramesOutcome {
|
||||
requested: count,
|
||||
completed,
|
||||
stop: AdvanceFramesStop::Terminated,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed })
|
||||
}
|
||||
|
||||
pub fn set_input(&mut self, signals: InputSignals) {
|
||||
@@ -185,20 +287,24 @@ impl HeadlessHost {
|
||||
self.signals.right_signal = down;
|
||||
}
|
||||
|
||||
pub fn capture_frame(&mut self) -> Result<CapturedFrame, HostError> {
|
||||
let frame = self.wait_for_published_frame(self.previous_frame_id)?;
|
||||
Ok(CapturedFrame {
|
||||
logical_frame_index: self.firmware.os.vm().logical_frame_index(),
|
||||
frame,
|
||||
})
|
||||
pub fn capture_frame(&self) -> Result<CapturedFrame, HostError> {
|
||||
let completed = self.last_completed_frame.ok_or(HostError::NoFrameAvailable)?;
|
||||
let frame = self.platform.store.latest_frame().ok_or(HostError::NoFrameAvailable)?;
|
||||
if frame.frame_id != completed.frame_id {
|
||||
return Err(HostError::FrameNotPublished { previous: Some(completed.frame_id) });
|
||||
}
|
||||
Ok(CapturedFrame { logical_frame_index: completed.logical_frame_index, frame })
|
||||
}
|
||||
|
||||
pub fn get_state(&mut self) -> HostState {
|
||||
let status = self.execution_status();
|
||||
HostState {
|
||||
pc: self.firmware.os.vm().active_pc().unwrap_or(0),
|
||||
stack_top: self.firmware.os.vm().active_operand_stack_top(10),
|
||||
frame_index: self.firmware.os.vm().logical_frame_index(),
|
||||
tick_index: self.firmware.os.vm().tick_index(),
|
||||
app_id: self.firmware.os.vm().current_app_id(),
|
||||
status,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,49 +323,35 @@ impl HeadlessHost {
|
||||
self.platform.hardware.audio.clear_commands();
|
||||
}
|
||||
|
||||
fn execution_status(&mut self) -> HostExecutionStatus {
|
||||
if self.fault_is_visible() {
|
||||
HostExecutionStatus::Faulted
|
||||
} else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
HostExecutionStatus::Terminated
|
||||
} else if self.firmware.os.vm().paused() {
|
||||
HostExecutionStatus::Paused
|
||||
} else {
|
||||
HostExecutionStatus::Running
|
||||
}
|
||||
}
|
||||
|
||||
fn fault_is_visible(&mut self) -> bool {
|
||||
self.firmware.os.vm().last_crash_report().is_some()
|
||||
|| matches!(self.firmware.state, FirmwareState::AppCrashes(_))
|
||||
}
|
||||
|
||||
fn ensure_worker(&mut self) -> Result<(), HostError> {
|
||||
if self.firmware.os.vm().render_worker_controller().is_some() {
|
||||
return Ok(());
|
||||
fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> {
|
||||
let status = self.execution_status();
|
||||
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(HostError::InvalidState { operation, status })
|
||||
}
|
||||
|
||||
let backend = LocalFramebufferRenderBackend::new_with_memory_banks(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::clone(&self.platform.hardware.memory_banks),
|
||||
self.platform.hardware.assets.glyph_asset_slot_index(),
|
||||
);
|
||||
let store = self.platform.store.clone();
|
||||
self.firmware.os.vm().start_render_worker(RenderWorkerConfig::default(), backend, store);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wait_for_published_frame(
|
||||
&mut self,
|
||||
previous: Option<FrameId>,
|
||||
) -> Result<OwnedRgba8888Frame, HostError> {
|
||||
for _ in 0..FRAME_PUBLISH_SPINS {
|
||||
if let Some(error) = self
|
||||
.firmware
|
||||
.os
|
||||
.vm()
|
||||
.render_worker_controller()
|
||||
.and_then(|worker| worker.last_error())
|
||||
{
|
||||
return Err(HostError::RenderWorker(error));
|
||||
}
|
||||
if let Some(frame) = self.platform.store.latest_frame()
|
||||
&& Some(frame.frame_id) != previous
|
||||
{
|
||||
return Ok(frame);
|
||||
}
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
Err(HostError::FrameNotPublished)
|
||||
fn finish_frame_step(&mut self) {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
self.firmware.os.vm().clear_debug_step_request();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,4 +8,7 @@
|
||||
|
||||
mod host;
|
||||
|
||||
pub use host::{CapturedFrame, HeadlessHost, HostError, HostState};
|
||||
pub use host::{
|
||||
AdvanceFrameOutcome, AdvanceFramesOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost,
|
||||
HostError, HostExecutionStatus, HostState,
|
||||
};
|
||||
|
||||
@@ -2,21 +2,151 @@ use std::fs;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use prometeu_bytecode::SourceSpan;
|
||||
use prometeu_bytecode::assembler::assemble;
|
||||
use prometeu_bytecode::model::{BytecodeModule, DebugInfo, Export, FunctionMeta, SyscallDecl};
|
||||
use prometeu_hal::InputSignals;
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_host_headless::{CapturedFrame, HeadlessHost, HostState};
|
||||
use prometeu_host_headless::{
|
||||
AdvanceFrameOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost, HostError,
|
||||
HostExecutionStatus, HostState,
|
||||
};
|
||||
use prometeu_system::CrashReport;
|
||||
|
||||
const RED: u32 = Color::RED.raw();
|
||||
const BLUE: u32 = Color::BLUE.raw();
|
||||
const GREEN: u32 = Color::GREEN.raw();
|
||||
const BLACK: u32 = Color::BLACK.raw();
|
||||
|
||||
#[test]
|
||||
fn headless_source_has_no_timing_wait_or_interactive_backend_dependency() {
|
||||
let source = include_str!("../src/host.rs");
|
||||
let manifest = include_str!("../Cargo.toml");
|
||||
|
||||
for forbidden in
|
||||
["FRAME_PUBLISH_SPINS", "spin_loop", "thread::sleep", "ensure_worker", "RenderWorkerConfig"]
|
||||
{
|
||||
assert!(!source.contains(forbidden), "headless source contains {forbidden}");
|
||||
}
|
||||
for forbidden in ["winit", "pixels", "cpal"] {
|
||||
assert!(!manifest.contains(forbidden), "headless manifest contains {forbidden}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_state_and_preconditions_are_structural() {
|
||||
let mut host = HeadlessHost::new();
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Terminated);
|
||||
assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable));
|
||||
assert_eq!(
|
||||
host.pause(),
|
||||
Err(HostError::InvalidState {
|
||||
operation: "pause",
|
||||
status: HostExecutionStatus::Terminated,
|
||||
})
|
||||
);
|
||||
|
||||
let cartridge = color_cartridge();
|
||||
host.boot(&cartridge).expect("boot");
|
||||
let booted = host.get_state();
|
||||
assert_eq!(booted.status, HostExecutionStatus::Running);
|
||||
assert_eq!(booted.pc, 0, "boot must not execute the first game instruction");
|
||||
assert_eq!(host.boot(&cartridge), Err(HostError::AlreadyBooted));
|
||||
|
||||
host.pause().expect("pause");
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||
host.resume().expect("resume");
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Running);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_does_not_complete_a_logical_frame() {
|
||||
let mut host = boot_color();
|
||||
let before = host.get_state();
|
||||
assert_eq!(host.step().expect("step"), None);
|
||||
let after = host.get_state();
|
||||
assert_eq!(after.frame_index, before.frame_index);
|
||||
assert_ne!(after.pc, before.pc);
|
||||
assert_eq!(after.status, HostExecutionStatus::Paused);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stepping_frame_sync_is_not_a_fault_or_completed_runtime_frame() {
|
||||
let dir = temp_cart("step-frame-sync");
|
||||
write_cartridge(&dir, 51, "Step Frame Sync", &module(asm("FRAME_SYNC\nRET\n"), vec![]), &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot frame-sync cartridge");
|
||||
let before = host.get_state().frame_index;
|
||||
host.step();
|
||||
|
||||
assert_eq!(host.step().expect("step frame sync"), None);
|
||||
assert_eq!(host.get_state().frame_index, before);
|
||||
assert!(host.get_fault().is_none());
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_logical_frame_may_span_multiple_internal_ticks() {
|
||||
let dir = temp_cart("multi-tick");
|
||||
write_cartridge(&dir, 47, "Multi Tick", &multi_tick_program(), &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot multi-tick cartridge");
|
||||
let before = host.get_state();
|
||||
|
||||
completed(host.advance_frame().expect("multi-tick frame"));
|
||||
|
||||
let after = host.get_state();
|
||||
assert_eq!(after.frame_index, before.frame_index + 1);
|
||||
assert!(after.tick_index >= before.tick_index + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outer_frame_limit_is_a_host_error_and_finishes_paused() {
|
||||
let dir = temp_cart("frame-limit");
|
||||
write_cartridge(&dir, 50, "Frame Limit", &module(asm("JMP 0\n"), vec![]), &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot non-closing cartridge");
|
||||
|
||||
assert_eq!(host.advance_frame(), Err(HostError::LogicalFrameDidNotClose));
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||
assert!(host.get_fault().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_returns_and_captures_the_exact_published_frame() {
|
||||
let mut host = boot_color();
|
||||
let before = host.get_state().frame_index;
|
||||
let (logical_frame_index, frame_id) = completed(host.advance_frame().expect("frame"));
|
||||
let captured = host.capture_frame().expect("capture");
|
||||
|
||||
assert_eq!(logical_frame_index, before + 1);
|
||||
assert_eq!(captured.logical_frame_index, logical_frame_index);
|
||||
assert_eq!(captured.frame.frame_id, frame_id);
|
||||
assert_eq!(captured.frame.ownership.app_mode, AppMode::Game);
|
||||
assert_eq!(captured.frame.ownership.app_id, 41);
|
||||
assert_eq!(captured.frame.stride_pixels, captured.frame.width);
|
||||
assert_eq!(captured.frame.pixels.len(), 480 * 270);
|
||||
assert_eq!(host.capture_frame().expect("repeat capture"), captured);
|
||||
|
||||
let mut mutated_clone = captured.clone();
|
||||
mutated_clone.frame.pixels[0] = GREEN;
|
||||
assert_ne!(host.capture_frame().expect("owned capture").frame.pixels[0], GREEN);
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_frames_is_an_explicit_noop() {
|
||||
let mut host = boot_color();
|
||||
let before = host.get_state();
|
||||
let outcome = host.advance_frames(0).expect("zero frames");
|
||||
|
||||
assert_eq!(outcome.requested, 0);
|
||||
assert_eq!(outcome.completed, 0);
|
||||
assert_eq!(outcome.stop, AdvanceFramesStop::Completed);
|
||||
let after = host.get_state();
|
||||
assert_eq!(after.frame_index, before.frame_index);
|
||||
assert_eq!(after.tick_index, before.tick_index);
|
||||
assert_eq!(after.status, before.status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -24,7 +154,7 @@ fn clear_input_drops_right() {
|
||||
let mut host = boot_color();
|
||||
host.set_right(true);
|
||||
host.clear_input();
|
||||
host.advance_frame().expect("frame");
|
||||
completed(host.advance_frame().expect("frame"));
|
||||
assert_color(&host.capture_frame().expect("frame"), BLUE);
|
||||
}
|
||||
|
||||
@@ -34,20 +164,68 @@ fn right_hold_then_release_changes_pixels() {
|
||||
let before = host.get_state().frame_index;
|
||||
|
||||
host.set_right(true);
|
||||
host.advance_frames(60).expect("hold");
|
||||
assert_completed(host.advance_frames(60).expect("hold"), 60);
|
||||
let held = host.capture_frame().expect("held frame");
|
||||
assert_eq!(host.get_state().frame_index, before + 60);
|
||||
assert_color(&held, RED);
|
||||
assert!(host.get_fault().is_none());
|
||||
|
||||
host.set_right(false);
|
||||
host.advance_frames(1).expect("release");
|
||||
assert_completed(host.advance_frames(1).expect("release"), 1);
|
||||
let released = host.capture_frame().expect("released frame");
|
||||
assert_eq!(released.logical_frame_index, before + 61);
|
||||
assert_color(&released, BLUE);
|
||||
assert!(host.get_fault().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalized_button_press_hold_release_and_clear_are_observable() {
|
||||
let mut host = boot_input_edges();
|
||||
|
||||
let mut signals = InputSignals { right_signal: true, ..InputSignals::default() };
|
||||
host.set_input(signals);
|
||||
completed(host.advance_frame().expect("press"));
|
||||
assert_color(&host.capture_frame().expect("pressed"), RED);
|
||||
|
||||
completed(host.advance_frame().expect("hold"));
|
||||
assert_color(&host.capture_frame().expect("held"), BLUE);
|
||||
|
||||
signals.right_signal = false;
|
||||
host.set_input(signals);
|
||||
completed(host.advance_frame().expect("release"));
|
||||
assert_color(&host.capture_frame().expect("released"), GREEN);
|
||||
|
||||
host.set_input(InputSignals {
|
||||
right_signal: true,
|
||||
f_signal: true,
|
||||
x_pos: 123,
|
||||
y_pos: 45,
|
||||
..InputSignals::default()
|
||||
});
|
||||
host.clear_input();
|
||||
completed(host.advance_frame().expect("clear"));
|
||||
assert_color(&host.capture_frame().expect("cleared"), BLACK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalized_touch_edges_and_coordinates_use_the_same_input_surface() {
|
||||
let mut host = boot_touch_edges();
|
||||
let mut signals =
|
||||
InputSignals { f_signal: true, x_pos: 123, y_pos: 45, ..InputSignals::default() };
|
||||
|
||||
host.set_input(signals);
|
||||
completed(host.advance_frame().expect("touch press"));
|
||||
assert_color(&host.capture_frame().expect("touch pressed"), RED);
|
||||
|
||||
completed(host.advance_frame().expect("touch hold"));
|
||||
assert_color(&host.capture_frame().expect("touch held"), BLUE);
|
||||
|
||||
signals.f_signal = false;
|
||||
host.set_input(signals);
|
||||
completed(host.advance_frame().expect("touch release"));
|
||||
assert_color(&host.capture_frame().expect("touch released"), GREEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_runs_match_oracle() {
|
||||
let first = run_color_sequence();
|
||||
@@ -67,6 +245,8 @@ fn reset_matches_fresh_host() {
|
||||
let mut host = boot_color();
|
||||
let _ = run_on(&mut host);
|
||||
host.reset();
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Terminated);
|
||||
assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable));
|
||||
host.boot(color_cartridge()).expect("reboot");
|
||||
let after_reset = run_on(&mut host);
|
||||
let fresh = run_color_sequence();
|
||||
@@ -86,28 +266,101 @@ fn trap_is_structured() {
|
||||
write_cartridge(&dir, 42, "Fault", &fault_program(), &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot fault cartridge");
|
||||
host.advance_frame().expect("faulting frame");
|
||||
let outcome = host.advance_frame().expect("faulting frame");
|
||||
|
||||
match host.get_fault() {
|
||||
Some(report @ CrashReport::VmTrap { .. }) => {
|
||||
assert!(report.pc().is_some());
|
||||
match outcome {
|
||||
AdvanceFrameOutcome::Faulted(CrashReport::VmTrap { trap }) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::TRAP_EXPLICIT);
|
||||
assert_eq!(trap.opcode, prometeu_bytecode::isa::core::CoreOpCode::Trap as u16);
|
||||
assert_eq!(trap.pc, 0);
|
||||
assert_eq!(trap.span, Some(SourceSpan { file_id: 7, start: 11, end: 15 }));
|
||||
assert!(trap.message.contains("main"));
|
||||
}
|
||||
other => panic!("expected VmTrap, got {other:?}"),
|
||||
other => panic!("expected VmTrap outcome, got {other:?}"),
|
||||
}
|
||||
assert!(matches!(host.get_fault(), Some(CrashReport::VmTrap { .. })));
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Faulted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instruction_step_fault_remains_structured() {
|
||||
let dir = temp_cart("step-fault");
|
||||
write_cartridge(&dir, 48, "Step Fault", &fault_program(), &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot fault cartridge");
|
||||
|
||||
let report = host.step().expect("step result").expect("structured step fault");
|
||||
assert!(matches!(report, CrashReport::VmTrap { .. }));
|
||||
assert_eq!(host.get_fault(), Some(report));
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Faulted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_stops_early_on_fault_and_reports_partial_progress() {
|
||||
let dir = temp_cart("fault-batch");
|
||||
write_cartridge(&dir, 43, "Fault Batch", &delayed_fault_program(), &gfx_syscalls());
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot fault cartridge");
|
||||
|
||||
let outcome = host.advance_frames(5).expect("batch outcome");
|
||||
assert_eq!(outcome.requested, 5);
|
||||
assert_eq!(outcome.completed, 2);
|
||||
assert!(matches!(outcome.stop, AdvanceFramesStop::Faulted(CrashReport::VmTrap { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advance_after_reset_reports_termination_without_ticking() {
|
||||
let mut host = boot_color();
|
||||
host.reset();
|
||||
let before = host.get_state().tick_index;
|
||||
|
||||
assert_eq!(host.advance_frame().expect("termination outcome"), AdvanceFrameOutcome::Terminated);
|
||||
assert_eq!(host.get_state().tick_index, before);
|
||||
let batch = host.advance_frames(3).expect("terminated batch");
|
||||
assert_eq!(batch.completed, 0);
|
||||
assert_eq!(batch.stop, AdvanceFramesStop::Terminated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vm_init_failure_is_returned_as_structured_boot_failure() {
|
||||
let dir = temp_cart("bad-pbx");
|
||||
write_cartridge(&dir, 44, "Bad PBX", b"not a pbx", &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
|
||||
let error = host.boot(&dir).expect_err("invalid PBX must fail boot");
|
||||
assert!(matches!(
|
||||
error,
|
||||
HostError::BootFailed { report: Some(CrashReport::VmInit { .. }), .. }
|
||||
));
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Faulted);
|
||||
assert!(matches!(host.get_fault(), Some(CrashReport::VmInit { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_rom_completes_a_logical_frame() {
|
||||
let dir = temp_cart("end-of-rom");
|
||||
write_cartridge(&dir, 45, "End Of Rom", &module(asm("RET\n"), vec![]), &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot end-of-rom cartridge");
|
||||
|
||||
let first = completed(host.advance_frame().expect("first frame"));
|
||||
let second = completed(host.advance_frame().expect("second frame"));
|
||||
assert_eq!(second.0, first.0 + 1);
|
||||
assert_ne!(second.1, first.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_hundred_frames_finish_without_refresh_sleep() {
|
||||
let mut host = boot_color();
|
||||
let started = Instant::now();
|
||||
host.advance_frames(300).expect("fast frames");
|
||||
assert_completed(host.advance_frames(300).expect("fast frames"), 300);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_play_does_not_need_a_device() {
|
||||
let mut host = boot_color();
|
||||
host.advance_frame().expect("frame with audio.play");
|
||||
completed(host.advance_frame().expect("frame with audio.play"));
|
||||
assert!(host.get_fault().is_none());
|
||||
assert_color(&host.capture_frame().expect("frame"), BLUE);
|
||||
}
|
||||
@@ -125,6 +378,22 @@ fn boot_color() -> HeadlessHost {
|
||||
host
|
||||
}
|
||||
|
||||
fn boot_input_edges() -> HeadlessHost {
|
||||
let dir = temp_cart("input-edges");
|
||||
write_cartridge(&dir, 46, "Input Edges", &input_edge_program(), &gfx_syscalls());
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot input cartridge");
|
||||
host
|
||||
}
|
||||
|
||||
fn boot_touch_edges() -> HeadlessHost {
|
||||
let dir = temp_cart("touch-edges");
|
||||
write_cartridge(&dir, 49, "Touch Edges", &touch_edge_program(), &gfx_syscalls());
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot touch cartridge");
|
||||
host
|
||||
}
|
||||
|
||||
fn color_cartridge() -> String {
|
||||
let dir = temp_cart("color");
|
||||
write_cartridge(&dir, 41, "Right Pixel", &color_program(), &color_syscalls());
|
||||
@@ -138,16 +407,31 @@ fn run_color_sequence() -> ColorOracle {
|
||||
|
||||
fn run_on(host: &mut HeadlessHost) -> ColorOracle {
|
||||
host.set_right(true);
|
||||
host.advance_frames(60).expect("hold");
|
||||
assert_completed(host.advance_frames(60).expect("hold"), 60);
|
||||
let held = host.capture_frame().expect("held");
|
||||
host.set_right(false);
|
||||
host.advance_frames(1).expect("release");
|
||||
assert_completed(host.advance_frames(1).expect("release"), 1);
|
||||
let released = host.capture_frame().expect("released");
|
||||
let state = host.get_state();
|
||||
let fault = host.get_fault();
|
||||
ColorOracle { held, released, state, fault }
|
||||
}
|
||||
|
||||
fn completed(outcome: AdvanceFrameOutcome) -> (u64, prometeu_hal::FrameId) {
|
||||
match outcome {
|
||||
AdvanceFrameOutcome::FrameCompleted { logical_frame_index, frame_id } => {
|
||||
(logical_frame_index, frame_id)
|
||||
}
|
||||
other => panic!("expected completed frame, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_completed(outcome: prometeu_host_headless::AdvanceFramesOutcome, expected: u64) {
|
||||
assert_eq!(outcome.requested, expected);
|
||||
assert_eq!(outcome.completed, expected);
|
||||
assert_eq!(outcome.stop, AdvanceFramesStop::Completed);
|
||||
}
|
||||
|
||||
fn assert_color(captured: &CapturedFrame, color: u32) {
|
||||
assert_eq!(captured.frame.width, 480);
|
||||
assert_eq!(captured.frame.height, 270);
|
||||
@@ -157,7 +441,9 @@ fn assert_color(captured: &CapturedFrame, color: u32) {
|
||||
fn assert_same_state(left: &HostState, right: &HostState) {
|
||||
assert_eq!(left.pc, right.pc);
|
||||
assert_eq!(left.frame_index, right.frame_index);
|
||||
assert_eq!(left.tick_index, right.tick_index);
|
||||
assert_eq!(left.app_id, right.app_id);
|
||||
assert_eq!(left.status, right.status);
|
||||
assert_eq!(format!("{:?}", left.stack_top), format!("{:?}", right.stack_top));
|
||||
}
|
||||
|
||||
@@ -207,12 +493,91 @@ fn color_program() -> Vec<u8> {
|
||||
module(rom, color_syscalls())
|
||||
}
|
||||
|
||||
fn input_edge_program() -> Vec<u8> {
|
||||
let mut rom = Vec::new();
|
||||
let pressed_jump = emit_right_predicate(&mut rom, 0x2030);
|
||||
rom.extend(asm(&format!("PUSH_I64 {RED}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
let released_at = rom.len() as u32;
|
||||
rom[pressed_jump..pressed_jump + 4].copy_from_slice(&released_at.to_le_bytes());
|
||||
|
||||
let released_jump = emit_right_predicate(&mut rom, 0x2031);
|
||||
rom.extend(asm(&format!("PUSH_I64 {GREEN}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
let down_at = rom.len() as u32;
|
||||
rom[released_jump..released_jump + 4].copy_from_slice(&down_at.to_le_bytes());
|
||||
|
||||
let down_jump = emit_right_predicate(&mut rom, 0x2032);
|
||||
rom.extend(asm(&format!("PUSH_I64 {BLUE}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
let idle_at = rom.len() as u32;
|
||||
rom[down_jump..down_jump + 4].copy_from_slice(&idle_at.to_le_bytes());
|
||||
rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
|
||||
module(rom, gfx_syscalls())
|
||||
}
|
||||
|
||||
fn emit_right_predicate(rom: &mut Vec<u8>, predicate: u32) -> usize {
|
||||
rom.extend(asm(&format!("INTRINSIC 0x2000\nINTRINSIC 0x2013\nINTRINSIC {predicate:#x}\n")));
|
||||
let target = rom.len() + 2;
|
||||
rom.extend(asm("JMP_IF_FALSE 0\n"));
|
||||
target
|
||||
}
|
||||
|
||||
fn touch_edge_program() -> Vec<u8> {
|
||||
let mut rom = Vec::new();
|
||||
let pressed_jump = emit_touch_predicate(&mut rom, 0x2030);
|
||||
rom.extend(asm(&format!("PUSH_I64 {RED}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
let released_at = rom.len() as u32;
|
||||
rom[pressed_jump..pressed_jump + 4].copy_from_slice(&released_at.to_le_bytes());
|
||||
|
||||
let released_jump = emit_touch_predicate(&mut rom, 0x2031);
|
||||
rom.extend(asm(&format!("PUSH_I64 {GREEN}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
let down_at = rom.len() as u32;
|
||||
rom[released_jump..released_jump + 4].copy_from_slice(&down_at.to_le_bytes());
|
||||
|
||||
let down_jump = emit_touch_predicate(&mut rom, 0x2032);
|
||||
rom.extend(asm(&format!("PUSH_I64 {BLUE}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
let idle_at = rom.len() as u32;
|
||||
rom[down_jump..down_jump + 4].copy_from_slice(&idle_at.to_le_bytes());
|
||||
rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
|
||||
module(rom, gfx_syscalls())
|
||||
}
|
||||
|
||||
fn emit_touch_predicate(rom: &mut Vec<u8>, predicate: u32) -> usize {
|
||||
rom.extend(asm(&format!(
|
||||
"INTRINSIC 0x2001\nINTRINSIC 0x2020\nINTRINSIC {predicate:#x}\n\
|
||||
INTRINSIC 0x2001\nINTRINSIC 0x2021\nPUSH_I64 123\nEQ\nAND\n\
|
||||
INTRINSIC 0x2001\nINTRINSIC 0x2022\nPUSH_I64 45\nEQ\nAND\n"
|
||||
)));
|
||||
let target = rom.len() + 2;
|
||||
rom.extend(asm("JMP_IF_FALSE 0\n"));
|
||||
target
|
||||
}
|
||||
|
||||
fn fault_program() -> Vec<u8> {
|
||||
// `INTRINSIC 0xDEADBEEF` is rejected by the loader as `VerificationFailed`.
|
||||
// `TRAP` is a legal instruction that becomes `CrashReport::VmTrap` at runtime.
|
||||
module(asm("TRAP\nFRAME_SYNC\nRET\n"), vec![])
|
||||
}
|
||||
|
||||
fn delayed_fault_program() -> Vec<u8> {
|
||||
let mut rom =
|
||||
asm("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I32 3\nEQ\n");
|
||||
let continue_jump = rom.len() + 2;
|
||||
rom.extend(asm("JMP_IF_FALSE 0\nTRAP\n"));
|
||||
let continue_at = rom.len() as u32;
|
||||
rom[continue_jump..continue_jump + 4].copy_from_slice(&continue_at.to_le_bytes());
|
||||
rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
module(rom, gfx_syscalls())
|
||||
}
|
||||
|
||||
fn multi_tick_program() -> Vec<u8> {
|
||||
let mut rom = asm("PUSH_I32 30000\nSET_LOCAL 0\n");
|
||||
let loop_at = rom.len() as u32;
|
||||
rom.extend(asm("GET_LOCAL 0\nPUSH_I32 1\nSUB\nSET_LOCAL 0\nGET_LOCAL 0\nPUSH_I32 0\nGT\n"));
|
||||
rom.extend(asm(&format!("JMP_IF_TRUE {loop_at}\nFRAME_SYNC\nRET\n")));
|
||||
module_with_locals(rom, vec![], 1)
|
||||
}
|
||||
|
||||
fn color_syscalls() -> Vec<SyscallDecl> {
|
||||
vec![
|
||||
SyscallDecl {
|
||||
@@ -232,7 +597,21 @@ fn color_syscalls() -> Vec<SyscallDecl> {
|
||||
]
|
||||
}
|
||||
|
||||
fn gfx_syscalls() -> Vec<SyscallDecl> {
|
||||
vec![SyscallDecl {
|
||||
module: "gfx2d".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}]
|
||||
}
|
||||
|
||||
fn module(code: Vec<u8>, syscalls: Vec<SyscallDecl>) -> Vec<u8> {
|
||||
module_with_locals(code, syscalls, 0)
|
||||
}
|
||||
|
||||
fn module_with_locals(code: Vec<u8>, syscalls: Vec<SyscallDecl>, local_slots: u16) -> Vec<u8> {
|
||||
BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
@@ -240,13 +619,13 @@ fn module(code: Vec<u8>, syscalls: Vec<SyscallDecl>) -> Vec<u8> {
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
local_slots,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 8,
|
||||
}],
|
||||
code,
|
||||
debug_info: Some(DebugInfo {
|
||||
pc_to_span: vec![],
|
||||
pc_to_span: vec![(0, SourceSpan { file_id: 7, start: 11, end: 15 })],
|
||||
function_names: vec![(0, "main".into())],
|
||||
}),
|
||||
exports: vec![Export { symbol: "main".into(), func_idx: 0 }],
|
||||
|
||||
Reference in New Issue
Block a user