diff --git a/CHANGELOG.md b/CHANGELOG.md index 952251a..ef754db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ 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 persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`. + - 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`. diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 34356cf..c16fc40 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -69,12 +69,50 @@ struct GuestFrame { } } +/// The frame produced by running the textured fixture (Gate 5, #279). +struct TexturedFrame { + let status: Int32 + let width: Int + let height: Int + let rgba: [UInt8] + + static func run() -> TexturedFrame { + var session: xenora_session = 0 + var status = xenora_session_create(XENORA_ABI_VERSION, &session) + guard status == XENORA_OK else { return TexturedFrame(status: status, width: 0, height: 0, rgba: []) } + defer { _ = xenora_session_destroy(session) } + var rgba = [UInt8](repeating: 0, count: 16) + var width: UInt32 = 0 + var height: UInt32 = 0 + status = rgba.withUnsafeMutableBufferPointer { buffer in + xenora_session_run_textured_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height) + } + return TexturedFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : []) + } + + var image: CGImage? { + guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil } + return CGImage( + width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue), + provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) + } + + var summary: String { + let pixels = rgba.map(String.init).joined(separator: ",") + return "status=\(status) frame=\(width)x\(height) pixels=[\(pixels)]" + } +} + /// Owns the latest fixture run. A class with @Published avoids SwiftUI macros, /// which the command-line toolchain does not ship. @MainActor final class FrameModel: ObservableObject { @Published var frame: GuestFrame? @Published var running = false + @Published var texturedFrame: TexturedFrame? + @Published var runningTextured = false func run() { running = true @@ -84,6 +122,14 @@ final class FrameModel: ObservableObject { running = false } } + + func runTextured() { + runningTextured = true + Task { + texturedFrame = await Task.detached { TexturedFrame.run() }.value + runningTextured = false + } + } } /// Persistent guest rendering model (Gate 3, #266; Gate 4, #276). @@ -359,8 +405,23 @@ struct ContentView: View { Text("Run failed (status \(frame.status)). No frame is shown.") .foregroundStyle(.red) } - Button(running ? "Running…" : "Run trusted fixture") { model.run() } - .disabled(running || !probe.connected) + if let tImage = model.texturedFrame?.image { + Image(decorative: tImage, scale: 1) + .resizable() + .interpolation(.none) + .aspectRatio(contentMode: .fit) + .frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160) + .accessibilityLabel("Textured guest frame, 2 by 2 pixels") + Text("Textured fixture ran: persistent texture created, dynamically updated, rendered on Metal, and retired.") + .font(.callout) + .foregroundStyle(.secondary) + } + HStack { + Button(running ? "Running…" : "Run trusted fixture") { model.run() } + .disabled(running || !probe.connected) + Button(model.runningTextured ? "Running…" : "Run textured fixture") { model.runTextured() } + .disabled(model.runningTextured || !probe.connected) + } } Section("Persistent frame loop") { if let image = loop.image { @@ -441,6 +502,14 @@ if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < Comm exit(status == Int32(XENORA_OK) ? 0 : 1) } +// `--smoke-resources` tests persistent texture lifecycle, dynamic subregion updates, and retirement on Metal. +if CommandLine.arguments.contains("--smoke-resources") { + let frame = TexturedFrame.run() + print("smoke-resources: \(frame.summary)") + let expected: [UInt8] = [255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 64, 64, 64, 255] + exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.rgba == expected ? 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 diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index 69773c4..b3e7259 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -146,6 +146,85 @@ xenora_status xenora_session_frame_loop_status( /* Largest file xenora_inspect_executable accepts, in bytes. */ #define XENORA_MAX_INSPECT_BYTES 268435456u +/* Opaque persistent GPU resource handle (Gate 5, #279) */ +typedef uint64_t xenora_resource; +#define XENORA_NO_RESOURCE 0u + +enum { + XENORA_RESOURCE_TYPE_TEXTURE_2D = 1, + XENORA_RESOURCE_TYPE_BUFFER = 2, +}; + +/* + * Create a persistent RGBA8 2D texture owned by the session. + * If `initial_rgba` is non-null, it must point to at least width * height * 4 bytes. + */ +xenora_status xenora_session_create_texture( + xenora_session session, + uint32_t width, + uint32_t height, + const uint8_t *initial_rgba, + xenora_resource *out_resource +); + +/* + * Dynamically update a subregion of a persistent texture. + */ +xenora_status xenora_session_update_texture( + xenora_session session, + xenora_resource resource, + uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height, + const uint8_t *rgba, + uint64_t byte_count +); + +/* + * Destroy or retire a persistent resource. If in-flight GPU execution is using + * the resource, destruction is deferred until the execution completes. + */ +xenora_status xenora_session_destroy_resource( + xenora_session session, + xenora_resource resource +); + +/* + * Query type, dimensions, and in-flight status of a persistent resource. + */ +xenora_status xenora_session_resource_info( + xenora_session session, + xenora_resource resource, + uint32_t *out_type, + uint32_t *out_width, + uint32_t *out_height, + uint32_t *out_in_flight +); + +/* + * Render a frame using a persistent texture resource. + */ +xenora_status xenora_session_render_textured( + xenora_session session, + xenora_resource resource, + uint8_t *out_rgba, + uint64_t capacity, + uint32_t *out_width, + uint32_t *out_height +); + +/* + * Run the original textured PE fixture and verify its read-back frame. + */ +xenora_status xenora_session_run_textured_fixture( + xenora_session session, + uint8_t *out_rgba, + uint64_t capacity, + uint32_t *out_width, + uint32_t *out_height +); + /* * Read-only compatibility inspection of a caller-supplied PE file. Nothing in * `bytes` is executed: it is parsed and statically disassembled (bounded) only. diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index f0d3c9c..5fbdcdd 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -14,7 +14,7 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::{Arc, Mutex}; use xenora_loader::startup::{StartupLayout, run_synthetic_startup}; use xenora_loader::{ExitReason, ImportRegistry, ParsedPe, ProbeConfig, Register, probe_pe_bytes}; -use xenora_metal::NativeCompute; +use xenora_metal::{MetalRgba8Texture, MetalRgba8TextureDesc, NativeCompute, Rgba8MipLevel}; use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; pub const XENORA_ABI_VERSION: u32 = 1; @@ -58,11 +58,35 @@ const MAX_SESSIONS: usize = 64; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); +pub const XENORA_NO_RESOURCE: u64 = 0; +pub const XENORA_RESOURCE_TYPE_TEXTURE_2D: u32 = 1; +pub const XENORA_RESOURCE_TYPE_BUFFER: u32 = 2; +const MAX_RESOURCES_PER_SESSION: usize = 256; + +#[derive(Clone)] +struct SendSyncTexture(MetalRgba8Texture); +// SAFETY: Apple Metal textures are thread-safe native GPU resources. +unsafe impl Send for SendSyncTexture {} +unsafe impl Sync for SendSyncTexture {} + +pub struct ResourceSlot { + pub generation: u32, + pub resource_type: u32, + pub width: u32, + pub height: u32, + pub pixels: Vec, + metal_texture: Option, + pub in_flight: u32, + pub retired: bool, +} + struct Slot { /// Odd while live, even while free; starts at 0 so the first handle is never 0. generation: u32, /// The session's persistent frame loop, if one was started. frame_loop: Option>, + /// Persistent GPU resources owned by this session (Gate 5, #279). + resources: Vec, } static SESSIONS: Mutex> = Mutex::new(Vec::new()); @@ -107,6 +131,7 @@ pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *m slots.push(Slot { generation: 0, frame_loop: None, + resources: Vec::new(), }); slots.len() - 1 } @@ -136,6 +161,7 @@ pub extern "C" fn xenora_session_destroy(session: u64) -> i32 { let slot = &mut slots[split(session).0]; slot.generation += 1; let running = slot.frame_loop.take(); + slot.resources.clear(); drop(slots); // Stop and join the guest thread without holding the session table. if let Some(running) = running { @@ -518,6 +544,590 @@ pub unsafe extern "C" fn xenora_session_run_trusted_fixture( }) } +fn get_resource_mut(slot: &mut Slot, resource: u64) -> Result<&mut ResourceSlot, i32> { + let (index, generation) = split(resource); + let res = slot.resources.get_mut(index).ok_or(XENORA_INVALID_HANDLE)?; + if res.generation != generation || generation % 2 == 0 || res.retired { + return Err(XENORA_INVALID_HANDLE); + } + Ok(res) +} + +/// # Safety +/// `out_resource` must be non-null and valid for one aligned `u64` write. +/// If `initial_rgba` is non-null, it must point to at least `width * height * 4` readable bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_create_texture( + session: u64, + width: u32, + height: u32, + initial_rgba: *const u8, + out_resource: *mut u64, +) -> i32 { + guarded(|| { + if out_resource.is_null() || width == 0 || height == 0 || width > 4096 || height > 4096 { + return XENORA_INVALID_ARGUMENT; + } + let total_pixels = match (width as usize).checked_mul(height as usize) { + Some(pixels) if pixels <= 16384 * 16384 => pixels, + _ => return XENORA_INVALID_ARGUMENT, + }; + let total_bytes = total_pixels * 4; + + 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]; + + let res_idx = match slot + .resources + .iter() + .position(|r| r.generation % 2 == 0 && !r.retired && r.in_flight == 0) + { + Some(idx) => idx, + None if slot.resources.len() < MAX_RESOURCES_PER_SESSION => { + slot.resources.push(ResourceSlot { + generation: 0, + resource_type: XENORA_RESOURCE_TYPE_TEXTURE_2D, + width: 0, + height: 0, + pixels: Vec::new(), + metal_texture: None, + in_flight: 0, + retired: false, + }); + slot.resources.len() - 1 + } + None => return XENORA_LIMIT_EXCEEDED, + }; + + let res = &mut slot.resources[res_idx]; + let Some(generation) = res.generation.checked_add(1) else { + return XENORA_LIMIT_EXCEEDED; + }; + res.generation = generation; + res.resource_type = XENORA_RESOURCE_TYPE_TEXTURE_2D; + res.width = width; + res.height = height; + res.in_flight = 0; + res.retired = false; + + let mut pixels = vec![0u8; total_bytes]; + if !initial_rgba.is_null() { + // SAFETY: Caller guarantees at least width * height * 4 readable bytes when initial_rgba is non-null. + unsafe { + std::ptr::copy_nonoverlapping(initial_rgba, pixels.as_mut_ptr(), total_bytes); + } + } + + res.metal_texture = if let Ok(gpu) = NativeCompute::new() { + if let Ok(desc) = MetalRgba8TextureDesc::new(width as usize, height as usize, 1) { + let mip = Rgba8MipLevel::new_packed(0, width as usize, height as usize, &pixels); + MetalRgba8Texture::upload(gpu.device(), desc, &[mip]) + .ok() + .map(SendSyncTexture) + } else { + None + } + } else { + None + }; + res.pixels = pixels; + + let handle = (u64::from(generation) << 32) | (res_idx as u64); + // SAFETY: checked non-null above. + unsafe { out_resource.write(handle) }; + XENORA_OK + }) +} + +/// # Safety +/// `rgba` must be non-null and valid for `byte_count` readable bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_update_texture( + session: u64, + resource: u64, + x: u32, + y: u32, + width: u32, + height: u32, + rgba: *const u8, + byte_count: u64, +) -> i32 { + guarded(|| { + if rgba.is_null() || width == 0 || height == 0 { + return XENORA_INVALID_ARGUMENT; + } + let update_pixels = match (width as usize).checked_mul(height as usize) { + Some(pixels) => pixels, + None => return XENORA_INVALID_ARGUMENT, + }; + let required_bytes = (update_pixels * 4) as u64; + if byte_count < required_bytes { + 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]; + let res = match get_resource_mut(slot, resource) { + Ok(r) => r, + Err(e) => return e, + }; + + if res.resource_type != XENORA_RESOURCE_TYPE_TEXTURE_2D { + return XENORA_INVALID_ARGUMENT; + } + if x.checked_add(width).is_none_or(|end_x| end_x > res.width) + || y.checked_add(height).is_none_or(|end_y| end_y > res.height) + { + return XENORA_INVALID_ARGUMENT; + } + + // SAFETY: caller guarantees byte_count readable bytes, and required_bytes <= byte_count. + let src_slice = unsafe { std::slice::from_raw_parts(rgba, required_bytes as usize) }; + for dy in 0..height { + let src_start = (dy as usize * width as usize) * 4; + let dst_start = (((y + dy) as usize * res.width as usize) + x as usize) * 4; + let row_bytes = width as usize * 4; + res.pixels[dst_start..dst_start + row_bytes] + .copy_from_slice(&src_slice[src_start..src_start + row_bytes]); + } + + if let Some(ref tex) = res.metal_texture { + let mip = + Rgba8MipLevel::new_packed(0, res.width as usize, res.height as usize, &res.pixels); + if tex.0.upload_mip(&mip).is_err() { + return XENORA_INTERNAL_ERROR; + } + } + + XENORA_OK + }) +} + +#[unsafe(no_mangle)] +pub extern "C" fn xenora_session_destroy_resource(session: u64, resource: u64) -> i32 { + guarded(|| { + 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]; + let res = match get_resource_mut(slot, resource) { + Ok(r) => r, + Err(e) => return e, + }; + + if res.in_flight > 0 { + res.retired = true; + } else { + res.generation += 1; + res.metal_texture = None; + res.pixels.clear(); + res.retired = false; + } + + XENORA_OK + }) +} + +/// # Safety +/// Each output pointer must be non-null and valid for one aligned `u32` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_resource_info( + session: u64, + resource: u64, + out_type: *mut u32, + out_width: *mut u32, + out_height: *mut u32, + out_in_flight: *mut u32, +) -> i32 { + guarded(|| { + if out_type.is_null() + || out_width.is_null() + || out_height.is_null() + || out_in_flight.is_null() + { + 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]; + let res = match get_resource_mut(slot, resource) { + Ok(r) => r, + Err(e) => return e, + }; + + // SAFETY: checked non-null above. + unsafe { + out_type.write(res.resource_type); + out_width.write(res.width); + out_height.write(res.height); + out_in_flight.write(res.in_flight); + } + XENORA_OK + }) +} + +const TEXTURE_RENDER_MSL: &str = r#" +#include +using namespace metal; + +struct VertexOut { + float4 position [[position]]; + float4 uv [[user(param0)]]; +}; + +vertex VertexOut textured_vs(device const float4 *positions [[buffer(0)]], + device const float4 *uvs [[buffer(1)]], + uint vid [[vertex_id]]) { + VertexOut out; + out.position = positions[vid]; + out.uv = uvs[vid]; + return out; +} + +fragment float4 textured_ps(VertexOut in [[stage_in]], + texture2d tex [[texture(0)]], + sampler samp [[sampler(0)]]) { + return tex.sample(samp, in.uv.xy); +} +"#; + +const FULLSCREEN_VERTICES: [[f32; 4]; 3] = [ + [-1.0, -1.0, 0.5, 1.0], + [3.0, -1.0, 0.5, 1.0], + [-1.0, 3.0, 0.5, 1.0], +]; + +const FULLSCREEN_UVS: [[f32; 4]; 3] = [ + [0.0, 1.0, 0.0, 1.0], + [2.0, 1.0, 0.0, 1.0], + [0.0, -1.0, 0.0, 1.0], +]; + +/// # Safety +/// `out_rgba` must be non-null and valid for `capacity` byte writes; +/// `out_width` and `out_height` must be non-null and valid for one aligned `u32` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_render_textured( + session: u64, + resource: u64, + out_rgba: *mut u8, + capacity: u64, + out_width: *mut u32, + out_height: *mut u32, +) -> i32 { + guarded(|| { + if out_rgba.is_null() || out_width.is_null() || out_height.is_null() { + return XENORA_INVALID_ARGUMENT; + } + + let (width, height, metal_tex) = { + 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]; + let res = match get_resource_mut(slot, resource) { + Ok(r) => r, + Err(e) => return e, + }; + if res.resource_type != XENORA_RESOURCE_TYPE_TEXTURE_2D { + return XENORA_INVALID_ARGUMENT; + } + let required_bytes = (res.width as u64) * (res.height as u64) * 4; + if capacity < required_bytes { + return XENORA_BUFFER_TOO_SMALL; + } + res.in_flight += 1; + (res.width, res.height, res.metal_texture.clone()) + }; + + // Render on Metal outside the session lock + let render_result: Result, ()> = if let Some(tex) = metal_tex { + match NativeCompute::new() { + Ok(gpu) => { + match xenora_metal::MetalSampler::new(gpu.device(), Default::default()) { + Ok(sampler) => gpu + .render_rgba8_sampled( + TEXTURE_RENDER_MSL, + ["textured_vs", "textured_ps"], + &FULLSCREEN_VERTICES, + &FULLSCREEN_UVS, + [width as usize, height as usize], + [0, 0, 0, 0], + Some((&tex.0, &sampler)), + ) + .map_err(|_| ()), + Err(_) => Err(()), + } + } + Err(_) => Err(()), + } + } else { + Err(()) + }; + + // Re-lock to decrement in_flight and finalize retirement if marked retired + { + let Ok(mut slots) = SESSIONS.lock() else { + return XENORA_INTERNAL_ERROR; + }; + let (sess_idx, _) = split(session); + if let Some(slot) = slots.get_mut(sess_idx) { + let (res_idx, _) = split(resource); + if let Some(res) = slot.resources.get_mut(res_idx) { + res.in_flight = res.in_flight.saturating_sub(1); + if res.retired && res.in_flight == 0 { + res.generation += 1; + res.retired = false; + res.metal_texture = None; + res.pixels.clear(); + } + } + } + } + + let pixels = match render_result { + Ok(p) => p, + Err(_) => return XENORA_EXECUTION_FAILED, + }; + + // SAFETY: non-null and capacity checked above. + unsafe { + std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, pixels.len()); + out_width.write(width); + out_height.write(height); + } + XENORA_OK + }) +} + +const TEXTURED_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/textured.exe"); + +const INITIAL_TEXTURE_2X2: [u8; 16] = [ + 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, +]; + +const UPDATED_TEXTURE_2X2: [u8; 16] = [ + 255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 64, 64, 64, 255, +]; + +fn run_textured_fixture(session: u64) -> Result, String> { + let last_frame = Arc::new(Mutex::new(None)); + let frame_sink = Arc::clone(&last_frame); + let mut imports = ImportRegistry::new(); + + imports.register("xenora.dll", "texture_create", move |args, _, memory| { + let w = args.get(0, memory).map_err(ExitReason::MemoryFault)? as u32; + let h = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; + if w != 2 || h != 2 { + return Err(ExitReason::IllegalInstruction(0xfe)); + } + let mut res_handle: u64 = 0; + let status = unsafe { + xenora_session_create_texture( + session, + w, + h, + INITIAL_TEXTURE_2X2.as_ptr(), + &mut res_handle, + ) + }; + if status != XENORA_OK { + return Err(ExitReason::IllegalInstruction(0xfd)); + } + Ok(res_handle) + }); + + let sink = Arc::clone(&frame_sink); + imports.register( + "xenora.dll", + "frame_submit_textured", + move |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let mut rendered = vec![0u8; 16]; + let mut rw = 0u32; + let mut rh = 0u32; + let status = unsafe { + xenora_session_render_textured( + session, + handle, + rendered.as_mut_ptr(), + 16, + &mut rw, + &mut rh, + ) + }; + if status != XENORA_OK || rw != 2 || rh != 2 { + return Err(ExitReason::IllegalInstruction(0xfc)); + } + if let Ok(mut slot) = sink.lock() { + *slot = Some(rendered); + } + Ok(1) + }, + ); + + imports.register("xenora.dll", "texture_update", move |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let x = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; + let y = args.get(2, memory).map_err(ExitReason::MemoryFault)? as u32; + let w = args.get(3, memory).map_err(ExitReason::MemoryFault)? as u32; + let h = 2u32; + let status = unsafe { + xenora_session_update_texture( + session, + handle, + x, + y, + w, + h, + UPDATED_TEXTURE_2X2.as_ptr(), + 16, + ) + }; + if status != XENORA_OK { + return Err(ExitReason::IllegalInstruction(0xfb)); + } + Ok(1) + }); + + imports.register("xenora.dll", "texture_destroy", move |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let status = xenora_session_destroy_resource(session, handle); + if status != XENORA_OK { + return Err(ExitReason::IllegalInstruction(0xfa)); + } + Ok(1) + }); + + let startup = run_synthetic_startup( + TEXTURED_FIXTURE, + StartupLayout { + image_base: 0x1_4000_0000, + stack_top: 0x2_0001_0000, + tls_base: 0x3_0000_0000, + }, + imports, + 100, + ) + .map_err(|e| format!("synthetic startup: {e}"))?; + + if startup.execution.exit_reason != ExitReason::Halt { + return Err(format!( + "unexpected exit reason: {:?}", + startup.execution.exit_reason + )); + } + + let final_pixels = last_frame + .lock() + .map_err(|_| "frame lock poisoned")? + .take() + .ok_or_else(|| "guest halted without rendering a frame".to_string())?; + + if final_pixels != UPDATED_TEXTURE_2X2 { + return Err("final read-back frame did not match updated texture".into()); + } + + Ok(final_pixels) +} + +/// # Safety +/// `out_rgba` must be non-null and valid for `capacity` byte writes; +/// `out_width` and `out_height` must be non-null and valid for one aligned `u32` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_run_textured_fixture( + session: u64, + out_rgba: *mut u8, + capacity: u64, + out_width: *mut u32, + out_height: *mut u32, +) -> i32 { + guarded(|| { + if out_rgba.is_null() || out_width.is_null() || out_height.is_null() { + return XENORA_INVALID_ARGUMENT; + } + if capacity < 16 { + return XENORA_BUFFER_TOO_SMALL; + } + match SESSIONS.lock() { + Ok(slots) if is_live(&slots, session) => {} + Ok(_) => return XENORA_INVALID_HANDLE, + Err(_) => return XENORA_INTERNAL_ERROR, + } + let Ok(pixels) = run_textured_fixture(session) else { + return XENORA_EXECUTION_FAILED; + }; + // SAFETY: non-null and at least 16 bytes, checked above. + unsafe { + std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, 16); + out_width.write(2); + out_height.write(2); + } + XENORA_OK + }) +} + +/// Internal test helper for acquiring a resource in-flight reference. +pub fn test_acquire_resource_in_flight(session: u64, resource: u64) -> Result<(), i32> { + let Ok(mut slots) = SESSIONS.lock() else { + return Err(XENORA_INTERNAL_ERROR); + }; + if !is_live(&slots, session) { + return Err(XENORA_INVALID_HANDLE); + } + let slot = &mut slots[split(session).0]; + let res = get_resource_mut(slot, resource)?; + res.in_flight += 1; + Ok(()) +} + +/// Internal test helper for releasing a resource in-flight reference. +pub fn test_release_resource_in_flight(session: u64, resource: u64) -> Result<(), i32> { + let Ok(mut slots) = SESSIONS.lock() else { + return Err(XENORA_INTERNAL_ERROR); + }; + if !is_live(&slots, session) { + return Err(XENORA_INVALID_HANDLE); + } + let slot = &mut slots[split(session).0]; + let (res_idx, res_gen) = split(resource); + let res = slot + .resources + .get_mut(res_idx) + .ok_or(XENORA_INVALID_HANDLE)?; + if res.generation != res_gen { + return Err(XENORA_INVALID_HANDLE); + } + res.in_flight = res.in_flight.saturating_sub(1); + if res.retired && res.in_flight == 0 { + res.generation += 1; + res.retired = false; + res.metal_texture = None; + res.pixels.clear(); + } + Ok(()) +} + pub const XENORA_MAX_INSPECT_BYTES: u64 = 256 * 1024 * 1024; /// Build the read-only inspection report and its status: `XENORA_OK`, `XENORA_PE_ERROR` @@ -1003,4 +1613,185 @@ mod tests { XENORA_INVALID_HANDLE ); } + + #[test] + fn test_resource_management_lifecycle_and_validation() { + let _guard = serial(); + let session = create(); + + let mut res = 0u64; + let initial = [ + 255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, + ]; + assert_eq!( + unsafe { xenora_session_create_texture(session, 2, 2, initial.as_ptr(), &mut res) }, + XENORA_OK + ); + assert_ne!(res, XENORA_NO_RESOURCE); + + // Invalid creation parameters + let mut dummy = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(session, 0, 2, std::ptr::null(), &mut dummy) }, + XENORA_INVALID_ARGUMENT + ); + assert_eq!( + unsafe { + xenora_session_create_texture(session, 2, 2, std::ptr::null(), std::ptr::null_mut()) + }, + XENORA_INVALID_ARGUMENT + ); + + // Query info + let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_resource_info( + session, + res, + &mut r_type, + &mut r_w, + &mut r_h, + &mut r_flight, + ) + }, + XENORA_OK + ); + assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D); + assert_eq!(r_w, 2); + assert_eq!(r_h, 2); + assert_eq!(r_flight, 0); + + // Subregion update + let update_pixel = [128u8, 128u8, 128u8, 255u8]; + assert_eq!( + unsafe { + xenora_session_update_texture(session, res, 1, 1, 1, 1, update_pixel.as_ptr(), 4) + }, + XENORA_OK + ); + + // Out-of-bounds update + assert_eq!( + unsafe { + xenora_session_update_texture(session, res, 2, 0, 1, 1, update_pixel.as_ptr(), 4) + }, + XENORA_INVALID_ARGUMENT + ); + assert_eq!( + unsafe { + xenora_session_update_texture(session, res, 0, 0, 2, 2, update_pixel.as_ptr(), 8) + }, + XENORA_INVALID_ARGUMENT + ); + + // Destroy resource + assert_eq!(xenora_session_destroy_resource(session, res), XENORA_OK); + + // Double destroy rejected + assert_eq!( + xenora_session_destroy_resource(session, res), + XENORA_INVALID_HANDLE + ); + // Stale handle queries rejected + assert_eq!( + unsafe { + xenora_session_resource_info( + session, + res, + &mut r_type, + &mut r_w, + &mut r_h, + &mut r_flight, + ) + }, + XENORA_INVALID_HANDLE + ); + assert_eq!( + unsafe { + xenora_session_update_texture(session, res, 0, 0, 1, 1, update_pixel.as_ptr(), 4) + }, + XENORA_INVALID_HANDLE + ); + + // Next allocation reuses slot with incremented generation + let mut res2 = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(session, 4, 4, std::ptr::null(), &mut res2) }, + XENORA_OK + ); + assert_eq!(split(res).0, split(res2).0); + assert_ne!(split(res).1, split(res2).1); + + xenora_session_destroy(session); + } + + #[test] + fn test_deferred_resource_retirement_waits_for_in_flight() { + let _guard = serial(); + let session = create(); + + let mut res = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(session, 2, 2, std::ptr::null(), &mut res) }, + XENORA_OK + ); + + // Acquire an in-flight reference + assert_eq!(test_acquire_resource_in_flight(session, res), Ok(())); + + let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_resource_info( + session, + res, + &mut r_type, + &mut r_w, + &mut r_h, + &mut r_flight, + ) + }, + XENORA_OK + ); + assert_eq!(r_flight, 1); + + // Destroy while in flight -> marked retired + assert_eq!(xenora_session_destroy_resource(session, res), XENORA_OK); + + // Subsequent user queries see handle as invalid + assert_eq!( + unsafe { + xenora_session_resource_info( + session, + res, + &mut r_type, + &mut r_w, + &mut r_h, + &mut r_flight, + ) + }, + XENORA_INVALID_HANDLE + ); + assert_eq!( + xenora_session_destroy_resource(session, res), + XENORA_INVALID_HANDLE + ); + + // Release in flight -> slot is freed + assert_eq!(test_release_resource_in_flight(session, res), Ok(())); + + // Slot can be reused now + let mut res_reused = 0u64; + assert_eq!( + unsafe { + xenora_session_create_texture(session, 2, 2, std::ptr::null(), &mut res_reused) + }, + XENORA_OK + ); + assert_eq!(split(res).0, split(res_reused).0); + assert!(split(res_reused).1 > split(res).1); + + xenora_session_destroy(session); + } } diff --git a/crates/ffi/tests/resources.rs b/crates/ffi/tests/resources.rs new file mode 100644 index 0000000..cf117e4 --- /dev/null +++ b/crates/ffi/tests/resources.rs @@ -0,0 +1,375 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Gate 5 acceptance on a native Metal device: persistent GPU resources, +//! dynamic texture updates, and completion-aware resource retirement through +//! the C interface (#279). +//! Needs `--features gpu-tests` (scripts/test-gpu.sh). +#![cfg(feature = "gpu-tests")] + +use std::sync::Mutex; +use xenora_ffi::*; + +/// Tests share the process-wide session table and one GPU; run them one at a time. +static SERIAL: Mutex<()> = Mutex::new(()); + +fn session() -> u64 { + let mut handle = 0; + assert_eq!( + unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) }, + XENORA_OK + ); + assert_ne!(handle, 0); + handle +} + +#[test] +fn persistent_texture_lifecycle_survives_across_multiple_frames() { + let _guard = SERIAL.lock().unwrap(); + let sess = session(); + + // 2x2 initial texture: + // (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white + let initial_rgba: [u8; 16] = [ + 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, + ]; + + let mut res = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) }, + XENORA_OK + ); + assert_ne!(res, XENORA_NO_RESOURCE); + + // Render 5 consecutive frames from this single persistent texture resource without re-allocation. + for frame_idx in 0..5 { + let mut out_rgba = [0u8; 16]; + let mut out_w = 0u32; + let mut out_h = 0u32; + + assert_eq!( + unsafe { + xenora_session_render_textured( + sess, + res, + out_rgba.as_mut_ptr(), + 16, + &mut out_w, + &mut out_h, + ) + }, + XENORA_OK, + "render frame {} failed", + frame_idx + ); + + assert_eq!(out_w, 2); + assert_eq!(out_h, 2); + assert_eq!( + out_rgba, initial_rgba, + "frame {} pixel mismatch with persistent texture", + frame_idx + ); + } + + // Verify resource is still live and un-retired after all frames + let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight) + }, + XENORA_OK + ); + assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D); + assert_eq!(r_w, 2); + assert_eq!(r_h, 2); + assert_eq!(r_flight, 0); + + assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK); + assert_eq!(xenora_session_destroy(sess), XENORA_OK); +} + +#[test] +fn dynamic_texture_subregion_update_is_reflected_on_metal() { + let _guard = SERIAL.lock().unwrap(); + let sess = session(); + + // 2x2 initial texture: + // (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white + let initial_rgba: [u8; 16] = [ + 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, + ]; + + let mut res = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) }, + XENORA_OK + ); + + // 1. Update 1x1 subregion at (x=1, y=0) from green to yellow [255, 255, 0, 255] + let yellow_pixel = [255u8, 255, 0, 255]; + assert_eq!( + unsafe { xenora_session_update_texture(sess, res, 1, 0, 1, 1, yellow_pixel.as_ptr(), 4) }, + XENORA_OK + ); + + let mut frame1 = [0u8; 16]; + let (mut w, mut h) = (0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_render_textured(sess, res, frame1.as_mut_ptr(), 16, &mut w, &mut h) + }, + XENORA_OK + ); + + let expected_frame1: [u8; 16] = [ + 255, 0, 0, 255, // (0,0) red (untouched) + 255, 255, 0, 255, // (1,0) yellow (updated) + 0, 0, 255, 255, // (0,1) blue (untouched) + 255, 255, 255, 255, // (1,1) white (untouched) + ]; + assert_eq!( + frame1, expected_frame1, + "Metal read-back did not reflect 1x1 subregion update" + ); + + // 2. Update 2x1 subregion across the bottom row: (0,1) and (1,1) + // (0,1)=magenta [255, 0, 255, 255], (1,1)=cyan [0, 255, 255, 255] + let bottom_row = [255u8, 0, 255, 255, 0, 255, 255, 255]; + assert_eq!( + unsafe { xenora_session_update_texture(sess, res, 0, 1, 2, 1, bottom_row.as_ptr(), 8) }, + XENORA_OK + ); + + let mut frame2 = [0u8; 16]; + assert_eq!( + unsafe { + xenora_session_render_textured(sess, res, frame2.as_mut_ptr(), 16, &mut w, &mut h) + }, + XENORA_OK + ); + + let expected_frame2: [u8; 16] = [ + 255, 0, 0, 255, // (0,0) red + 255, 255, 0, 255, // (1,0) yellow + 255, 0, 255, 255, // (0,1) magenta + 0, 255, 255, 255, // (1,1) cyan + ]; + assert_eq!( + frame2, expected_frame2, + "Metal read-back did not reflect 2x1 bottom row update" + ); + + assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK); + assert_eq!(xenora_session_destroy(sess), XENORA_OK); +} + +#[test] +fn deferred_resource_retirement_safely_waits_for_completion() { + let _guard = SERIAL.lock().unwrap(); + let sess = session(); + + let mut res = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) }, + XENORA_OK + ); + + // Acquire an in-flight reference simulating active GPU encoding/submission + assert_eq!(test_acquire_resource_in_flight(sess, res), Ok(())); + + let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight) + }, + XENORA_OK + ); + assert_eq!(r_flight, 1); + + // Calling destroy while in-flight marks the resource retired without dangling pointers + assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK); + + // Subsequent caller operations on the retired handle are rejected + assert_eq!( + unsafe { + xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight) + }, + XENORA_INVALID_HANDLE + ); + assert_eq!( + xenora_session_destroy_resource(sess, res), + XENORA_INVALID_HANDLE + ); + + let dummy_pixel = [0u8; 4]; + assert_eq!( + unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, dummy_pixel.as_ptr(), 4) }, + XENORA_INVALID_HANDLE + ); + + let mut out_rgba = [0u8; 16]; + let (mut w, mut h) = (0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h) + }, + XENORA_INVALID_HANDLE + ); + + // Now in-flight execution completes and releases its reference + assert_eq!(test_release_resource_in_flight(sess, res), Ok(())); + + // The slot is now safely reclaimed; the next allocation reuses the slot with a new generation + let mut res2 = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res2) }, + XENORA_OK + ); + assert_eq!((res & 0xFFFF_FFFF), (res2 & 0xFFFF_FFFF)); // same slot index + assert_ne!(res >> 32, res2 >> 32); // higher generation + + assert_eq!(xenora_session_destroy_resource(sess, res2), XENORA_OK); + assert_eq!(xenora_session_destroy(sess), XENORA_OK); +} + +#[test] +fn invalid_stale_and_double_destroyed_resource_handles_are_rejected() { + let _guard = SERIAL.lock().unwrap(); + let sess = session(); + + // Zero handle + assert_eq!( + xenora_session_destroy_resource(sess, XENORA_NO_RESOURCE), + XENORA_INVALID_HANDLE + ); + + // Unallocated slot index + let unallocated_handle = (1u64 << 32) | 999u64; + assert_eq!( + xenora_session_destroy_resource(sess, unallocated_handle), + XENORA_INVALID_HANDLE + ); + + // Create and destroy a valid resource + let mut res = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) }, + XENORA_OK + ); + assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK); + + // Double destroy + assert_eq!( + xenora_session_destroy_resource(sess, res), + XENORA_INVALID_HANDLE + ); + + // Stale handle queries + let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight) + }, + XENORA_INVALID_HANDLE + ); + + let pixel = [0u8; 4]; + assert_eq!( + unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, pixel.as_ptr(), 4) }, + XENORA_INVALID_HANDLE + ); + + let mut out_rgba = [0u8; 16]; + let (mut w, mut h) = (0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h) + }, + XENORA_INVALID_HANDLE + ); + + assert_eq!(xenora_session_destroy(sess), XENORA_OK); +} + +#[test] +fn repeated_resource_allocations_and_retirements_do_not_leak_slots() { + let _guard = SERIAL.lock().unwrap(); + let sess = session(); + + let initial = [ + 255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, + ]; + let update = [255u8, 255, 0, 255]; + + // Run 200 cycles of create -> update -> render -> destroy + for i in 0..200 { + let mut res = 0u64; + assert_eq!( + unsafe { xenora_session_create_texture(sess, 2, 2, initial.as_ptr(), &mut res) }, + XENORA_OK, + "create failed at cycle {}", + i + ); + + // Verify slot index is reused (res_idx is 0) + let slot_idx = (res & 0xFFFF_FFFF) as usize; + assert_eq!(slot_idx, 0, "slot index leaked at cycle {}", i); + + assert_eq!( + unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, update.as_ptr(), 4) }, + XENORA_OK + ); + + let mut out = [0u8; 16]; + let (mut w, mut h) = (0u32, 0u32); + assert_eq!( + unsafe { + xenora_session_render_textured(sess, res, out.as_mut_ptr(), 16, &mut w, &mut h) + }, + XENORA_OK + ); + + assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK); + } + + assert_eq!(xenora_session_destroy(sess), XENORA_OK); +} + +#[test] +fn textured_pe_fixture_executes_dynamic_updates_and_retirement() { + let _guard = SERIAL.lock().unwrap(); + let sess = session(); + + let mut out_rgba = [0u8; 16]; + let mut out_w = 0u32; + let mut out_h = 0u32; + + assert_eq!( + unsafe { + xenora_session_run_textured_fixture( + sess, + out_rgba.as_mut_ptr(), + 16, + &mut out_w, + &mut out_h, + ) + }, + XENORA_OK + ); + + assert_eq!(out_w, 2); + assert_eq!(out_h, 2); + + let expected_final: [u8; 16] = [ + 255, 255, 0, 255, // (0,0) yellow + 0, 255, 255, 255, // (1,0) cyan + 255, 0, 255, 255, // (0,1) magenta + 64, 64, 64, 255, // (1,1) dark grey + ]; + assert_eq!( + out_rgba, expected_final, + "guest textured fixture read-back frame mismatch" + ); + + assert_eq!(xenora_session_destroy(sess), XENORA_OK); +} diff --git a/fixtures/pe/textured.exe b/fixtures/pe/textured.exe new file mode 100644 index 0000000..78ed831 Binary files /dev/null and b/fixtures/pe/textured.exe differ diff --git a/fixtures/pe/textured.py b/fixtures/pe/textured.py new file mode 100644 index 0000000..f0a862f --- /dev/null +++ b/fixtures/pe/textured.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Generate the original PE32+ persistent texture fixture without an x86 toolchain. + +The guest demonstrates persistent GPU resource ownership, dynamic texture updates, +and completion-aware resource retirement through runtime services: +1. Calls xenora.dll!texture_create(2, 2) to allocate a persistent 2x2 texture. +2. Calls xenora.dll!frame_submit_textured(handle) to render frame 0 with initial contents. +3. Calls xenora.dll!texture_update(handle, 0, 0, 2, 2) to dynamically update texture pixels. +4. Calls xenora.dll!frame_submit_textured(handle) to render frame 1 with updated contents. +5. Calls xenora.dll!texture_destroy(handle) to retire the resource. +6. Halts cleanly. +""" + +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 + 0x60 + module = imports + 0x90 + sym_create = imports + 0xA0 + sym_update = imports + 0xC0 + sym_submit = imports + 0xE0 + sym_destroy = imports + 0x100 + + data = bytearray(0x800) + data[:2] = b"MZ" + pack_into(" iat[0]: texture_create] + code += b"\xff\x15" + pack(" iat[2]: frame_submit_textured] + code += b"\xff\x15" + pack(" iat[1]: texture_update] + code += b"\xff\x15" + pack(" iat[2]: frame_submit_textured] + code += b"\xff\x15" + pack(" iat[3]: texture_destroy] + code += b"\xff\x15" + pack("