From 7fa240f7bab94f839d709b68d644966e75bf6a80 Mon Sep 17 00:00:00 2001 From: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:09:15 +0530 Subject: [PATCH] app: open a PE executable and show read-only compatibility diagnostics (#267) Add xenora_inspect_executable to the C interface: a bounded, read-only report from the static probe and loader validation (hash, headers, sections, imports not provided by the standard runtime services, DBT coverage of the bounded disassembly, relocation and TLS counts). Nothing in the file is executed. A probe panic becomes a report labelled as a Xenora defect (#270). Xenora.app opens files via Open Executable..., drag and drop, and Finder (alternate viewer for Windows executables). Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> --- CHANGELOG.md | 1 + app/Sources/Xenora/main.swift | 104 +++++++++++++++- crates/ffi/include/xenora.h | 21 ++++ crates/ffi/src/lib.rs | 222 +++++++++++++++++++++++++++++++++- scripts/build-app.sh | 10 ++ 5 files changed, 356 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e68bed8..d3a4fdb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ remains unsupported. ### Added +- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised. - Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot. - Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI. - Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D. diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 043d6ca..201720c 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -4,9 +4,11 @@ // bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered // by native Metal) and shows the verified read-back frame. No other executable can run. +import AppKit import CXenora import Foundation import SwiftUI +import UniformTypeIdentifiers struct RuntimeProbe { var abiVersion: UInt32 = 0 @@ -84,14 +86,97 @@ final class FrameModel: ObservableObject { } } +/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed. +@MainActor +final class InspectionModel: ObservableObject { + static let shared = InspectionModel() + @Published var fileName: String? + @Published var report = "" + @Published var status: Int32 = Int32(XENORA_OK) + @Published var busy = false + @Published var importing = false + + func inspect(_ url: URL) { + fileName = url.lastPathComponent + busy = true + Task { + let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value + status = newStatus + report = newReport + busy = false + } + } + + nonisolated static func run(_ url: URL) -> (Int32, String) { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + // Check the size before reading so an oversized file is never loaded into memory. + guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else { + return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.") + } + guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else { + return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).") + } + guard let data = try? Data(contentsOf: url) else { + return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.") + } + return data.withUnsafeBytes { raw in + let bytes = raw.bindMemory(to: UInt8.self).baseAddress + var required: UInt64 = 0 + var probe: CChar = 0 + var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required) + guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") } + var text = [CChar](repeating: 0, count: Int(required)) + status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required) + return (status, String(cString: text)) + } + } +} + +/// Receives files opened from Finder (double-click or Open With). +final class AppDelegate: NSObject, NSApplicationDelegate { + func application(_ application: NSApplication, open urls: [URL]) { + guard let url = urls.first else { return } + MainActor.assumeIsolated { InspectionModel.shared.inspect(url) } + } +} + +struct InspectorView: View { + @ObservedObject var model: InspectionModel + + var body: some View { + Section("Executable inspection (read-only)") { + HStack { + Button("Open Executable…") { model.importing = true } + Text("or drop a file on this window").foregroundStyle(.secondary) + } + if let name = model.fileName { + LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name) + ScrollView { + Text(model.report) + .font(.system(.caption, design: .monospaced)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + } + .frame(minHeight: 160, maxHeight: 320) + } + Text("Opened files are inspected only. Running them is not available.") + .font(.callout) + .foregroundStyle(.secondary) + } + } +} + struct ContentView: View { let probe = RuntimeProbe.run() @ObservedObject var model: FrameModel + @ObservedObject var inspection = InspectionModel.shared private var frame: GuestFrame? { model.frame } private var running: Bool { model.running } var body: some View { Form { + InspectorView(model: inspection) Section("Guest display") { if let image = frame?.image { Image(decorative: image, scale: 1) @@ -118,11 +203,20 @@ struct ContentView: View { .foregroundStyle(.secondary) } .formStyle(.grouped) - .frame(minWidth: 460, minHeight: 420) + .fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in + if case .success(let url) = result { inspection.inspect(url) } + } + .dropDestination(for: URL.self) { urls, _ in + guard let url = urls.first, url.isFileURL else { return false } + inspection.inspect(url) + return true + } + .frame(minWidth: 520, minHeight: 560) } } struct XenoraApp: App { + @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate let model = FrameModel() var body: some Scene { @@ -130,6 +224,14 @@ struct XenoraApp: App { } } +// `--inspect ` prints the read-only report for a file and exits with its status. +if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count { + let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1])) + print(report.hasSuffix("\n") ? report : report + "\n", terminator: "") + print("status=\(status)") + exit(status == Int32(XENORA_OK) ? 0 : 1) +} + // `--smoke-frame` runs the trusted fixture on the Metal device and exits; it needs a GPU. if CommandLine.arguments.contains("--smoke-frame") { let frame = GuestFrame.run() diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index 239c61c..f78f3f4 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -65,4 +65,25 @@ xenora_status xenora_session_run_trusted_fixture( uint32_t *out_width, uint32_t *out_height); +/* Largest file xenora_inspect_executable accepts, in bytes. */ +#define XENORA_MAX_INSPECT_BYTES 268435456u + +/* + * Read-only compatibility inspection of a caller-supplied PE file. Nothing in + * `bytes` is executed: it is parsed and statically disassembled (bounded) only. + * On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a + * NUL-terminated UTF-8 report of `*out_required` bytes including the NUL. + * XENORA_PE_ERROR means the file is not an acceptable PE32+ image; + * XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity` + * is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required` + * set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return + * XENORA_LIMIT_EXCEEDED. + */ +xenora_status xenora_inspect_executable( + const uint8_t *bytes, + uint64_t length, + char *out_report, + uint64_t capacity, + uint64_t *out_required); + #endif diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index e87e6da..51f979c 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -6,10 +6,11 @@ //! 32 bits hold that slot's generation, so a stale handle never reaches a reused slot. //! Every exported function catches panics and reports them as `XENORA_INTERNAL_ERROR`. +use std::fmt::Write as _; 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, Register}; +use xenora_loader::{ExitReason, ImportRegistry, ParsedPe, ProbeConfig, Register, probe_pe_bytes}; use xenora_metal::NativeCompute; use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; @@ -266,6 +267,133 @@ pub unsafe extern "C" fn xenora_session_run_trusted_fixture( }) } +pub const XENORA_MAX_INSPECT_BYTES: u64 = 256 * 1024 * 1024; + +/// Build the read-only inspection report and its status: `XENORA_OK`, `XENORA_PE_ERROR` +/// for a rejected file, or `XENORA_INTERNAL_ERROR` if Xenora's own probe failed. +fn inspection_report(bytes: &[u8]) -> (i32, String) { + let mut out = String::from("Xenora read-only inspection: nothing in this file was executed.\n"); + let _ = writeln!(out, "file_size: {} bytes", bytes.len()); + let probed = catch_unwind(AssertUnwindSafe(|| { + probe_pe_bytes(bytes, &ProbeConfig::default()) + })); + let report = match probed { + Ok(Ok(report)) => report, + Ok(Err(e)) => { + let _ = writeln!(out, "verdict: not a supported PE32+ (x86-64) image: {e}"); + return (XENORA_PE_ERROR, out); + } + Err(_) => { + out.push_str( + "verdict: inspection failed inside Xenora's static probe. This is a Xenora \ + defect, not a finding about the file.\n", + ); + return (XENORA_INTERNAL_ERROR, out); + } + }; + let pe = &report.parsed; + let _ = writeln!(out, "sha256: {}", report.sha256); + let _ = writeln!( + out, + "machine: {:#06x} image_base: {:#x} entry_rva: {:#x} size_of_image: {:#x}", + pe.machine, pe.image_base, pe.entry_point_rva, pe.size_of_image + ); + match ParsedPe::parse(bytes) { + Ok(_) => out.push_str("loader_validation: accepted\n"), + Err(e) => { + let _ = writeln!(out, "loader_validation: rejected: {e}"); + } + } + let _ = writeln!(out, "\nsections ({}):", pe.sections.len()); + for s in &pe.sections { + let p = s.permissions; + let _ = writeln!( + out, + " {:<8} rva {:#010x} vsize {:#x} raw {:#x} {}{}{}", + s.name, + s.virtual_address, + s.virtual_size, + s.raw_data_size, + if p.read { 'r' } else { '-' }, + if p.write { 'w' } else { '-' }, + if p.execute { 'x' } else { '-' }, + ); + } + let missing: Vec<_> = report.imports.iter().filter(|i| !i.is_supported).collect(); + let _ = writeln!( + out, + "\nimports: {} total, {} provided by Xenora's standard runtime services, {} not provided", + report.imports.len(), + report.imports.len() - missing.len(), + missing.len() + ); + for i in &missing { + let _ = writeln!(out, " not provided: {}!{}", i.dll, i.symbol); + } + let decoded = report.instruction_records.len(); + let unsupported = report + .instruction_records + .iter() + .filter(|r| !r.is_supported_dbt) + .count(); + let _ = writeln!( + out, + "\nstatic disassembly (bounded): {decoded} instructions decoded, {unsupported} not supported by the ARM64 DBT" + ); + if let Some(first) = &report.first_unsupported_dbt_insn { + let hex: String = first.bytes.iter().map(|b| format!("{b:02x}")).collect(); + let _ = writeln!( + out, + " first unsupported: rva {:#x} {} [{hex}]", + first.rva, first.mnemonic + ); + } + let _ = writeln!( + out, + "\nrelocations: {} entries\ntls callbacks: {}", + report.relocations.total_entries, + report.tls.callback_targets.len() + ); + out.push_str("\nExecution of opened files is not available (see #257).\n"); + (XENORA_OK, out) +} + +/// # Safety +/// `bytes` must be valid for `length` reads; `out_report` must be null or valid +/// for `capacity` writes; `out_required` must be null or valid for one `u64` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_inspect_executable( + bytes: *const u8, + length: u64, + out_report: *mut std::ffi::c_char, + capacity: u64, + out_required: *mut u64, +) -> i32 { + guarded(|| { + if bytes.is_null() || out_report.is_null() || out_required.is_null() { + return XENORA_INVALID_ARGUMENT; + } + if length > XENORA_MAX_INSPECT_BYTES { + return XENORA_LIMIT_EXCEEDED; + } + // SAFETY: non-null, and the caller guarantees `length` readable bytes. + let input = unsafe { std::slice::from_raw_parts(bytes, length as usize) }; + let (status, text) = inspection_report(input); + let required = text.len() as u64 + 1; + // SAFETY: non-null, checked above. + unsafe { out_required.write(required) }; + if capacity < required { + return XENORA_BUFFER_TOO_SMALL; + } + // SAFETY: `capacity >= required`, checked above. + unsafe { + std::ptr::copy_nonoverlapping(text.as_ptr(), out_report.cast::(), text.len()); + out_report.add(text.len()).write(0); + } + status + }) +} + #[cfg(test)] mod tests { use super::*; @@ -435,4 +563,96 @@ mod tests { assert_eq!((w, h), (0, 0), "outputs untouched on failure"); assert!(buf.iter().all(|&b| b == 0)); } + + fn inspect_bytes(bytes: &[u8]) -> (i32, String) { + let mut required = 0; + let mut buf = vec![0 as std::ffi::c_char; 1]; + let status = unsafe { + xenora_inspect_executable( + bytes.as_ptr(), + bytes.len() as u64, + buf.as_mut_ptr(), + 1, + &mut required, + ) + }; + assert_eq!(status, XENORA_BUFFER_TOO_SMALL); + assert_eq!(buf[0], 0, "nothing written when the buffer is too small"); + buf.resize(required as usize, 0); + let status = unsafe { + xenora_inspect_executable( + bytes.as_ptr(), + bytes.len() as u64, + buf.as_mut_ptr(), + required, + &mut required, + ) + }; + let text = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) } + .to_str() + .unwrap() + .to_owned(); + assert_eq!(text.len() as u64 + 1, required); + (status, text) + } + + #[test] + fn inspection_reports_independently_read_facts_of_a_fixture() { + let (status, text) = inspect_bytes(FIXTURE); + assert_eq!(status, XENORA_OK); + let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize; + let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap()); + let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap()); + assert!(text.contains(&format!("file_size: {} bytes", FIXTURE.len()))); + assert!(text.contains(&format!("entry_rva: {entry:#x}"))); + assert!(text.contains(&format!("sections ({sections}):"))); + assert!(text.contains("loader_validation: accepted")); + assert!( + text.contains("xenora.dll") || text.contains("1 provided by Xenora"), + "{text}" + ); + assert!(text.contains("nothing in this file was executed")); + } + + #[test] + fn inspection_rejects_malformed_and_oversized_input() { + for bad in [&b""[..], b"not a pe file", &[0u8; 0x100]] { + let (status, text) = inspect_bytes(bad); + assert_eq!(status, XENORA_PE_ERROR, "{text}"); + assert!(text.contains("not a supported PE32+"), "{text}"); + } + // Every truncation of a valid file yields a report and a deterministic status. + // Some truncations currently hit a panic inside the loader's static probe + // (probe.rs, #270); the boundary must turn it into a report. + for len in (0..FIXTURE.len()).step_by(7) { + let (status, text) = inspect_bytes(&FIXTURE[..len]); + assert!( + matches!(status, XENORA_OK | XENORA_PE_ERROR | XENORA_INTERNAL_ERROR), + "len {len}" + ); + assert_eq!( + inspect_bytes(&FIXTURE[..len]), + (status, text), + "len {len} is deterministic" + ); + } + let (mut req, mut c) = (0u64, 0 as std::ffi::c_char); + let one = [0u8]; + assert_eq!( + unsafe { + xenora_inspect_executable( + one.as_ptr(), + XENORA_MAX_INSPECT_BYTES + 1, + &mut c, + 1, + &mut req, + ) + }, + XENORA_LIMIT_EXCEEDED + ); + assert_eq!( + unsafe { xenora_inspect_executable(std::ptr::null(), 0, &mut c, 1, &mut req) }, + XENORA_INVALID_ARGUMENT + ); + } } diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 2aac89b..3b778f0 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -35,6 +35,16 @@ cat > "$bundle/Contents/Info.plist" <CFBundleShortVersionString0.1.0 LSMinimumSystemVersion14.0 NSHighResolutionCapable + CFBundleDocumentTypes + + + CFBundleTypeNameWindows Executable + CFBundleTypeRoleViewer + LSHandlerRankAlternate + LSItemContentTypes + com.microsoft.windows-executable + + PLIST