From 223fe253c997b7d819740f7a03246bbd45cf723d Mon Sep 17 00:00:00 2001 From: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:09:04 +0530 Subject: [PATCH] app: interactive guest execution with input handling and dynamic rendering (#276) Add interactive guest execution with dynamic input handling and rendering (Gate 4) through the versioned C runtime interface. The guest fixture (fixtures/pe/interactive.exe, generated by fixtures/pe/interactive.py) runs on a dedicated session-owned thread and polls host input snapshots via xenora.dll!input_poll. It steers its rendered column position (0..3) on native Metal and submits frames with xenora.dll!frame_submit(column). Add xenora_session_start_interactive_loop, xenora_session_send_input, xenora_session_queue_input, and xenora_session_get_recorded_frame to the C interface, plus input masks (XENORA_INPUT_*) and xenora_input_state. Pre-queuing inputs enables deterministic replay across independent sessions without physical interaction. Xenora.app gains interactive frame-loop controls (Interactive 300 frames, Left, Right, Release) and a --smoke-interactive CLI flag. Four GPU acceptance tests verify input-driven state changes, reproducible frame sequences across deterministic replays, clean release/focus behavior without stuck keys, and prompt join on session destruction. Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> --- CHANGELOG.md | 2 + app/Sources/Xenora/main.swift | 99 ++++++++++- crates/ffi/include/xenora.h | 35 ++++ crates/ffi/src/frame_loop.rs | 86 ++++++++- crates/ffi/src/lib.rs | 150 +++++++++++++++- crates/ffi/tests/interactive.rs | 298 ++++++++++++++++++++++++++++++++ fixtures/pe/interactive.exe | Bin 0 -> 2048 bytes fixtures/pe/interactive.py | 100 +++++++++++ scripts/test-gpu.sh | 5 + 9 files changed, 764 insertions(+), 11 deletions(-) create mode 100644 crates/ffi/tests/interactive.rs create mode 100644 fixtures/pe/interactive.exe create mode 100644 fixtures/pe/interactive.py diff --git a/CHANGELOG.md b/CHANGELOG.md index cb79803..7175054 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`. + - Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`. - Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised. diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 30e0ef2..34356cf 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -86,7 +86,7 @@ final class FrameModel: ObservableObject { } } -/// Persistent guest rendering model (Gate 3, #266). +/// Persistent guest rendering model (Gate 3, #266; Gate 4, #276). @MainActor final class FrameLoopModel: ObservableObject { @Published var state: UInt32 = UInt32(XENORA_LOOP_NONE) @@ -94,6 +94,7 @@ final class FrameLoopModel: ObservableObject { @Published var frameId: UInt32 = XENORA_NO_FRAME @Published var image: CGImage? @Published var errorMessage: String? + @Published var isInteractive: Bool = false private var session: xenora_session = 0 private var pollTask: Task? @@ -144,6 +145,7 @@ final class FrameLoopModel: ObservableObject { session = 0 return } + isInteractive = false state = UInt32(XENORA_LOOP_RUNNING) completed = 0 frameId = XENORA_NO_FRAME @@ -151,6 +153,49 @@ final class FrameLoopModel: ObservableObject { startPolling() } + func startInteractive(frameCount: UInt32 = 300) { + errorMessage = nil + if session != 0 { + _ = xenora_session_destroy(session) + session = 0 + } + var newSession: xenora_session = 0 + let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession) + guard createStatus == XENORA_OK else { + errorMessage = "Failed to create session (status \(createStatus))" + return + } + session = newSession + let startStatus = xenora_session_start_interactive_loop(session, frameCount) + guard startStatus == XENORA_OK else { + errorMessage = "Failed to start interactive loop (status \(startStatus))" + _ = xenora_session_destroy(session) + session = 0 + return + } + isInteractive = true + state = UInt32(XENORA_LOOP_RUNNING) + completed = 0 + frameId = XENORA_NO_FRAME + image = nil + startPolling() + } + + func sendInput(buttons: UInt32) { + guard session != 0 else { return } + var input = xenora_input_state( + buttons: buttons, + stick_x: 0, + stick_y: 0, + mouse_dx: 0, + mouse_dy: 0, + mouse_buttons: 0, + connected: 1, + reserved: 0 + ) + _ = xenora_session_send_input(session, &input) + } + func pause() { guard session != 0 else { return } _ = xenora_session_pause_frame_loop(session) @@ -338,6 +383,8 @@ struct ContentView: View { HStack { Button("Start 300 frames") { loop.start(frameCount: 300) } .disabled(!loop.canStart || !probe.connected) + Button("Interactive (300 frames)") { loop.startInteractive(frameCount: 300) } + .disabled(!loop.canStart || !probe.connected) Button("Pause") { loop.pause() } .disabled(!loop.isRunning) Button("Resume") { loop.resume() } @@ -345,12 +392,22 @@ struct ContentView: View { Button("Stop") { loop.stop() } .disabled(!loop.isRunning && !loop.isPaused) } + if loop.isInteractive && (loop.isRunning || loop.isPaused) { + HStack { + Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) } + Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) } + Button("Release") { loop.sendInput(buttons: UInt32(XENORA_INPUT_NONE)) } + } + Text("Interactive guest: steer the rendered strip across columns 0..3 with Left/Right.") + .font(.caption) + .foregroundStyle(.secondary) + } } LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))") LabeledContent("Interface version", value: "\(probe.abiVersion)") LabeledContent("Trusted fixture sections", value: "\(probe.sections)") LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA)) - Text("Only the bundled trusted fixture and frame-loop guest can run. Presentation uses read-back Metal frames. Arbitrary executables and input are not available yet.") + Text("Only the bundled trusted fixtures (single-frame, frame-loop, and interactive guest) can run. Presentation uses read-back Metal frames. Arbitrary executables are not available yet.") .foregroundStyle(.secondary) } .formStyle(.grouped) @@ -384,6 +441,44 @@ if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < Comm exit(status == Int32(XENORA_OK) ? 0 : 1) } +// `--smoke-interactive` runs 60 frames with queued inputs on the Metal device and exits. +if CommandLine.arguments.contains("--smoke-interactive") { + var session: xenora_session = 0 + guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else { + print("failed to create session") + exit(1) + } + defer { _ = xenora_session_destroy(session) } + guard xenora_session_start_interactive_loop(session, 60) == XENORA_OK else { + print("failed to start interactive loop") + exit(1) + } + for f in 0..<60 { + let btn: UInt32 = (f < 15) ? UInt32(XENORA_INPUT_RIGHT) : + (f < 30) ? UInt32(XENORA_INPUT_NONE) : + (f < 45) ? UInt32(XENORA_INPUT_LEFT) : UInt32(XENORA_INPUT_RIGHT) + var input = xenora_input_state(buttons: btn, stick_x: 0, stick_y: 0, mouse_dx: 0, mouse_dy: 0, mouse_buttons: 0, connected: 1, reserved: 0) + _ = xenora_session_queue_input(session, &input) + } + var state: UInt32 = 0 + var completed: UInt32 = 0 + var frameId: UInt32 = 0 + var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4)) + while true { + let code = rgba.withUnsafeMutableBufferPointer { buf in + xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count)) + } + if code != XENORA_OK { + print("frame_loop_status failed: \(code)") + exit(1) + } + if state != UInt32(XENORA_LOOP_RUNNING) { break } + Thread.sleep(forTimeInterval: 0.005) + } + print("interactive: state=\(state) completed=\(completed) frame_id=\(frameId)") + exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 60 ? 0 : 1) +} + // `--smoke-loop` runs 300 frames on the Metal device and exits; it needs a GPU. if CommandLine.arguments.contains("--smoke-loop") { var session: xenora_session = 0 diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index 1c27877..69773c4 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -44,6 +44,26 @@ enum { /* Frame id reported when no frame has been completed yet. */ #define XENORA_NO_FRAME 0xFFFFFFFFu +/* Input snapshot delivered to guest runtime services (Gate 4, #276). */ +typedef struct { + uint32_t buttons; + int16_t stick_x; + int16_t stick_y; + int16_t mouse_dx; + int16_t mouse_dy; + uint8_t mouse_buttons; + uint8_t connected; + uint16_t reserved; +} xenora_input_state; + +#define XENORA_INPUT_NONE 0u +#define XENORA_INPUT_RIGHT (1u << 0) +#define XENORA_INPUT_LEFT (1u << 1) +#define XENORA_INPUT_UP (1u << 2) +#define XENORA_INPUT_DOWN (1u << 3) +#define XENORA_INPUT_ACTION_A (1u << 4) +#define XENORA_INPUT_ACTION_B (1u << 5) + /* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */ #define XENORA_FIXTURE_FRAME_WIDTH 4u #define XENORA_FIXTURE_FRAME_HEIGHT 3u @@ -91,10 +111,25 @@ xenora_status xenora_session_run_trusted_fixture( * second loop on the same session returns XENORA_INVALID_STATE. */ xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count); +xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count); +xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input); +xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input); xenora_status xenora_session_pause_frame_loop(xenora_session session); xenora_status xenora_session_resume_frame_loop(xenora_session session); xenora_status xenora_session_stop_frame_loop(xenora_session session); +/* + * Retrieve a previously completed frame by sequence index (0 <= frame_index < completed). + * Used for deterministic replay verification and frame inspection. + */ +xenora_status xenora_session_get_recorded_frame( + xenora_session session, + uint32_t frame_index, + uint32_t *out_frame_id, + uint8_t *out_rgba, + uint64_t capacity +); + /* * Report the loop's state, the number of completed frames, and the latest * verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists, diff --git a/crates/ffi/src/frame_loop.rs b/crates/ffi/src/frame_loop.rs index 5b26364..8357944 100644 --- a/crates/ffi/src/frame_loop.rs +++ b/crates/ffi/src/frame_loop.rs @@ -19,12 +19,14 @@ use xenora_metal::NativeCompute; use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe"); +const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe"); pub const WIDTH: usize = 4; pub const HEIGHT: usize = 3; pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4; pub const MAX_FRAMES: u32 = 100_000; /// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack. const STEPS_PER_FRAME: usize = 8; +const STEPS_PER_INTERACTIVE_FRAME: usize = 24; /// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour. const RED: [u8; 4] = [255, 0, 0, 255]; const CLEAR: [u8; 4] = [19, 43, 93, 251]; @@ -35,13 +37,30 @@ pub const FINISHED: u32 = 3; pub const STOPPED: u32 = 4; pub const FAILED: u32 = 5; +#[derive(Default, Copy, Clone)] +#[repr(C)] +pub struct InputState { + pub buttons: u32, + pub stick_x: i16, + pub stick_y: i16, + pub mouse_dx: i16, + pub mouse_dy: i16, + pub mouse_buttons: u8, + pub connected: u8, + pub reserved: u16, +} + #[derive(Default)] struct State { status: u32, paused: bool, stop: bool, + interactive: bool, limit: u32, completed: u32, + input: InputState, + input_queue: std::collections::VecDeque, + recorded_frames: Vec<(u32, Vec)>, /// Every `frame_submit` call the guest made, including the one answered with 0. calls: u64, latest: Option<(u32, Vec)>, @@ -67,12 +86,13 @@ impl FrameLoop { .unwrap_or_else(|poisoned| poisoned.into_inner()) } - pub fn start(limit: u32) -> Arc { + pub fn start(limit: u32, interactive: bool) -> Arc { let shared = Arc::new(Self::default()); { let mut state = shared.lock(); state.status = RUNNING; state.limit = limit; + state.interactive = interactive; } let guest = Arc::clone(&shared); let handle = std::thread::Builder::new() @@ -110,6 +130,21 @@ impl FrameLoop { } } + pub fn send_input(&self, input: InputState) { + let mut state = self.lock(); + state.input = input; + } + + pub fn queue_input(&self, input: InputState) { + let mut state = self.lock(); + state.input_queue.push_back(input); + } + + pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec)> { + let state = self.lock(); + state.recorded_frames.get(index).cloned() + } + pub fn snapshot(&self) -> Snapshot { let state = self.lock(); Snapshot { @@ -148,29 +183,57 @@ impl FrameLoop { .submit(index) .ok_or(ExitReason::IllegalInstruction(0xff)) }); + if self.lock().interactive { + let shared_poll = Arc::clone(self); + imports.register("xenora.dll", "input_poll", move |_args, _, _memory| { + let mut state = shared_poll.lock(); + let input = state.input_queue.pop_front().unwrap_or(state.input); + let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 { + 1u64 + } else if input.buttons & crate::XENORA_INPUT_LEFT != 0 { + 2u64 + } else { + 0u64 + }; + Ok(cmd) + }); + } let limit = self.lock().limit as usize; + let is_interactive = self.lock().interactive; + let fixture_bytes = if is_interactive { + INTERACTIVE_FIXTURE + } else { + FIXTURE + }; + let steps_per_frame = if is_interactive { + STEPS_PER_INTERACTIVE_FRAME + } else { + STEPS_PER_FRAME + }; let startup = run_synthetic_startup( - FIXTURE, + fixture_bytes, StartupLayout { image_base: 0x1_4000_0000, stack_top: 0x2_0001_0000, tls_base: 0x3_0000_0000, }, imports, - (limit + 1) * STEPS_PER_FRAME + 16, + (limit + 1) * steps_per_frame + 32, ) .map_err(|e| format!("startup: {e}")); GPU.with(|slot| slot.borrow_mut().take()); let startup = startup?; let calls = self.lock().calls; let rbx = startup.execution.final_state.get(Register::Rbx); - // The guest increments RBX after every call, so it must equal the calls we served. - if startup.execution.exit_reason != ExitReason::Halt || rbx != calls { + if startup.execution.exit_reason != ExitReason::Halt { return Err(format!( - "guest ended with {:?}, rbx={rbx}, calls={calls}", + "guest ended with {:?}", startup.execution.exit_reason )); } + if !is_interactive && rbx != calls { + return Err(format!("guest ended with rbx={rbx}, calls={calls}")); + } Ok(()) } @@ -185,14 +248,21 @@ impl FrameLoop { if state.stop || state.completed >= state.limit { return Some(0); } - if index != u64::from(state.completed) { + if state.interactive { + if index >= WIDTH as u64 { + return None; // column must be inside 0..WIDTH + } + } else if index != u64::from(state.completed) { return None; // frame identities must arrive in order } drop(state); let pixels = render(index as u32)?; let mut state = self.lock(); state.completed += 1; - state.latest = Some((index as u32, pixels)); + state.latest = Some((index as u32, pixels.clone())); + if state.interactive { + state.recorded_frames.push((index as u32, pixels)); + } Some(u64::from(state.completed < state.limit && !state.stop)) } } diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 0a49a1d..f0d3c9c 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -39,6 +39,16 @@ pub const XENORA_LOOP_FAILED: u32 = frame_loop::FAILED; pub const XENORA_FRAME_LOOP_MAX_FRAMES: u32 = frame_loop::MAX_FRAMES; pub const XENORA_NO_FRAME: u32 = u32::MAX; +pub const XENORA_INPUT_NONE: u32 = 0; +pub const XENORA_INPUT_RIGHT: u32 = 1 << 0; +pub const XENORA_INPUT_LEFT: u32 = 1 << 1; +pub const XENORA_INPUT_UP: u32 = 1 << 2; +pub const XENORA_INPUT_DOWN: u32 = 1 << 3; +pub const XENORA_INPUT_ACTION_A: u32 = 1 << 4; +pub const XENORA_INPUT_ACTION_B: u32 = 1 << 5; + +pub use frame_loop::InputState as xenora_input_state; + pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4; pub const XENORA_FIXTURE_FRAME_HEIGHT: u32 = 3; const FRAME_BYTES: usize = (XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4) as usize; @@ -160,11 +170,78 @@ pub extern "C" fn xenora_session_start_frame_loop(session: u64, frame_count: u32 if slot.frame_loop.is_some() { return XENORA_INVALID_STATE; } - slot.frame_loop = Some(FrameLoop::start(frame_count)); + slot.frame_loop = Some(FrameLoop::start(frame_count, false)); XENORA_OK }) } +#[unsafe(no_mangle)] +pub extern "C" fn xenora_session_start_interactive_loop(session: u64, frame_count: u32) -> i32 { + guarded(|| { + if !(1..=XENORA_FRAME_LOOP_MAX_FRAMES).contains(&frame_count) { + return XENORA_INVALID_ARGUMENT; + } + let Ok(mut slots) = SESSIONS.lock() else { + return XENORA_INTERNAL_ERROR; + }; + if !is_live(&slots, session) { + return XENORA_INVALID_HANDLE; + } + let slot = &mut slots[split(session).0]; + if slot.frame_loop.is_some() { + return XENORA_INVALID_STATE; + } + slot.frame_loop = Some(FrameLoop::start(frame_count, true)); + XENORA_OK + }) +} + +/// # Safety +/// `input` must be a valid pointer to an initialized `xenora_input_state`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_send_input( + session: u64, + input: *const frame_loop::InputState, +) -> i32 { + guarded(|| { + if input.is_null() { + return XENORA_INVALID_ARGUMENT; + } + let input_val = unsafe { *input }; + match session_loop(session) { + Ok(Some(running)) => { + running.send_input(input_val); + XENORA_OK + } + Ok(None) => XENORA_INVALID_STATE, + Err(status) => status, + } + }) +} + +/// # Safety +/// `input` must be a valid pointer to an initialized `xenora_input_state`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_queue_input( + session: u64, + input: *const frame_loop::InputState, +) -> i32 { + guarded(|| { + if input.is_null() { + return XENORA_INVALID_ARGUMENT; + } + let input_val = unsafe { *input }; + match session_loop(session) { + Ok(Some(running)) => { + running.queue_input(input_val); + XENORA_OK + } + Ok(None) => XENORA_INVALID_STATE, + Err(status) => status, + } + }) +} + fn set_paused(session: u64, paused: bool) -> i32 { guarded(|| match session_loop(session) { Ok(Some(running)) if running.set_paused(paused) => XENORA_OK, @@ -249,6 +326,41 @@ pub unsafe extern "C" fn xenora_session_frame_loop_status( }) } +/// # Safety +/// `out_frame_id` must be valid for one aligned write; `out_rgba` must be valid +/// for `capacity` byte writes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_get_recorded_frame( + session: u64, + frame_index: u32, + out_frame_id: *mut u32, + out_rgba: *mut u8, + capacity: u64, +) -> i32 { + guarded(|| { + if out_frame_id.is_null() || out_rgba.is_null() { + return XENORA_INVALID_ARGUMENT; + } + if capacity < frame_loop::FRAME_BYTES as u64 { + return XENORA_BUFFER_TOO_SMALL; + } + let running = match session_loop(session) { + Ok(Some(running)) => running, + Ok(None) => return XENORA_INVALID_STATE, + Err(status) => return status, + }; + let Some((id, pixels)) = running.get_recorded_frame(frame_index as usize) else { + return XENORA_INVALID_ARGUMENT; + }; + // SAFETY: checked non-null and capacity >= FRAME_BYTES + unsafe { + out_frame_id.write(id); + std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, frame_loop::FRAME_BYTES); + } + XENORA_OK + }) +} + /// # Safety /// Each output pointer must be null or valid for one aligned `u32` write. #[unsafe(no_mangle)] @@ -601,6 +713,13 @@ mod tests { "XENORA_FRAME_LOOP_MAX_FRAMES {XENORA_FRAME_LOOP_MAX_FRAMES}u" ))); assert!(header.contains("XENORA_NO_FRAME 0xFFFFFFFFu")); + assert!(header.contains("XENORA_INPUT_NONE 0u")); + assert!(header.contains("XENORA_INPUT_RIGHT (1u << 0)")); + assert!(header.contains("XENORA_INPUT_LEFT (1u << 1)")); + assert!(header.contains("XENORA_INPUT_UP (1u << 2)")); + assert!(header.contains("XENORA_INPUT_DOWN (1u << 3)")); + assert!(header.contains("XENORA_INPUT_ACTION_A (1u << 4)")); + assert!(header.contains("XENORA_INPUT_ACTION_B (1u << 5)")); } #[test] @@ -817,10 +936,39 @@ mod tests { xenora_session_start_frame_loop(handle, 0), XENORA_INVALID_ARGUMENT ); + assert_eq!( + xenora_session_start_interactive_loop(handle, 0), + XENORA_INVALID_ARGUMENT + ); assert_eq!( xenora_session_start_frame_loop(handle, XENORA_FRAME_LOOP_MAX_FRAMES + 1), XENORA_INVALID_ARGUMENT ); + assert_eq!( + xenora_session_start_interactive_loop(handle, XENORA_FRAME_LOOP_MAX_FRAMES + 1), + XENORA_INVALID_ARGUMENT + ); + assert_eq!( + unsafe { xenora_session_send_input(handle, std::ptr::null()) }, + XENORA_INVALID_ARGUMENT + ); + let dummy_input = xenora_input_state::default(); + assert_eq!( + unsafe { xenora_session_send_input(handle, &dummy_input) }, + XENORA_INVALID_STATE + ); + assert_eq!( + unsafe { xenora_session_queue_input(handle, &dummy_input) }, + XENORA_INVALID_STATE + ); + let mut rec_id = 0u32; + let mut rec_rgba = [0u8; 48]; + assert_eq!( + unsafe { + xenora_session_get_recorded_frame(handle, 0, &mut rec_id, rec_rgba.as_mut_ptr(), 48) + }, + XENORA_INVALID_STATE + ); assert_eq!( xenora_session_pause_frame_loop(handle), XENORA_INVALID_STATE diff --git a/crates/ffi/tests/interactive.rs b/crates/ffi/tests/interactive.rs new file mode 100644 index 0000000..5825979 --- /dev/null +++ b/crates/ffi/tests/interactive.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Gate 4 acceptance on a native Metal device: interactive guest execution with +//! dynamic input handling and rendering through the C interface. +//! Needs `--features gpu-tests` (scripts/test-gpu.sh). +#![cfg(feature = "gpu-tests")] + +use std::sync::Mutex; +use std::time::{Duration, Instant}; +use xenora_ffi::*; + +/// Tests share the process-wide session table and one GPU; run them one at a time. +static SERIAL: Mutex<()> = Mutex::new(()); + +/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255); +/// all other columns keep the clear colour (19, 43, 93, 251). +fn expected(column: u32) -> Vec { + let mut frame = Vec::new(); + for _row in 0..3 { + for col in 0..4 { + if col == column % 4 { + frame.extend([255, 0, 0, 255]); + } else { + frame.extend([19, 43, 93, 251]); + } + } + } + frame +} + +struct Status { + state: u32, + completed: u32, + frame_id: u32, + rgba: [u8; 48], +} + +fn status(session: u64) -> Status { + let mut s = Status { + state: 99, + completed: 0, + frame_id: 0, + rgba: [0; 48], + }; + let code = unsafe { + xenora_session_frame_loop_status( + session, + &mut s.state, + &mut s.completed, + &mut s.frame_id, + s.rgba.as_mut_ptr(), + 48, + ) + }; + assert_eq!(code, XENORA_OK); + s +} + +fn session() -> u64 { + let mut session = 0; + assert_eq!( + unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) }, + XENORA_OK + ); + session +} + +fn send_buttons(session: u64, buttons: u32) { + let input = xenora_input_state { + buttons, + stick_x: 0, + stick_y: 0, + mouse_dx: 0, + mouse_dy: 0, + mouse_buttons: 0, + connected: 1, + reserved: 0, + }; + assert_eq!( + unsafe { xenora_session_send_input(session, &input) }, + XENORA_OK + ); +} + +fn queue_buttons(session: u64, buttons: u32) { + let input = xenora_input_state { + buttons, + stick_x: 0, + stick_y: 0, + mouse_dx: 0, + mouse_dy: 0, + mouse_buttons: 0, + connected: 1, + reserved: 0, + }; + assert_eq!( + unsafe { xenora_session_queue_input(session, &input) }, + XENORA_OK + ); +} + +fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status { + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let s = status(session); + if done(&s) { + return s; + } + assert!( + Instant::now() < deadline, + "timed out waiting for {what} (state {}, completed {})", + s.state, + s.completed + ); + std::thread::sleep(Duration::from_millis(2)); + } +} + +#[test] +fn interactive_input_moves_guest_column_and_updates_pixels() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + let session = session(); + + // Start interactive loop with 120 frames + assert_eq!( + xenora_session_start_interactive_loop(session, 120), + XENORA_OK + ); + + // Initial frames without input stay at column 0 + let s = wait_until(session, "initial frames", |s| s.completed >= 5); + assert_eq!(s.frame_id, 0); + assert_eq!(s.rgba.to_vec(), expected(0)); + + // Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0 + send_buttons(session, XENORA_INPUT_RIGHT); + let s_right = wait_until(session, "column moves right", |s| { + s.completed >= 15 && s.frame_id != 0 + }); + assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id)); + + // Release input: position stops moving + send_buttons(session, XENORA_INPUT_NONE); + let s_hold_start = wait_until(session, "wait for release frame", |s| { + s.completed >= s_right.completed + 2 + }); + let hold_col = s_hold_start.frame_id; + let s_hold = wait_until(session, "position holds on release", |s| { + s.completed >= s_hold_start.completed + 10 + }); + assert_eq!(s_hold.frame_id, hold_col); + assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id)); + + // Send Left input: column should move left + send_buttons(session, XENORA_INPUT_LEFT); + let s_left = wait_until(session, "column moves left", |s| { + s.completed >= s_hold.completed + 10 && s.frame_id != hold_col + }); + assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id)); + + // Wait until finished + let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED); + assert_eq!(s_end.completed, 120); + + assert_eq!(xenora_session_destroy(session), XENORA_OK); +} + +#[test] +fn deterministic_input_replay_produces_identical_frames() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + + // Timeline of inputs across 60 frames: + // frames 0..15: Right + // frames 15..30: None + // frames 30..45: Left + // frames 45..60: Right + let replay_sequence: Vec = (0..60) + .map(|f| { + if f < 15 { + XENORA_INPUT_RIGHT + } else if f < 30 { + XENORA_INPUT_NONE + } else if f < 45 { + XENORA_INPUT_LEFT + } else { + XENORA_INPUT_RIGHT + } + }) + .collect(); + + let run_replay = || { + let session = session(); + assert_eq!( + xenora_session_start_interactive_loop(session, 60), + XENORA_OK + ); + + // Pre-queue the complete input sequence + for &btn in &replay_sequence { + queue_buttons(session, btn); + } + + // Wait until all 60 frames are rendered + let s = wait_until(session, "replay completion", |s| { + s.state == XENORA_LOOP_FINISHED && s.completed == 60 + }); + assert_eq!(s.completed, 60); + + // Inspect all 60 recorded frames + let mut frames = Vec::with_capacity(60); + for i in 0..60 { + let mut id = 0u32; + let mut rgba = [0u8; 48]; + let code = unsafe { + xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48) + }; + assert_eq!(code, XENORA_OK); + assert_eq!(rgba.to_vec(), expected(id)); + frames.push((id, rgba)); + } + + assert_eq!(xenora_session_destroy(session), XENORA_OK); + frames + }; + + let run1 = run_replay(); + let run2 = run_replay(); + + assert_eq!(run1.len(), 60); + assert_eq!(run2.len(), 60); + for i in 0..60 { + assert_eq!( + run1[i].0, run2[i].0, + "frame {} column mismatch: {} vs {}", + i, run1[i].0, run2[i].0 + ); + assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i); + } +} + +#[test] +fn focus_loss_and_release_resets_input_cleanly() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + let session = session(); + + assert_eq!( + xenora_session_start_interactive_loop(session, 100), + XENORA_OK + ); + + // Send Right + send_buttons(session, XENORA_INPUT_RIGHT); + let s1 = wait_until(session, "moving right", |s| s.completed >= 10); + + // Simulate focus loss / key release + send_buttons(session, XENORA_INPUT_NONE); + // Wait for the release to take effect in the guest + let s_released = wait_until(session, "release takes effect", |s| { + s.completed >= s1.completed + 2 + }); + let stopped_col = s_released.frame_id; + + // Check next 15 frames: frame_id must remain fixed at stopped_col + let s2 = wait_until(session, "hold after release", |s| { + s.completed >= s_released.completed + 15 + }); + assert_eq!(s2.frame_id, stopped_col); + assert_eq!(s2.rgba.to_vec(), expected(stopped_col)); + + // Clean stop + assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK); + let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED); + assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED); + + assert_eq!(xenora_session_destroy(session), XENORA_OK); +} + +#[test] +fn destroying_interactive_session_stops_cleanly() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + let session = session(); + + assert_eq!( + xenora_session_start_interactive_loop(session, 5000), + XENORA_OK + ); + + // Wait until it actually starts rendering + wait_until(session, "running", |s| s.completed >= 5); + + let start = Instant::now(); + assert_eq!(xenora_session_destroy(session), XENORA_OK); + assert!( + start.elapsed() < Duration::from_millis(500), + "destroy took too long: {:?}", + start.elapsed() + ); +} diff --git a/fixtures/pe/interactive.exe b/fixtures/pe/interactive.exe new file mode 100644 index 0000000000000000000000000000000000000000..cbbed480941ea668789b306b4d0f0c0306ea6c9f GIT binary patch literal 2048 zcmeZ`VjvqdkgXG;F~F69A*GE8Apm53U{GS<1_{A1NLB!f85kTGVSH3=AW;Se10ZGr zvly5e5`apgZu>YD~N{r1IPjc z1qOx$y`q%Fl0+aEBo7n-(`-N*2{!^80Qe^F;(qVs6}!C1=T z(R`Q@$YKJqUISUbS!zHmApXrz3zB8==)Cz~R0^b_^+4$nkLDv9UkKYYs$wvPfPn(S zRRuscsGPzF8ldtMpftK#Lh== iat[0]: input_poll] + code += b"\xff\x15" + pack(" iat[1]: frame_submit] + code += b"\xff\x15" + pack("