Merge pull request #278 from Swastickc/task/276-native-app-gate4

app: interactive guest execution with input handling and dynamic rendering (#276)
This commit is contained in:
Ranveer Soni authored and GitHub committed 2026-11-24 17:11:42 +05:30
commit 19bea60d25
9 files changed
+767 -11

No files matched your search

+5
View File
@@ -15,6 +15,11 @@ remains unsupported.
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- 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.
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
+97 -2
View File
@@ -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<Void, Never>?
@@ -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
+35
View File
@@ -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,
+78 -8
View File
@@ -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<InputState>,
recorded_frames: Vec<(u32, Vec<u8>)>,
/// Every `frame_submit` call the guest made, including the one answered with 0.
calls: u64,
latest: Option<(u32, Vec<u8>)>,
@@ -67,12 +86,13 @@ impl FrameLoop {
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn start(limit: u32) -> Arc<Self> {
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
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<u8>)> {
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))
}
}
+149 -1
View File
@@ -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
+298
View File
@@ -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<u8> {
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<u32> = (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()
);
}
Binary file not shown.
+100
View File
@@ -0,0 +1,100 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ interactive fixture without an x86 toolchain.
The guest polls host input via xenora.dll!input_poll() and updates its
internal position:
- input 1 (Right): column = (column + 1) % 4
- input 2 (Left): column = (column - 1) % 4
- other: column stays unchanged
The guest then calls xenora.dll!frame_submit(column) and stops when the
import returns 0, then halts.
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
lookup = imports + 0x30
iat = imports + 0x50
module = imports + 0x70
sym_poll = imports + 0x80
sym_submit = imports + 0x90
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 24)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
code = bytearray()
code += b"\x48\x83\xec\x28" # sub rsp, 0x28
code += b"\x48\x31\xdb" # xor rbx, rbx (column: 0)
loop_start = entry + len(code)
# call [rip -> iat[0]: input_poll]
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
# cmp rax, 1; jne not_right; add rbx, 1
code += b"\x48\x83\xf8\x01\x75\x04\x48\x83\xc3\x01"
# cmp rax, 2; jne not_left; sub rbx, 1
code += b"\x48\x83\xf8\x02\x75\x04\x48\x83\xeb\x01"
# wrap check: cmp rbx, 4; jl check_min; sub rbx, 4
code += b"\x48\x83\xfb\x04\x7c\x04\x48\x83\xeb\x04"
# check_min: cmp rbx, 0; jge do_submit; add rbx, 4
code += b"\x48\x83\xfb\x00\x7d\x04\x48\x83\xc3\x04"
# do_submit:
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[1]: frame_submit]
code += b"\xff\x15" + pack("<i", (iat + 8) - (entry + len(code) + 6))
code += b"\x48\x85\xc0" # test rax, rax
rel_loop = loop_start - (entry + len(code) + 2)
code += b"\x75" + pack("<b", rel_loop)
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
code += b"\xf4" # hlt
data[0x400:0x400 + len(code)] = code
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
pack_into("<QQ", data, 0x600 + (lookup - imports), sym_poll, sym_submit)
pack_into("<QQ", data, 0x600 + (iat - imports), sym_poll, sym_submit)
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
data[0x600 + (sym_poll - imports) + 2:0x600 + (sym_poll - imports) + 2 + 10] = b"input_poll"
data[0x600 + (sym_submit - imports) + 2:0x600 + (sym_submit - imports) + 2 + 12] = b"frame_submit"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
+5
View File
@@ -35,6 +35,11 @@ cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop --no-ru
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop -- \
--nocapture --test-threads=1
# Interactive guest execution with dynamic input handling and rendering (Gate 4, #276).
cargo test --locked -p xenora-ffi --features gpu-tests --test interactive --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test interactive -- \
--nocapture --test-threads=1
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run