Compare commits

...
Author SHA1 Message Date
Ranveer Soni 0bfb12fd17 Merge branch 'main' into task/261-native-app-gate1 2026-11-24 15:45:49 +05:30
Swastick Chowdhury c6d0986da2 app: add native macOS shell and versioned C runtime interface (#261)
Add crates/ffi, a static library exposing a version 1 C interface with
opaque generation-checked session handles, stable status codes and
panic containment. It can create and destroy sessions and parse the
bundled trusted PE fixture; no guest code runs. Add a minimal SwiftUI
app (Swift Package Manager) that links it, and scripts/build-app.sh to
build an ad-hoc signed, arm64-only Xenora.app and run its smoke check.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:43:08 +05:30
Ranveer Soni 9a9422c7da Merge pull request #260 from elforeign/task/215-stage-c
isa: eight SOP2 logical and shift forms through the semantic registry (#215 stage C)
2026-11-24 15:41:50 +05:30
9 changed files with 465 additions and 0 deletions

No files matched your search

+3
View File
@@ -37,3 +37,6 @@ __pycache__/
*.pyc
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
# Native application build output
/app/.build/
Generated
+7
View File
@@ -179,6 +179,13 @@ dependencies = [
"xenora-ref",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
]
[[package]]
name = "xenora-import-gen"
version = "0.1.0"
+13
View File
@@ -0,0 +1,13 @@
// swift-tools-version: 6.0
// SPDX-License-Identifier: GPL-3.0-or-later
// Build with scripts/build-app.sh, which builds the Rust static library first.
import PackageDescription
let package = Package(
name: "Xenora",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
]
)
+5
View File
@@ -0,0 +1,5 @@
module CXenora [system] {
header "../../../crates/ffi/include/xenora.h"
link "xenora_ffi"
export *
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Gate 1 shell: proves the app links the Rust runtime through the versioned C
// interface. It inspects the bundled trusted fixture and executes no guest code.
import CXenora
import Foundation
import SwiftUI
struct RuntimeProbe {
var abiVersion: UInt32 = 0
var status: Int32 = -1
var sections: UInt32 = 0
var entryRVA: UInt32 = 0
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
static func run() -> RuntimeProbe {
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
var session: xenora_session = 0
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard probe.status == XENORA_OK else { return probe }
defer { _ = xenora_session_destroy(session) }
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
return probe
}
var summary: String {
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
}
}
struct ContentView: View {
let probe = RuntimeProbe.run()
var body: some View {
Form {
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
LabeledContent("Interface version", value: "\(probe.abiVersion)")
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
Text("Guest execution and live display are not available in this build.")
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.frame(minWidth: 420, minHeight: 240)
}
}
struct XenoraApp: App {
var body: some Scene {
WindowGroup("Xenora") { ContentView() }
}
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
print(probe.summary)
exit(probe.connected ? 0 : 1)
}
XenoraApp.main()
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "xenora-ffi"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
description = "Versioned C interface between the native macOS application and the Xenora runtime"
[lib]
crate-type = ["staticlib", "rlib"]
[lints]
workspace = true
[dependencies]
xenora-loader = { path = "../loader" }
+47
View File
@@ -0,0 +1,47 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Xenora native application interface, version 1.
*
* Every function returns a xenora_status. Sessions are identified by opaque
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
* handle stays invalid even if its slot is reused. Output pointers are owned
* by the caller and are written only when the call returns XENORA_OK.
* All functions are thread-safe. No Rust panic crosses this boundary: one is
* reported as XENORA_INTERNAL_ERROR.
*/
#ifndef XENORA_H
#define XENORA_H
#include <stdint.h>
#define XENORA_ABI_VERSION 1u
typedef int32_t xenora_status;
enum {
XENORA_OK = 0,
XENORA_INVALID_ARGUMENT = 1,
XENORA_INVALID_HANDLE = 2,
XENORA_VERSION_MISMATCH = 3,
XENORA_INTERNAL_ERROR = 4,
XENORA_PE_ERROR = 5,
XENORA_LIMIT_EXCEEDED = 6,
};
typedef uint64_t xenora_session;
/* The interface version this library implements. */
uint32_t xenora_abi_version(void);
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
xenora_status xenora_session_destroy(xenora_session session);
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
xenora_status xenora_session_inspect_trusted_fixture(
xenora_session session,
uint32_t *out_section_count,
uint32_t *out_entry_rva);
#endif
+264
View File
@@ -0,0 +1,264 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Versioned C interface for the native macOS application (see `include/xenora.h`).
//!
//! Sessions are opaque 64-bit handles: the low 32 bits index a slot and the high
//! 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::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Mutex;
use xenora_loader::ParsedPe;
pub const XENORA_ABI_VERSION: u32 = 1;
pub const XENORA_OK: i32 = 0;
pub const XENORA_INVALID_ARGUMENT: i32 = 1;
pub const XENORA_INVALID_HANDLE: i32 = 2;
pub const XENORA_VERSION_MISMATCH: i32 = 3;
pub const XENORA_INTERNAL_ERROR: i32 = 4;
pub const XENORA_PE_ERROR: i32 = 5;
pub const XENORA_LIMIT_EXCEEDED: i32 = 6;
/// Upper bound on simultaneously live sessions.
const MAX_SESSIONS: usize = 64;
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
struct Slot {
/// Odd while live, even while free; starts at 0 so the first handle is never 0.
generation: u32,
}
static SESSIONS: Mutex<Vec<Slot>> = Mutex::new(Vec::new());
fn guarded(f: impl FnOnce() -> i32) -> i32 {
catch_unwind(AssertUnwindSafe(f)).unwrap_or(XENORA_INTERNAL_ERROR)
}
fn split(handle: u64) -> (usize, u32) {
((handle & 0xFFFF_FFFF) as usize, (handle >> 32) as u32)
}
fn is_live(slots: &[Slot], handle: u64) -> bool {
let (index, generation) = split(handle);
slots
.get(index)
.is_some_and(|slot| slot.generation == generation && generation % 2 == 1)
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_abi_version() -> u32 {
XENORA_ABI_VERSION
}
/// # Safety
/// `out_session` must be null or valid for one aligned `u64` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *mut u64) -> i32 {
guarded(|| {
if out_session.is_null() {
return XENORA_INVALID_ARGUMENT;
}
if abi_version != XENORA_ABI_VERSION {
return XENORA_VERSION_MISMATCH;
}
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
let index = match slots.iter().position(|slot| slot.generation % 2 == 0) {
Some(index) => index,
None if slots.len() < MAX_SESSIONS => {
slots.push(Slot { generation: 0 });
slots.len() - 1
}
None => return XENORA_LIMIT_EXCEEDED,
};
let slot = &mut slots[index];
// 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;
};
slot.generation = generation;
// SAFETY: checked non-null above; the caller guarantees validity.
unsafe { out_session.write((u64::from(generation) << 32) | index as u64) };
XENORA_OK
})
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_destroy(session: u64) -> i32 {
guarded(|| {
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
if !is_live(&slots, session) {
return XENORA_INVALID_HANDLE;
}
slots[split(session).0].generation += 1;
XENORA_OK
})
}
/// # Safety
/// Each output pointer must be null or valid for one aligned `u32` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_inspect_trusted_fixture(
session: u64,
out_section_count: *mut u32,
out_entry_rva: *mut u32,
) -> i32 {
guarded(|| {
if out_section_count.is_null() || out_entry_rva.is_null() {
return XENORA_INVALID_ARGUMENT;
}
match SESSIONS.lock() {
Ok(slots) if is_live(&slots, session) => {}
Ok(_) => return XENORA_INVALID_HANDLE,
Err(_) => return XENORA_INTERNAL_ERROR,
}
let Ok(pe) = ParsedPe::parse(FIXTURE) else {
return XENORA_PE_ERROR;
};
// SAFETY: both checked non-null above; the caller guarantees validity.
unsafe {
out_section_count.write(u32::from(pe.number_of_sections));
out_entry_rva.write(pe.entry_point_rva);
}
XENORA_OK
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ptr::null_mut;
/// The session table is process-global, so tests that fill or count it run one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn create() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
fn inspect(handle: u64) -> (i32, u32, u32) {
let (mut sections, mut entry) = (u32::MAX, u32::MAX);
let status =
unsafe { xenora_session_inspect_trusted_fixture(handle, &mut sections, &mut entry) };
(status, sections, entry)
}
#[test]
fn header_and_rust_constants_agree() {
let header = include_str!("../include/xenora.h");
assert!(header.contains(&format!("#define XENORA_ABI_VERSION {XENORA_ABI_VERSION}u")));
for (name, value) in [
("XENORA_OK", XENORA_OK),
("XENORA_INVALID_ARGUMENT", XENORA_INVALID_ARGUMENT),
("XENORA_INVALID_HANDLE", XENORA_INVALID_HANDLE),
("XENORA_VERSION_MISMATCH", XENORA_VERSION_MISMATCH),
("XENORA_INTERNAL_ERROR", XENORA_INTERNAL_ERROR),
("XENORA_PE_ERROR", XENORA_PE_ERROR),
("XENORA_LIMIT_EXCEEDED", XENORA_LIMIT_EXCEEDED),
] {
assert!(header.contains(&format!("{name} = {value},")), "{name}");
}
}
#[test]
fn session_inspects_the_trusted_fixture() {
let _serial = serial();
let handle = create();
// Independent expectation: read straight from the fixture's COFF and optional headers.
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_eq!(inspect(handle), (XENORA_OK, u32::from(sections), entry));
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
#[test]
fn version_mismatch_and_null_outputs_are_rejected() {
let _serial = serial();
let mut handle = 7;
assert_eq!(
unsafe { xenora_session_create(2, &mut handle) },
XENORA_VERSION_MISMATCH
);
assert_eq!(handle, 7, "output untouched on failure");
assert_eq!(
unsafe { xenora_session_create(1, null_mut()) },
XENORA_INVALID_ARGUMENT
);
let live = create();
let mut x = 0;
assert_eq!(
unsafe { xenora_session_inspect_trusted_fixture(live, null_mut(), &mut x) },
XENORA_INVALID_ARGUMENT
);
xenora_session_destroy(live);
}
#[test]
fn invalid_stale_and_double_destroyed_handles_are_rejected() {
let _serial = serial();
for bogus in [0, u64::MAX, 0xFFFF_FFFF, 1 << 32] {
assert_eq!(
xenora_session_destroy(bogus),
XENORA_INVALID_HANDLE,
"{bogus:#x}"
);
assert_eq!(inspect(bogus), (XENORA_INVALID_HANDLE, u32::MAX, u32::MAX));
}
let handle = create();
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_INVALID_HANDLE);
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
// Reusing the slot must not revive the old handle.
let reused: Vec<u64> = (0..MAX_SESSIONS).map(|_| create()).collect();
assert!(!reused.contains(&handle));
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
for h in reused {
xenora_session_destroy(h);
}
}
#[test]
fn repeated_and_concurrent_lifecycles_do_not_leak_slots() {
let _serial = serial();
let threads: Vec<_> = (0..8)
.map(|_| {
std::thread::spawn(|| {
for _ in 0..500 {
let mut handle = 0;
let status = unsafe { xenora_session_create(1, &mut handle) };
assert_eq!(status, XENORA_OK);
assert_eq!(inspect(handle).0, XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
})
})
.collect();
for t in threads {
t.join().unwrap();
}
assert!(SESSIONS.lock().unwrap().len() <= MAX_SESSIONS);
}
#[test]
fn panics_do_not_cross_the_boundary() {
assert_eq!(guarded(|| panic!("injected")), XENORA_INTERNAL_ERROR);
}
}
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check.
# Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain.
set -eu
cd "$(dirname "$0")/.."
root=$(pwd)
fail() { echo "build-app: $*" >&2; exit 1; }
[ "$(uname -s)" = Darwin ] || fail "macOS is required"
[ "$(uname -m)" = arm64 ] || fail "a native arm64 host is required"
[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 0 ] || fail "running under Rosetta is not supported"
command -v cargo >/dev/null || fail "cargo not found; install Rust 1.100"
command -v swift >/dev/null || fail "swift not found; install the Xcode command line tools"
target=aarch64-apple-darwin
# Match the app's LSMinimumSystemVersion so the static library links cleanly.
MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --target "$target"
swift build --package-path app -c release --arch arm64 \
-Xlinker -L -Xlinker "$root/target/$target/release"
bundle="$root/build/Xenora.app"
rm -rf "$bundle"
mkdir -p "$bundle/Contents/MacOS"
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora"
cat > "$bundle/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key><string>Xenora</string>
<key>CFBundleIdentifier</key><string>local.xenora.Xenora</string>
<key>CFBundleName</key><string>Xenora</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
# Ad-hoc signature for local development only. No entitlements are requested:
# this build executes no guest code, so it needs no JIT entitlement.
codesign --force --sign - "$bundle"
binary="$bundle/Contents/MacOS/Xenora"
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
"$binary" --smoke
echo "build-app: built $bundle"