Compare commits

..
Author SHA1 Message Date
Swastick Chowdhury 5a6a3b3e4f test(ffi): read a settled memory footprint in the frame-loop test (#290)
After a session is destroyed, Metal returns its memory asynchronously;
an immediate reading can sit up to about 45 MiB above the floor it
returns to within a second. Read the footprint until two consecutive
readings agree within 1 MiB (at most 5 s) for both the baseline and the
final sample. The 16 MiB threshold and Metal validation are unchanged,
and an injected per-session leak still fails the test.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:35 +05:30
Ranveer Soni 4db0b9c530 Merge pull request #286 from Swastickc/task/270-probe-truncated-names
loader: stop the static probe panicking on truncated PE names (#270)
2026-11-24 18:01:12 +05:30
Ranveer Soni 2b97a66db9 Merge pull request #287 from Swastickc/task/284-native-app-gate6
app: audio PCM streaming and virtual filesystem integration (#284)
2026-11-24 18:00:58 +05:30
Swastick Chowdhury b0984673d8 app: audio PCM streaming and virtual filesystem integration (#284)
Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:57:54 +05:30
Ranveer Soni c6a354bca5 Merge pull request #285 from ranveersoni98/feat/rdna2-planner-opt
feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion
2026-11-24 17:57:31 +05:30
Swastick Chowdhury c4d0b6c000 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>
2026-11-24 17:57:26 +05:30
Ranveer Soni 9d83e09aa6 feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion.
Add family/status filters, compact output, Codex manifests, path-only vs family claim scoping, and coverage reconcile without inflating counts.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:56:13 +05:30
Ranveer Soni 3bdc43d3ad Merge pull request #281 from Swastickc/task/66-movsx-movzx
loader: implement MOVZX and MOVSX in the interpreter (#66)
2026-11-24 17:47:21 +05:30
Ranveer Soni fa434d7174 Merge pull request #282 from Swastickc/task/279-native-app-gate5
app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
2026-11-24 17:46:43 +05:30
Ranveer Soni ed657ad802 Merge pull request #280 from Swastickc/task/72-segment-override
loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
2026-11-24 17:46:25 +05:30
Swastick Chowdhury f6dfe58695 loader: implement MOVZX and MOVSX in the interpreter (#66)
The native DBT translator implements the four extension opcodes MOVZX r32/r64,
r/m8 (0F B6), MOVZX r32/r64, r/m16 (0F B7), MOVSX r32/r64, r/m8 (0F BE) and
MOVSX r32/r64, r/m16 (0F BF), with both register and memory source operands.
The interpreter implemented none of them: its 0x0F handler covered only SYSCALL
(0F 05) and BSWAP (0F C8..CF), so any of the four opcodes exited with
IllegalInstruction and the two execution paths accepted different instruction
sets for the same bytes.

Implement them in the interpreter:

- The source width follows the opcode, so 0F B6 and 0F BE read one byte and
  0F B7 and 0F BF read one word.
- The destination width follows REX.W. Without REX.W the destination is 32
  bits and its upper half is cleared; with REX.W it is 64 bits.
- MOVZX zero-extends, so both destination widths hold the same value.
- MOVSX sign-extends to the destination width, so a 32-bit destination keeps
  the sign in bits 31:0 with the upper half cleared, while a 64-bit
  destination keeps the sign extension across all 64 bits.

The effective-address computation shared by the memory forms of MOV,
MOVZX and MOVSX is extracted into an `effective_address` method so both
instruction families use one implementation. That is a pure refactor: the
address computation itself is unchanged.

Add six regression tests in crates/loader/tests/bootstrap.rs covering the
register and the memory source forms independently, both destination widths,
and the sign-extension boundary values. Every encoding was produced by LLVM
23.1.6 llvm-mc -show-encoding and the expected values follow the Intel SDM
rules for MOVZX and MOVSX.

All six tests fail against the unmodified interpreter and pass with this
change.

A related defect in the native DBT translator was found while writing these
tests: its MOVSX paths sign-extend to 64 bits unconditionally, so a 32-bit
destination keeps the sign extension in bits 63:32 instead of having them
cleared. That belongs to #65, which permits the translator files, and is
reported there rather than fixed here.

Closes #66

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:37:02 +05:30
Swastick Chowdhury 259b3054e1 app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:34:01 +05:30
23 changed files with 3974 additions and 100 deletions

No files matched your search

+7
View File
@@ -9,6 +9,9 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Changed
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
@@ -16,6 +19,10 @@ 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`.
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
+155 -2
View File
@@ -69,12 +69,105 @@ struct GuestFrame {
}
}
/// The frame produced by running the textured fixture (Gate 5, #279).
struct TexturedFrame {
let status: Int32
let width: Int
let height: Int
let rgba: [UInt8]
static func run() -> TexturedFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else { return TexturedFrame(status: status, width: 0, height: 0, rgba: []) }
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: 16)
var width: UInt32 = 0
var height: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_textured_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
}
return TexturedFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let pixels = rgba.map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) pixels=[\(pixels)]"
}
}
/// 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
final class FrameModel: ObservableObject {
@Published var frame: GuestFrame?
@Published var running = false
@Published var texturedFrame: TexturedFrame?
@Published var runningTextured = false
@Published var audioVfsFrame: AudioVfsFrame?
@Published var runningAudioVfs = false
func run() {
running = true
@@ -84,6 +177,22 @@ final class FrameModel: ObservableObject {
running = false
}
}
func runTextured() {
runningTextured = true
Task {
texturedFrame = await Task.detached { TexturedFrame.run() }.value
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).
@@ -359,8 +468,36 @@ struct ContentView: View {
Text("Run failed (status \(frame.status)). No frame is shown.")
.foregroundStyle(.red)
}
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
.disabled(running || !probe.connected)
if let tImage = model.texturedFrame?.image {
Image(decorative: tImage, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160)
.accessibilityLabel("Textured guest frame, 2 by 2 pixels")
Text("Textured fixture ran: persistent texture created, dynamically updated, rendered on Metal, and retired.")
.font(.callout)
.foregroundStyle(.secondary)
}
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") {
if let image = loop.image {
@@ -441,6 +578,22 @@ if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < Comm
exit(status == Int32(XENORA_OK) ? 0 : 1)
}
// `--smoke-resources` tests persistent texture lifecycle, dynamic subregion updates, and retirement on Metal.
if CommandLine.arguments.contains("--smoke-resources") {
let frame = TexturedFrame.run()
print("smoke-resources: \(frame.summary)")
let expected: [UInt8] = [255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 64, 64, 64, 255]
exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.rgba == expected ? 0 : 1)
}
// `--smoke-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
+204
View File
@@ -146,6 +146,210 @@ xenora_status xenora_session_frame_loop_status(
/* Largest file xenora_inspect_executable accepts, in bytes. */
#define XENORA_MAX_INSPECT_BYTES 268435456u
/* Opaque persistent GPU resource handle (Gate 5, #279) */
typedef uint64_t xenora_resource;
#define XENORA_NO_RESOURCE 0u
enum {
XENORA_RESOURCE_TYPE_TEXTURE_2D = 1,
XENORA_RESOURCE_TYPE_BUFFER = 2,
};
/*
* Create a persistent RGBA8 2D texture owned by the session.
* If `initial_rgba` is non-null, it must point to at least width * height * 4 bytes.
*/
xenora_status xenora_session_create_texture(
xenora_session session,
uint32_t width,
uint32_t height,
const uint8_t *initial_rgba,
xenora_resource *out_resource
);
/*
* Dynamically update a subregion of a persistent texture.
*/
xenora_status xenora_session_update_texture(
xenora_session session,
xenora_resource resource,
uint32_t x,
uint32_t y,
uint32_t width,
uint32_t height,
const uint8_t *rgba,
uint64_t byte_count
);
/*
* Destroy or retire a persistent resource. If in-flight GPU execution is using
* the resource, destruction is deferred until the execution completes.
*/
xenora_status xenora_session_destroy_resource(
xenora_session session,
xenora_resource resource
);
/*
* Query type, dimensions, and in-flight status of a persistent resource.
*/
xenora_status xenora_session_resource_info(
xenora_session session,
xenora_resource resource,
uint32_t *out_type,
uint32_t *out_width,
uint32_t *out_height,
uint32_t *out_in_flight
);
/*
* Render a frame using a persistent texture resource.
*/
xenora_status xenora_session_render_textured(
xenora_session session,
xenora_resource resource,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height
);
/*
* Run the original textured PE fixture and verify its read-back frame.
*/
xenora_status xenora_session_run_textured_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height
);
/* 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.
+1626 -1
View File
File diff suppressed because it is too large. Load diff
+374
View File
@@ -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);
}
+21 -2
View File
@@ -82,6 +82,25 @@ fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Statu
}
}
/// Footprint once it has stopped changing. After a session is destroyed, Metal gives
/// back its memory asynchronously: measured on an Apple M5, a reading taken right after
/// destroy was up to about 45 MiB above the floor it returned to within one second,
/// every time. A single immediate reading therefore mixes in memory that is already on
/// its way out. Read every 50 ms until two consecutive readings agree within 1 MiB
/// (at most 5 s). A genuine leak still settles high, so it is still caught.
fn settled_footprint() -> u64 {
let deadline = Instant::now() + Duration::from_secs(5);
let mut previous = footprint();
loop {
std::thread::sleep(Duration::from_millis(50));
let current = footprint();
if current.abs_diff(previous) < 1 << 20 || Instant::now() >= deadline {
return current;
}
previous = current;
}
}
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
fn footprint() -> u64 {
unsafe extern "C" {
@@ -245,11 +264,11 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() {
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
run();
run();
let baseline = footprint();
let baseline = settled_footprint();
for _ in 0..5 {
run();
}
let after = footprint();
let after = settled_footprint();
let growth = after.saturating_sub(baseline);
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
assert!(
+375
View File
@@ -0,0 +1,375 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 5 acceptance on a native Metal device: persistent GPU resources,
//! dynamic texture updates, and completion-aware resource retirement through
//! the C interface (#279).
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn session() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
#[test]
fn persistent_texture_lifecycle_survives_across_multiple_frames() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
assert_ne!(res, XENORA_NO_RESOURCE);
// Render 5 consecutive frames from this single persistent texture resource without re-allocation.
for frame_idx in 0..5 {
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_render_textured(
sess,
res,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK,
"render frame {} failed",
frame_idx
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
assert_eq!(
out_rgba, initial_rgba,
"frame {} pixel mismatch with persistent texture",
frame_idx
);
}
// Verify resource is still live and un-retired after all frames
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D);
assert_eq!(r_w, 2);
assert_eq!(r_h, 2);
assert_eq!(r_flight, 0);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn dynamic_texture_subregion_update_is_reflected_on_metal() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
// 1. Update 1x1 subregion at (x=1, y=0) from green to yellow [255, 255, 0, 255]
let yellow_pixel = [255u8, 255, 0, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 1, 0, 1, 1, yellow_pixel.as_ptr(), 4) },
XENORA_OK
);
let mut frame1 = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame1.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame1: [u8; 16] = [
255, 0, 0, 255, // (0,0) red (untouched)
255, 255, 0, 255, // (1,0) yellow (updated)
0, 0, 255, 255, // (0,1) blue (untouched)
255, 255, 255, 255, // (1,1) white (untouched)
];
assert_eq!(
frame1, expected_frame1,
"Metal read-back did not reflect 1x1 subregion update"
);
// 2. Update 2x1 subregion across the bottom row: (0,1) and (1,1)
// (0,1)=magenta [255, 0, 255, 255], (1,1)=cyan [0, 255, 255, 255]
let bottom_row = [255u8, 0, 255, 255, 0, 255, 255, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 1, 2, 1, bottom_row.as_ptr(), 8) },
XENORA_OK
);
let mut frame2 = [0u8; 16];
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame2.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame2: [u8; 16] = [
255, 0, 0, 255, // (0,0) red
255, 255, 0, 255, // (1,0) yellow
255, 0, 255, 255, // (0,1) magenta
0, 255, 255, 255, // (1,1) cyan
];
assert_eq!(
frame2, expected_frame2,
"Metal read-back did not reflect 2x1 bottom row update"
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn deferred_resource_retirement_safely_waits_for_completion() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
// Acquire an in-flight reference simulating active GPU encoding/submission
assert_eq!(test_acquire_resource_in_flight(sess, res), Ok(()));
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_flight, 1);
// Calling destroy while in-flight marks the resource retired without dangling pointers
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Subsequent caller operations on the retired handle are rejected
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
let dummy_pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, dummy_pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
// Now in-flight execution completes and releases its reference
assert_eq!(test_release_resource_in_flight(sess, res), Ok(()));
// The slot is now safely reclaimed; the next allocation reuses the slot with a new generation
let mut res2 = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res2) },
XENORA_OK
);
assert_eq!((res & 0xFFFF_FFFF), (res2 & 0xFFFF_FFFF)); // same slot index
assert_ne!(res >> 32, res2 >> 32); // higher generation
assert_eq!(xenora_session_destroy_resource(sess, res2), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn invalid_stale_and_double_destroyed_resource_handles_are_rejected() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// Zero handle
assert_eq!(
xenora_session_destroy_resource(sess, XENORA_NO_RESOURCE),
XENORA_INVALID_HANDLE
);
// Unallocated slot index
let unallocated_handle = (1u64 << 32) | 999u64;
assert_eq!(
xenora_session_destroy_resource(sess, unallocated_handle),
XENORA_INVALID_HANDLE
);
// Create and destroy a valid resource
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Double destroy
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
// Stale handle queries
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
let pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn repeated_resource_allocations_and_retirements_do_not_leak_slots() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let initial = [
255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let update = [255u8, 255, 0, 255];
// Run 200 cycles of create -> update -> render -> destroy
for i in 0..200 {
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial.as_ptr(), &mut res) },
XENORA_OK,
"create failed at cycle {}",
i
);
// Verify slot index is reused (res_idx is 0)
let slot_idx = (res & 0xFFFF_FFFF) as usize;
assert_eq!(slot_idx, 0, "slot index leaked at cycle {}", i);
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, update.as_ptr(), 4) },
XENORA_OK
);
let mut out = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
}
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn textured_pe_fixture_executes_dynamic_updates_and_retirement() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_run_textured_fixture(
sess,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
let expected_final: [u8; 16] = [
255, 255, 0, 255, // (0,0) yellow
0, 255, 255, 255, // (1,0) cyan
255, 0, 255, 255, // (0,1) magenta
64, 64, 64, 255, // (1,1) dark grey
];
assert_eq!(
out_rgba, expected_final,
"guest textured fixture read-back frame mismatch"
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
+116 -30
View File
@@ -466,6 +466,12 @@ impl<'a> Interpreter<'a> {
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
// MOVZX r32/r64, r/m8 (0xB6), MOVZX r32/r64, r/m16 (0xB7),
// MOVSX r32/r64, r/m8 (0xBE), MOVSX r32/r64, r/m16 (0xBF).
op @ (0xB6 | 0xB7 | 0xBE | 0xBF) => {
let modrm = self.fetch_u8()?;
self.execute_mov_ext(modrm, &prefixes, op)
}
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
@@ -722,6 +728,72 @@ impl<'a> Interpreter<'a> {
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
/// Execute a MOVZX or MOVSX extension instruction.
///
/// `op` is the second opcode byte: `0xB6` extends a byte, `0xB7` extends
/// a word, `0xBE` sign-extends a byte and `0xBF` sign-extends a word.
///
/// The source width follows the opcode and the destination width follows
/// REX.W: without REX.W the destination is 32 bits and its upper half is
/// cleared, and with REX.W it is 64 bits. MOVSX sign-extends to the
/// destination width, so a 32-bit destination keeps the sign in bits
/// 31:0 and a zeroed upper half, while a 64-bit destination keeps the
/// sign extension across all 64 bits.
fn execute_mov_ext(
&mut self,
modrm: u8,
prefixes: &Prefixes,
op: u8,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let is_word = op == 0xB7 || op == 0xBF;
let is_signed = op == 0xBE || op == 0xBF;
let source = if mode == 3 {
// Register source: only the low 8 or 16 bits are read.
let value = self.cpu.get(Register::from_index(rm_idx));
if is_word {
value as u16 as u64
} else {
value as u8 as u64
}
} else {
let address = self.effective_address(modrm, prefixes)?;
if is_word {
self.memory
.read_u16(address)
.map_err(ExitReason::MemoryFault)? as u64
} else {
self.memory
.read_u8(address)
.map_err(ExitReason::MemoryFault)? as u64
}
};
let extended = if is_signed {
if is_word {
source as u16 as i16 as i64 as u64
} else {
source as u8 as i8 as i64 as u64
}
} else {
source
};
// A 32-bit destination holds a 32-bit result, so its upper half is
// cleared; a 64-bit destination keeps the full extension.
let result = if prefixes.rex_w {
extended
} else {
extended as u32 as u64
};
self.cpu.set(reg, result);
Ok(None)
}
fn execute_mov_rm(
&mut self,
modrm: u8,
@@ -761,6 +833,49 @@ impl<'a> Interpreter<'a> {
}
// Memory operand [rm + disp] or SIB
let effective_addr = self.effective_address(modrm, prefixes)?;
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
}
/// Compute the effective address of a memory operand.
///
/// Consumes the SIB byte and the displacement from the instruction
/// stream. The FS or GS segment base is added when the corresponding
/// segment override prefix is present.
fn effective_address(&mut self, modrm: u8, prefixes: &Prefixes) -> Result<u64, ExitReason> {
let mode = (modrm >> 6) & 3;
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
@@ -832,36 +947,7 @@ impl<'a> Interpreter<'a> {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
Ok(effective_addr)
}
fn update_flags_logic(&mut self, val: u64, is_64: bool) {
+38 -18
View File
@@ -791,17 +791,42 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
});
}
// Map an RVA to a file offset.
//
// The offset is derived from the section header, so on a truncated file it
// can point past the end of the buffer. Such an offset is not readable, so
// it is reported as unmapped rather than returned and sliced later.
let rva_to_offset = |rva: u32| -> Option<usize> {
for sec in &sections {
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<String> {
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<ProbeReport,
}
desc_off += 20;
let dll_name = if let Some(no) = rva_to_offset(name_rva) {
let mut end = no;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
String::from_utf8_lossy(&bytes[no..end]).into_owned()
} else {
"UNKNOWN.dll".to_string()
let dll_name = match rva_to_offset(name_rva).and_then(read_c_string) {
Some(name) => 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<ProbeReport,
format!("Ordinal#{}", val & 0xFFFF)
} else {
let hint_rva = (val & 0x7FFF_FFFF) as u32;
if let Some(ho) = rva_to_offset(hint_rva) {
let str_start = ho + 2;
let mut str_end = str_start;
while str_end < bytes.len() && bytes[str_end] != 0 {
str_end += 1;
}
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
} else {
"UNKNOWN_SYM".to_string()
// The hint is two bytes, so the name starts after it.
match rva_to_offset(hint_rva)
.and_then(|ho| ho.checked_add(2))
.and_then(read_c_string)
{
Some(name) => name,
None => "UNKNOWN_SYM".to_string(),
}
};
+247
View File
@@ -462,3 +462,250 @@ fn test_sib_index_field_100b_without_rex_x_means_no_index() {
0x1234_5678_9abc_def0
);
}
/// Build a guest program that loads `value` into `rdi` and then runs `body`.
///
/// `mov rdi, imm64` is 48 BF <imm64>.
fn program_with_rdi(value: u64, body: &[u8]) -> Vec<u8> {
let mut code = vec![0x48, 0xBF];
code.extend_from_slice(&value.to_le_bytes());
code.extend_from_slice(body);
code.push(0xF4); // hlt
code
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run_interpreter(code: &[u8]) -> (CpuState, ExitReason) {
let pe_bytes = build_synthetic_pe32_plus(code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// MOVZX with a register source, for both destination widths.
///
/// The encodings are `movzbl eax, bl` (0F B6 C3) and
/// `movzbq rdx, bl` (48 0F B6 D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A zero extension always produces a zero-extended
/// value, so the 32-bit form clears the upper half of rax while the 64-bit
/// form produces the same 64-bit value.
#[test]
fn test_movzx_register_source_zero_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xB6, 0xC3]); // movzbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xB6, 0xD3]); // movzbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds a zero-extended byte: 0x00000000000000ff.
assert_eq!(state.get(Register::Rax), 0x0000_0000_0000_00ff);
// The 64-bit destination holds the same zero-extended value.
assert_eq!(state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a register source, for both destination widths.
///
/// The encodings are `movsbl eax, bl` (0F BE C3) and
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A sign extension reaches the destination width,
/// so the 32-bit form keeps the sign in bits 31:0 and clears the upper half,
/// while the 64-bit form sign-extends across all 64 bits.
#[test]
fn test_movsx_register_source_sign_extends_to_the_destination_width() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]); // movsbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]); // movsbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff and its upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVSX from a 16-bit source sign-extends to the destination width.
///
/// The encodings are `movswl eax, bx` (0F BF C3) and
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_word_register_source_sign_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]); // movswl eax, bx
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]); // movswq rdx, bx
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVZX with a memory source reads only the low byte of the operand.
///
/// The encodings are `movzbl eax, byte [rdi]` (0F B6 07) and
/// `movzbq rdx, byte [rdi]` (48 0F B6 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movzx_memory_source_reads_one_byte() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movzbl eax, byte [rdi] (0F B6 07)
// movzbq rdx, byte [rdi] (48 0F B6 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xB6, 0x07, 0x48, 0x0F, 0xB6, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The byte at the source address has the high bit set, so a sign
// extension would produce a negative value and a zero extension must not.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_0000_00ff);
assert_eq!(result.final_state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a memory source sign-extends the byte that was read.
///
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_memory_source_sign_extends() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movsbl eax, byte [rdi] (0F BE 07)
// movsbq rdx, byte [rdi] (48 0F BE 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xBE, 0x07, 0x48, 0x0F, 0xBE, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff with the upper half cleared.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// The interpreter must implement the same extension opcodes as the native
/// DBT translator.
///
/// The program exercises all four opcodes with both a register and a memory
/// source, and both destination widths:
///
/// - `movzbl eax, bl` (0F B6 C3), `movzbq rdx, bl` (48 0F B6 D3)
/// - `movswl eax, bx` (0F BF C3), `movswq rdx, bx` (48 0F BF D3)
/// - `movzbl eax, byte [rdi]` (0F B6 07), `movzbq rdx, byte [rdi]`
/// (48 0F B6 17)
/// - `movsbl eax, byte [rdi]` (0F BE 07), `movsbq rdx, byte [rdi]`
/// (48 0F BE 17)
///
/// All encodings were produced by LLVM 23.1.6 `llvm-mc -show-encoding`.
///
/// The expected values follow the Intel SDM rules for MOVZX and MOVSX: MOVZX
/// always zero-extends, and MOVSX sign-extends to the destination width, so a
/// 32-bit destination keeps the sign in bits 31:0 and clears the upper half
/// while a 64-bit destination keeps the sign extension across all 64 bits.
#[test]
fn test_interpreter_implements_the_extension_opcodes() {
let code = program_with_rdi(
DATA_BASE,
&[
0x0F, 0xB6, 0xC3, // movzbl eax, bl
0x48, 0x0F, 0xB6, 0xD3, // movzbq rdx, bl
0x0F, 0xBF, 0xC3, // movswl eax, bx
0x48, 0x0F, 0xBF, 0xD3, // movswq rdx, bx
0x0F, 0xB6, 0x07, // movzbl eax, byte [rdi]
0x48, 0x0F, 0xB6, 0x17, // movzbq rdx, byte [rdi]
0x0F, 0xBE, 0x07, // movsbl eax, byte [rdi]
0x48, 0x0F, 0xBE, 0x17, // movsbq rdx, byte [rdi]
],
);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The bytes at the source address have the high bit set and clear, so a
// sign extension and a zero extension give different results.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
loaded
.memory
.write_u8(DATA_BASE + 1, 0x7F)
.expect("source byte");
let mut cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
// rbx and rsi hold the register-source values.
cpu.set(Register::Rbx, u64::MAX);
cpu.set(Register::Rsi, 0x0000_0000_0000_7FFF);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The last write to rax is the 32-bit sign extension of the byte 0xFF.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The last write to rdx is the 64-bit sign extension of the same byte.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
+18
View File
@@ -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());
}
}
+9 -4
View File
@@ -29,10 +29,13 @@ PYTHONPATH=scripts python3 -m unittest discover -s tests/release
## Phase II CLIs
```sh
PYTHONPATH=scripts python3 -m qa rdna2 inventory
PYTHONPATH=scripts python3 -m qa rdna2 candidates --limit 50
PYTHONPATH=scripts python3 -m qa rdna2 plan
PYTHONPATH=scripts python3 -m qa rdna2 inventory --compact
PYTHONPATH=scripts python3 -m qa rdna2 candidates --family SOP2 --status reuse-primitives --limit 50
PYTHONPATH=scripts python3 -m qa rdna2 plan --limit 20 --compact
PYTHONPATH=scripts python3 -m qa rdna2 manifests --status reuse-primitives --limit 10 --claims claims.json
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
PYTHONPATH=scripts python3 -m qa rdna2 discrepancies
PYTHONPATH=scripts python3 -m qa rdna2 diff --before before.json --after after.json --compact
PYTHONPATH=scripts python3 -m qa verify quick
PYTHONPATH=scripts python3 -m qa cpu-coverage --blockers
PYTHONPATH=scripts python3 -m qa bench-compare --baseline b.json --current c.json
@@ -40,4 +43,6 @@ PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary
```
RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder tables and
`docs/status.toml`. Candidates are never counted as implemented forms.
`docs/status.toml`. Candidates and manifests are never counted as implemented forms.
Family claims exclude those families; path-only claims block candidates whose default
permitted files overlap. Reconcile reports mismatches without adjusting planner counts.
Binary file not shown.
+49
View File
@@ -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("<IIII", 1, 2, 2, 256)
# 2. Texture data: 2x2 RGBA8 (16 bytes)
# (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]
texture_bytes = bytes([
255, 128, 0, 255,
128, 0, 255, 255,
0, 255, 128, 255,
255, 0, 128, 255,
])
data += texture_bytes
# 3. Audio data: 256 samples of 440Hz sine wave (16-bit signed PCM mono, 512 bytes)
sample_rate = 48000
freq = 440.0
for i in range(256):
sample_val = int(32767.0 * 0.5 * math.sin(2.0 * math.pi * freq * (i / sample_rate)))
data += pack("<h", sample_val)
return bytes(data)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).parent / "asset.bin"
expected = generate_asset()
if args.check:
if not path.exists() or path.read_bytes() != expected:
parser.exit(1, f"asset binary differs from generator: {path}\n")
else:
path.write_bytes(expected)
Binary file not shown.
+124
View File
@@ -0,0 +1,124 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the clean-room PE32+ audio and virtual filesystem fixture without an x86 toolchain.
The guest demonstrates virtual asset loading and PCM audio streaming through runtime services:
1. Calls xenora.dll!vfs_open_asset() to open the authorized asset 'asset.bin'.
2. Calls xenora.dll!vfs_read_asset(handle, 548) to load asset header, texture, and PCM audio.
3. Calls xenora.dll!vfs_close_asset(handle) to close the asset file.
4. Calls xenora.dll!audio_init(48000, 1, 1) to initialize audio (48kHz, mono, S16LE).
5. Calls xenora.dll!audio_submit_pcm(512) to submit the 256 PCM audio samples.
6. Calls xenora.dll!frame_submit_textured(0) to render the 2x2 loaded texture on Metal.
7. Halts cleanly.
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
lookup = imports + 0x30
iat = imports + 0x70
module = imports + 0xB0
sym_vfs_open = imports + 0xC0
sym_vfs_read = imports + 0xE0
sym_vfs_close = imports + 0x100
sym_audio_init = imports + 0x120
sym_audio_submit = imports + 0x140
sym_frame_submit = imports + 0x160
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 56)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
code = bytearray()
code += b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
# 1. vfs_open_asset() -> rax = file handle
# call [rip -> iat[0]: vfs_open_asset]
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
code += b"\x48\x89\xc3" # mov rbx, rax (save file handle)
# 2. vfs_read_asset(handle, 548) -> 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("<i", (iat + 8) - (entry + len(code) + 6))
# 3. vfs_close_asset(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx (handle)
# call [rip -> iat[2]: vfs_close_asset]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 4. audio_init(48000, 1, 1)
code += b"\xb9\x80\xbb\x00\x00" # mov ecx, 48000 (sample rate)
code += b"\xba\x01\x00\x00\x00" # mov edx, 1 (mono)
code += b"\x41\xb8\x01\x00\x00\x00" # mov r8d, 1 (S16LE)
# call [rip -> iat[3]: audio_init]
code += b"\xff\x15" + pack("<i", (iat + 24) - (entry + len(code) + 6))
# 5. audio_submit_pcm(512)
code += b"\xb9\x00\x02\x00\x00" # mov ecx, 512 (bytes)
# call [rip -> iat[4]: audio_submit_pcm]
code += b"\xff\x15" + pack("<i", (iat + 32) - (entry + len(code) + 6))
# 6. frame_submit_textured(0)
code += b"\x31\xc9" # xor ecx, ecx
# call [rip -> iat[5]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 40) - (entry + len(code) + 6))
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
code += b"\xf4" # hlt
data[0x400:0x400 + len(code)] = code
# Import directory table
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
# Lookups & IAT (6 imports)
for off in (lookup - imports, iat - imports):
pack_into("<QQQQQQ", data, 0x600 + off,
sym_vfs_open, sym_vfs_read, sym_vfs_close,
sym_audio_init, sym_audio_submit, sym_frame_submit)
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
data[0x600 + (sym_vfs_open - imports) + 2:0x600 + (sym_vfs_open - imports) + 2 + 14] = b"vfs_open_asset"
data[0x600 + (sym_vfs_read - imports) + 2:0x600 + (sym_vfs_read - imports) + 2 + 14] = b"vfs_read_asset"
data[0x600 + (sym_vfs_close - imports) + 2:0x600 + (sym_vfs_close - imports) + 2 + 15] = b"vfs_close_asset"
data[0x600 + (sym_audio_init - imports) + 2:0x600 + (sym_audio_init - imports) + 2 + 10] = b"audio_init"
data[0x600 + (sym_audio_submit - imports) + 2:0x600 + (sym_audio_submit - imports) + 2 + 16] = b"audio_submit_pcm"
data[0x600 + (sym_frame_submit - imports) + 2:0x600 + (sym_frame_submit - imports) + 2 + 21] = b"frame_submit_textured"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
expected = fixture()
if args.check:
if not path.exists() or path.read_bytes() != expected:
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(expected)
Binary file not shown.
+114
View File
@@ -0,0 +1,114 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ persistent texture fixture without an x86 toolchain.
The guest demonstrates persistent GPU resource ownership, dynamic texture updates,
and completion-aware resource retirement through runtime services:
1. Calls xenora.dll!texture_create(2, 2) to allocate a persistent 2x2 texture.
2. Calls xenora.dll!frame_submit_textured(handle) to render frame 0 with initial contents.
3. Calls xenora.dll!texture_update(handle, 0, 0, 2, 2) to dynamically update texture pixels.
4. Calls xenora.dll!frame_submit_textured(handle) to render frame 1 with updated contents.
5. Calls xenora.dll!texture_destroy(handle) to retire the resource.
6. Halts cleanly.
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
lookup = imports + 0x30
iat = imports + 0x60
module = imports + 0x90
sym_create = imports + 0xA0
sym_update = imports + 0xC0
sym_submit = imports + 0xE0
sym_destroy = imports + 0x100
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 40)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
code = bytearray()
code += b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
# 1. texture_create(2, 2)
code += b"\x48\xc7\xc1\x02\x00\x00\x00" # mov rcx, 2
code += b"\x48\xc7\xc2\x02\x00\x00\x00" # mov rdx, 2
# call [rip -> iat[0]: texture_create]
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
code += b"\x48\x89\xc3" # mov rbx, rax (save handle)
# 2. frame_submit_textured(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[2]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 3. texture_update(handle, 0, 0, 2, 2)
code += b"\x48\x89\xd9" # mov rcx, rbx
code += b"\x48\x31\xd2" # xor rdx, rdx (x=0)
code += b"\x49\xc7\xc0\x00\x00\x00\x00" # mov r8, 0 (y=0)
code += b"\x49\xc7\xc1\x02\x00\x00\x00" # mov r9, 2 (w=2)
# call [rip -> iat[1]: texture_update]
code += b"\xff\x15" + pack("<i", (iat + 8) - (entry + len(code) + 6))
# 4. frame_submit_textured(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[2]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 5. texture_destroy(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[3]: texture_destroy]
code += b"\xff\x15" + pack("<i", (iat + 24) - (entry + len(code) + 6))
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
code += b"\xf4" # hlt
data[0x400:0x400 + len(code)] = code
# Import directory table
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
# Lookups & IAT
for off in (lookup - imports, iat - imports):
pack_into("<QQQQ", data, 0x600 + off, sym_create, sym_update, sym_submit, sym_destroy)
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
data[0x600 + (sym_create - imports) + 2:0x600 + (sym_create - imports) + 2 + 14] = b"texture_create"
data[0x600 + (sym_update - imports) + 2:0x600 + (sym_update - imports) + 2 + 14] = b"texture_update"
data[0x600 + (sym_submit - imports) + 2:0x600 + (sym_submit - imports) + 2 + 21] = b"frame_submit_textured"
data[0x600 + (sym_destroy - imports) + 2:0x600 + (sym_destroy - imports) + 2 + 15] = b"texture_destroy"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
+101 -11
View File
@@ -8,6 +8,7 @@ import shlex
import subprocess
import sys
from pathlib import Path
from typing import Any
from .bench_regress import IncompatibleComparison, compare_records, dumps_comparison, load_record
from .bench_stats import export_json, human_report, summarize
@@ -35,14 +36,21 @@ from .pr_validate import (
merge_reports,
)
from .rdna2_plan import (
build_manifests,
classify_unsupported,
compact_candidates,
compact_inventory,
compact_manifests,
coverage_diff,
discrepancies,
dumps_candidates,
dumps_inventory,
load_inventories,
parse_claims_file,
plan_batches,
reconcile_with_coverage_report,
summarize_inventory,
write_json,
)
from .coverage_history import historical_report, snapshot_inventory, write_snapshot
from .stale_branch import classify_sync, format_sync_reports
@@ -91,8 +99,21 @@ def main(argv: list[str] | None = None) -> int:
v.add_argument("--allowed", action="append", default=[])
r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning")
r.add_argument("action", choices=("inventory", "candidates", "plan", "discrepancies", "diff"))
r.add_argument(
"action",
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"),
)
r.add_argument("--limit", type=int, default=0)
r.add_argument("--family", action="append", default=[], help="filter by encoding family")
r.add_argument(
"--status",
action="append",
default=[],
help="filter: reuse-primitives|needs-primitives|needs-operand-rules",
)
r.add_argument("--claims", default="", help="JSON claims file to exclude overlapping work")
r.add_argument("--compact", action="store_true", help="print compact summary to stdout")
r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)")
r.add_argument("--before", default="", help="JSON inventory for diff")
r.add_argument("--after", default="", help="JSON inventory for diff")
@@ -199,24 +220,93 @@ def main(argv: list[str] | None = None) -> int:
return Inventory(**{k: d[k] for k in (
"identified", "declared", "decoder_supported", "reference_verified",
"metal_verified", "unsupported", "by_family")})
print(json.dumps(coverage_diff(inv(before), inv(after)), indent=2, sort_keys=True))
payload = coverage_diff(inv(before), inv(after))
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(
f"declared_delta={payload['declared_delta']} "
f"unsupported_delta={payload['unsupported_delta']}"
)
else:
print(json.dumps(payload, indent=2, sort_keys=True))
return 0
data = load_inventories(root)
inv = summarize_inventory(data)
exclude_families: list[str] = []
claimed_paths: list[str] = []
if args.claims:
fams, paths = parse_claims_file(Path(args.claims))
exclude_families = sorted(fams)
claimed_paths = sorted(paths)
limit = args.limit or None
def emit(payload: Any, compact_text: str, full_text: str | None = None) -> int:
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(compact_text, end="")
elif full_text is not None:
print(full_text, end="")
else:
print(json.dumps(payload, indent=2, sort_keys=True) + "\n", end="")
return 0
if args.action == "inventory":
print(dumps_inventory(inv), end="")
return 0
return emit(json.loads(dumps_inventory(inv)), compact_inventory(inv), dumps_inventory(inv))
if args.action == "candidates":
limit = args.limit or None
print(dumps_candidates(classify_unsupported(data, limit=limit)), end="")
return 0
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = json.loads(dumps_candidates(cands))
return emit(payload, compact_candidates(cands), dumps_candidates(cands))
if args.action == "plan":
cands = classify_unsupported(data, limit=(args.limit or None))
print(json.dumps(plan_batches(cands), indent=2, sort_keys=True))
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = plan_batches(cands)
return emit(payload, compact_candidates(cands))
if args.action == "manifests":
cands = classify_unsupported(
data,
limit=None,
families=args.family or None,
statuses=args.status or ["reuse-primitives"],
exclude_families=exclude_families,
)
manifests = build_manifests(
cands,
exclude_families=exclude_families,
claimed_paths=claimed_paths,
limit=limit,
)
payload = {
"note": "Codex-ready planning manifests only; forms are not implemented.",
"count": len(manifests),
"manifests": manifests,
}
out = args.out or "artifacts/rdna2-manifests.json"
write_json(Path(out), payload)
print(compact_manifests(manifests), end="")
print(f"wrote {out}")
return 0
if args.action == "discrepancies":
print(json.dumps(discrepancies(data), indent=2, sort_keys=True))
return 0
payload = discrepancies(data)
return emit(payload, f"discrepancies={len(payload)}\n")
if args.action == "reconcile":
payload = reconcile_with_coverage_report(root, data)
return emit(
payload,
f"reconcile_ok={payload['ok']} mismatches={len(payload['mismatches'])}\n",
)
if args.command == "cpu-coverage":
report = build_cpu_report(root)
+278 -28
View File
@@ -9,12 +9,13 @@ implemented forms.
from __future__ import annotations
import json
import re
import runpy
import tomllib
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
from typing import Any, Iterable, Sequence
def _load_coverage_module(root: Path):
@@ -46,6 +47,8 @@ class Candidate:
missing_effects: list[str] = field(default_factory=list)
spec_refs: list[dict[str, Any]] = field(default_factory=list)
priority_batch: str = "unclassified"
priority_rank: int = 99
status: str = "unsupported"
notes: list[str] = field(default_factory=list)
@@ -60,6 +63,27 @@ class Inventory:
by_family: dict[str, dict[str, int]]
# Conventional GPU semantic-expansion file set for Codex manifests only.
# Planning does not claim or edit these paths.
DEFAULT_PERMITTED_FILES = (
"crates/isa/semantics/rdna2.toml",
"crates/isa/src/semantics_gen.rs",
"crates/decoder/src/lib.rs",
"crates/shader/",
"crates/ref/",
"tests/validation/",
"docs/status.toml",
"CHANGELOG.md",
)
DEFAULT_ACCEPTANCE = (
"cargo test --locked -p xenora-ref",
"cargo test --locked -p xenora-semantic-review",
"scripts/test-gpu.sh",
"python3 scripts/audit/semantic_coverage.py --check",
)
def load_inventories(root: Path) -> dict[str, Any]:
sc = _load_coverage_module(root)
identified = sc["load_snapshot"](root)
@@ -146,52 +170,65 @@ def _declared_ops(registry: dict[str, Any]) -> set[str]:
return {form.get("operation") for form in registry.get("form", []) if form.get("operation")}
def _declared_rules(registry: dict[str, Any]) -> set[str]:
return set(registry.get("operand_rules", {}))
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> tuple[str, int, str]:
"""Return (batch_id, priority_rank, status). Lower rank is higher priority."""
if family_rule_names and ops:
return f"batch-{family.lower()}-reuse-primitives", 0, "reuse-primitives"
if family_rule_names:
return f"batch-{family.lower()}-needs-primitives", 1, "needs-primitives"
return f"batch-{family.lower()}-needs-operand-rules", 2, "needs-operand-rules"
def classify_unsupported(data: dict[str, Any], *, limit: int | None = None) -> list[Candidate]:
def classify_unsupported(
data: dict[str, Any],
*,
limit: int | None = None,
families: Sequence[str] | None = None,
statuses: Sequence[str] | None = None,
exclude_families: Sequence[str] | None = None,
) -> list[Candidate]:
"""Build candidates for identified forms that are not registry-declared.
Does not infer behaviour from the mnemonic. Width/type/layout are filled
only when already present on related declared forms in the same family, or
left null.
left null. Results are sorted by priority_rank then family/name.
"""
identified = data["identified"]
declared = data["declared"]
registry = data["registry"]
rules = data["rules"]
ops = _declared_ops(registry)
rule_names = _declared_rules(registry)
family_rules = defaultdict(list)
family_widths = defaultdict(set)
family_types = defaultdict(set)
family_widths: dict[str, set[int]] = defaultdict(set)
family_types: dict[str, set[str]] = defaultdict(set)
for form in registry.get("form", []):
family_rules[form["family"]].append(form.get("operands"))
if "width" in form:
family_widths[form["family"]].add(form["width"])
if "signedness" in form:
family_types[form["family"]].add(form["signedness"])
family_filter = {f.upper() for f in families} if families else None
status_filter = {s for s in statuses} if statuses else None
excluded = {f.upper() for f in (exclude_families or ())}
candidates: list[Candidate] = []
unsupported = sorted(set(identified) - set(declared))
if limit is not None:
unsupported = unsupported[:limit]
for family, name in unsupported:
if family_filter is not None and family.upper() not in family_filter:
continue
if family.upper() in excluded:
continue
opcode = identified[(family, name)]
reusable = sorted(op for op in ops if op) # available primitives, not guessed mapping
missing_rules = []
# If the family has no operand rule yet, record that gap.
reusable = sorted(op for op in ops if op)
family_rule_names = [n for n, (fam, _) in rules.items() if fam == family]
missing_rules = []
if not family_rule_names:
missing_rules.append(f"no operand_rules for family {family}")
missing_effects = []
# Architectural effects are unknown until specified; flag absence.
missing_effects.append("scc/vcc/exec effects unspecified until registry declaration")
widths = sorted(family_widths.get(family, []))
types = sorted(family_types.get(family, []))
layout = family_rule_names[0] if len(family_rule_names) == 1 else None
batch = _batch_for(family, family_rule_names, ops)
batch, rank, status = _batch_for(family, family_rule_names, ops)
if status_filter is not None and status not in status_filter:
continue
candidates.append(Candidate(
family=family,
name=name,
@@ -201,25 +238,22 @@ def classify_unsupported(data: dict[str, Any], *, limit: int | None = None) -> l
operand_layout=layout,
reusable_primitives=reusable[:20],
missing_operand_rules=missing_rules,
missing_effects=missing_effects,
missing_effects=["scc/vcc/exec effects unspecified until registry declaration"],
spec_refs=[{"document": "xml", "note": "identity from pinned AMD snapshot only"}],
priority_batch=batch,
priority_rank=rank,
status=status,
notes=[
"behaviour must come from the public AMD guide, never the mnemonic",
"candidate is not implemented",
],
))
candidates.sort(key=lambda c: (c.priority_rank, c.family, c.name, c.opcode))
if limit is not None:
candidates = candidates[:limit]
return candidates
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> str:
if family_rule_names and ops:
return f"batch-{family.lower()}-reuse-primitives"
if family_rule_names:
return f"batch-{family.lower()}-needs-primitives"
return f"batch-{family.lower()}-needs-operand-rules"
def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]:
batches: dict[str, list[dict[str, Any]]] = defaultdict(list)
for cand in candidates:
@@ -227,6 +261,7 @@ def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
"status": cand.status,
"missing_operand_rules": cand.missing_operand_rules,
"reusable_primitives": cand.reusable_primitives[:5],
})
@@ -275,6 +310,179 @@ def discrepancies(data: dict[str, Any]) -> list[dict[str, str]]:
return issues
def reconcile_with_coverage_report(root: Path, data: dict[str, Any]) -> dict[str, Any]:
"""Compare planner inventory to canonical semantic_coverage collect_coverage.
Does not inflate planner counts. Reports per-family deltas only.
"""
sc = data["sc"]
identified = data["identified"]
registry = data["registry"]
decoder = data["decoder"]
status = data["status"]
counts, _rules = sc["collect_coverage"](identified, registry, decoder, status)
# collect_coverage tuple per family:
# Identified, Encoding-validated, Declared, Decoder-supported, IR, MSL,
# Reference-verified, Metal-verified, Unsupported operand variants
inv = summarize_inventory(data)
mismatches: list[dict[str, Any]] = []
for family, values in sorted(counts.items()):
canon_identified, _enc, canon_declared, canon_decoder, _ir, _msl, canon_ref, canon_metal, _u = values
bucket = inv.by_family.get(family, {})
pairs = (
("identified", canon_identified, bucket.get("identified", 0)),
("declared", canon_declared, bucket.get("declared", 0)),
("decoder", canon_decoder, bucket.get("decoder", 0)),
("reference", canon_ref, bucket.get("reference", 0)),
("metal", canon_metal, bucket.get("metal", 0)),
)
for field_name, canon, plan in pairs:
if canon != plan:
mismatches.append({
"family": family,
"field": field_name,
"canonical": canon,
"planner": plan,
"delta": plan - canon,
})
return {
"ok": not mismatches,
"canonical_totals": {
"identified": sum(v[0] for v in counts.values()),
"declared": sum(v[2] for v in counts.values()),
"decoder_supported": sum(v[3] for v in counts.values()),
"reference_verified": sum(v[6] for v in counts.values()),
"metal_verified": sum(v[7] for v in counts.values()),
},
"planner_totals": {
"identified": inv.identified,
"declared": inv.declared,
"decoder_supported": inv.decoder_supported,
"reference_verified": inv.reference_verified,
"metal_verified": inv.metal_verified,
},
"mismatches": mismatches,
"note": "Planner counts are not adjusted to match; mismatches must be investigated.",
}
@dataclass(frozen=True)
class ClaimScope:
"""One active claim. Families exclude those families; path-only claims
block candidates whose default permitted files overlap the claimed paths.
A claim that lists both families and paths excludes only the families —
the paths document the claim and do not blanket-block other families.
"""
families: frozenset[str] = frozenset()
paths: frozenset[str] = frozenset()
def parse_claims_file(path: Path) -> tuple[set[str], set[str]]:
"""Load excluded families and path-only claim prefixes.
Expected shape: {"claims":[{"families":["VOP2"], "paths":["crates/isa/**"]}, ...]}
or a bare list of such objects.
Returns (exclude_families, path_only_claimed_paths). Path prefixes from
claims that also name families are ignored for blocking so a SOP2+isa
claim does not suppress every other family's manifests.
"""
scopes = load_claim_scopes(path)
families: set[str] = set()
path_only: set[str] = set()
for scope in scopes:
families.update(scope.families)
if scope.families:
continue
path_only.update(scope.paths)
return families, path_only
def load_claim_scopes(path: Path) -> list[ClaimScope]:
raw = json.loads(path.read_text(encoding="utf-8"))
items = raw["claims"] if isinstance(raw, dict) and "claims" in raw else raw
if not isinstance(items, list):
raise ValueError("claims file must be a list or {\"claims\": [...]}")
scopes: list[ClaimScope] = []
for item in items:
fams = frozenset(str(f).upper() for f in (item.get("families") or []))
paths = frozenset(str(p) for p in (item.get("paths") or []))
if not fams and not paths:
continue
scopes.append(ClaimScope(families=fams, paths=paths))
return scopes
def claims_block_candidate(cand: Candidate, claimed_paths: set[str]) -> bool:
"""True if a path-only claim overlaps the default GPU expansion files."""
if not claimed_paths:
return False
for permitted in DEFAULT_PERMITTED_FILES:
for claimed in claimed_paths:
if _path_overlap(permitted, claimed):
return True
return False
def _path_overlap(a: str, b: str) -> bool:
a = a.rstrip("/")
b = b.rstrip("/")
if a.endswith("/**"):
a = a[:-3].rstrip("/")
if b.endswith("/**"):
b = b[:-3].rstrip("/")
return a == b or a.startswith(b + "/") or b.startswith(a + "/")
def build_manifests(
candidates: list[Candidate],
*,
exclude_families: Sequence[str] | None = None,
claimed_paths: Sequence[str] | None = None,
limit: int | None = None,
) -> list[dict[str, Any]]:
"""Deterministic Codex-ready implementation manifests.
Prioritises reuse-primitives, then needs-primitives, then needs-operand-rules.
Excludes active claim families and path-only claims. Does not invent semantics.
"""
excluded = {f.upper() for f in (exclude_families or ())}
claimed = set(claimed_paths or ())
manifests: list[dict[str, Any]] = []
for cand in candidates:
if cand.family.upper() in excluded:
continue
if claims_block_candidate(cand, claimed):
continue
deps: list[str] = []
if cand.status == "needs-operand-rules":
deps.append(f"define operand_rules for family {cand.family}")
if cand.status == "needs-primitives":
deps.append("add registry operation primitive before declaring this form")
if cand.status == "reuse-primitives":
deps.append("reuse existing registry primitives/operand rules; declare form from AMD guide")
deps.append("do not infer behaviour from the mnemonic")
manifest = {
"id": f"{cand.family}:{cand.name}",
"instruction": {
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
},
"priority_rank": cand.priority_rank,
"status": cand.status,
"dependencies": deps,
"specification_references": cand.spec_refs,
"permitted_files": list(DEFAULT_PERMITTED_FILES),
"acceptance_tests": list(DEFAULT_ACCEPTANCE),
"notes": list(cand.notes),
}
manifests.append(manifest)
if limit is not None and len(manifests) >= limit:
break
return manifests
def coverage_diff(before: Inventory, after: Inventory) -> dict[str, Any]:
return {
"identified_delta": after.identified - before.identified,
@@ -299,3 +507,45 @@ def dumps_candidates(candidates: list[Candidate]) -> str:
def dumps_inventory(inv: Inventory) -> str:
return json.dumps(asdict(inv), indent=2, sort_keys=True) + "\n"
def compact_inventory(inv: Inventory) -> str:
lines = [
f"identified={inv.identified} declared={inv.declared} "
f"decoder={inv.decoder_supported} unsupported={inv.unsupported} "
f"ref={inv.reference_verified} metal={inv.metal_verified}",
]
for family, bucket in inv.by_family.items():
if bucket.get("unsupported", 0) == 0 and bucket.get("declared", 0) == 0:
continue
lines.append(
f" {family}: id={bucket['identified']} decl={bucket['declared']} "
f"dec={bucket['decoder']} unsup={bucket['unsupported']}"
)
return "\n".join(lines) + "\n"
def compact_candidates(candidates: Sequence[Candidate]) -> str:
lines = [f"candidates={len(candidates)}"]
for cand in candidates:
lines.append(
f" [{cand.priority_rank}:{cand.status}] {cand.family}:{cand.name} "
f"op=0x{cand.opcode:x} batch={cand.priority_batch}"
)
return "\n".join(lines) + "\n"
def compact_manifests(manifests: Sequence[dict[str, Any]]) -> str:
lines = [f"manifests={len(manifests)}"]
for item in manifests:
inst = item["instruction"]
lines.append(
f" [{item['priority_rank']}:{item['status']}] {inst['family']}:{inst['name']} "
f"deps={len(item['dependencies'])}"
)
return "\n".join(lines) + "\n"
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+11 -1
View File
@@ -40,7 +40,17 @@ cargo test --locked -p xenora-ffi --features gpu-tests --test interactive --no-r
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test interactive -- \
--nocapture --test-threads=1
# Persistent GPU resources, dynamic texture updates, and resource retirement (Gate 5, #279).
cargo test --locked -p xenora-ffi --features gpu-tests --test resources --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test resources -- \
--nocapture --test-threads=1
# Audio PCM streaming and sandboxed virtual filesystem integration (Gate 6, #284).
cargo test --locked -p xenora-ffi --features gpu-tests --test audio_vfs --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_vfs -- \
--nocapture --test-threads=1
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
timeout 60s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
+21
View File
@@ -32,6 +32,27 @@ class CliSmoke(unittest.TestCase):
data = json.loads(inv.stdout)
self.assertGreater(data["identified"], data["declared"])
compact = run("qa", "rdna2", "candidates", "--status", "reuse-primitives", "--limit", "2", "--compact")
self.assertEqual(compact.returncode, 0, compact.stderr)
self.assertIn("candidates=2", compact.stdout)
recon = run("qa", "rdna2", "reconcile", "--compact")
self.assertEqual(recon.returncode, 0, recon.stderr)
self.assertIn("reconcile_ok=", recon.stdout)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "manifests.json"
man = run(
"qa", "rdna2", "manifests",
"--status", "reuse-primitives",
"--limit", "2",
"--out", str(out),
)
self.assertEqual(man.returncode, 0, man.stderr)
payload = json.loads(out.read_text(encoding="utf-8"))
self.assertEqual(payload["count"], 2)
self.assertIn("not implemented", payload["note"].lower())
def test_release_readiness_cli_negative(self):
r = run(
"release", "readiness",
+86 -3
View File
@@ -1,16 +1,22 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import tempfile
import unittest
from pathlib import Path
from qa.rdna2_plan import (
Inventory,
build_manifests,
classify_unsupported,
compact_candidates,
compact_inventory,
coverage_diff,
discrepancies,
dumps_candidates,
load_inventories,
parse_claims_file,
plan_batches,
reconcile_with_coverage_report,
summarize_inventory,
)
@@ -40,9 +46,85 @@ class Rdna2Plan(unittest.TestCase):
batches = plan_batches(cands)
self.assertTrue(batches)
def test_discrepancies_and_diff(self):
issues = discrepancies(self.data)
self.assertIsInstance(issues, list)
def test_family_status_limit_and_priority(self):
reuse = classify_unsupported(
self.data, families=["SOP2"], statuses=["reuse-primitives"], limit=5
)
self.assertLessEqual(len(reuse), 5)
for cand in reuse:
self.assertEqual(cand.family, "SOP2")
self.assertEqual(cand.status, "reuse-primitives")
self.assertEqual(cand.priority_rank, 0)
needs_rules = classify_unsupported(
self.data, statuses=["needs-operand-rules"], limit=3
)
for cand in needs_rules:
self.assertEqual(cand.status, "needs-operand-rules")
self.assertEqual(cand.priority_rank, 2)
# Priority ordering: reuse before needs-operand-rules when unfiltered.
mixed = classify_unsupported(self.data, limit=20)
ranks = [c.priority_rank for c in mixed]
self.assertEqual(ranks, sorted(ranks))
def test_manifests_exclude_claims_and_stay_deterministic(self):
cands = classify_unsupported(self.data, statuses=["reuse-primitives"], limit=50)
with tempfile.TemporaryDirectory() as tmp:
claims = Path(tmp) / "claims.json"
claims.write_text(
json.dumps({"claims": [{"families": ["SOP2"], "paths": ["crates/isa/**"]}]}),
encoding="utf-8",
)
fams, paths = parse_claims_file(claims)
self.assertIn("SOP2", fams)
# Family+path claims must not path-block every other family.
self.assertEqual(paths, set())
manifests = build_manifests(
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
)
self.assertGreater(len(manifests), 0)
for item in manifests:
self.assertNotEqual(item["instruction"]["family"], "SOP2")
self.assertIn("permitted_files", item)
self.assertIn("acceptance_tests", item)
self.assertIn("specification_references", item)
self.assertIn("dependencies", item)
again = build_manifests(
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
)
self.assertEqual(manifests, again)
path_only = Path(tmp) / "path_only.json"
path_only.write_text(
json.dumps({"claims": [{"paths": ["crates/isa/**"]}]}),
encoding="utf-8",
)
_, path_claims = parse_claims_file(path_only)
self.assertIn("crates/isa/**", path_claims)
blocked = build_manifests(
cands, claimed_paths=sorted(path_claims), limit=5
)
self.assertEqual(blocked, [])
def test_reconcile_does_not_inflate_coverage(self):
report = reconcile_with_coverage_report(ROOT, self.data)
self.assertIn("mismatches", report)
self.assertEqual(
report["planner_totals"]["identified"],
report["canonical_totals"]["identified"],
)
# Declared/decoder may differ in representation but planner must not
# silently bump counts to hide mismatches.
before = self.inv.declared
_ = reconcile_with_coverage_report(ROOT, self.data)
after = summarize_inventory(self.data).declared
self.assertEqual(before, after)
self.assertTrue(report["ok"] or isinstance(report["mismatches"], list))
def test_compact_helpers_and_diff(self):
text = compact_inventory(self.inv)
self.assertIn("identified=", text)
cands = classify_unsupported(self.data, limit=2)
self.assertIn("candidates=2", compact_candidates(cands))
before = Inventory(
identified=self.inv.identified,
declared=self.inv.declared - 1 if self.inv.declared else 0,
@@ -54,6 +136,7 @@ class Rdna2Plan(unittest.TestCase):
)
delta = coverage_diff(before, self.inv)
self.assertEqual(delta["declared_delta"], self.inv.declared - before.declared)
self.assertIsInstance(discrepancies(self.data), list)
if __name__ == "__main__":