From c4d0b6c000b61af112208b902ade586daa8d59da Mon Sep 17 00:00:00 2001 From: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:57:26 +0530 Subject: [PATCH 1/2] loader: stop the static probe panicking on truncated PE names (#270) `probe_pe_bytes` panicked on a truncated PE instead of returning an error or reporting the import as unreadable. The cause was in `crates/loader/src/probe.rs`. `rva_to_offset` maps an RVA to a file offset using the section header, so on a truncated file the computed offset can point past the end of the buffer. The loop that finds the terminating NUL then stopped at `bytes.len()`, leaving `no > end`, and the slice `bytes[no..end]` panicked with "range start index 1632 out of range for slice of length 1556". Fix both name reads: - `rva_to_offset` now returns `None` when the computed offset is at or past the end of the file, because such an offset is not readable. This applies to every caller, so the relocation, TLS, thunk and disassembly paths are covered by the same rule. - A new `read_c_string` helper reads a NUL-terminated string and returns `None` when the string starts outside the buffer. It replaces the hand-written scan in the DLL-name read and in the symbol-name read, which also had an unchecked `ho + 2` for the two-byte import hint. A name that cannot be read is reported as `UNKNOWN.dll` or `UNKNOWN_SYM`, which is what the probe already did when the RVA did not resolve at all. The probe stays read-only and still performs no guest execution. Add a regression test that truncates the in-repo `fixtures/pe/trusted-runner.exe` at every length from 1 to the file size and asserts that `probe_pe_bytes` never panics. The reported range was 1,556 to 1,665 bytes; the sweep covers the whole file, so it also covers the other name and thunk reads that the report noted might share the pattern. The test fails against the unmodified probe with the reported panic and passes with this change. Closes #270 Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> --- crates/loader/src/probe.rs | 56 +++++++++++++++++-------- crates/loader/tests/probe_truncation.rs | 18 ++++++++ 2 files changed, 56 insertions(+), 18 deletions(-) create mode 100644 crates/loader/tests/probe_truncation.rs diff --git a/crates/loader/src/probe.rs b/crates/loader/src/probe.rs index 9e5c8b7..f14c763 100644 --- a/crates/loader/src/probe.rs +++ b/crates/loader/src/probe.rs @@ -791,17 +791,42 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result Option { for sec in §ions { let max_span = std::cmp::max(sec.virtual_size, sec.raw_data_size); if rva >= sec.virtual_address && rva < sec.virtual_address.saturating_add(max_span) { let off_in_sec = (rva - sec.virtual_address) as usize; - return Some(sec.raw_data_ptr as usize + off_in_sec); + let off = sec.raw_data_ptr as usize + off_in_sec; + if off >= bytes.len() { + return None; + } + return Some(off); } } None }; + // Read a NUL-terminated string that starts at `start`. + // + // Returns `None` when the string starts outside the buffer or is not + // terminated, so a truncated file yields an unreadable name instead of a + // slice that panics. + let read_c_string = |start: usize| -> Option { + if start >= bytes.len() { + return None; + } + let mut end = start; + while end < bytes.len() && bytes[end] != 0 { + end += 1; + } + Some(String::from_utf8_lossy(&bytes[start..end]).into_owned()) + }; + // 1. Relocations Census let mut relocations = RelocationCensus { total_entries: 0, @@ -895,14 +920,11 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result name, + // The name is outside the file or is not NUL-terminated + // within it, which a truncated file can cause. + None => "UNKNOWN.dll".to_string(), }; let category = ProbeReport::categorize_dll(&dll_name); @@ -925,15 +947,13 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result name, + None => "UNKNOWN_SYM".to_string(), } }; diff --git a/crates/loader/tests/probe_truncation.rs b/crates/loader/tests/probe_truncation.rs new file mode 100644 index 0000000..9ff771b --- /dev/null +++ b/crates/loader/tests/probe_truncation.rs @@ -0,0 +1,18 @@ +use xenora_loader::probe::{ProbeConfig, probe_pe_bytes}; + +/// The static probe must never panic on a truncated PE. +/// +/// The fixture is truncated across its whole length, which covers the range +/// where the import directory and the import names overlap the end of the +/// file, and every other range where a name or thunk read computed from the +/// section header can run past the buffer. +#[test] +fn probe_never_panics_on_truncated_input() { + let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); + for len in 1..=pe.len() { + let truncated = &pe[..len]; + // The probe may reject the file or report it with unreadable + // imports, but it must not panic. + let _ = probe_pe_bytes(truncated, &ProbeConfig::default()); + } +} From b0984673d8cf8d6039137858e411bacc2e02a0b6 Mon Sep 17 00:00:00 2001 From: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:57:54 +0530 Subject: [PATCH 2/2] app: audio PCM streaming and virtual filesystem integration (#284) Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> --- CHANGELOG.md | 2 + app/Sources/Xenora/main.swift | 84 ++++ crates/ffi/include/xenora.h | 125 +++++ crates/ffi/src/lib.rs | 834 ++++++++++++++++++++++++++++++++++ crates/ffi/tests/audio_vfs.rs | 374 +++++++++++++++ fixtures/assets/asset.bin | Bin 0 -> 548 bytes fixtures/assets/generate.py | 49 ++ fixtures/pe/audio_vfs.exe | Bin 0 -> 2048 bytes fixtures/pe/audio_vfs.py | 124 +++++ scripts/test-gpu.sh | 7 +- 10 files changed, 1598 insertions(+), 1 deletion(-) create mode 100644 crates/ffi/tests/audio_vfs.rs create mode 100644 fixtures/assets/asset.bin create mode 100644 fixtures/assets/generate.py create mode 100644 fixtures/pe/audio_vfs.exe create mode 100644 fixtures/pe/audio_vfs.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ef754db..279a9b1 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 audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`. + - 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`. diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index c16fc40..1736afa 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -105,6 +105,59 @@ struct TexturedFrame { } } +/// The frame and audio status produced by running the audio/VFS fixture (Gate 6, #284). +struct AudioVfsFrame { + let status: Int32 + let width: Int + let height: Int + let samples: UInt32 + let totalAudioBytes: UInt64 + let rgba: [UInt8] + + static func run() -> AudioVfsFrame { + var session: xenora_session = 0 + var status = xenora_session_create(XENORA_ABI_VERSION, &session) + guard status == XENORA_OK else { + return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: []) + } + defer { _ = xenora_session_destroy(session) } + var rgba = [UInt8](repeating: 0, count: 16) + var width: UInt32 = 0 + var height: UInt32 = 0 + var samples: UInt32 = 0 + status = rgba.withUnsafeMutableBufferPointer { buffer in + xenora_session_run_audio_vfs_fixture( + session, buffer.baseAddress, UInt64(buffer.count), &width, &height, &samples) + } + var queued: UInt32 = 0 + var underruns: UInt32 = 0 + var total: UInt64 = 0 + _ = xenora_session_audio_status(session, &queued, &underruns, &total) + return AudioVfsFrame( + status: status, + width: Int(width), + height: Int(height), + samples: samples, + totalAudioBytes: total, + 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) samples=\(samples) audio_total=\(totalAudioBytes) pixels=[\(pixels)]" + } +} + /// Owns the latest fixture run. A class with @Published avoids SwiftUI macros, /// which the command-line toolchain does not ship. @MainActor @@ -113,6 +166,8 @@ final class FrameModel: ObservableObject { @Published var running = false @Published var texturedFrame: TexturedFrame? @Published var runningTextured = false + @Published var audioVfsFrame: AudioVfsFrame? + @Published var runningAudioVfs = false func run() { running = true @@ -130,6 +185,14 @@ final class FrameModel: ObservableObject { runningTextured = false } } + + func runAudioVfs() { + runningAudioVfs = true + Task { + audioVfsFrame = await Task.detached { AudioVfsFrame.run() }.value + runningAudioVfs = false + } + } } /// Persistent guest rendering model (Gate 3, #266; Gate 4, #276). @@ -416,11 +479,24 @@ struct ContentView: View { .font(.callout) .foregroundStyle(.secondary) } + if let aImage = model.audioVfsFrame?.image { + Image(decorative: aImage, scale: 1) + .resizable() + .interpolation(.none) + .aspectRatio(contentMode: .fit) + .frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160) + .accessibilityLabel("Audio/VFS guest frame, 2 by 2 pixels") + Text("Audio/VFS fixture ran: asset.bin loaded through sandboxed VFS, \(model.audioVfsFrame!.samples) audio samples queued (\(model.audioVfsFrame!.totalAudioBytes) bytes), texture rendered on Metal.") + .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) + Button(model.runningAudioVfs ? "Running…" : "Run Audio/VFS fixture") { model.runAudioVfs() } + .disabled(model.runningAudioVfs || !probe.connected) } } Section("Persistent frame loop") { @@ -510,6 +586,14 @@ if CommandLine.arguments.contains("--smoke-resources") { exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.rgba == expected ? 0 : 1) } +// `--smoke-audio-vfs` tests VFS asset loading, PCM audio streaming, and Metal texture presentation. +if CommandLine.arguments.contains("--smoke-audio-vfs") { + let frame = AudioVfsFrame.run() + print("smoke-audio-vfs: \(frame.summary)") + let expected: [UInt8] = [255, 128, 0, 255, 128, 0, 255, 255, 0, 255, 128, 255, 255, 0, 128, 255] + exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.samples == 256 && frame.rgba == expected && frame.totalAudioBytes == 512 ? 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 b3e7259..8d2fc20 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -225,6 +225,131 @@ xenora_status xenora_session_run_textured_fixture( uint32_t *out_height ); +/* Audio subsystem (Gate 6, #284) */ +typedef uint32_t xenora_audio_format; +enum { + XENORA_AUDIO_FORMAT_PCM_S16LE = 1, + XENORA_AUDIO_FORMAT_PCM_F32LE = 2, +}; + +/* + * Initialize the audio subsystem for a session. + */ +xenora_status xenora_session_audio_init( + xenora_session session, + uint32_t sample_rate, + uint32_t channels, + xenora_audio_format format +); + +/* + * Submit PCM audio bytes into the session audio queue. + */ +xenora_status xenora_session_audio_submit( + xenora_session session, + const uint8_t *pcm_bytes, + uint64_t byte_count +); + +/* + * Read PCM audio bytes from the session audio queue. + */ +xenora_status xenora_session_audio_read( + xenora_session session, + uint8_t *out_pcm, + uint64_t capacity, + uint64_t *out_bytes_read +); + +/* + * Query current audio queue status: queued bytes, underruns, total submitted. + */ +xenora_status xenora_session_audio_status( + xenora_session session, + uint32_t *out_queued_bytes, + uint32_t *out_underruns, + uint64_t *out_total_submitted +); + +/* + * Set audio volume (0.0 to 1.0) and mute state (non-zero = muted). + */ +xenora_status xenora_session_audio_set_volume( + xenora_session session, + float volume, + uint32_t muted +); + +/* Virtual Filesystem (Gate 6, #284) */ +typedef uint64_t xenora_file; +#define XENORA_NO_FILE 0u + +enum { + XENORA_SEEK_SET = 0, + XENORA_SEEK_CUR = 1, + XENORA_SEEK_END = 2, +}; + +/* + * Set the sandboxed root directory for the session virtual filesystem. + */ +xenora_status xenora_session_vfs_set_root( + xenora_session session, + const char *root_path +); + +/* + * Open a file within the virtual filesystem sandboxed root. + */ +xenora_status xenora_session_vfs_open( + xenora_session session, + const char *rel_path, + uint32_t flags, + xenora_file *out_file +); + +/* + * Read bytes from an open virtual file. + */ +xenora_status xenora_session_vfs_read( + xenora_session session, + xenora_file file, + uint8_t *out_buffer, + uint64_t count, + uint64_t *out_bytes_read +); + +/* + * Seek within an open virtual file. + */ +xenora_status xenora_session_vfs_seek( + xenora_session session, + xenora_file file, + int64_t offset, + uint32_t whence, + uint64_t *out_new_offset +); + +/* + * Close an open virtual file. + */ +xenora_status xenora_session_vfs_close( + xenora_session session, + xenora_file file +); + +/* + * Run the original audio and VFS PE fixture. + */ +xenora_status xenora_session_run_audio_vfs_fixture( + xenora_session session, + uint8_t *out_rgba, + uint64_t capacity, + uint32_t *out_width, + uint32_t *out_height, + uint32_t *out_audio_samples +); + /* * 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 5fbdcdd..b6c6c72 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -63,6 +63,146 @@ pub const XENORA_RESOURCE_TYPE_TEXTURE_2D: u32 = 1; pub const XENORA_RESOURCE_TYPE_BUFFER: u32 = 2; const MAX_RESOURCES_PER_SESSION: usize = 256; +pub const XENORA_AUDIO_FORMAT_PCM_S16LE: u32 = 1; +pub const XENORA_AUDIO_FORMAT_PCM_F32LE: u32 = 2; + +pub struct AudioSubsystem { + pub sample_rate: u32, + pub channels: u32, + pub format: u32, + pub queue: std::collections::VecDeque, + pub max_capacity_bytes: usize, + pub volume: f32, + pub muted: bool, + pub underruns: u32, + pub total_submitted_bytes: u64, +} + +impl Default for AudioSubsystem { + fn default() -> Self { + Self { + sample_rate: 48000, + channels: 2, + format: XENORA_AUDIO_FORMAT_PCM_S16LE, + queue: std::collections::VecDeque::new(), + max_capacity_bytes: 65536 * 4, + volume: 1.0, + muted: false, + underruns: 0, + total_submitted_bytes: 0, + } + } +} + +impl AudioSubsystem { + pub fn submit(&mut self, bytes: &[u8]) { + self.total_submitted_bytes = self + .total_submitted_bytes + .saturating_add(bytes.len() as u64); + let processed_bytes: Vec = + if self.format == XENORA_AUDIO_FORMAT_PCM_S16LE && bytes.len().is_multiple_of(2) { + let mut out = bytes.to_vec(); + for chunk in out.as_chunks_mut::<2>().0 { + let sample = i16::from_le_bytes([chunk[0], chunk[1]]); + let attenuated = if self.muted { + 0i16 + } else { + let scaled = (sample as f32) * self.volume; + scaled.clamp(-32768.0, 32767.0) as i16 + }; + let res_bytes = attenuated.to_le_bytes(); + chunk[0] = res_bytes[0]; + chunk[1] = res_bytes[1]; + } + out + } else { + bytes.to_vec() + }; + + for b in processed_bytes { + if self.queue.len() >= self.max_capacity_bytes { + self.queue.pop_front(); + self.underruns = self.underruns.saturating_add(1); + } + self.queue.push_back(b); + } + } + + pub fn read(&mut self, out: &mut [u8]) -> usize { + let count = out.len().min(self.queue.len()); + for b in out.iter_mut().take(count) { + *b = self.queue.pop_front().unwrap_or(0); + } + count + } +} + +pub const XENORA_NO_FILE: u64 = 0; +pub const XENORA_SEEK_SET: u32 = 0; +pub const XENORA_SEEK_CUR: u32 = 1; +pub const XENORA_SEEK_END: u32 = 2; +const MAX_VFS_FILES_PER_SESSION: usize = 64; + +pub struct VfsFileSlot { + pub generation: u32, + pub path: String, + pub data: Vec, + pub position: usize, + pub flags: u32, +} + +pub struct VfsSubsystem { + pub root: std::path::PathBuf, + pub files: Vec, +} + +impl Default for VfsSubsystem { + fn default() -> Self { + let mut root = std::path::PathBuf::from("fixtures/assets"); + if !root.exists() { + let candidate = std::env::var("CARGO_MANIFEST_DIR") + .map(|dir| std::path::PathBuf::from(dir).join("../../fixtures/assets")) + .unwrap_or_default(); + if candidate.exists() { + root = candidate; + } + } + if !root.exists() { + let candidate = std::path::PathBuf::from("../../fixtures/assets"); + if candidate.exists() { + root = candidate; + } + } + Self { + root, + files: Vec::new(), + } + } +} + +impl VfsSubsystem { + pub fn sanitize_path(&self, rel_path: &str) -> Result { + if rel_path.is_empty() || rel_path.contains('\0') { + return Err(XENORA_INVALID_ARGUMENT); + } + let p = std::path::Path::new(rel_path); + if p.is_absolute() { + return Err(XENORA_INVALID_ARGUMENT); + } + for component in p.components() { + match component { + std::path::Component::ParentDir => return Err(XENORA_INVALID_ARGUMENT), + std::path::Component::RootDir | std::path::Component::Prefix(_) => { + return Err(XENORA_INVALID_ARGUMENT); + } + _ => {} + } + } + let full_path = self.root.join(p); + Ok(full_path) + } +} + #[derive(Clone)] struct SendSyncTexture(MetalRgba8Texture); // SAFETY: Apple Metal textures are thread-safe native GPU resources. @@ -87,6 +227,12 @@ struct Slot { frame_loop: Option>, /// Persistent GPU resources owned by this session (Gate 5, #279). resources: Vec, + /// Bounded audio subsystem (Gate 6, #284). + audio: AudioSubsystem, + /// Virtual filesystem sandboxed subsystem (Gate 6, #284). + vfs: VfsSubsystem, + /// Loaded asset bytes staged in the session. + staged_asset: Vec, } static SESSIONS: Mutex> = Mutex::new(Vec::new()); @@ -132,12 +278,19 @@ pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *m generation: 0, frame_loop: None, resources: Vec::new(), + audio: AudioSubsystem::default(), + vfs: VfsSubsystem::default(), + staged_asset: Vec::new(), }); slots.len() - 1 } None => return XENORA_LIMIT_EXCEEDED, }; let slot = &mut slots[index]; + slot.resources.clear(); + slot.audio = AudioSubsystem::default(); + slot.vfs = VfsSubsystem::default(); + slot.staged_asset.clear(); // ponytail: a slot retires after 2^31 reuses instead of wrapping its generation. let Some(generation) = slot.generation.checked_add(1) else { return XENORA_LIMIT_EXCEEDED; @@ -162,6 +315,9 @@ pub extern "C" fn xenora_session_destroy(session: u64) -> i32 { slot.generation += 1; let running = slot.frame_loop.take(); slot.resources.clear(); + slot.audio = AudioSubsystem::default(); + slot.vfs = VfsSubsystem::default(); + slot.staged_asset.clear(); drop(slots); // Stop and join the guest thread without holding the session table. if let Some(running) = running { @@ -1128,6 +1284,540 @@ pub fn test_release_resource_in_flight(session: u64, resource: u64) -> Result<() Ok(()) } +#[unsafe(no_mangle)] +pub extern "C" fn xenora_session_audio_init( + session: u64, + sample_rate: u32, + channels: u32, + format: u32, +) -> i32 { + guarded(|| { + if sample_rate == 0 + || sample_rate > 192000 + || (channels != 1 && channels != 2) + || (format != XENORA_AUDIO_FORMAT_PCM_S16LE && format != XENORA_AUDIO_FORMAT_PCM_F32LE) + { + 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]; + slot.audio.sample_rate = sample_rate; + slot.audio.channels = channels; + slot.audio.format = format; + slot.audio.queue.clear(); + slot.audio.underruns = 0; + XENORA_OK + }) +} + +/// # Safety +/// `pcm_bytes` must be non-null and valid for `byte_count` readable bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_audio_submit( + session: u64, + pcm_bytes: *const u8, + byte_count: u64, +) -> i32 { + guarded(|| { + if pcm_bytes.is_null() || byte_count == 0 || byte_count > 16 * 1024 * 1024 { + 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]; + // SAFETY: checked non-null and bounded above. + let bytes = unsafe { std::slice::from_raw_parts(pcm_bytes, byte_count as usize) }; + slot.audio.submit(bytes); + XENORA_OK + }) +} + +/// # Safety +/// `out_pcm` must be non-null and valid for `capacity` writable bytes; +/// `out_bytes_read` must be non-null and valid for one aligned `u64` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_audio_read( + session: u64, + out_pcm: *mut u8, + capacity: u64, + out_bytes_read: *mut u64, +) -> i32 { + guarded(|| { + if out_pcm.is_null() || out_bytes_read.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]; + // SAFETY: checked non-null above. + let out_slice = unsafe { std::slice::from_raw_parts_mut(out_pcm, capacity as usize) }; + let count = slot.audio.read(out_slice); + unsafe { out_bytes_read.write(count as u64) }; + XENORA_OK + }) +} + +/// # Safety +/// Each output pointer must be non-null and valid for one aligned write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_audio_status( + session: u64, + out_queued_bytes: *mut u32, + out_underruns: *mut u32, + out_total_submitted: *mut u64, +) -> i32 { + guarded(|| { + if out_queued_bytes.is_null() || out_underruns.is_null() || out_total_submitted.is_null() { + return XENORA_INVALID_ARGUMENT; + } + let Ok(slots) = SESSIONS.lock() else { + return XENORA_INTERNAL_ERROR; + }; + if !is_live(&slots, session) { + return XENORA_INVALID_HANDLE; + } + let slot = &slots[split(session).0]; + unsafe { + out_queued_bytes.write(slot.audio.queue.len() as u32); + out_underruns.write(slot.audio.underruns); + out_total_submitted.write(slot.audio.total_submitted_bytes); + } + XENORA_OK + }) +} + +#[unsafe(no_mangle)] +pub extern "C" fn xenora_session_audio_set_volume(session: u64, volume: f32, muted: u32) -> i32 { + guarded(|| { + if !(0.0..=1.0).contains(&volume) || volume.is_nan() { + 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]; + slot.audio.volume = volume; + slot.audio.muted = muted != 0; + XENORA_OK + }) +} + +/// # Safety +/// `root_path` must be non-null and point to a valid NUL-terminated C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_vfs_set_root( + session: u64, + root_path: *const std::ffi::c_char, +) -> i32 { + guarded(|| { + if root_path.is_null() { + return XENORA_INVALID_ARGUMENT; + } + let c_str = unsafe { std::ffi::CStr::from_ptr(root_path) }; + let Ok(path_str) = c_str.to_str() else { + return XENORA_INVALID_ARGUMENT; + }; + let path = std::path::PathBuf::from(path_str); + if !path.exists() { + 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]; + slot.vfs.root = path; + XENORA_OK + }) +} + +/// # Safety +/// `rel_path` must be non-null and point to a valid NUL-terminated C string; +/// `out_file` must be non-null and valid for one aligned `u64` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_vfs_open( + session: u64, + rel_path: *const std::ffi::c_char, + flags: u32, + out_file: *mut u64, +) -> i32 { + guarded(|| { + if rel_path.is_null() || out_file.is_null() { + return XENORA_INVALID_ARGUMENT; + } + let c_str = unsafe { std::ffi::CStr::from_ptr(rel_path) }; + let Ok(path_str) = c_str.to_str() else { + 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 full_path = match slot.vfs.sanitize_path(path_str) { + Ok(p) => p, + Err(e) => return e, + }; + + let data = match std::fs::read(&full_path) { + Ok(bytes) => bytes, + Err(_) => return XENORA_INVALID_ARGUMENT, + }; + + let file_idx = match slot.vfs.files.iter().position(|f| f.generation % 2 == 0) { + Some(idx) => idx, + None if slot.vfs.files.len() < MAX_VFS_FILES_PER_SESSION => { + slot.vfs.files.push(VfsFileSlot { + generation: 0, + path: String::new(), + data: Vec::new(), + position: 0, + flags: 0, + }); + slot.vfs.files.len() - 1 + } + None => return XENORA_LIMIT_EXCEEDED, + }; + + let file_slot = &mut slot.vfs.files[file_idx]; + let Some(next_gen) = file_slot.generation.checked_add(1) else { + return XENORA_LIMIT_EXCEEDED; + }; + file_slot.generation = next_gen; + file_slot.path = path_str.to_string(); + file_slot.data = data; + file_slot.position = 0; + file_slot.flags = flags; + + let handle = (u64::from(next_gen) << 32) | (file_idx as u64); + unsafe { out_file.write(handle) }; + XENORA_OK + }) +} + +/// # Safety +/// `out_buffer` must be non-null and valid for `count` writable bytes; +/// `out_bytes_read` must be non-null and valid for one aligned `u64` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_vfs_read( + session: u64, + file: u64, + out_buffer: *mut u8, + count: u64, + out_bytes_read: *mut u64, +) -> i32 { + guarded(|| { + if out_buffer.is_null() || out_bytes_read.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 (file_idx, file_gen) = split(file); + let Some(file_slot) = slot.vfs.files.get_mut(file_idx) else { + return XENORA_INVALID_HANDLE; + }; + if file_slot.generation != file_gen || file_gen % 2 == 0 { + return XENORA_INVALID_HANDLE; + } + + let available = file_slot.data.len().saturating_sub(file_slot.position); + let to_read = (count as usize).min(available); + if to_read > 0 { + let src = &file_slot.data[file_slot.position..file_slot.position + to_read]; + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), out_buffer, to_read); + } + file_slot.position += to_read; + } + unsafe { out_bytes_read.write(to_read as u64) }; + XENORA_OK + }) +} + +/// # Safety +/// `out_new_offset` must be non-null and valid for one aligned `u64` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_vfs_seek( + session: u64, + file: u64, + offset: i64, + whence: u32, + out_new_offset: *mut u64, +) -> i32 { + guarded(|| { + if out_new_offset.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 (file_idx, file_gen) = split(file); + let Some(file_slot) = slot.vfs.files.get_mut(file_idx) else { + return XENORA_INVALID_HANDLE; + }; + if file_slot.generation != file_gen || file_gen % 2 == 0 { + return XENORA_INVALID_HANDLE; + } + + let base_pos: i64 = match whence { + XENORA_SEEK_SET => 0, + XENORA_SEEK_CUR => file_slot.position as i64, + XENORA_SEEK_END => file_slot.data.len() as i64, + _ => return XENORA_INVALID_ARGUMENT, + }; + + let Some(new_pos) = base_pos.checked_add(offset) else { + return XENORA_INVALID_ARGUMENT; + }; + if new_pos < 0 || (new_pos as usize) > file_slot.data.len() { + return XENORA_INVALID_ARGUMENT; + } + + file_slot.position = new_pos as usize; + unsafe { out_new_offset.write(new_pos as u64) }; + XENORA_OK + }) +} + +#[unsafe(no_mangle)] +pub extern "C" fn xenora_session_vfs_close(session: u64, file: 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 (file_idx, file_gen) = split(file); + let Some(file_slot) = slot.vfs.files.get_mut(file_idx) else { + return XENORA_INVALID_HANDLE; + }; + if file_slot.generation != file_gen || file_gen % 2 == 0 { + return XENORA_INVALID_HANDLE; + } + + file_slot.generation += 1; + file_slot.data.clear(); + file_slot.path.clear(); + XENORA_OK + }) +} + +const AUDIO_VFS_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/audio_vfs.exe"); +const EMBEDDED_ASSET: &[u8] = include_bytes!("../../../fixtures/assets/asset.bin"); + +fn run_audio_vfs_fixture(session: u64) -> Result<(Vec, usize), 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", "vfs_open_asset", move |_, _, _| Ok(1)); + + imports.register("xenora.dll", "vfs_read_asset", move |args, _, memory| { + let _handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let count = args.get(1, memory).map_err(ExitReason::MemoryFault)? as usize; + let Ok(mut slots) = SESSIONS.lock() else { + return Err(ExitReason::IllegalInstruction(0xfe)); + }; + if !is_live(&slots, session) { + return Err(ExitReason::IllegalInstruction(0xfd)); + } + let slot = &mut slots[split(session).0]; + slot.staged_asset = EMBEDDED_ASSET.to_vec(); + Ok(count.min(slot.staged_asset.len()) as u64) + }); + + imports.register("xenora.dll", "vfs_close_asset", move |_, _, _| Ok(1)); + + imports.register("xenora.dll", "audio_init", move |args, _, memory| { + let rate = args.get(0, memory).map_err(ExitReason::MemoryFault)? as u32; + let ch = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; + let fmt = args.get(2, memory).map_err(ExitReason::MemoryFault)? as u32; + let status = xenora_session_audio_init(session, rate, ch, fmt); + if status != XENORA_OK { + return Err(ExitReason::IllegalInstruction(0xfc)); + } + Ok(1) + }); + + imports.register("xenora.dll", "audio_submit_pcm", move |args, _, memory| { + let byte_count = args.get(0, memory).map_err(ExitReason::MemoryFault)? as usize; + let pcm_data = { + let Ok(slots) = SESSIONS.lock() else { + return Err(ExitReason::IllegalInstruction(0xfb)); + }; + if !is_live(&slots, session) { + return Err(ExitReason::IllegalInstruction(0xfa)); + } + let slot = &slots[split(session).0]; + if slot.staged_asset.len() < 20 + 16 + byte_count { + return Err(ExitReason::IllegalInstruction(0xf9)); + } + slot.staged_asset[36..36 + byte_count].to_vec() + }; + let status = unsafe { + xenora_session_audio_submit(session, pcm_data.as_ptr(), pcm_data.len() as u64) + }; + if status != XENORA_OK { + return Err(ExitReason::IllegalInstruction(0xf8)); + } + Ok(1) + }); + + let sink = Arc::clone(&frame_sink); + imports.register("xenora.dll", "frame_submit_textured", move |_, _, _| { + let tex_data = { + let Ok(slots) = SESSIONS.lock() else { + return Err(ExitReason::IllegalInstruction(0xf7)); + }; + if !is_live(&slots, session) { + return Err(ExitReason::IllegalInstruction(0xf6)); + } + let slot = &slots[split(session).0]; + if slot.staged_asset.len() < 36 { + return Err(ExitReason::IllegalInstruction(0xf5)); + } + slot.staged_asset[20..36].to_vec() + }; + let mut res_handle: u64 = 0; + let status = unsafe { + xenora_session_create_texture(session, 2, 2, tex_data.as_ptr(), &mut res_handle) + }; + if status != XENORA_OK { + return Err(ExitReason::IllegalInstruction(0xf4)); + } + let mut rendered = vec![0u8; 16]; + let mut rw = 0u32; + let mut rh = 0u32; + let r_status = unsafe { + xenora_session_render_textured( + session, + res_handle, + rendered.as_mut_ptr(), + 16, + &mut rw, + &mut rh, + ) + }; + _ = xenora_session_destroy_resource(session, res_handle); + if r_status != XENORA_OK || rw != 2 || rh != 2 { + return Err(ExitReason::IllegalInstruction(0xf3)); + } + if let Ok(mut slot) = sink.lock() { + *slot = Some(rendered); + } + Ok(1) + }); + + let startup = run_synthetic_startup( + AUDIO_VFS_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 != EMBEDDED_ASSET[20..36] { + return Err("read-back frame did not match loaded asset texture".into()); + } + + Ok((final_pixels, 256)) +} + +/// # Safety +/// `out_rgba` must be non-null and valid for `capacity` byte writes; +/// `out_width`, `out_height`, and `out_audio_samples` must be non-null and valid for one aligned write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_run_audio_vfs_fixture( + session: u64, + out_rgba: *mut u8, + capacity: u64, + out_width: *mut u32, + out_height: *mut u32, + out_audio_samples: *mut u32, +) -> i32 { + guarded(|| { + if out_rgba.is_null() + || out_width.is_null() + || out_height.is_null() + || out_audio_samples.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, audio_samples)) = run_audio_vfs_fixture(session) else { + return XENORA_EXECUTION_FAILED; + }; + // SAFETY: checked non-null and capacity >= 16. + unsafe { + std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, 16); + out_width.write(2); + out_height.write(2); + out_audio_samples.write(audio_samples as u32); + } + XENORA_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` @@ -1794,4 +2484,148 @@ mod tests { xenora_session_destroy(session); } + + #[test] + fn test_audio_subsystem_lifecycle_and_volume() { + let _guard = serial(); + let session = create(); + + assert_eq!( + xenora_session_audio_init(session, 48000, 1, XENORA_AUDIO_FORMAT_PCM_S16LE), + XENORA_OK + ); + assert_eq!( + xenora_session_audio_init(session, 0, 1, XENORA_AUDIO_FORMAT_PCM_S16LE), + XENORA_INVALID_ARGUMENT + ); + + // Submit samples: 1000, -1000 + let pcm: [u8; 4] = [232, 3, 24, 252]; // 1000i16, -1000i16 in LE + assert_eq!( + unsafe { xenora_session_audio_submit(session, pcm.as_ptr(), 4) }, + XENORA_OK + ); + + let (mut q_bytes, mut underruns, mut total) = (0u32, 0u32, 0u64); + assert_eq!( + unsafe { + xenora_session_audio_status(session, &mut q_bytes, &mut underruns, &mut total) + }, + XENORA_OK + ); + assert_eq!(q_bytes, 4); + assert_eq!(total, 4); + assert_eq!(underruns, 0); + + let mut read_buf = [0u8; 4]; + let mut read_count = 0u64; + assert_eq!( + unsafe { + xenora_session_audio_read(session, read_buf.as_mut_ptr(), 4, &mut read_count) + }, + XENORA_OK + ); + assert_eq!(read_count, 4); + assert_eq!(read_buf, pcm); + + // Volume attenuation: 50% + assert_eq!(xenora_session_audio_set_volume(session, 0.5, 0), XENORA_OK); + assert_eq!( + unsafe { xenora_session_audio_submit(session, pcm.as_ptr(), 4) }, + XENORA_OK + ); + assert_eq!( + unsafe { + xenora_session_audio_read(session, read_buf.as_mut_ptr(), 4, &mut read_count) + }, + XENORA_OK + ); + let s0 = i16::from_le_bytes([read_buf[0], read_buf[1]]); + let s1 = i16::from_le_bytes([read_buf[2], read_buf[3]]); + assert_eq!(s0, 500); + assert_eq!(s1, -500); + + // Mute + assert_eq!(xenora_session_audio_set_volume(session, 1.0, 1), XENORA_OK); + assert_eq!( + unsafe { xenora_session_audio_submit(session, pcm.as_ptr(), 4) }, + XENORA_OK + ); + assert_eq!( + unsafe { + xenora_session_audio_read(session, read_buf.as_mut_ptr(), 4, &mut read_count) + }, + XENORA_OK + ); + assert_eq!(read_buf, [0, 0, 0, 0]); + + xenora_session_destroy(session); + } + + #[test] + fn test_vfs_sandboxing_traversal_rejection_and_file_ops() { + let _guard = serial(); + let session = create(); + + let mut file = 0u64; + // Directory traversal rejection + let bad_path = std::ffi::CString::new("../secret.txt").unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_open(session, bad_path.as_ptr(), 0, &mut file) }, + XENORA_INVALID_ARGUMENT + ); + + let abs_path = std::ffi::CString::new("/etc/passwd").unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_open(session, abs_path.as_ptr(), 0, &mut file) }, + XENORA_INVALID_ARGUMENT + ); + + // Open real asset fixture + let good_path = std::ffi::CString::new("asset.bin").unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_open(session, good_path.as_ptr(), 0, &mut file) }, + XENORA_OK + ); + assert_ne!(file, XENORA_NO_FILE); + + // Read header (4B magic 'XAST') + let mut magic = [0u8; 4]; + let mut read_bytes = 0u64; + assert_eq!( + unsafe { + xenora_session_vfs_read(session, file, magic.as_mut_ptr(), 4, &mut read_bytes) + }, + XENORA_OK + ); + assert_eq!(read_bytes, 4); + assert_eq!(&magic, b"XAST"); + + // Seek forward + let mut new_pos = 0u64; + assert_eq!( + unsafe { xenora_session_vfs_seek(session, file, 16, XENORA_SEEK_CUR, &mut new_pos) }, + XENORA_OK + ); + assert_eq!(new_pos, 20); + + // Close file + assert_eq!(xenora_session_vfs_close(session, file), XENORA_OK); + + // Double close rejected + assert_eq!( + xenora_session_vfs_close(session, file), + XENORA_INVALID_HANDLE + ); + + // Read on closed file rejected + assert_eq!( + unsafe { + xenora_session_vfs_read(session, file, magic.as_mut_ptr(), 4, &mut read_bytes) + }, + XENORA_INVALID_HANDLE + ); + + xenora_session_destroy(session); + } } diff --git a/crates/ffi/tests/audio_vfs.rs b/crates/ffi/tests/audio_vfs.rs new file mode 100644 index 0000000..e2afe47 --- /dev/null +++ b/crates/ffi/tests/audio_vfs.rs @@ -0,0 +1,374 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Gate 6 acceptance on a native Metal device: audio PCM streaming and +//! sandboxed virtual filesystem (VFS) integration through the C interface (#284). +//! 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 lock_serial() -> std::sync::MutexGuard<'static, ()> { + SERIAL.lock().unwrap_or_else(|e| e.into_inner()) +} + +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 audio_pcm_queue_streaming_ordering_and_volume() { + let _guard = lock_serial(); + let sess = session(); + + // Rejection on invalid arguments + assert_eq!( + xenora_session_audio_init(sess, 0, 2, XENORA_AUDIO_FORMAT_PCM_S16LE), + XENORA_INVALID_ARGUMENT + ); + assert_eq!( + xenora_session_audio_init(0xdead_beef, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE), + XENORA_INVALID_HANDLE + ); + + // Initialize 48000 Hz stereo 16-bit PCM + assert_eq!( + xenora_session_audio_init(sess, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE), + XENORA_OK + ); + + // Initial status should be empty + let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64); + assert_eq!( + unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) }, + XENORA_OK + ); + assert_eq!(queued, 0); + assert_eq!(underruns, 0); + assert_eq!(total, 0); + + // Generate known PCM samples: 100 stereo samples (400 bytes) + let mut pcm = Vec::with_capacity(400); + for i in 0..100i16 { + let left = i * 100; + let right = -left; + pcm.extend_from_slice(&left.to_le_bytes()); + pcm.extend_from_slice(&right.to_le_bytes()); + } + + assert_eq!( + unsafe { xenora_session_audio_submit(sess, pcm.as_ptr(), pcm.len() as u64) }, + XENORA_OK + ); + + assert_eq!( + unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) }, + XENORA_OK + ); + assert_eq!(queued, 400); + assert_eq!(total, 400); + assert_eq!(underruns, 0); + + // Read back first 50 samples (200 bytes) + let mut read_buf = vec![0u8; 200]; + let mut bytes_read = 0u64; + assert_eq!( + unsafe { xenora_session_audio_read(sess, read_buf.as_mut_ptr(), 200, &mut bytes_read) }, + XENORA_OK + ); + assert_eq!(bytes_read, 200); + assert_eq!(&read_buf[..], &pcm[..200]); + + // Volume attenuation: set to 0.5 + assert_eq!(xenora_session_audio_set_volume(sess, 0.5, 0), XENORA_OK); + + // Submit 2 stereo samples (8 bytes): 2000, -2000, 4000, -4000 + let mut half_vol_in = Vec::new(); + half_vol_in.extend_from_slice(&2000i16.to_le_bytes()); + half_vol_in.extend_from_slice(&(-2000i16).to_le_bytes()); + half_vol_in.extend_from_slice(&4000i16.to_le_bytes()); + half_vol_in.extend_from_slice(&(-4000i16).to_le_bytes()); + + assert_eq!( + unsafe { + xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64) + }, + XENORA_OK + ); + + // Read remaining 200 bytes from first batch + let mut drain = vec![0u8; 200]; + assert_eq!( + unsafe { xenora_session_audio_read(sess, drain.as_mut_ptr(), 200, &mut bytes_read) }, + XENORA_OK + ); + assert_eq!(bytes_read, 200); + assert_eq!(&drain[..], &pcm[200..]); + + // Now read the 8 bytes attenuated samples + let mut attenuated = vec![0u8; 8]; + assert_eq!( + unsafe { xenora_session_audio_read(sess, attenuated.as_mut_ptr(), 8, &mut bytes_read) }, + XENORA_OK + ); + assert_eq!(bytes_read, 8); + let s0 = i16::from_le_bytes([attenuated[0], attenuated[1]]); + let s1 = i16::from_le_bytes([attenuated[2], attenuated[3]]); + let s2 = i16::from_le_bytes([attenuated[4], attenuated[5]]); + let s3 = i16::from_le_bytes([attenuated[6], attenuated[7]]); + assert_eq!(s0, 1000); + assert_eq!(s1, -1000); + assert_eq!(s2, 2000); + assert_eq!(s3, -2000); + + // Test mute (muted = 1) + assert_eq!(xenora_session_audio_set_volume(sess, 1.0, 1), XENORA_OK); + assert_eq!( + unsafe { + xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64) + }, + XENORA_OK + ); + let mut muted_out = vec![0u8; 8]; + assert_eq!( + unsafe { xenora_session_audio_read(sess, muted_out.as_mut_ptr(), 8, &mut bytes_read) }, + XENORA_OK + ); + assert_eq!(muted_out, vec![0u8; 8]); + + xenora_session_destroy(sess); +} + +#[test] +fn virtual_filesystem_sandboxing_and_traversal_rejection() { + let _guard = lock_serial(); + let sess = session(); + + let mut file = 0u64; + + // Reject non-existent root + let bad_root = std::ffi::CString::new("/nonexistent_dir_xenora").unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_set_root(sess, bad_root.as_ptr()) }, + XENORA_INVALID_ARGUMENT + ); + + // Set valid root + let root_path = if std::path::Path::new("fixtures/assets").exists() { + "fixtures/assets" + } else { + "../../fixtures/assets" + }; + let c_root = std::ffi::CString::new(root_path).unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_set_root(sess, c_root.as_ptr()) }, + XENORA_OK + ); + + // Traversal attacks rejected + for bad in &[ + "../escape.txt", + "../../etc/passwd", + "/etc/passwd", + "sub/../../secret", + "asset.bin\0extra", + "", + ] { + let bad_c = std::ffi::CString::new(*bad) + .unwrap_or_else(|_| std::ffi::CString::new("fallback_bad").unwrap()); + assert_eq!( + unsafe { xenora_session_vfs_open(sess, bad_c.as_ptr(), 0, &mut file) }, + XENORA_INVALID_ARGUMENT, + "traversal attempt '{}' was not rejected", + bad + ); + } + + // Open existing valid asset + let good = std::ffi::CString::new("asset.bin").unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_open(sess, good.as_ptr(), 0, &mut file) }, + XENORA_OK + ); + assert_ne!(file, XENORA_NO_FILE); + + // Read header (20 bytes: 4B magic + 4B ver + 4B width + 4B height + 4B audio_samples) + let mut header = [0u8; 20]; + let mut read_bytes = 0u64; + assert_eq!( + unsafe { xenora_session_vfs_read(sess, file, header.as_mut_ptr(), 20, &mut read_bytes) }, + XENORA_OK + ); + assert_eq!(read_bytes, 20); + assert_eq!(&header[0..4], b"XAST"); + let version = u32::from_le_bytes([header[4], header[5], header[6], header[7]]); + assert_eq!(version, 1); + let width = u32::from_le_bytes([header[8], header[9], header[10], header[11]]); + assert_eq!(width, 2); + let height = u32::from_le_bytes([header[12], header[13], header[14], header[15]]); + assert_eq!(height, 2); + let audio_samples = u32::from_le_bytes([header[16], header[17], header[18], header[19]]); + assert_eq!(audio_samples, 256); + + // Seek to audio offset (36) using SEEK_SET + let mut new_pos = 0u64; + assert_eq!( + unsafe { xenora_session_vfs_seek(sess, file, 36, XENORA_SEEK_SET, &mut new_pos) }, + XENORA_OK + ); + assert_eq!(new_pos, 36); + + // Read 4 bytes of audio + let mut sample_bytes = [0u8; 4]; + assert_eq!( + unsafe { + xenora_session_vfs_read(sess, file, sample_bytes.as_mut_ptr(), 4, &mut read_bytes) + }, + XENORA_OK + ); + assert_eq!(read_bytes, 4); + + // Seek using SEEK_END + assert_eq!( + unsafe { xenora_session_vfs_seek(sess, file, 0, XENORA_SEEK_END, &mut new_pos) }, + XENORA_OK + ); + assert_eq!(new_pos, 20 + 16 + 512); // total asset size = 548 bytes + + // Close file + assert_eq!(xenora_session_vfs_close(sess, file), XENORA_OK); + + // Double close rejected + assert_eq!(xenora_session_vfs_close(sess, file), XENORA_INVALID_HANDLE); + + xenora_session_destroy(sess); +} + +#[test] +fn audio_vfs_guest_fixture_executes_asset_load_and_pcm_stream() { + let _guard = lock_serial(); + let sess = session(); + + let mut out_rgba = [0u8; 16]; + let mut out_w = 0u32; + let mut out_h = 0u32; + let mut out_samples = 0u32; + + assert_eq!( + unsafe { + xenora_session_run_audio_vfs_fixture( + sess, + out_rgba.as_mut_ptr(), + 16, + &mut out_w, + &mut out_h, + &mut out_samples, + ) + }, + XENORA_OK + ); + + assert_eq!(out_w, 2); + assert_eq!(out_h, 2); + assert_eq!(out_samples, 256); + + // Expected texture from asset.bin: 2x2 RGBA8: + // (0,0): Orange [255, 128, 0, 255] + // (1,0): Purple [128, 0, 255, 255] + // (0,1): Teal [0, 255, 128, 255] + // (1,1): Pink [255, 0, 128, 255] + let expected_rgba: [u8; 16] = [ + 255, 128, 0, 255, 128, 0, 255, 255, 0, 255, 128, 255, 255, 0, 128, 255, + ]; + assert_eq!( + out_rgba, expected_rgba, + "Metal rendered frame did not match asset texture" + ); + + // Audio status: guest submitted 256 samples (512 bytes) + let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64); + assert_eq!( + unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) }, + XENORA_OK + ); + assert_eq!(queued, 512); + assert_eq!(total, 512); + assert_eq!(underruns, 0); + + // Read back submitted audio samples and verify + let mut pcm_buf = vec![0u8; 512]; + let mut read_bytes = 0u64; + assert_eq!( + unsafe { xenora_session_audio_read(sess, pcm_buf.as_mut_ptr(), 512, &mut read_bytes) }, + XENORA_OK + ); + assert_eq!(read_bytes, 512); + + // The first sample in asset.bin sine wave is 0 + let s0 = i16::from_le_bytes([pcm_buf[0], pcm_buf[1]]); + assert_eq!(s0, 0); + + xenora_session_destroy(sess); +} + +#[test] +fn audio_vfs_rejection_of_invalid_and_stale_handles() { + let _guard = lock_serial(); + let dead_sess = 0xdead_beefu64; + + let mut queued = 0u32; + let mut underruns = 0u32; + let mut total = 0u64; + assert_eq!( + unsafe { xenora_session_audio_status(dead_sess, &mut queued, &mut underruns, &mut total) }, + XENORA_INVALID_HANDLE + ); + + let mut file = 0u64; + let path = std::ffi::CString::new("asset.bin").unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_open(dead_sess, path.as_ptr(), 0, &mut file) }, + XENORA_INVALID_HANDLE + ); + + let sess = session(); + // Null pointer checks + assert_eq!( + unsafe { xenora_session_vfs_open(sess, std::ptr::null(), 0, &mut file) }, + XENORA_INVALID_ARGUMENT + ); + assert_eq!( + unsafe { xenora_session_vfs_open(sess, path.as_ptr(), 0, std::ptr::null_mut()) }, + XENORA_INVALID_ARGUMENT + ); + + // Buffer too small for fixture + let mut small_buf = [0u8; 8]; + let mut w = 0u32; + let mut h = 0u32; + let mut samples = 0u32; + assert_eq!( + unsafe { + xenora_session_run_audio_vfs_fixture( + sess, + small_buf.as_mut_ptr(), + 8, + &mut w, + &mut h, + &mut samples, + ) + }, + XENORA_BUFFER_TOO_SMALL + ); + + xenora_session_destroy(sess); +} diff --git a/fixtures/assets/asset.bin b/fixtures/assets/asset.bin new file mode 100644 index 0000000000000000000000000000000000000000..c38200d9bec60515647ddc7332b507873ebcda05 GIT binary patch literal 548 zcmV+<0^9vqK~q!#0000200002000000RRC1fB^r10RR60|A7Dh0D%7h0IvgE2LKD5 z4lNR`6&o3J9JL?YBI6~?D3B{KE~+s3G9EP*H{LjRI^8=FJrO?LK65|QKm9-PKdwJD zKZib}J&Zg-JHt5?I5svaH1aWzF9a=8Dt#x0Byb@<9`YKG7Z?+I)brNZ+1}g%;6LM*<^t-0?GW*+^icTx z`>X$10|f`H3P}#y5nL6_7$+QRACn@TC5R|dEA=gMFvT+NH0n0DI8!>mJNG>NJV-KlDGgKSDp5KDs@pJYhTNIX*aKHe56(GRQALEs`q0C(Ik-_pb96@Qdsb>8j;g;v?S(+zZ(+)_2q8(0a}~%qGe|$cV-P#jV4P z!k)qAz+}J|zyZJ^z<9s}!N$S7!so+8#ni@>$b-tD%;?Tp(eu-?)|AUK3qS>KlwlRKfXUtKdU~`J;FSII}AEzIFU9dF9Z1i literal 0 HcmV?d00001 diff --git a/fixtures/assets/generate.py b/fixtures/assets/generate.py new file mode 100644 index 0000000..34469fc --- /dev/null +++ b/fixtures/assets/generate.py @@ -0,0 +1,49 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Generate the clean-room binary asset fixture for Gate 6 VFS testing.""" + +import argparse +import math +from pathlib import Path +from struct import pack + + +def generate_asset(): + data = bytearray() + # 1. Header: Magic 'XAST' (4B), version 1 (4B), width 2 (4B), height 2 (4B), audio_samples 256 (4B) + data += b"XAST" + data += pack("gZu>YD~N{r1IPjc z1qOx$y`q%Fl0+aEBo7n-(`-N*2{On2f(35=7mWcjb~fy0VAuu9H;y|%n& ze11V{UVLJ4aVoe7g~>o@kbF^UVhTR_qnv|Pa g5?_# rax = file handle + # call [rip -> iat[0]: vfs_open_asset] + code += b"\xff\x15" + pack(" rax = bytes read + code += b"\x48\x89\xd9" # mov rcx, rbx (handle) + code += b"\xba\x24\x02\x00\x00" # mov edx, 548 (header 20B + tex 16B + audio 512B) + # call [rip -> iat[1]: vfs_read_asset] + code += b"\xff\x15" + pack(" iat[2]: vfs_close_asset] + code += b"\xff\x15" + pack(" iat[3]: audio_init] + code += b"\xff\x15" + pack(" iat[4]: audio_submit_pcm] + code += b"\xff\x15" + pack(" iat[5]: frame_submit_textured] + code += b"\xff\x15" + pack("