Compare commits

..
Author SHA1 Message Date
ates 43f32acb82 Implement bounded audio queues and GameInput COM stub
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:06:36 +03:00
Ateş a51271d125 Merge pull request #421 from MacosPorters/docs/agents-onboarding
docs: add first-time contributor onboarding flow to AGENTS.md
2026-11-26 08:37:16 +03:00
ates 4fc5d9e5a4 docs: add first-time contributor onboarding flow to AGENTS.md
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 08:31:41 +03:00
atharvranjan f2c42ba110 Merge pull request #406 from MacosPorters/m0/hybrid-foundation
M0: Overhaul repo into clean 6-track parallel hybrid foundation (ADR 0006)
2026-11-25 23:06:36 -06:00
ates 30e551a161 Overhaul repo into clean 6-track hybrid M0 workspace and retire legacy native files
Rebases onto origin/main and retires the paused in-tree native-first workspace, legacy scripts, legacy CI, and native-only docs per ADR 0006 (preserving full history permanently at Git tag native-first-final).

Addresses all maintainer review findings on PR #406:
- Isolate CrossOver/Wine child process environment in bx-cli (env_clear + minimal allowlist + opt-in --inherit-env, with unit tests)
- Replace naive objdump grep in scripts/build-shims.sh with strict PE Export Directory verification (exact names, ordinals, forwarders, 0 extra exports, 0 forbidden MinGW imports across all 16 DLLs / 102 exports)
- Restore global * @MacosPorters/maintainers fallback in .github/CODEOWNERS alongside per-track rules
- Restore independent-verification, claims/evidence-class, provenance-first, and contributor clean-room protections in AGENTS.md
- Unify docs/roadmap.md, CONTRIBUTING.md, README.md, docs/README.md, THIRD_PARTY_NOTICES.md, and CHANGELOG.md around Milestones M0-M6 and ADR 0006

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 07:59:27 +03:00
atharvranjan d9333d272f Merge pull request #396 from IamHeavyLazer/feature/353-hybrid-measurement-protocol
docs: define hybrid workloads and measurement protocol
2026-11-25 16:26:56 -06:00
atharvranjan 395aaeb4e7 Merge pull request #379 from erkinemreta1/docs/354-crossover-licensing
Record CrossOver component licenses and redistribution boundaries
2026-11-25 16:13:15 -06:00
HeavyLazer efb63a37d4 docs: define hybrid workloads and measurement protocol
Signed-off-by: HeavyLazer <iamheavylazer@gmail.com>
2026-11-25 23:12:40 +01:00
erkinemreta1 35cdf56e80 Address the independent review of the licensing note
Record the public CrossOver EULA and its section 2/3 terms, correct the
source-page inventory (no DXMT or VKD3D-Proton), cite DXMT's MIT
LICENSE.OLD and VKD3D-Proton's COPYING, soften the MoltenVK NOTICE
claim, add the reviewed pins and name the D3DMetal third-party source.

Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-26 00:12:18 +03:00
atharvranjan db3bdb5a5c Merge pull request #380 from MacosPorters/remove-agent-pr-checks
Remove the agent-pr-checks workflow
2026-11-25 14:48:58 -06:00
atharvranjan 9b20f78a06 Remove agent-pr-checks tests and docs 2026-11-25 14:41:35 -06:00
erkinemreta1 b39780b421 Fold the reported D3DMetal reading into the licensing note
Record the third-party 4.0 License.pdf summary as evidence class D,
unconfirmed against Apple's own copy, and keep D3DMetal user-supplied
and never bundled. Update the licenses.md row and the changelog entry
to match.

Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-25 23:39:44 +03:00
erkinemreta1 f8f497b578 Record CrossOver component licenses and redistribution boundaries
Add docs/research/crossover-licensing.md with the license text read for
each component, its source link and the redistribution status, plus a
matching section in docs/licenses.md. D3DMetal, Rosetta 2 and the
CrossOver product terms stay unknown with the missing document named.

Closes #354

Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-25 23:39:27 +03:00
atharvranjan 77cec214c0 Merge pull request #378 from MacosPorters/planning/hybrid-first-transition
Transition to a CrossOver-based hybrid direction with progressive planning; archive native work
2026-11-25 14:32:48 -06:00
atharvranjan 953254a435 Remove the agent-pr-checks workflow 2026-11-25 14:30:07 -06:00
atharvranjan 39b628d60d Fix a link in the archived README milestones 2026-11-25 14:23:04 -06:00
atharvranjan 1d70633958 Keep the local Agent Spawning section out of the shared engineering rules
That section was an uncommitted local addition and is not part of main.
2026-11-25 14:22:57 -06:00
atharvranjan a9f55b51f7 State that the native-first-final tag marks the last main commit before the transition 2026-11-25 14:22:38 -06:00
atharvranjan 722388a46d Record the planning transition in the changelog
CrossOver-based hybrid direction, rewritten engineering rules, native work paused and archived, upstream registry and research records.
2026-11-25 14:22:17 -06:00
atharvranjan e7ff293eba Record primary-source verification and finalize the Phase 1 backlog
Add the hybrid research record and a primary-source re-check (CodeWeavers, Apple, DXMT, Wine, Rust toolchain), rename the roadmap's parked section to Parked ideas, and add the matching changelog and docs index entries. Unrelated local work stays uncommitted.
2026-11-25 14:22:09 -06:00
atharvranjan dfaaa07df4 Update README, CONTRIBUTING, docs index, changelog and template for progressive planning
Only this task's hunks are committed; unrelated local edits remain uncommitted.
2026-11-25 14:21:53 -06:00
atharvranjan 962b83c731 Extend the upstream registry with unreviewed candidates
llvm-mingw, Sikarugir, macOS Wine builds, Mythic and Playdock, metadata only.
2026-11-25 14:21:47 -06:00
atharvranjan 7fff77c801 Simplify the roadmap to one active phase and archive the native issue backlog
Five provisional phases with only Phase 1 active, parked ideas, Phase 1 completion criteria, a simple project board guide, the retired H0 to H7 breakdown, and an index of the closed native issues with preserved findings and contributor attribution.
2026-11-25 14:21:47 -06:00
atharvranjan c3684a1ae8 Add progressive planning rules to the engineering rules
Only the current phase has a milestone and open issues; future ideas are parked in the roadmap; issues carry evidence, reuse assessment and validation; no native-only issues.
2026-11-25 14:21:47 -06:00
atharvranjan d561595599 Replace issue templates and add a pull request template
Hybrid task, bug, research, performance, validation and documentation forms with problem, context, scope, dependencies, acceptance, validation and licensing sections. Fix invalid YAML in the agent-task template.
2026-11-25 14:21:47 -06:00
atharvranjan 8cab0b1de8 Describe the hybrid direction in README, CONTRIBUTING, docs index and changelog
Only this task's hunks are committed; unrelated local edits to CHANGELOG.md and docs/README.md remain uncommitted.
2026-11-25 14:21:40 -06:00
atharvranjan d2367dca30 Add the upstream research registry and component reuse matrix
Public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch with license, pin and reuse decisions. VIctory-family projects are excluded from reuse on provenance grounds.
2026-11-25 14:20:55 -06:00
atharvranjan 60ad6c779e Add the CrossOver-based hybrid roadmap and archive the native-first plan
Add docs/roadmap.md (phases H0 to H7, critical path), ADR 0005 (accepted direction; proposed architecture and unverified assumptions kept separate), the deferred native roadmap and the project board setup guide. Archive the native-first plan and the seven retired milestones. Mark the PortWatch review as superseded in part.
2026-11-25 14:20:55 -06:00
atharvranjan ffc7056d26 Rewrite engineering rules for the CrossOver-based hybrid direction
Replace the native-first prohibition on Wine, CrossOver, Rosetta and MoltenVK with dependency, reuse, licensing and provenance rules. Keep the honesty, independent-verification, clean-room, claiming, changelog and subagent rules. CLAUDE.md remains a symlink to AGENTS.md. Resolves #345 once reviewed.
2026-11-25 14:20:55 -06:00
696 changed files with 4770 additions and 192481 deletions

No files matched your search

+34 -2
View File
@@ -1,2 +1,34 @@
# Every change needs a review from the maintainers team.
* @MacosPorters/maintainers
# Global fallback: every file in the repository requires maintainer review.
* @MacosPorters/maintainers
# Frozen cross-track ABI contracts (fast-tracked [ABI] PRs)
/abi/ @MacosPorters/maintainers
/Cargo.toml @MacosPorters/maintainers
/shims/CMakeLists.txt @MacosPorters/maintainers
# Track A: Host launcher, CrossOver/Rosetta runner, runtime VEH & Win32 forwarders
/launcher/ @MacosPorters/maintainers
/shims/runtime_veh/ @MacosPorters/maintainers
/shims/win32_bridge/ @MacosPorters/maintainers
/scripts/build-shims.sh @MacosPorters/maintainers
# Track B: Memory (xmem) & Storage (XCRDAPI / DirectStorage)
/shims/xmem/ @MacosPorters/maintainers
/shims/xcrdapi/ @MacosPorters/maintainers
# Track C: Graphics (d3d12_xs, xg_xs, FidelityFX/BVH hooks)
/shims/d3d12_xs/ @MacosPorters/maintainers
/shims/xg_xs/ @MacosPorters/maintainers
/shims/ffx_bvh_hooks/ @MacosPorters/maintainers
# Track D: Shader pipeline (DXBC/DXIL/ACCC/FSPX & RDNA2 transpiler)
/shader-transpiler/ @MacosPorters/maintainers
# Track E: Platform runtime (xgameruntime), Input (GameInput) & Audio/DSP
/shims/xgameruntime/ @MacosPorters/maintainers
/shims/gameinput/ @MacosPorters/maintainers
/shims/audio/ @MacosPorters/maintainers
# Track F: Conformance tests & documentation
/tests/conformance/ @MacosPorters/maintainers
/docs/ @MacosPorters/maintainers
-67
View File
@@ -1,67 +0,0 @@
name: Agent task
description: A self-contained work item that a contributor or coding agent can claim with /claim.
title: "task: "
labels: [agent:ready]
body:
- type: dropdown
id: area
attributes:
label: Area
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
options:
- cpu
- gpu
- runtime
- shared
- qa
validations:
required: true
- type: dropdown
id: priority
attributes:
label: Priority
options:
- critical
- high
- medium
- low
validations:
required: true
- type: input
id: interface
attributes:
label: Interface
description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise.
- type: textarea
id: goal
attributes:
label: Goal
description: What must be true when the task is finished, in one or two sentences.
validations:
required: true
- type: textarea
id: files
attributes:
label: Files
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
render: text
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance command
description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance.
render: sh
validations:
required: true
- type: input
id: depends
attributes:
label: Depends on
description: Issue numbers that must be closed first, for example "#12, #15". Leave empty when none.
- type: textarea
id: context
attributes:
label: Context
description: Specification sections, interface notes and known limits. Public sources only.
+30 -15
View File
@@ -1,42 +1,57 @@
name: Bug report
description: Report a reproducible defect in Xenora or XenoMetal.
description: A reproducible defect.
title: "bug: "
labels: [bug]
body:
- type: markdown
attributes:
value: |
Use synthetic or authorized inputs only. For vulnerabilities, follow SECURITY.md. Remove personal paths, credentials and private data from logs.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. For vulnerabilities follow SECURITY.md.'
- type: textarea
id: description
attributes:
label: Description
description: What went wrong? Identify the affected subsystem and expected behavior.
description: 'What went wrong and what you expected.'
validations:
required: true
- type: textarea
id: steps
attributes:
label: Reproduction steps
description: Include exact commands and a minimal, legally distributable input if applicable.
description: 'Exact commands and a minimal, legally distributable input.'
validations:
required: true
- type: textarea
id: environment
attributes:
label: Environment
description: Commit, macOS, Apple GPU, RAM, Rust, Xcode and relevant tool versions. Include sanitized doctor output if available.
description: 'Commit, macOS, chip, memory, CrossOver and Rosetta 2 versions, graphics backend. Remove personal paths and credentials.'
validations:
required: true
- type: textarea
id: output
id: scope
attributes:
label: Actual output and diagnostics
description: Include expected versus actual results, validation-layer messages and relevant logs.
- type: checkboxes
id: confirmation
label: Scope and dependencies
description: 'Affected area; related issues.'
validations:
required: false
- type: textarea
id: acceptance
attributes:
label: Confirmation
options:
- label: I searched for existing reports and have not included sensitive or unauthorized material.
required: true
label: Acceptance criteria
description: 'When is this fixed?'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How to confirm the fix independently.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: 'Only if third-party code or a dependency is involved.'
validations:
required: false
+50
View File
@@ -0,0 +1,50 @@
name: Documentation
description: Fix, add or restructure documentation.
title: "docs: "
labels: [documentation]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is unclear, wrong or missing.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Pages and sources involved.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Files to change; update docs/README.md if pages are added or moved.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'None if none.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Claims are scoped to their evidence; links work.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'scripts/audit/docs_hygiene.py and claims audit pass.'
validations:
required: true
-31
View File
@@ -1,31 +0,0 @@
name: Feature proposal
description: Propose a compiler, graphics, tooling or other project enhancement.
title: "feat: "
labels: [enhancement]
body:
- type: textarea
id: problem
attributes:
label: Problem or gap
description: Which limitation does this feature address?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed approach
description: Explain the intended behavior and affected components. Link relevant public specifications when available.
validations:
required: true
- type: textarea
id: criteria
attributes:
label: Acceptance criteria
description: What observable results and tests would demonstrate completion?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives and trade-offs
description: Include limitations, dependency costs or impacts on native ARM64 and Metal if relevant.
-31
View File
@@ -1,31 +0,0 @@
name: Hardware verification report
description: Submit real hardware test results for Xenora.
title: "hardware: "
labels: [needs-verification]
body:
- type: textarea
id: environment
attributes:
label: Test environment
description: Commit, Apple chip/GPU, RAM, macOS, Xcode/Metal version, Rust version, validation settings. Do not include serial numbers or registry IDs.
validations:
required: true
- type: textarea
id: commands
attributes:
label: Commands and inputs
description: Include exact commands and synthetic or authorized fixture identifiers.
validations:
required: true
- type: textarea
id: results
attributes:
label: Results
description: Report actual output, pass/fail/skip counts, and limitations. Compilation alone does not prove execution.
validations:
required: true
- type: textarea
id: performance
attributes:
label: Performance data (optional)
description: Include repetitions, warm-up, timing method, validation state and variability if reporting measurements.
+57
View File
@@ -0,0 +1,57 @@
name: Hybrid engineering task
description: Integration, configuration, diagnostics or tooling around CrossOver.
title: "task: "
labels: [track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Performance investigation
description: Measure or improve performance with evidence.
title: "perf: "
labels: [performance,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. Do not promise gains before measuring.'
- type: textarea
id: problem
attributes:
label: Problem and metric
description: 'Which metric (average FPS, 1% low, frame-time percentiles, CPU or GPU use, memory, startup, shader compile latency) and why.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Workload, hardware (reference: M4, 24 GB), software versions, settings.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Measurement only, or change as well.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Measurement protocol (#353) and baseline (#355).'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Measured before-and-after under equivalent conditions, with variance.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'Correctness and rendering equivalence verified before the result counts.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+37 -22
View File
@@ -1,42 +1,57 @@
name: Technical research
description: Record an ISA, Metal or publicly documented graphics research finding.
name: Upstream research or dependency evaluation
description: Assess a project, component or license from public sources.
title: "research: "
labels: [research]
labels: [research,track: hybrid]
body:
- type: markdown
attributes:
value: Use only public, authorized sources. Do not link to leaked SDKs, private documentation or unauthorized game content.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: question
id: problem
attributes:
label: Research question or finding
label: Question
description: 'The decision this research informs.'
validations:
required: true
- type: textarea
id: sources
id: context
attributes:
label: Sources and applicability
description: URLs, specification sections or revision, exact architecture and license/provenance if relevant.
label: Technical context
description: 'What is already known; link docs/research/upstream-registry.md entries.'
validations:
required: true
- type: dropdown
id: evidence
- type: textarea
id: scope
attributes:
label: Evidence class (highest applicable)
options:
- A - Measured on named hardware
- B - Normative source for exact target
- C - Normative source for related target
- D - Non-normative official material
- E - Independent software behavior
- F - Uncorroborated community claim
- U - Unknown or assumption
label: Scope
description: 'Which versions or components; desk research or execution.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Other issues or decisions; execution may need a maintainer-approved environment.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Each claim cites vendor or upstream documentation, or a recorded observation of a stated version; unknowns stay marked unknown.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation, limitations and proposed next steps
description: Distinguish Apple or desktop RDNA observations from Xbox behavior.
label: Validation requirements
description: 'Independent re-derivation and evidence class (A to U).'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+82
View File
@@ -0,0 +1,82 @@
name: Parallel track handoff issue
description: Self-contained engineering task scoped to one BetterXen track (A-F) for conflict-free parallel work.
title: "[M1-X0] "
labels: ["track: hybrid"]
body:
- type: markdown
attributes:
value: |
Use this template to hand off work to contributors across Tracks A-F.
Keep file scopes disjoint so 5-8+ contributors can work concurrently without merge conflicts.
Never include proprietary game files, names, hashes, or leaked material in issues or PRs.
- type: dropdown
id: track
attributes:
label: Track
options:
- "Track A — Host Launcher, VEH & Win32 Bridge"
- "Track B — Memory (xmem) & Storage (XCRDAPI)"
- "Track C — Graphics (d3d12_xs, xg_xs, DXR/FFX)"
- "Track D — Shader Pipeline (DXBC/DXIL/ACCC)"
- "Track E — Platform (xgameruntime), Input & Audio"
- "Track F — Conformance, QA & Performance"
- "ABI Freeze — Shared Contract (abi/)"
validations:
required: true
- type: dropdown
id: milestone
attributes:
label: Milestone
options:
- "M0 — Repo, ABI & Cross-Build"
- "M1 — Boot to D3D12XboxCreateDevice"
- "M2 — First Frame & Shader Format Gate"
- "M3 — Full Shaders, Streaming & Texture Correctness"
- "M4 — 3D Rendering, DXR/BVH & Input"
- "M5 — Audio, Saves & Stability"
- "M6 — Shader Cache, 16 GB Optimization & Polish"
validations:
required: true
- type: textarea
id: file_scope
attributes:
label: Exclusive file scope
description: Exact directories/files this issue may modify. Do not overlap with other active issues.
placeholder: |
- `shims/xmem/**`
- `tests/conformance/test_xmem/**`
validations:
required: true
- type: textarea
id: api_contract
attributes:
label: Exact API / export / COM contract
description: Exported symbols (referencing `abi/defs/*.def`), COM interface IIDs/vtable slots, or CLI flags to implement.
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Hard dependencies
description: Blocking `[ABI]` or prerequisite issues (`none` if immediately claimable).
value: "none"
validations:
required: true
- type: textarea
id: synthetic_test
attributes:
label: Required synthetic conformance test
description: Clean-room synthetic test in `tests/conformance/` or `cargo test` proving correctness.
validations:
required: true
- type: textarea
id: exit_criteria
attributes:
label: Definition of done
description: Exact commands that must succeed locally and in CI.
placeholder: |
- `cargo fmt --all -- --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace`
- `scripts/build-shims.sh` (all DLL export checks pass)
- Synthetic conformance binary passes under CrossOver/Wine
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Testing and validation
description: Add or run a validation for a workload or behaviour.
title: "validate: "
labels: [needs-verification,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
-8
View File
@@ -1,8 +0,0 @@
{
"lease_hours": 168,
"upstream": "MacosPorters/betterxen",
"maintainers": [
"Arths17"
],
"contributors": {}
}
+29
View File
@@ -0,0 +1,29 @@
## Related issue
Closes #
## Summary
## Technical changes
## Tests performed
Commands, versions, pass/fail/skip counts and hardware. A skipped test is not a pass.
## Performance impact
Measured before and after under equivalent conditions, or "none expected" with reason.
## Compatibility impact
Workloads, macOS or CrossOver versions and hardware affected. Do not claim support that was not tested.
## Known limitations
## Third-party code attribution
Source repository, exact commit, license, modifications. "None" if none.
## Dependency and licensing considerations
New or changed dependencies, license compatibility with GPL-3.0-or-later, redistribution limits (proprietary components are never bundled). DCO: commits are signed off.
-89
View File
@@ -1,89 +0,0 @@
name: Agent task claims
# Applies queue commands (/claim, /release, /reassign, /progress, /blocked,
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
# text is only parsed as data by scripts/agent_queue; it is never executed and
# never interpolated into a shell. Not yet run on GitHub.
#
# Both jobs share one concurrency group, so decisions never race. GitHub keeps
# at most one pending run per group and cancels the older pending run when a
# newer one queues, so a run does not decide only its own comment: `replay`
# decides every command of the last lease_hours that has no bot reply yet,
# oldest first. The surviving run, or at the latest the hourly audit, answers
# the commands of cancelled runs. Comments that do not start with `/` start no run.
on:
issue_comment:
types: [created]
schedule:
- cron: "17 * * * *"
workflow_dispatch:
permissions: {}
jobs:
command:
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request && startsWith(github.event.comment.body, '/')
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: write
# One global group: claims are decided one at a time so file-overlap checks cannot race.
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide and apply
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/state.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
audit:
if: github.event_name != 'issue_comment'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide commands whose runs were cancelled
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/commands.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/commands.json" > "$RUNNER_TEMP/replay.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/replay.json"
- name: Lapse stale claims, flag invalid tasks, write summary
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
{
echo '## Agent queue summary'
echo '```json'
python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
-102
View File
@@ -1,102 +0,0 @@
name: Agent PR checks
# Checks pull requests against the task queue: linked claimed task, file
# ownership, overlap with other open pull requests, and independent
# verification. Runs on the base branch only: pull request code is never checked
# out or executed; changed files come from the API. Not yet run on GitHub.
#
# Advisory: problems are reported as a warning and in the run summary, but the
# check does not fail until a live smoke test and the migration of existing
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
# with /verified starts the verify job; ordinary comments start nothing.
on:
pull_request_target:
types: [opened, synchronize, reopened, edited]
issue_comment:
types: [created]
permissions: {}
jobs:
check:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: read
pull-requests: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check pull request
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
verify:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
runs-on: ubuntu-24.04-arm
# issues: write posts the reply.
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and check again
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
# Check again only after an accepted verification of the current head: refused, stale,
# malformed or unauthorized /verified comments get a reply and nothing else.
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
# pull_request_target runs are recorded against the base branch, not the pull request
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check after verification'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
-120
View File
@@ -1,120 +0,0 @@
name: Native Rust checks
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: native-rust-${{ github.ref }}
cancel-in-progress: true
jobs:
native-rust:
name: ARM64 CPU and build checks
runs-on: macos-26
timeout-minutes: 15
env:
CARGO_BUILD_JOBS: 3
PYTHONDONTWRITEBYTECODE: 1
CARGO_BUILD_TARGET: aarch64-apple-darwin
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify runner architecture
run: |
uname -m
test "$(uname -m)" = arm64
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install native Rust
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustc -vV
- name: Install the Gate A2 C toolchain
# crates/loader/tests/gate_a2.rs builds a hosted C program from source
# with mingw-w64 and fails, never skips, when the compiler is missing.
env:
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
run: |
brew install mingw-w64
compiler="$(brew --prefix mingw-w64)/bin/x86_64-w64-mingw32-gcc"
file -bL "$compiler" | grep arm64
lipo -archs "$compiler" | grep arm64
otool -L "$compiler"
"$compiler" --version | head -1
- name: Check generated status and PE fixtures
run: |
python3 crates/isa/generate_rdna2_meta.py --check
python3 crates/isa/generate_semantics.py --check
python3 scripts/audit/semantic_coverage.py --check
python3 scripts/audit/status.py --check
# The generated status check must not depend on the host locale encoding.
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
- name: Test agent task queue
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
- name: Check formatting and lint
run: |
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo fmt --manifest-path experiments/x1/Cargo.toml -- --check
cargo clippy --locked --manifest-path experiments/x1/Cargo.toml --all-targets --all-features -- -D warnings
- name: Run CPU tests and dependency checks
run: |
cargo test --locked --workspace
cargo test --locked --manifest-path experiments/x1/Cargo.toml
scripts/audit/dependencies.sh
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
- name: Inspect native CLI
run: |
cargo build --locked -p betterxen
binary=target/aarch64-apple-darwin/debug/betterxen
file "$binary"
test "$(lipo -archs "$binary")" = arm64
otool -L "$binary"
native-app:
name: Native app build and smoke
runs-on: macos-26
timeout-minutes: 20
env:
CARGO_BUILD_JOBS: 3
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify runner architecture
run: |
uname -m
test "$(uname -m)" = arm64
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install native Rust
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal
rustc -vV
- name: Show Swift and Xcode
run: |
xcodebuild -version
swift --version
# Builds the locked C ABI library and the Swift app together, checks the
# executable is arm64-only and links only system libraries, and runs
# `--smoke`. This is an app build and smoke result, not GPU verification.
- name: Build BetterXen.app and run its smoke check
run: scripts/build-app.sh
+53
View File
@@ -0,0 +1,53 @@
name: Hybrid build and shim checks
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: hybrid-ci-${{ github.ref }}
cancel-in-progress: true
jobs:
arm64-host-and-shims:
name: ARM64 host Rust + x86-64 PE32+ shims
runs-on: macos-26
timeout-minutes: 15
env:
CARGO_BUILD_JOBS: 3
CARGO_BUILD_TARGET: aarch64-apple-darwin
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify Apple Silicon runner
run: |
test "$(uname -m)" = arm64
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install Rust toolchain
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustc -vV
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
run: |
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli
binary=target/aarch64-apple-darwin/debug/bx-cli
file "$binary"
test "$(lipo -archs "$binary")" = arm64
- name: Install mingw-w64 and CMake
env:
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
run: |
brew install mingw-w64 cmake
x86_64-w64-mingw32-g++ --version | head -n 1
- name: Cross-compile all x86-64 PE32+ shim DLLs and verify exports
run: scripts/build-shims.sh
+1 -1
View File
@@ -37,7 +37,7 @@ jobs:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
changed="$(git diff --name-only "$BASE_SHA"...HEAD || true)"
if printf '%s\n' "$changed" | grep -Eq '^(crates|scripts|shaders|fixtures)/' \
if printf '%s\n' "$changed" | grep -Eq '^(abi|launcher|shims|shader-transpiler|scripts|tests)/' \
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
fi
+3 -11
View File
@@ -1,10 +1,9 @@
# Rust and local builds
/target/
/experiments/x1/target/
/build/
/build-shims/
/cmake-build-*/
/fuzz/target/
/fuzz/artifacts/
/local-runs/
# macOS / Xcode local state
.DS_Store
@@ -20,8 +19,6 @@
*.profraw
*.profdata
# Keep Cargo.lock, source fixtures, reviewed golden files and documentation tracked.
# Local AI agent tooling
.agents/
.claude/
@@ -29,15 +26,10 @@
.cursor/
.gemini/
# Local gate evidence and intermediate fixture objects
# Local gate evidence and ignored probes
/artifacts/
/tests/validation/target/
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/title-candidate-*/
/diagnostics/title-check/
# Native application build output
/app/.build/
+116 -76
View File
@@ -1,104 +1,144 @@
# BetterXen engineering rules
# BetterXen Engineering & Agent Rules
### Native Apple Silicon
These rules apply to every human contributor and coding agent (`CLAUDE.md` is a symlink to this file). Strategic decisions are recorded in `docs/adr/0005-crossover-hybrid-direction.md` and `docs/adr/0006-retire-in-tree-native-workspace.md`; the single authoritative roadmap is `docs/roadmap.md`.
Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dependencies, Wine, CrossOver, Windows compatibility layers, OpenGL fallback rendering, or unnecessary graphics abstraction layers.
---
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
- The guest architecture being decoded may be x86-64, but BetterXen itself runs natively on ARM64.
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
- Use aarch64-apple-darwin as the Rust target.
## 0. First-Time Contributor Onboarding
### Honesty and evidence
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
- Never report a test as passed unless it ran and passed. Never count a skipped test as GPU verification.
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities or implementation status.
- Never claim a clean build unless the commands actually succeeded.
- Never present planned features as working. State clearly that game execution is not supported unless demonstrated.
- Never replace GPU tests with mocks and then claim GPU support.
- Unknown information is classified as unknown and becomes a documented research task.
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
- Never claim "verified on Xbox hardware". BetterXen has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
1. **Preflight host & tools:**
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
2. **Discover & pick an unclaimed issue:**
- Query ready issues in the active milestone:
```sh
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
```
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
3. **Claim & isolate:**
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
4. **Implement strictly in scope:**
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
5. **Verify locally (including hosts without CrossOver):**
- Run every command in Section 8 and fix all warnings/failures before stopping.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
6. **Review & submit PR:**
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
### Independence of verification
---
- The agent that writes a component does not certify it. The two independent reviewers (section 5) re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
- The same faulty code must never produce both the expected and the actual values in a test.
## 1. Direction & Architecture
### Legal and clean-room
- **Hybrid-first on Apple Silicon:** CrossOver 26.3+ (externally installed), Wine runtime APIs, Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`), and D3DMetal 3.0 (subject to license terms) form the external compatibility foundation. DXMT, DXVK, VKD3D-Proton, MoltenVK, and `utmapp/d3dmetal-native` may be evaluated and used where license-compatible and technically justified.
- **BetterXen's in-tree scope:**
- `abi/` — Frozen cross-DLL C headers (`abi/include/*.h`) and canonical `.def` export tables (`abi/defs/*.def`).
- `launcher/` — Native **ARM64** macOS Rust CLI (`bx-cli`), PE32+ import classifier (`bx-probe`), and JSONL trace aggregator (`bx-telemetry`).
- `shims/` — Cross-compiled **x86-64 Windows PE32+** Xbox Game OS shim DLLs (C++20 via `x86_64-w64-mingw32-g++` + CMake, statically linked against GCC/C++/winpthread so Wine bottles need zero extra MinGW runtime DLLs).
- `shader-transpiler/` — Rust shader container classifier (`dxbc-accc`) and RDNA 2 (`gfx1030`) transpiler pipeline (expanded on demand per the M2 shader-format gate).
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
- Include a plain statement in docs/legal.md: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
- Keep BetterXen's emulator implementation original. Never copy, port, translate or adapt emulator source from PE-Vulkan project, KyTx, AnyPS5 or similar projects.
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
- Never place restricted material in the repository or its Git history.
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
---
### Quality
## 2. Parallel Track Ownership (5–8+ Concurrent Contributors / Agents)
No AI slop (section 29).
Every feature issue belongs to **one track** and defines an **exclusive file scope**. Stay strictly inside your issue's file scope to avoid merge conflicts across concurrent contributors and agents:
Read docs/interfaces.md and docs/progress.md before implementation.
| Track | Exclusive Directories | Responsibility |
| --- | --- | --- |
| **ABI Gate** | `abi/` | Frozen headers & `.def` files (small `[ABI]` PRs merged first) |
| **Track A** | `launcher/`, `shims/runtime_veh/`, `shims/win32_bridge/`, `scripts/build-shims.sh` | ARM64 CLI/runner (with `env_clear()` isolation), `clwb` VEH trap, ADX tripwire, JSONL telemetry, Win32/PSM forwarders |
| **Track B** | `shims/xmem/`, `shims/xcrdapi/` | `xmem.dll` (virtual/physical/scatter allocator, Lockhart 8–10 GB budget) & `XCRDAPI.dll` (DirectStorage) |
| **Track C** | `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Xbox D3D12 COM proxy → D3DMetal 3.0, `PresentX`, RDNA 2 texture tiling (`XG`), DXR/BVH4 & FidelityFX hooks |
| **Track D** | `shader-transpiler/` | `DXBC`/`DXIL`/`ACCC`/`FSPX` parser, RDNA 2 → DXIL/MSL transpiler, shader cache, `d3dmetal-native` harness |
| **Track E** | `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Offline GDK runtime, `GameInput.dll` (`@1`), `AcpHal.dll`, `xapu.dll`, `chad.dll` |
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
## Claiming work before you start
### Cross-Track `[ABI]` Rule
- Never edit another track's directory inside a feature PR.
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
Several people and coding agents work on this repository at the same time. Claim an issue before you edit anything, and never take work someone else has claimed.
---
1. **Check.** Read every comment on the issue and look for open pull requests that link it. A claim is any comment in which someone says they are taking the issue, in any words (for example "I'll take this" or `/claim`). If a claim exists and is not stale (step 4), pick another issue.
2. **Claim.** Reply on the issue in plain words, for example: "I'm taking this. Plan: …". No command, label or bot step is needed. The earliest claim wins. Claim one issue per comment.
3. **Stay in scope.** If the issue lists files, edit only those, and ask on the issue before widening the list. Do not start work that edits the same files as another claimed issue.
4. **Stale claims.** A claim is stale when the claimer has not opened a pull request for the issue within about one week (7 days) of the claim. Only then may someone else take it, by replying on the issue, for example: "Taking this over: @name's claim from <date> has no pull request after 7 days." A claim with an open pull request is never stale; ask the claimer or the maintainer instead.
5. **Release.** If you stop working on an issue, say so on the issue so others can take it.
6. **Link.** Put `Closes #<n>` in the pull request description.
## 3. Native Apple Silicon Host & Runtime Isolation
A coding agent claims in the name of the person it works for and follows the same rules. It must read the comments before claiming, and must never claim over, remove or ignore another person's claim. The optional task-queue commands in `docs/coordination/agent-tasks.md` do not replace these rules: a plain-reply claim counts even though the bot does not track it.
- **ARM64 host binaries:** BetterXen's own host executables (`bx-cli`, etc.) must be native `arm64`-only (`aarch64-apple-darwin`); verify with `file` and `lipo -archs`. Only guest shim DLLs under `shims/` and conformance EXEs under `tests/conformance/` target x86-64 Windows PE32+.
- **Apple Silicon generations:** Support M1 through M5 and future generations via runtime capability detection; do not hardcode single-generation GPU or RAM assumptions (default to Lockhart memory limits on 16 GiB hosts).
- **Child environment isolation:** `bx-cli run` must isolate the child CrossOver/Wine process (`env_clear()` + minimal explicit allowlist; `--inherit-env` opt-in only) so host credentials and stray variables never leak into guest processes.
- **Build concurrency:** Use at most four Cargo/CMake build jobs across simultaneous local builds, with one GPU workload at a time.
## Changelog maintenance
---
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
- Update the changelog in the same task for every meaningful addition, modification, fix, removal or security change, including work implemented by another agent. Use `Added`, `Changed`, `Fixed`, `Removed` or `Security` as appropriate.
- Write concise entries that explain the effect for users or contributors. Distinguish implemented behavior, local verification and independent acceptance. Never invent release dates, versions, benchmark results, passing tests or compatibility claims.
- Omit trivial formatting and intermediate steps unless they materially affect maintainability. Keep unreleased changes under `[Unreleased]` until a release is authorized.
- Before concluding the task, check whether the changelog needs an update and make it when warranted. Rewrite historical entries only to correct factual errors. Preserve existing content when tightening the prose.
## 4. Dependencies, Licensing & Provenance
## Public documentation and terminology
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
- Write public documentation so readers can understand it without earlier agent conversations. Keep `README.md` and `docs/README.md` accessible to new contributors.
- Introduce descriptive names before internal identifiers such as X1, G10 or P2-04. Define specialist abbreviations on first meaningful use.
- Write changelog entries around actual behavior and its effect on users or contributors. Distinguish implementation, synthetic demonstrations, independent verification and real Xbox execution.
- Review terminology whenever editing documentation. Use concise, precise explanations and preserve evidence scope.
- Update `docs/README.md` whenever you add, remove, rename or substantially reorganize documentation.
---
## Subagent reasoning
## 5. Honesty, Evidence & Independent Verification
**Every spawned subagent must use LOW reasoning effort.** Explicitly select LOW and verify the resolved configuration. Never use Medium, High or Extra High. If LOW cannot be guaranteed, proceed without that subagent. The lead agent may use the user-selected reasoning setting.
- **Never fabricate verification:** Never report a test as passed unless it ran and passed on this revision. Never count a skipped test or unavailable tool as a pass. Never invent benchmark results, API names, encodings, hardware capabilities, or compatibility claims.
- **No silent fallbacks:** Do not hide errors behind silent no-ops. Every unimplemented shim export must call `BX_STUB_LOG(dll, sym)` and every unimplemented COM vtable slot must call `BX_VTABLE_STUB_LOG(iface, slot, method)` so `bx-cli trace` surfaces exact blockers. Do not weaken or delete tests to make them pass.
- **Evidence classes & hardware claims:** Classify evidence per `docs/claims.toml`. Never claim "verified on Xbox hardware" — BetterXen has no Xbox hardware access; agreement with a public specification or Apple Silicon run is not Xbox hardware verification.
- **Independence of verification:** The agent or contributor who writes a component does not independently certify it. Independent reviewers re-derive expectations from primary sources and are not told the implementer's conclusions as ground truth. The same faulty code must never produce both the expected and actual values in a test.
- **Milestone completion:** A milestone is complete only when every exit condition has recorded evidence — never from commit counts, lines of code, or isolated stubs.
## Checkout commands
---
- Format: `cargo fmt --all -- --check`
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
- Test: `cargo test --workspace`
- Verify the synthetic fixtures: `scripts/assemble-fixture.sh --check`
- Run native GPU correctness: `scripts/test-gpu.sh`
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
- Check generated status tables: `python3 scripts/audit/status.py --check`.
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
- Fuzz one target at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services>` (600 seconds by default). `runtime_services` drives the standard guest service registry.
## 6. Legal & Clean-Room Rules
Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time.
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
- **Contributor clean-room rule:** Contributors who have seen leaked or confidential Xbox materials must not contribute (`CONTRIBUTING.md`, DCO `Signed-off-by` required on all commits).
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
Do not add AI attribution or Co-authored-by trailers to commits.
Never commit or push without explicit permission.
Preserve the configured Git author and committer identity.
---
## Ownership
## 7. Claiming, Git Safety & Changelog
Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
3. **Isolate with branches or worktrees:**
```sh
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
```
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
---
## 8. Verification Commands (Run Before Every Handoff / PR)
```sh
# 1. ARM64 Rust workspace (launcher + shader-transpiler)
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
scripts/build-shims.sh
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
target/debug/bx-cli trace /tmp/bx-test.jsonl
# 4. Repository Markdown link & hygiene check
python3 scripts/audit/docs_hygiene.py
```
+13
View File
@@ -10,6 +10,13 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
- Added Section 0 (`First-Time Contributor Onboarding`) to `AGENTS.md` (`CLAUDE.md` symlink) giving coding agents a turnkey step-by-step onboarding flow (preflight, `bx-cli doctor`, unclaimed `status: ready` issue discovery, claiming, scoped implementation, local verification including hosts without CrossOver, DCO commit, and PR CI watching).
- Overhauled the repository into a clean 6-track parallel hybrid workspace (Milestone M0) designed for 5–8+ concurrent contributors and coding agents: added frozen cross-DLL ABI headers and canonical `.def` export tables (`abi/`), native ARM64 Rust workspace (`launcher/crates/{bx-cli,bx-probe,bx-telemetry}` with `env_clear()` child environment isolation, and `shader-transpiler/crates/dxbc-accc`), CMake + `mingw-w64` superbuild (`shims/`, `scripts/build-shims.sh`) producing 16 standalone x86-64 PE32+ shim DLLs (`bx_runtime_veh.dll` with working `clwb` VEH trap and JSONL logger, `xmem.dll`, `XCRDAPI.dll`, `d3d12_xs.dll`, `xg_xs.dll`, `xgameruntime.dll`, `GameInput.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, and PSM/ntuser forwarders) with strict PE Export Directory verification (exact names, ordinals, forwarders, zero extra exports, zero dynamic MinGW runtime dependencies), auto-discovered synthetic PE32+ conformance tests (`tests/conformance/`), `.github/workflows/hybrid-ci.yml`, `.github/ISSUE_TEMPLATE/track-handoff.yml`, `docs/adr/0006-retire-in-tree-native-workspace.md`, `docs/architecture/parallel-tracks.md`, and `docs/issues/wave-1-backlog.md`. Unified `docs/roadmap.md`, `CONTRIBUTING.md`, `AGENTS.md`, `README.md`, and `.github/CODEOWNERS` (retaining global `* @MacosPorters/maintainers` fallback and full provenance/independent-verification rules). Verified locally on Apple M5 (macOS 27.2.1, CrossOver 26.3, Rosetta 2) with all Rust checks, strict 16-DLL export verification, and live `test_veh_clwb.exe` + `test_shim_exports.exe` smoke tests passing.
- Documented the original Windows workload set and Phase 1 hybrid measurement protocol (#353), including receipt-field sources, percentile definitions, negative controls and independent reproduction requirements. The protocol identifies the unmerged runner candidate and its missing raw traces and measurements; it adds no execution or compatibility claim.
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
- Added `docs/research/crossover-licensing.md`, a per-component license and redistribution record for the hybrid direction: CrossOver itself, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, Apple's Game Porting Toolkit repository, D3DMetal and Rosetta 2, each with the exact text read or the missing document named, plus an entry in `docs/licenses.md` (#354). Nothing is bundled or redistributed; the D3DMetal text (third-party copy, not confirmed against Apple's) and Rosetta 2 terms remain unverified, and CrossOver 26.3.0's FOSS inventory is unknown. Research only; no code or dependency change.
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed.
- Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally.
@@ -17,9 +24,15 @@ remains unsupported.
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
### Removed
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
- Replaced our own references to a specific commercial game title (README non-affiliation line, research and integration notes, ignored diagnostics folder names) with generic "commercial title" wording. The ignored folder names are now `diagnostics/title-candidate-*` and `diagnostics/title-check`. Third-party repository names, URLs and code-span paths in research notes are unchanged so their provenance stays accurate. Our own prose references to the upstream project formerly named in the research notes now read "PE-Vulkan project". Added the PortWatch native-macOS research notes. No behavior change.
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
- Removed the contributor avatar section from the README.
+32 -41
View File
@@ -1,61 +1,52 @@
# Contributing to BetterXen
BetterXen is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
BetterXen is a modular, CrossOver-based Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS. Contributions are organized into **6 parallel tracks** so 5–8+ human contributors and coding agents can work simultaneously without merge conflicts.
## Getting started
## Active Work & Track Ownership
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Claim an issue before working on it by replying on it in plain words, after checking its comments for an existing claim. Never claim over someone else. A claim with no pull request after about one week may be taken over with a reply saying so. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones M0–M6), supported by [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and the ready-to-claim Wave 1 issues in [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md). The earlier native-first workspace was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently at Git tag `native-first-final`.
## Development and verification
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
When the Cargo workspace exists, run from its root:
## Development & Verification
Requirements on Apple Silicon macOS: Rust 1.85+ (`aarch64-apple-darwin`), `mingw-w64` & `cmake` (`brew install mingw-w64 cmake`), Python 3.11+, Rosetta 2, and CrossOver 26.3+ (externally installed, never bundled).
Run these checks before opening a PR:
```sh
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli
scripts/build-shims.sh
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
python3 scripts/audit/docs_hygiene.py
```
Follow repository documentation for actual GPU tests, fuzzing, mutation testing and benchmarks. Report commands, versions, pass/fail/skip counts and hardware used. A successful shader compile is not successful GPU execution. Do not report unavailable tools or skipped tests as passes.
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
For an instruction or compiler change, cite the applicable ISA section, state the exact architecture, document operand and execution-mask semantics, and add tests for encodings, edge cases, unsupported cases and independent expected results. Where applicable, verify the resulting MSL through actual Metal execution. Do not convert unsupported instructions into silent no-ops.
## Clean-Room, Licensing & Provenance Policy
For a performance change, provide reproducible before-and-after results using equivalent inputs, hardware and settings. For a new dependency, explain why it is needed, verify its license and native ARM64 compatibility, and record its provenance.
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
## Research and clean-room policy
## Pull Requests & DCO Sign-Off
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware.
BetterXen implements its own Rust guest runtime, decoder, typed IR, shader
compiler and native Metal backend from public technical specifications
and independently derived tests. Contributions must not copy, port or
adapt code, decoder tables, internal metadata or implementation
architecture from other emulators. External results can inform test
selection. Author the resulting code and fixtures independently.
Before incorporating third-party code, verify per-file license compatibility with GPL-3.0-or-later, record the exact upstream revision and original paths, preserve copyright notices and document changes. Update applicable attribution records. Public visibility alone is not proof of authorization or license compatibility.
## Pull requests
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Describe what changes and why, link the issue you claimed with `Closes #<number>`, state which checks you actually ran, and disclose material AI assistance. Separate unverified work from supported behavior.
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
- Never include secrets, personal paths, credentials or private data in patches or logs.
- Do not claim approval from an independent reviewer unless one has actually reviewed the change.
Sign off each commit under the [Developer Certificate of Origin](https://developercertificate.org/):
- Branch from `main`, keep changes focused inside your track scope, link the issue with `Closes #<number>`, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Disclose material AI assistance and personally review generated changes. Never include secrets, personal paths, or credentials in patches or logs.
- Sign off every commit under the [Developer Certificate of Origin](https://developercertificate.org/):
```sh
git commit -s -m "Describe the change"
```
Use your configured Git identity and a privacy-preserving email address if desired. Sign-off is your certification of the contribution; do not sign off work on another person's behalf. Contributions are subject to the repository license and any applicable, compatible third-party notices.
For security-sensitive findings, see [SECURITY.md](SECURITY.md). Community expectations are in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
Generated
+11 -232
View File
@@ -3,243 +3,22 @@
version = 4
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
name = "bx-cli"
version = "0.2.0"
dependencies = [
"generic-array",
"bx-probe",
"bx-telemetry",
"dxbc-accc",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
name = "bx-probe"
version = "0.2.0"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
name = "bx-telemetry"
version = "0.2.0"
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags",
"dispatch2",
"objc2",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "objc2-metal"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
dependencies = [
"bitflags",
"objc2",
"objc2-core-foundation",
"objc2-foundation",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "betterxen"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "xenora-benchmarks"
version = "0.1.0"
dependencies = [
"xenora-isa",
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "xenora-decoder"
version = "0.1.0"
dependencies = [
"xenora-isa",
"xenora-ref",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
"xenora-metal",
"xenora-shader",
]
[[package]]
name = "xenora-import-gen"
version = "0.1.0"
[[package]]
name = "xenora-isa"
version = "0.1.0"
[[package]]
name = "xenora-loader"
version = "0.1.0"
dependencies = [
"libc",
"sha2",
"xenora-metal",
"xenora-shader",
"xenora-texture",
]
[[package]]
name = "xenora-metal"
version = "0.1.0"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-metal",
"xenora-ref",
"xenora-shader",
"xenora-texture",
]
[[package]]
name = "xenora-ref"
version = "0.1.0"
[[package]]
name = "xenora-semantic-review"
version = "0.1.0"
dependencies = [
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "xenora-shader"
version = "0.1.0"
dependencies = [
"xenora-decoder",
]
[[package]]
name = "xenora-texture"
version = "0.1.0"
name = "dxbc-accc"
version = "0.2.0"
+10 -7
View File
@@ -1,19 +1,22 @@
[workspace]
members = ["crates/*", "tests/validation", "benchmarks"]
members = [
"launcher/crates/bx-cli",
"launcher/crates/bx-probe",
"launcher/crates/bx-telemetry",
"shader-transpiler/crates/dxbc-accc",
]
exclude = ["legacy-native"]
resolver = "3"
[workspace.package]
version = "0.1.0"
version = "0.2.0"
edition = "2024"
license = "GPL-3.0-or-later"
rust-version = "1.100"
rust-version = "1.85"
[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
# Whole-program optimization for release and bench builds (#116). On an Apple M5 the
# interpreter ran about 6 % and cold DBT about 9 % faster in `dbt_bench`, at the cost of
# slower release builds. Debug and test builds are unaffected.
[profile.release]
lto = "fat"
lto = "thin"
codegen-units = 1
+144 -455
View File
@@ -2,508 +2,197 @@
# BetterXen
**Experimental Xbox Series X|S emulation research, built natively for Apple Silicon.**
**Modular Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS — built on CrossOver, Rosetta 2, and D3DMetal 3.0.**
[![Native Rust checks](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
[![Hybrid build and shim checks](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml)
[![Repository hygiene](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml)
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: Metal](https://img.shields.io/badge/graphics-native%20Metal-8957e5)
![Language: Rust](https://img.shields.io/badge/language-Rust%201.100-dea584?logo=rust&logoColor=white)
![Status: experimental](https://img.shields.io/badge/status-experimental-d29922)
![Graphics: D3DMetal 3.0](https://img.shields.io/badge/graphics-D3DMetal%203.0%20%2F%20Metal-8957e5)
![Stack: Rust + C++20 PE32+](https://img.shields.io/badge/stack-Rust%20%2B%20C%2B%2B20%20PE32%2B-dea584)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M0)-d29922)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
</div>
BetterXen is a community-maintained, open-source project written primarily in Rust. It builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend. The host runs as ARM64 code; the x86-64 code being emulated is guest data.
> [!IMPORTANT]
> **BetterXen is experimental.** Verified work is restricted to independently authored synthetic programs and shaders. Authentic Xbox executable loading, system-service compatibility and commercial game execution are **not supported**. Progress is measured by reproducible tests, not by estimated game compatibility percentages. See the [current limitations](#current-limitations).
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
- **Cross-compiled x86-64 Windows PE32+ shim DLLs** (`shims/`, C++20 via `mingw-w64`) implementing Xbox runtime APIs (`xmem`, `XCRDAPI`, `d3d12_xs`, `xg_xs`, `xgameruntime`, `GameInput`, `AcpHal`/`xapu`/`chad`, Win32/PSM forwarders, and a `clwb` Vectored Exception Handler).
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
> [!CAUTION]
> **BetterXen strictly opposes piracy.** BetterXen is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. BetterXen is not affiliated with Microsoft or any other publisher or platform holder.
> **Clean-room and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
---
## How it fits together
## Architecture
One guest program travels through three native subsystems. Every stage is checked against an independently derived expectation.
Rosetta 2 executes x86-64 CPU code (including AVX/AVX2/FMA/F16C/BMI1/BMI2/128-bit VAES when launched with `ROSETTA_ADVERTISE_AVX=1`), CrossOver/Wine provides Win32/NT/CRT/XAudio2/WinHTTP, and D3DMetal 3.0 translates Direct3D 12 + DXR onto Metal. BetterXen supplies the modular Xbox Game OS shims, `clwb` exception handling, shader bridge, and ARM64 orchestration around that stack.
```mermaid
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
flowchart LR
A["Original PE32+<br/>test program"]:::guest --> B["Loader<br/>relocations, TLS, imports"]:::guest
B --> C["x86-64 interpreter<br/>+ ARM64 translator"]:::cpu
C --> D["Typed runtime<br/>services"]:::cpu
D --> E["Guest graphics<br/>commands"]:::gpu
S["Original gfx1030<br/>shader bytes"]:::shader --> T["RDNA 2 decoder<br/>+ validated IR"]:::shader --> U["Metal Shading<br/>Language"]:::shader
E --> M["Native Metal<br/>pipelines"]:::gpu
U --> M
M --> G["Apple Silicon GPU<br/>+ readback"]:::gpu
G --> V{"Matches the<br/>independent<br/>CPU reference?"}:::check
S -.-> R["Independent<br/>CPU reference"]:::check -.-> V
flowchart TD
Guest["Scarlett x86-64 PE32+ Executable"]
classDef guest fill:#ddf4ff,stroke:#0969da,color:#0a3069
classDef cpu fill:#dafbe1,stroke:#1a7f37,color:#0f5323
classDef shader fill:#fbefff,stroke:#8250df,color:#512a97
classDef gpu fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef check fill:#ffebe9,stroke:#cf222e,color:#82071e
subgraph Shims["BetterXen x86-64 Wine Shims (Cross-Compiled on macOS)"]
VEH["bx_runtime_veh.dll (clwb VEH trap, JSONL trace, Lockhart cap)"]
XMem["xmem.dll (Physical/Virtual/Scatter Allocator)"]
DS["XCRDAPI.dll (DirectStorage Async I/O)"]
D3DX["d3d12_xs.dll + xg_xs.dll (Xbox D3D12 COM Proxy & RDNA2 Tiling)"]
XGR["xgameruntime.dll + GameInput.dll + Audio/DSP"]
Bridge["PSM AppNotify & ntuser Win32 Forwarders"]
end
subgraph Shaders["Shader & DXR Bridge"]
DXIL["DXIL Fast Path (SM 6.5/6.6)"]
ACCC["ACCC / FSPX RDNA2 Transpiler"]
end
subgraph External["External Foundation (User-Installed)"]
Wine["CrossOver 26.3 / Wine (Win32, CRT, XAudio2, WinHTTP)"]
Rosetta["Rosetta 2 (ROSETTA_ADVERTISE_AVX=1)"]
D3DM["D3DMetal 3.0 (D3D12 + DXR on Apple Silicon Metal)"]
end
CLI["bx-cli (Native ARM64 macOS Launcher, Probe & Telemetry)"]
Guest --> Shims
D3DX --> DXIL --> D3DM
D3DX --> ACCC --> D3DM
XMem --> Wine
DS --> Wine
XGR --> Wine
Bridge --> Wine
VEH --> Rosetta
Wine --> Rosetta
CLI -.->|"Launches, sets overrides, summarizes traces"| External
```
Legend: 🟦 guest loading · 🟩 guest CPU and services · 🟪 shader translation · 🟨 native Metal · 🟥 independent verification.
---
## Repository Layout
The repository is organized into disjoint track directories around a single frozen `abi/` contract so **5–8+ contributors (and coding agents)** can work concurrently with minimal merge conflicts.
| Directory | Track | Stack | Contents |
| --- | --- | --- | --- |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Track E | C++20 (`x86_64` PE) | Offline GDK runtime (`xgameruntime.dll`), `GameInput.dll` (`@1`), and `AcpHal.dll`/`xapu.dll`/`chad.dll` |
| [`tests/conformance/`](tests/conformance/README.md) | Track F | C++20 (`x86_64` PE) | Auto-discovered clean-room synthetic PE32+ test binaries (`test_*/CMakeLists.txt`) |
---
## Milestones
BetterXen's work order is the six [development phases](docs/development-phases.md), which lead to one concrete target: the **first launchable application** (tracker [#311](https://github.com/MacosPorters/betterxen/issues/311)). That target is an original C program, built with native ARM64 tools, that runs through the ARM64 translator, controls its own translated shader pipeline, and shows its Metal frame in the native app window. It is **not** a commercial or authentic Xbox title, and no date or percentage is attached to it.
```mermaid
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
flowchart LR
P1["<b>Phase 1</b><br/>Trustworthy baseline"]:::wip --> P2["<b>Phase 2</b><br/>Hosted C application"]:::wip
P2 --> P3["<b>Phase 3</b><br/>Coherent threading"]:::wip
P3 --> P4["<b>Phase 4</b><br/>Resource updates<br/>to translated rendering"]:::wip
P4 --> P5["<b>Phase 5</b><br/>One integrated<br/>interactive application"]:::plan
P5 --> P6["<b>Phase 6</b><br/>Measured performance"]:::plan
P2 --> L(["<b>First launchable app</b><br/>issue 311"]):::goal
P4 --> L
classDef wip fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef plan fill:#eaeef2,stroke:#8c959f,color:#24292f
classDef goal fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:3px
```
<sub>🟨 work under way · ⬜ not started · 🟩 the next original-workload target. Nothing here is independently accepted.</sub>
| Phase | Goal | State | What exists now |
| --- | --- | --- | --- |
| **1 · Baseline** | Contributors can tell what exists on `main`, what is pending review, and which checks ran | 🟡 In progress | CODEOWNERS review, a fast repository hygiene check, claim-before-work rules, generated status tables and claim audits |
| **2 · Hosted C application** | An original hosted C program starts, uses the runtime, reports results and exits with checked cleanup | 🟡 In progress | CRT startup, arguments, exit handlers, formatted output, file streams and the hosted-C fixture (A2) are integrated; a stdio follow-up is still open and the result is not independently accepted |
| **3 · Threaded behavior** | A worker-based application can block and resume without stalling other guest work | 🟡 In progress | Deterministic scheduler, guest thread contexts, guarded stacks and thread services. Guest `Sleep` still delays all guest threads (#304); worker TLS and callback lifecycle is a design draft (#312) |
| **4 · Resource updates to rendering** | A guest updates a texture and geometry, submits translated rendering and gets a checked frame | 🟡 In progress | Persistent resources, descriptor-table texture binding, translated vertex and pixel stages, blend, depth and indexed draws. Guest-selected pipelines and the typed graphics bridge are open (#314–#316) |
| **5 · Integrated interactive app** | Guest execution, rendering, input, audio, filesystem and lifecycle in one session | ⚪ Planned | Swift app with frame loop, input, audio and sandboxed filesystem fixtures exists, but those demonstrations are not guest-integration evidence |
| **6 · Measured performance** | Faster execution of workloads whose correctness is already checked | ⚪ Planned | Startup, DBT and TLS measurements recorded; bottlenecks are chosen from measurements, not assumed |
The launch milestone's proposed acceptance is **60 bounded frames containing two independently distinguishable guest-controlled states, then a clean close and one restart**. Sixty is a fixture criterion, not a measured frame rate. The work is tracked as issues [#313](https://github.com/MacosPorters/betterxen/issues/313)–[#323](https://github.com/MacosPorters/betterxen/issues/323).
<details>
<summary><b>Capability reference: the original X1–X25 map</b></summary>
The X1–X25 names are an older, broad capability map. Keep them as a reference; use the phases above for the next work order. X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence.
| Milestone | Implementation | Status |
| Milestone | Scope | Status |
| --- | --- | --- |
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | One translated `image_sample_lz` pixel stage with point/clamp sampling of RGBA8 and BC1 2D textures bound through descriptor tables, locally verified on Apple M5 Pro; upload, readback and decode of BC compressed formats (see [Texture support](#texture-support)). Other image instructions and formats are not implemented | Implemented subset |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | **Verified locally on Apple M5** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | **Open (Wave 1 backlog ready)** |
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | Planned |
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | Planned |
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | Planned |
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | Planned |
| **M6 — Cache, 16 GB Tuning & Polish** | Persistent PSO/shader disk cache, Lockhart 16 GB unified memory optimization, Metal System Trace tuning | Planned |
</details>
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
---
## Repository at a glance
Counts below come from the generated registries and were read from the repository, not measured on new runs. They describe synthetic fixtures only.
| Area | Where | What exists today |
| --- | --- | --- |
| Guest CPU | `crates/loader` | A generated x86-64 decoder and interpreter, plus a native ARM64 dynamic binary translator (DBT) for a bounded subset. The instruction registry declares 213 operations, 403 forms and 498 opcode slots; 93 operations have at least one form lowered to ARM64 and the rest run through shared interpreter semantics. See the [instruction registry](docs/cpu/instruction-registry.md). |
| Executable loading | `crates/loader` | PE32+ loading, relocations, thread-local storage, import binding and a static inspection report. |
| Runtime services | `crates/loader`, `crates/import-gen` | A typed service registry: 47 declared services (7 implemented, 37 partial, 3 stubs), all exercised through guest dispatch, none independently accepted. See the [registry](docs/runtime/registry.md) and [generated coverage](docs/runtime/services.md). Guest threads run on a deterministic scheduler on one host thread. |
| Shader ISA | `crates/isa`, `crates/decoder`, `crates/shader`, `crates/ref` | The RDNA 2 (gfx1030) instruction snapshot lists 1,465 forms; 189 are decoder-supported, 185 are lowered to Metal Shading Language, and 18 are Metal-verified on fixtures. See the [semantic coverage](docs/shaders/semantic-coverage.md). An independent CPU reference checks GPU output. |
| Metal backend | `crates/metal` | Native compute, blend, indexed-draw, depth and sampled-texture passes, with Metal API and shader validation. |
| Textures | `crates/texture` | Upload, readback, BC1 to BC7 decoding and sampler code. |
| Application | `app`, `crates/ffi` | A Swift macOS app over a versioned C interface: frame loop, interactive input, persistent resources, audio and a sandboxed virtual filesystem, all against synthetic guests. |
| Test and tooling | `tests`, `fuzz`, `benchmarks`, `scripts` | Original guest programs, independent validation, fuzz targets (CPU decode, PE parse, instruction streams, fixtures, reference, runtime services), mutation testing, correctness-gated benchmarks, and audit scripts for claims, status tables and dependency direction. |
The `betterxen` command-line tool provides `info`, `demo`, `inspect <pe>`, `probe --pe <path> --mode static`, `run`, `imports` and `shaders`. Run `cargo run -p betterxen` with no arguments to see its usage.
### Where the numbers stand
Counts come from the repository's generated registries at this revision. They describe synthetic fixtures only and are not compatibility percentages.
```mermaid
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d0d7de','pieTitleTextSize':'16px','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
pie showData title Guest CPU — 213 declared x86-64 operations
"Lowered to ARM64 (at least one native form)" : 93
"Shared interpreter semantics only" : 120
```
```mermaid
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d4a72c','pie3':'#cf222e','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
pie showData title Runtime services — 47 declared, none independently accepted
"Implemented" : 7
"Partial" : 37
"Stub" : 3
```
```mermaid
%%{init: {'theme':'base','themeVariables':{'xyChart':{'plotColorPalette':'#8250df'}}}}%%
xychart-beta
title "gfx1030 instruction forms by stage (1,465 identified)"
x-axis ["Decoder-supported", "Lowered to MSL", "Metal-verified"]
y-axis "Forms" 0 --> 200
bar [189, 185, 18]
```
---
## Native graphics translation
BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
The translation process is:
```mermaid
flowchart TD
A["Original gfx1030 Machine Code"]
B["RDNA2 ISA Decoder"]
C["Validated Shader IR"]
D["Metal Shader Generation (MSL)"]
E["Native Metal Pipeline"]
F["Apple Silicon GPU"]
G["GPU Readback"]
H["Independent CPU Validation"]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
G --> H
```
The initial implementation focused on compute shaders. X9 extends this to actual translated **vertex and fragment/pixel shader stages**.
### Translated rendering
The current graphics subset supports:
- Original gfx1030 vertex and pixel shader fixtures.
- Decoding and translation into Metal shader functions.
- Vertex position transformation.
- Constant-color output and clipping.
- Interpolated vertex attributes.
- Offscreen RGBA8 render targets.
- Native GPU readback and pixel-by-pixel validation.
- Explicit rejection of unsupported shader forms.
- Flat-coloured triangle draws with colour write masks and blending (see [Blend pass](#blend-pass)).
- Indexed triangle draws (see [Indexed draws](#indexed-draws)).
- Depth testing with an optional `Depth32Float` attachment (see [Depth pass](#depth-pass)).
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
### Blend pass
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order into an offscreen RGBA8 target. Each draw has its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max). Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations.
GPU verification (Metal API and shader validation enabled): 39 Metal-validated passes over two original overlapping triangles — a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks; and a pass whose first draw is itself blended and masked. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly.
### Indexed draws
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an offscreen RGBA8 target. A draw can sample an original BC1 texture uploaded natively.
GPU verification (Metal API and shader validation enabled): 16 Metal-validated passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules.
### Depth pass
`NativeCompute::render_depth` draws up to 16 triangles in order into an offscreen RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. Colour and the stored depth are both read back.
GPU verification (Metal API and shader validation enabled): 30 Metal-validated passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled with an attachment and no attachment at all, and a BC1-textured draw.
### Verified Apple M5 results
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled. The newer passes below are separate Metal-validated campaigns, also with Metal API and shader validation enabled.
Representative checks include:
| Test | Verified behavior |
| --- | --- |
| Constant-color rendering | 12 red pixels and 12 clear pixels |
| Vertex transformation | 3 rendered pixels versus 7 for a pass-through control |
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
| BC1 texture handling | 33 texels across selected mip levels and array layers |
| Guest rendering | PE32+ guest receives and checks the translated render output |
| Blend pass | 39 Metal-validated passes over two overlapping triangles |
| Indexed draws | 16 Metal-validated passes (both index sizes, signed base vertices, draw order) |
| Depth pass | 30 Metal-validated passes (all eight compare functions, no-attachment case) |
The expected results were calculated independently of the production shader translation path.
**Important:** Correct output for these fixtures does not prove general RDNA2 compatibility or correctness for arbitrary Xbox shaders.
## Persistent GPU resources
X9 introduces a bounded GPU resource-management system for synthetic guest programs.
The implementation includes:
- Generation-checked guest resource handles.
- Buffer creation, updates, reuse and destruction.
- Checked buffer views and memory permissions.
- Repeated compute submissions.
- Resource lifetime validation.
- Snapshot behavior for queued submissions.
- Rejection of stale handles and malformed resource requests.
- Guest-visible readback and result verification.
The original X9 PE fixtures exercise these services through the guest execution environment.
The resource system remains experimental. Native GPU work already in flight during resource release, persistent Metal texture residency across guest calls, and general asynchronous execution are not yet implemented.
## Texture support
BetterXen includes original texture upload, readback and block-compression paths.
Implemented and tested functionality includes:
- Validated mip levels and array layers.
- Pitched texture uploads.
- Block-compressed texture handling, including BC4/BC5 upload and readback and a CPU BC7 decoder for the eight modes.
- Native Metal texture readback.
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture sampling covers one instruction and one sampler mode.** A guest draw with the translated `image_sample_lz` pixel stage and a point/clamp sampler matched the software reference and hand-derived images on a local Apple M5 Pro run (one-level RGBA8 and an 8×8 BC1 texture). Other image instructions, filtering modes and formats are not implemented, and this is local verification, not independent acceptance.
The texture upload and readback paths use authored Metal kernels. They should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
Xbox-specific texture layouts and additional compression formats require further research and validation.
## Architecture
BetterXen is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
```mermaid
flowchart TD
subgraph Guest["Guest execution"]
A["Original PE32+ test program"]
B["Bounded x86-64 interpreter"]
C["Synthetic imported services"]
D["Validated GPU resources and commands"]
A --> B
B --> C
C --> D
end
subgraph Shader["RDNA2 shader translation"]
E["Original gfx1030 shader bytes"]
F["ISA decoder"]
G["Validated intermediate representation"]
H["MSL generation"]
E --> F
F --> G
G --> H
end
subgraph Metal["Native Apple Metal"]
I["Compute or render pipeline"]
J["Apple Silicon GPU"]
K["GPU readback"]
D --> I
H --> I
I --> J
J --> K
end
subgraph Validation["Correctness verification"]
L["Independent CPU reference"]
M{"Expected output matches?"}
E --> L
L --> M
K --> M
end
classDef guestNode fill:#dafbe1,stroke:#1a7f37,color:#0f5323
classDef shaderNode fill:#fbefff,stroke:#8250df,color:#512a97
classDef metalNode fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef checkNode fill:#ffebe9,stroke:#cf222e,color:#82071e
class A,B,C,D guestNode
class E,F,G,H shaderNode
class I,J,K metalNode
class L,M checkNode
```
BetterXen's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
The native ARM64 dynamic recompiler covers a bounded subset of x86-64 instructions; the rest run through the shared interpreter semantics (see the [CPU coverage map](docs/testing/cpu-coverage.md) once it lands). The project does not provide a complete Xbox operating-system implementation.
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
---
## Current limitations
BetterXen is an engineering research project, not a working commercial-game emulator.
The following remain unsupported or incomplete:
| Subsystem | Outstanding work |
| --- | --- |
| Guest CPU | Broad x86-64 instruction coverage, multithreading and performant dynamic recompilation |
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
| Graphics | Broader translated texture sampling (one instruction and sampler mode exist) and broader resource binding |
| Textures | Authentic Xbox memory layouts and broader translated sampling |
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
BetterXen's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
Progress is measured by reproducible tests rather than estimated game compatibility percentages.
---
## Building BetterXen
## Quick Start
### Requirements
- Apple Silicon Mac running native ARM64 macOS.
- Rust toolchain with `aarch64-apple-darwin` support.
- Xcode and Metal development tools.
- Python 3.11 or newer.
- LLVM with AMDGPU support for applicable shader-fixture assembly and verification.
- **Apple Silicon Mac** running native ARM64 macOS with **Rosetta 2** and **CrossOver 26.3+** (external install).
- **Rust toolchain** (`aarch64-apple-darwin`, Rust 1.85+ / 1.100.0).
- **`mingw-w64` & `cmake`** (`brew install mingw-w64 cmake`) for cross-compiling x86-64 Windows PE32+ shims on macOS.
- **Python 3.11+** for export verification and repository hygiene checks.
The recorded Apple M5 environment uses Rust 1.100.0 and Xcode 27.2.
### Clone
### Build & Verify
```sh
git clone https://github.com/MacosPorters/betterxen.git
cd betterxen
```
### Build
```sh
scripts/bootstrap.sh
cargo build --locked -p betterxen
```
### Run core tests
```sh
# 1. Build & test the native ARM64 Rust workspace (launcher + shader-transpiler)
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo build -p bx-cli
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
target/debug/bx-cli doctor
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
scripts/build-shims.sh
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
target/debug/bx-cli trace /tmp/bx-test.jsonl
# 5. Check Markdown links & repository hygiene
python3 scripts/audit/docs_hygiene.py
```
The format, lint and test trio is the standard check set. The native Metal
passes use Metal API and shader validation; `scripts/audit/status.py --check`
verifies the generated status tables.
### `bx-cli` Commands
### Run native Metal tests
These require a Metal-capable Apple Silicon Mac.
```sh
scripts/test-gpu.sh
```
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
### Verify guest execution
```sh
cargo test --locked \
--manifest-path experiments/x1/Cargo.toml \
--target aarch64-apple-darwin \
--features metal
```
Run the original guest resource integration tests:
```sh
tests/compat_fixtures/verify-resources.sh
```
Additional checks:
```sh
tests/compat_fixtures/verify.sh
tests/compat_fixtures/verify-compute.sh
scripts/assemble-fixture.sh --check
scripts/demo.sh
```
Some verification paths require additional tools. Refer to the relevant test scripts and documentation before interpreting a missing dependency as a test failure.
### Test evidence
Testing distinguishes between:
- **CPU correctness:** Independent expected values and bounded execution.
- **Shader compilation:** Decoding, lowering and valid generated Metal source.
- **Native GPU execution:** Actual GPU work and checked readback.
- **Guest integration:** Original test executables invoking GPU services and checking results.
- **Unsupported behavior:** Explicit rejections and documented missing functionality.
Compiling a shader is not equivalent to proving its GPU output is correct.
### Contributing
Contributions are welcome, and several people and coding agents work in this repository at once. To avoid duplicated work:
1. Read every comment on an issue and check for open pull requests that link it.
2. Claim the issue with a plain reply (for example "I'm taking this. Plan: ...") before you edit anything. The earliest live claim wins, and a claim is stale only after about seven days without a pull request.
3. Stay inside the files the issue lists, and put `Closes #<n>` in the pull request description.
4. Sign off every commit (DCO) and use only public documentation and original code. Anyone who has seen leaked or confidential Xbox material must not contribute.
5. Update `CHANGELOG.md` for meaningful changes. Changes to `main` need maintainer review through [CODEOWNERS](.github/CODEOWNERS).
See [CONTRIBUTING.md](CONTRIBUTING.md), [docs/legal.md](docs/legal.md) and the [documentation index](docs/README.md) for the full rules.
### Where the work is heading
See the [milestones](#milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
| Command | Purpose |
| --- | --- |
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
---
**The goal is to build a trustworthy native Apple Silicon compatibility framework, one verifiable subsystem at a time.**
## Contributing with Humans & Coding Agents
BetterXen is built for **parallel work across 5–8+ contributors and coding agents** (`AGENTS.md` — symlinked as `CLAUDE.md` — holds the full ruleset):
1. **Pick a track & claim an issue** from [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md) (or GitHub Issues using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` before coding.
2. **Isolate your branch or worktree:** `git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main`.
3. **Stay inside your issue's exclusive file scope:** Never edit another track's directory inside a feature PR. Need a new cross-DLL helper? Open a small `[ABI]` PR touching only `abi/` first.
4. **Add a conflict-free conformance test:** Drop `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories with zero edits to shared files.
5. **Run the verification commands above**, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, sign off commits (DCO `Signed-off-by`), and open a PR with `Closes #<issue>`.
See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md), and [docs/README.md](docs/README.md).
---
## Current Verified Scope & Limitations
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- **Not yet implemented (M1–M6):**
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
- `xg_xs.dll` RDNA 2 texture tiling/deswizzling and DXR/BVH4 rehydration interception.
- Console `ACCC`/`FSPX` RDNA 2 → DXIL/MSL shader transpilation (gated on M2).
- Real software audio/DSP decoding behind `AcpHal`/`xapu`/`chad` and full `GameInput` polling.
- Commercial Xbox game execution.
---
## Historical Native-First Research
The earlier paused native-first implementation (independent x86-64 interpreter/ARM64 DBT, bounded `gfx1030` RDNA 2 → MSL translator, native Metal backend, and Swift app) was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently in Git history at tag `native-first-final`.
---
## License
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [docs/legal.md](docs/legal.md) for attribution and legal scope.
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, any game publisher or Apple.
---
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, or any game publisher.
+8 -12
View File
@@ -1,17 +1,13 @@
# Third-party notices
| Component | Version | License | Origin and notice |
|---|---|---|---|
| AMD RDNA 2 machine-readable ISA | 2026-02-20, schema 1.1.1 | MIT | Generated opcode masks derive from the AMD source identified in the [RDNA 2 research notes](docs/research/rdna2.md). [AMD license and copyright](crates/isa/LICENSE-AMD). |
| bitflags | 2.13.2 | MIT selected | [Upstream revision](https://github.com/bitflags/bitflags/tree/80ce9b545acb0bd42150695fc351889cac1d8eb4), [MIT license and copyright](licenses/bitflags-LICENSE-MIT). |
| objc2 | 0.6.5 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/d7d2fa23ceaa5e6096c923b081040e5d81b3b9df), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-encode | 4.1.0 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/8d214f5477365ffcbcbb7de058c86ed9a518efb7), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-foundation | 0.3.2 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-core-foundation | 0.3.2 | MIT selected | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-metal | 0.3.2 | MIT selected | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
Cargo resolves the Rust packages from crates.io at the source checksums in [Cargo.lock](Cargo.lock). The upstream objc2 notice discusses the derivation of bindings from Apple SDKs and an open question under Apple’s SDK terms. The maintainer confirmed upstream’s published license position in [issue #895](https://github.com/madsmtm/objc2/issues/895). No Apple SDK files or dependency crate archives ship in this repository. The [upstream MIT text](licenses/objc2-LICENSE-MIT.txt) is an unmodified copy from [objc2 commit ee9a7ad](https://github.com/madsmtm/objc2/blob/ee9a7ada2131f5944b8750428e265c15632f2a19/LICENSE-MIT.txt), added after the locked source revisions. Preserve it and the pinned licensing notice. See the [G11 review](docs/licenses.md#runtime-redistribution-review) for unresolved attribution and SDK questions.
## External Host Tools & Runtime Dependencies (Never Bundled)
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
| Component | Role | Licensing & Provenance |
| --- | --- | --- |
| CrossOver / Wine | External macOS Windows compatibility runtime | Proprietary product with FOSS subcomponents; externally installed by the user and never bundled. See [docs/research/crossover-licensing.md](docs/research/crossover-licensing.md). |
| Apple D3DMetal & Rosetta 2 | External Direct3D-to-Metal and x86-64 translation | Proprietary Apple components under Apple's license terms; externally installed and never bundled. |
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
+10
View File
@@ -0,0 +1,10 @@
# BetterXen Frozen ABI Contracts (`abi/`)
This directory holds the **only shared interface boundary** across BetterXen's six parallel development tracks.
## Rules for Contributors
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
+11
View File
@@ -0,0 +1,11 @@
LIBRARY AcpHal.dll
EXPORTS
AcpHalCreate
AcpHalAllocateShapeContexts
AcpHalReleaseShapeContexts
ApuCreateHeap
ApuAlloc
ApuFree
ApuIsVirtualAddressValid
ApuMapApuAddress
ApuMapVirtualAddress
+3
View File
@@ -0,0 +1,3 @@
LIBRARY GameInput.dll
EXPORTS
GameInputCreate @1
+3
View File
@@ -0,0 +1,3 @@
LIBRARY XCRDAPI.dll
EXPORTS
DStorageGetFactory
@@ -0,0 +1,4 @@
LIBRARY api-ms-win-core-psm-appnotify-l1-1-0.dll
EXPORTS
RegisterAppStateChangeNotification
UnregisterAppStateChangeNotification
@@ -0,0 +1,4 @@
LIBRARY api-ms-win-core-psm-appnotify-l1-1-1.dll
EXPORTS
RegisterAppConstrainedChangeNotification
UnregisterAppConstrainedChangeNotification
+8
View File
@@ -0,0 +1,8 @@
LIBRARY bx_runtime_veh.dll
EXPORTS
bx_log_emit
bx_log_unimpl_api
bx_log_unimpl_vtable
bx_get_runtime_config
bx_veh_install
bx_veh_get_clwb_trap_count
+7
View File
@@ -0,0 +1,7 @@
LIBRARY chad.dll
EXPORTS
XDspActivate
XDspDeactivate
XDspConnectWithMaximumStreamLimit
XDspDisconnect
XDspSubmitCommand
+6
View File
@@ -0,0 +1,6 @@
LIBRARY d3d12_xs.dll
EXPORTS
D3D12XboxCreateDevice
D3D12ConfigureVirtualMemoryX
D3D12SerializeVersionedRootSignature
D3D12CreateRootSignatureDeserializer
@@ -0,0 +1,4 @@
LIBRARY ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll
EXPORTS
DispatchMessageA = user32.DispatchMessageA
PeekMessageA = user32.PeekMessageA
@@ -0,0 +1,3 @@
LIBRARY ext-ms-win-rtcore-ntuser-message-l1-1-0.dll
EXPORTS
TranslateMessage = user32.TranslateMessage
@@ -0,0 +1,5 @@
LIBRARY ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll
EXPORTS
CreateWindowExA = user32.CreateWindowExA
DefWindowProcA = user32.DefWindowProcA
RegisterClassExA = user32.RegisterClassExA
@@ -0,0 +1,3 @@
LIBRARY ext-ms-win-rtcore-ntuser-window-l1-1-0.dll
EXPORTS
ShowWindow = user32.ShowWindow
+7
View File
@@ -0,0 +1,7 @@
LIBRARY xapu.dll
EXPORTS
XApuConnect
XApuDisconnect
XApuEnqueueCommand
XApuDequeueResult
XApuGetResultCount
+4
View File
@@ -0,0 +1,4 @@
LIBRARY xg_xs.dll
EXPORTS
XGCreateTextureComputer
XGSuggestSwizzleMode
+45
View File
@@ -0,0 +1,45 @@
LIBRARY xgameruntime.dll
EXPORTS
XGameRuntimeInitialize
XGameRuntimeInitializeWithOptions
XGameRuntimeUninitialize
XTaskQueueCreate
XTaskQueueCloseHandle
XTaskQueueDispatch
XTaskQueueSubmitCallback
XTaskQueueGetCurrentProcessTaskQueue
XAsyncGetStatus
XAsyncGetResultSize
XAsyncCancel
XUserAddAsync
XUserAddResult
XUserCloseHandle
XUserGetId
XUserGetGamertag
XUserGetTokenAndSignatureAsync
XUserGetTokenAndSignatureResultSize
XUserGetTokenAndSignatureResult
XUserResolvePrivilegeWithUiAsync
XUserResolvePrivilegeWithUiResult
XStoreCreateContext
XStoreCloseContextHandle
XStoreQueryGameLicenseAsync
XStoreQueryGameLicenseResult
XStoreAcquireLicenseForPackageAsync
XStoreAcquireLicenseForPackageResult
XStoreAcquireLicenseForDurablesAsync
XStoreAcquireLicenseForDurablesResult
XStoreQueryEntitledProductsAsync
XStoreQueryEntitledProductsResult
XStoreQueryAssociatedProductsAsync
XStoreQueryAssociatedProductsResult
XSystemGetConsoleId
XSystemGetDeviceType
XSystemGetXboxLiveSandboxId
XPersistentLocalStorageGetPathSize
XPersistentLocalStorageGetPath
XPersistentLocalStorageGetSpaceInfo
XGameUiShowPlayerProfileCardAsync
XGameUiShowTextEntryAsync
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
XNetworkingQuerySecurityInformationForUrlAsync
+17
View File
@@ -0,0 +1,17 @@
LIBRARY xmem.dll
EXPORTS
XMemAlloc
XMemAllocDefault
XMemAllocatePhysicalPages
XMemFree
XMemFreeDefault
XMemFreePhysicalPages
XMemGetWorkingSetStatistics
XMemIsToolsMemAvailable
XMemMapPhysicalPages
XMemMapPhysicalPagesScatter
XMemTransferMemory
XMemVirtualAlloc
XMemVirtualQuery
bx_xmem_query_region
bx_xmem_get_internal_stats
+48
View File
@@ -0,0 +1,48 @@
#ifndef BETTERXEN_BX_CONFIG_H
#define BETTERXEN_BX_CONFIG_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define BX_ABI_VERSION 1u
/* Environment variables configured by bx-cli when launching under CrossOver/Wine. */
#define BX_ENV_PROFILE "BX_PROFILE" /* "lockhart" (default) | "anaconda" */
#define BX_ENV_LOG_FILE "BX_LOG_FILE" /* Path to JSONL/text trace log inside guest */
#define BX_ENV_LOG_LEVEL "BX_LOG_LEVEL" /* "error" | "warn" | "info" | "trace" */
#define BX_ENV_TRACE_D3D "BX_TRACE_D3D" /* "1" to trace every COM call */
#define BX_ENV_SHADER_DUMP_DIR "BX_SHADER_DUMP_DIR" /* Optional local dump dir for shader blobs */
#define BX_ENV_MEM_LIMIT_MB "BX_MEM_LIMIT_MB" /* Override reported title working-set cap */
#define BX_ENV_RT_MODE "BX_RT_MODE" /* "rebuild" | "bypass" */
typedef enum bx_hardware_profile {
BX_PROFILE_LOCKHART = 0, /* Series S memory budget (~8-10 GB; default on 16 GB hosts) */
BX_PROFILE_ANACONDA = 1 /* Series X memory budget (~13.5 GB; opt-in on 32 GB+ hosts) */
} bx_hardware_profile_t;
typedef enum bx_log_level {
BX_LOG_ERROR = 0,
BX_LOG_WARN = 1,
BX_LOG_INFO = 2,
BX_LOG_TRACE = 3
} bx_log_level_t;
typedef struct bx_runtime_config {
uint32_t abi_version;
bx_hardware_profile_t profile;
bx_log_level_t log_level;
uint64_t title_memory_limit_bytes;
uint32_t trace_d3d;
uint32_t enable_clwb_veh;
uint32_t enable_adx_tripwire;
uint32_t reserved;
} bx_runtime_config_t;
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_CONFIG_H */
+27
View File
@@ -0,0 +1,27 @@
#ifndef BETTERXEN_BX_LOG_H
#define BETTERXEN_BX_LOG_H
#include <stdint.h>
#include "bx_config.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Structured runtime diagnostics exported by bx_runtime_veh.dll and consumed
* by all other BetterXen shim DLLs (via dynamic lookup or import library).
*/
void bx_log_emit(bx_log_level_t level, const char* subsystem, const char* event, const char* detail);
void bx_log_unimpl_api(const char* dll_name, const char* symbol_name);
void bx_log_unimpl_vtable(const char* iface_name, uint32_t slot_index, const char* method_name);
const bx_runtime_config_t* bx_get_runtime_config(void);
#define BX_STUB_LOG(dll, sym) bx_log_unimpl_api((dll), (sym))
#define BX_VTABLE_STUB_LOG(iface, slot, method) bx_log_unimpl_vtable((iface), (slot), (method))
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_LOG_H */
+83
View File
@@ -0,0 +1,83 @@
#ifndef BETTERXEN_BX_SHADER_BRIDGE_H
#define BETTERXEN_BX_SHADER_BRIDGE_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* C ABI contract between Track C (d3d12_xs.dll) and Track D (shader-transpiler).
* Used at Create*PipelineState / CreateStateObject time to inspect shader blobs
* (DXBC+DXIL vs DXBC+ACCC/FSPX RDNA2 ISA) and translate console-compiled shaders
* into D3DMetal-consumable DXIL (or report unsupported forms cleanly).
*/
typedef enum bx_shader_kind {
BX_SHADER_UNKNOWN = 0,
BX_SHADER_DXBC_DXIL = 1, /* Standard DXIL inside DXBC container (fast path to D3DMetal) */
BX_SHADER_DXBC_LEGACY = 2, /* Legacy SM5 SHDR/SHEX inside DXBC */
BX_SHADER_DXBC_ACCC = 3, /* Console-compiled AMD RDNA2 (ACCC / FSPX) without DXIL */
BX_SHADER_DXBC_DUAL = 4 /* Contains both DXIL and ACCC chunks */
} bx_shader_kind_t;
typedef enum bx_shader_stage {
BX_STAGE_UNKNOWN = 0,
BX_STAGE_PIXEL = 1,
BX_STAGE_VERTEX = 2,
BX_STAGE_GEOM = 3,
BX_STAGE_HULL = 4,
BX_STAGE_DOMAIN = 5,
BX_STAGE_COMPUTE = 6,
BX_STAGE_LIBRARY = 7,
BX_STAGE_MESH = 8,
BX_STAGE_AMP = 9
} bx_shader_stage_t;
typedef struct bx_shader_inspection {
bx_shader_kind_t kind;
bx_shader_stage_t stage;
uint32_t shader_model_major;
uint32_t shader_model_minor;
uint32_t container_size;
uint32_t dxil_chunk_size;
uint32_t accc_chunk_size;
uint32_t has_root_signature;
uint8_t digest_hash[16]; /* DXBC header digest or SHA-like key for caching */
} bx_shader_inspection_t;
typedef enum bx_shader_status {
BX_SHADER_OK = 0,
BX_SHADER_ERR_INVALID_BLOB = 1,
BX_SHADER_ERR_UNSUPPORTED = 2,
BX_SHADER_ERR_TRANSLATE = 3,
BX_SHADER_ERR_OOM = 4
} bx_shader_status_t;
/* Inspect a raw shader bytecode blob without allocating. */
bx_shader_status_t bx_shader_inspect(
const uint8_t* bytes,
size_t len,
bx_shader_inspection_t* out_info
);
/*
* Convert an incoming console shader blob into a D3DMetal-compatible DXBC/DXIL blob.
* On BX_SHADER_OK, caller must free `*out_bytes` with `bx_shader_free_buffer`.
*/
bx_shader_status_t bx_shader_prepare_for_d3dmetal(
const uint8_t* in_bytes,
size_t in_len,
uint8_t** out_bytes,
size_t* out_len
);
void bx_shader_free_buffer(uint8_t* ptr, size_t len);
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_SHADER_BRIDGE_H */
+43
View File
@@ -0,0 +1,43 @@
#ifndef BETTERXEN_BX_XMEM_INTERNAL_H
#define BETTERXEN_BX_XMEM_INTERNAL_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Internal cross-DLL contract between Track B (xmem.dll) and Track C (d3d12_xs.dll).
* Allows d3d12_xs placed-resource and virtual-memory translation to query allocations
* created through XMemVirtualAlloc / XMemAllocatePhysicalPages / XMemMapPhysicalPages.
*/
typedef struct bx_xmem_region_info {
uint64_t base_va;
uint64_t size_bytes;
uint64_t page_size_bytes;
uint32_t protect_flags;
uint32_t mem_type_flags;
uint64_t physical_tag;
} bx_xmem_region_info_t;
typedef struct bx_xmem_stats {
uint64_t title_limit_bytes;
uint64_t committed_virtual_bytes;
uint64_t allocated_physical_bytes;
uint64_t peak_committed_bytes;
} bx_xmem_stats_t;
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_XMEM_INTERNAL_H */
-13
View File
@@ -1,13 +0,0 @@
// swift-tools-version: 6.0
// SPDX-License-Identifier: GPL-3.0-or-later
// Build with scripts/build-app.sh, which builds the Rust static library first.
import PackageDescription
let package = Package(
name: "BetterXen",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "BetterXen", dependencies: ["CXenora"], path: "Sources/Xenora"),
]
)
-5
View File
@@ -1,5 +0,0 @@
module CXenora [system] {
header "../../../crates/ffi/include/xenora.h"
link "xenora_ffi"
export *
}
-84
View File
@@ -1,84 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import AVFoundation
import Foundation
struct AudioMixMeasurement {
let frames: Int
let mean: Double
let toneAmplitude: Double
}
enum AudioMixFixtureError: Error {
case bufferAllocation
case renderFailure(AVAudioEngineManualRenderingStatus)
case shortRender
}
func measureAudioMixFixture() throws -> AudioMixMeasurement {
let outputRate = 48_000.0
let toneRate = 44_100.0
let toneFrequency = 1_000.0
let blockSize: AVAudioFrameCount = 480
let totalFrames = 4_800
guard let outputFormat = AVAudioFormat(standardFormatWithSampleRate: outputRate, channels: 1),
let toneFormat = AVAudioFormat(standardFormatWithSampleRate: toneRate, channels: 1),
let constant = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: 4_800),
let tone = AVAudioPCMBuffer(pcmFormat: toneFormat, frameCapacity: 4_410),
let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: blockSize),
let constantSamples = constant.floatChannelData?[0],
let toneSamples = tone.floatChannelData?[0],
let outputSamples = output.floatChannelData?[0] else {
throw AudioMixFixtureError.bufferAllocation
}
constant.frameLength = constant.frameCapacity
tone.frameLength = tone.frameCapacity
for index in 0..<Int(constant.frameLength) {
constantSamples[index] = 0.125
}
for index in 0..<Int(tone.frameLength) {
toneSamples[index] = Float(0.25 * sin(2 * .pi * toneFrequency * Double(index) / toneRate))
}
let engine = AVAudioEngine()
let constantPlayer = AVAudioPlayerNode()
let tonePlayer = AVAudioPlayerNode()
engine.attach(constantPlayer)
engine.attach(tonePlayer)
engine.connect(constantPlayer, to: engine.mainMixerNode, format: outputFormat)
engine.connect(tonePlayer, to: engine.mainMixerNode, format: toneFormat)
try engine.enableManualRenderingMode(.offline, format: outputFormat, maximumFrameCount: blockSize)
defer {
constantPlayer.stop()
tonePlayer.stop()
engine.stop()
engine.disableManualRenderingMode()
}
try engine.start()
constantPlayer.scheduleBuffer(constant)
tonePlayer.scheduleBuffer(tone)
constantPlayer.play()
tonePlayer.play()
var mean = 0.0
var sine = 0.0
var cosine = 0.0
var measured = 0
for first in stride(from: 0, to: totalFrames, by: Int(blockSize)) {
let status = try engine.renderOffline(blockSize, to: output)
guard status == .success else { throw AudioMixFixtureError.renderFailure(status) }
guard output.frameLength == blockSize else { throw AudioMixFixtureError.shortRender }
// Exclude the leading and trailing conversion transients.
if first == 0 || first == totalFrames - Int(blockSize) { continue }
for offset in 0..<Int(blockSize) {
let sample = Double(outputSamples[offset])
let phase = 2 * Double.pi * toneFrequency * Double(first + offset) / outputRate
mean += sample
sine += sample * sin(phase)
cosine += sample * cos(phase)
measured += 1
}
}
let count = Double(measured)
return AudioMixMeasurement(frames: totalFrames, mean: mean / count, toneAmplitude: 2 * hypot(sine, cosine) / count)
}
-61
View File
@@ -1,61 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import CXenora
import GameController
struct ControllerSnapshot: Equatable {
let buttons: UInt32
let x: Int16
let y: Int16
let leftTrigger: Float
let rightTrigger: Float
init(buttons: UInt32, x: Float, y: Float, leftTrigger: Float, rightTrigger: Float) {
self.buttons = buttons
self.x = Self.axis(x)
self.y = Self.axis(y)
self.leftTrigger = Self.trigger(leftTrigger)
self.rightTrigger = Self.trigger(rightTrigger)
}
private static func axis(_ value: Float) -> Int16 {
guard value.isFinite else { return 0 }
let deadZone: Float = 0.15
let magnitude = max(0, min(1, abs(value)) - deadZone) / (1 - deadZone)
return Int16((magnitude * (value < 0 ? -32767 : 32767)).rounded())
}
private static func trigger(_ value: Float) -> Float {
value.isFinite ? min(1, max(0, value)) : 0
}
}
struct DetectedController: Equatable {
let identity: ObjectIdentifier
let name: String
let supportsHaptics: Bool
let snapshot: ControllerSnapshot
}
@MainActor
func pollGameController() -> DetectedController? {
let controller = GCController.current.flatMap { $0.extendedGamepad == nil ? nil : $0 }
?? GCController.controllers().first { $0.extendedGamepad != nil }
guard let controller, let pad = controller.capture().extendedGamepad else { return nil }
var buttons: UInt32 = 0
if pad.dpad.right.isPressed { buttons |= UInt32(XENORA_INPUT_RIGHT) }
if pad.dpad.left.isPressed { buttons |= UInt32(XENORA_INPUT_LEFT) }
if pad.dpad.up.isPressed { buttons |= UInt32(XENORA_INPUT_UP) }
if pad.dpad.down.isPressed { buttons |= UInt32(XENORA_INPUT_DOWN) }
if pad.buttonA.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_A) }
if pad.buttonB.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_B) }
return DetectedController(
identity: ObjectIdentifier(controller),
name: controller.vendorName ?? controller.productCategory,
supportsHaptics: controller.haptics != nil,
snapshot: ControllerSnapshot(
buttons: buttons, x: pad.leftThumbstick.xAxis.value, y: pad.leftThumbstick.yAxis.value,
leftTrigger: pad.leftTrigger.value, rightTrigger: pad.rightTrigger.value
)
)
}
File diff suppressed because it is too large. Load diff
-26
View File
@@ -1,26 +0,0 @@
[package]
name = "xenora-benchmarks"
description = "Correctness-gated native Metal benchmark harness for the Phase 01 corpus"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[[bin]]
name = "xenora-bench"
path = "src/main.rs"
[dependencies]
xenora-shader = { path = "../crates/shader" }
xenora-ref = { path = "../crates/ref" }
xenora-metal = { path = "../crates/metal" }
[dev-dependencies]
xenora-isa = { path = "../crates/isa" }
[[bench]]
name = "gfx1030_identify"
harness = false
@@ -1,16 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original gfx1030 Wave32 instruction stream for metadata identification.
s_mov_b32 s12, 0x89abcdef
v_add_f32_e32 v4, v5, v9
s_cmp_lt_u32 s12, s13
ds_read_b32 v8, v2 offset:12
v_mov_b32_dpp v9, v6 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf
s_add_u32 s16, s17, s18
buffer_store_dword v7, off, s[4:7], 0
v_fma_f32 v5, v8, v10, 0x3f800003
s_movk_i32 s19, 0x2345
global_load_dword v3, v[10:11], off
v_cmp_lt_u32_e32 vcc_lo, v3, v7
s_load_dword s20, s[22:23], 0x20
v_pk_add_f16 v3, v4, v6
s_waitcnt vmcnt(0)
-143
View File
@@ -1,143 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU-only gfx1030 metadata benchmark.
//!
//! Run `cargo bench --locked -p xenora-benchmarks --bench gfx1030_identify`
//! from the repository root. Repeat the command to collect independent
//! first-pass samples. The first pass is the first identification in a fresh
//! process with the input already in memory. It does not measure process
//! startup or guarantee cold hardware caches. Repeated passes use the same
//! stream after the untimed correctness check.
//!
//! To verify the fixture bytes and instruction lengths independently, run:
//! ```sh
//! llvm-mc -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
//! -show-encoding benchmarks/benches/fixtures/gfx1030_mixed.s
//! ```
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_isa::meta::{EncodingFamily, Identified, identify};
const COPIES: usize = 4096;
const WARM_PASSES: usize = 9;
// Encodings and lengths come from llvm-mc, one row per instruction in
// fixtures/gfx1030_mixed.s. Each word is stored in little-endian order.
const FIXTURE: &[(&str, EncodingFamily, &[u32])] = {
use EncodingFamily::*;
&[
("S_MOV_B32", Sop1, &[0xbe8c03ff, 0x89abcdef]),
("V_ADD_F32", Vop2, &[0x06081305]),
("S_CMP_LT_U32", Sopc, &[0xbf0a0d0c]),
("DS_READ_B32", Ds, &[0xd8d8000c, 0x08000002]),
("V_MOV_B32", Vop1, &[0x7e1202fa, 0xff004e06]),
("S_ADD_U32", Sop2, &[0x80101211]),
("BUFFER_STORE_DWORD", Mubuf, &[0xe0700000, 0x80010700]),
("V_FMA_F32", Vop3, &[0xd54b0005, 0x03fe1508, 0x3f800003]),
("S_MOVK_I32", Sopk, &[0xb0132345]),
("GLOBAL_LOAD_DWORD", Global, &[0xdc308000, 0x037d000a]),
("V_CMP_LT_U32", Vopc, &[0x7d820f03]),
("S_LOAD_DWORD", Smem, &[0xf400050b, 0xfa000020]),
("V_PK_ADD_F16", Vop3p, &[0xcc0f4003, 0x1a020d04]),
("S_WAITCNT", Sopp, &[0xbf8c3f70]),
]
};
fn walk(stream: &[u8], mut observe: impl FnMut(usize, Identified)) -> usize {
let mut offset = 0;
let mut count = 0;
while offset < stream.len() {
let identified = identify(&stream[offset..])
.unwrap_or_else(|error| panic!("identification failed at byte {offset}: {error}"));
observe(offset, identified);
offset += identified.len;
count += 1;
}
count
}
fn verify(stream: &[u8]) {
let mut expected_offset = 0;
let mut expected = FIXTURE.iter().cycle();
let count = walk(stream, |offset, identified| {
let &(name, family, words) = expected.next().expect("fixture is nonempty");
let len = std::mem::size_of_val(words);
assert_eq!(offset, expected_offset, "byte boundary for {name}");
assert_eq!(identified.len, len, "length of {name} at byte {offset}");
assert_eq!(identified.form.name, name, "mnemonic at byte {offset}");
assert_eq!(identified.form.family, family, "family at byte {offset}");
expected_offset += len;
});
assert_eq!(expected_offset, stream.len());
assert_eq!(count, COPIES * FIXTURE.len());
}
fn measure(stream: &[u8]) -> Duration {
let start = Instant::now();
let count = walk(black_box(stream), |_, identified| {
black_box(identified);
});
let elapsed = start.elapsed();
assert_eq!(count, COPIES * FIXTURE.len());
elapsed
}
fn report(label: &str, elapsed: Duration, byte_count: usize) {
let seconds = elapsed.as_secs_f64();
let count = (COPIES * FIXTURE.len()) as f64;
println!(
"{label}: {:.3} ms, {:.2} ns/instruction, {:.2} MiB/s",
seconds * 1e3,
seconds * 1e9 / count,
byte_count as f64 / (1024.0 * 1024.0) / seconds
);
}
fn main() {
let block: Vec<u8> = FIXTURE
.iter()
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
.collect();
let stream = block.repeat(COPIES);
// 'cargo test --all-targets' checks the fixture without timing it.
if !std::env::args().any(|arg| arg == "--bench") {
verify(&stream);
return;
}
// Keep the first pass ahead of any metadata lookups. Validate the entire
// stream before reporting any timings. That validation also warms the path.
let first = measure(&stream);
verify(&stream);
let mut warm = [Duration::ZERO; WARM_PASSES];
for sample in &mut warm {
*sample = measure(&stream);
}
warm.sort_unstable();
println!(
"gfx1030 metadata identification: {} instructions, {} bytes, {} repeated passes",
COPIES * FIXTURE.len(),
stream.len(),
WARM_PASSES
);
report("First pass in a fresh process", first, stream.len());
report("Repeated minimum", warm[0], stream.len());
report("Repeated median", warm[WARM_PASSES / 2], stream.len());
report("Repeated maximum", warm[WARM_PASSES - 1], stream.len());
}
#[cfg(test)]
mod tests {
#[test]
fn mixed_llvm_fixture_preserves_names_families_lengths_and_boundaries() {
let block: Vec<u8> = super::FIXTURE
.iter()
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
.collect();
super::verify(&block.repeat(super::COPIES));
}
}
-51
View File
@@ -1,51 +0,0 @@
# Benchmark corpus for the Phase 01 correctness-gated harness.
#
# Supported subset: `[[fixture]]` tables with string and integer-array values.
# A shader is timed only after it passes correctness in the same run. `sizes`
# are word counts for the one-invocation-per-word synthetic ABI.
# See docs/testing/benchmarks.md for the protocol and metadata fields.
[[fixture]]
name = "add"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/add.bin"
input = [0, 1, 4294967295, 3989547400]
expected = [305419896, 305419897, 305419895, 0]
sizes = [4, 64, 256, 1024, 4096]
[[fixture]]
name = "bitwise-branch"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/bitwise-branch.bin"
input = [0, 1, 4294967295, 3989547400]
expected = [305419896, 305419897, 315315847, 318723824]
sizes = [4, 64, 256, 1024, 4096]
[[fixture]]
name = "float-exact"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/float-exact.bin"
input = [0, 1, 4294967295, 3989547400]
expected = [1091305472, 1091305472, 1092616192, 1092616192]
sizes = [4, 64, 256, 1024, 4096]
[[fixture]]
name = "or"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/or.bin"
input = [0, 1, 4294967295, 2153054378, 2141912917, 2147483648, 5570730]
expected = [2153054378, 2153054379, 4294967295, 2153054378, 4294967295, 2153054378, 2153054378]
sizes = [7, 64, 256, 1024, 4096]
[[fixture]]
name = "shifts"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/shifts.bin"
input = [0, 1, 2, 30, 31, 32, 33, 63, 64, 2147483648, 2147483681, 4294967295]
expected = [2, 1073741830, 536870924, 3221225474, 2147483649, 2, 1073741830, 2147483649, 2, 2, 1073741830, 2147483649]
sizes = [12, 64, 256, 1024, 4096]
@@ -1,18 +0,0 @@
{
"run_id": "run-1795338391",
"timestamp": "unix:1795338391",
"device": "Apple M5",
"host_arch": "aarch64",
"os_version": "27.3",
"os_build": "26C5047e",
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew)",
"xcode": "Xcode 27.2",
"commit": "a34dadcbc06b696eae0d7b743845f4a2c9e67996",
"profile": "release",
"api_validation": "0",
"shader_validation": "0",
"power": "Battery Power",
"thermal": "no warnings recorded",
"reps": 7,
"warmup": 2
}
@@ -1,53 +0,0 @@
# Xenora benchmark report
Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol.
## Environment
| Field | Value |
| --- | --- |
| Device | Apple M5 |
| Host arch | aarch64 |
| macOS | 27.3 |
| Build | 26C5047e |
| Rust | rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew) |
| Xcode | Xcode 27.2 |
| Commit | a34dadcbc06b696eae0d7b743845f4a2c9e67996 |
| Profile | release |
| API validation | 0 |
| Shader validation | 0 |
| Power source | Battery Power |
| Thermal | no warnings recorded |
| Repetitions | 7 measured, 2 warm-up |
> **Protocol note.** The machine was not confirmed on AC power. The [benchmark protocol](../../../../docs/testing/benchmarks.md) requires AC power, so these timings are not protocol-compliant release evidence.
## Coverage
| Fixture | Stage | Source | Status |
| --- | --- | --- | --- |
| add | compute | translated-rdna | benchmarked |
| bitwise-branch | compute | translated-rdna | benchmarked |
| float-exact | compute | translated-rdna | benchmarked |
## Timings
Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, `library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer GPU time, and `host` is the wall time of one dispatch. Values are medians with interquartile range; minimum and maximum are in `results.json`.
| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| add | 4 | 5.42 | 15.04 | 36.33 | 6.08 | 525.50 | 0.29 | 0% |
| add | 64 | 4.54 | 11.83 | 28.17 | 6.08 | 529.92 | 0.06 | 0% |
| add | 256 | 4.46 | 11.42 | 27.33 | 5.88 | 519.17 | 0.19 | 0% |
| add | 1024 | 4.42 | 11.21 | 26.88 | 6.12 | 524.38 | 0.13 | 0% |
| add | 4096 | 4.38 | 11.17 | 27.92 | 6.25 | 523.58 | 0.08 | 0% |
| bitwise-branch | 4 | 11.38 | 13.00 | 28.96 | 6.12 | 509.37 | 0.00 | 0% |
| bitwise-branch | 64 | 7.75 | 11.33 | 26.92 | 6.12 | 526.50 | 0.02 | 0% |
| bitwise-branch | 256 | 7.71 | 11.21 | 26.62 | 6.00 | 513.71 | 0.02 | 0% |
| bitwise-branch | 1024 | 7.54 | 11.25 | 26.58 | 6.25 | 519.62 | 0.02 | 0% |
| bitwise-branch | 4096 | 7.58 | 11.21 | 27.25 | 6.21 | 523.33 | 0.04 | 0% |
| float-exact | 4 | 9.12 | 12.08 | 27.12 | 6.17 | 510.67 | 0.10 | 0% |
| float-exact | 64 | 8.58 | 11.46 | 26.50 | 6.04 | 523.79 | 0.06 | 0% |
| float-exact | 256 | 8.58 | 11.12 | 26.46 | 6.04 | 514.92 | 0.08 | 0% |
| float-exact | 1024 | 8.67 | 11.12 | 26.29 | 6.21 | 520.67 | 0.08 | 0% |
| float-exact | 4096 | 8.67 | 11.17 | 26.46 | 6.25 | 514.67 | 0.08 | 0% |
@@ -1,46 +0,0 @@
{
"fixtures": [
{
"name": "add",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 5.417000000e-6, "min": 4.875000000e-6, "max": 7.833000000e-6, "q1": 4.979500000e-6, "q3": 6.250500000e-6, "reps": 7 }, "library": { "median": 1.504200000e-5, "min": 1.254200000e-5, "max": 2.141700000e-5, "q1": 1.339600000e-5, "q3": 1.706300000e-5, "reps": 7 }, "pipeline": { "median": 3.633300000e-5, "min": 3.175000000e-5, "max": 4.900000000e-5, "q1": 3.245800000e-5, "q3": 4.106200000e-5, "reps": 7 }, "gpu": { "median": 6.083333574e-6, "min": 5.791662261e-6, "max": 6.125002983e-6, "q1": 5.833335308e-6, "q3": 6.124995707e-6, "reps": 7 }, "host": { "median": 5.255000000e-4, "min": 5.083750000e-4, "max": 5.870000000e-4, "q1": 5.120210000e-4, "q3": 5.354790000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 4.542000000e-6, "min": 4.417000000e-6, "max": 4.584000000e-6, "q1": 4.500000000e-6, "q3": 4.562500000e-6, "reps": 7 }, "library": { "median": 1.183300000e-5, "min": 1.158300000e-5, "max": 1.204200000e-5, "q1": 1.172900000e-5, "q3": 1.191650000e-5, "reps": 7 }, "pipeline": { "median": 2.816700000e-5, "min": 2.779200000e-5, "max": 3.250000000e-5, "q1": 2.814550000e-5, "q3": 2.933350000e-5, "reps": 7 }, "gpu": { "median": 6.083333574e-6, "min": 5.750000128e-6, "max": 6.125002983e-6, "q1": 6.041664165e-6, "q3": 6.104164640e-6, "reps": 7 }, "host": { "median": 5.299160000e-4, "min": 4.869160000e-4, "max": 5.916250000e-4, "q1": 5.180835000e-4, "q3": 5.309585000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 4.459000000e-6, "min": 4.375000000e-6, "max": 7.542000000e-6, "q1": 4.458000000e-6, "q3": 4.521000000e-6, "reps": 7 }, "library": { "median": 1.141700000e-5, "min": 1.120900000e-5, "max": 1.412500000e-5, "q1": 1.133350000e-5, "q3": 1.147900000e-5, "reps": 7 }, "pipeline": { "median": 2.733400000e-5, "min": 2.695800000e-5, "max": 2.758400000e-5, "q1": 2.706250000e-5, "q3": 2.750000000e-5, "reps": 7 }, "gpu": { "median": 5.875001079e-6, "min": 5.750000128e-6, "max": 6.000002031e-6, "q1": 5.791665899e-6, "q3": 5.979163689e-6, "reps": 7 }, "host": { "median": 5.191670000e-4, "min": 5.010000000e-4, "max": 5.346670000e-4, "q1": 5.137080000e-4, "q3": 5.276670000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 4.417000000e-6, "min": 4.250000000e-6, "max": 7.583000000e-6, "q1": 4.354500000e-6, "q3": 4.521000000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.091700000e-5, "max": 1.300000000e-5, "q1": 1.110400000e-5, "q3": 1.129150000e-5, "reps": 7 }, "pipeline": { "median": 2.687500000e-5, "min": 2.666600000e-5, "max": 3.350000000e-5, "q1": 2.670800000e-5, "q3": 2.716650000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.041664165e-6, "max": 6.208334526e-6, "q1": 6.062498869e-6, "q3": 6.187499821e-6, "reps": 7 }, "host": { "median": 5.243750000e-4, "min": 4.802500000e-4, "max": 6.343750000e-4, "q1": 5.193130000e-4, "q3": 5.442295000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 4.375000000e-6, "min": 4.250000000e-6, "max": 4.500000000e-6, "q1": 4.333000000e-6, "q3": 4.416500000e-6, "reps": 7 }, "library": { "median": 1.116600000e-5, "min": 1.095800000e-5, "max": 1.145900000e-5, "q1": 1.106250000e-5, "q3": 1.120800000e-5, "reps": 7 }, "pipeline": { "median": 2.791700000e-5, "min": 2.716700000e-5, "max": 3.229100000e-5, "q1": 2.743700000e-5, "q3": 2.833300000e-5, "reps": 7 }, "gpu": { "median": 6.249996659e-6, "min": 6.125002983e-6, "max": 6.250003935e-6, "q1": 6.166665116e-6, "q3": 6.250000297e-6, "reps": 7 }, "host": { "median": 5.235830000e-4, "min": 5.008330000e-4, "max": 5.484590000e-4, "q1": 5.165830000e-4, "q3": 5.246875000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "bitwise-branch",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 1.137500000e-5, "min": 8.125000000e-6, "max": 1.562500000e-5, "q1": 8.875000000e-6, "q3": 1.214650000e-5, "reps": 7 }, "library": { "median": 1.300000000e-5, "min": 1.150000000e-5, "max": 2.495800000e-5, "q1": 1.214600000e-5, "q3": 1.556200000e-5, "reps": 7 }, "pipeline": { "median": 2.895800000e-5, "min": 2.704200000e-5, "max": 5.566600000e-5, "q1": 2.762500000e-5, "q3": 3.600050000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.083333574e-6, "max": 6.208334526e-6, "q1": 6.124995707e-6, "q3": 6.125002983e-6, "reps": 7 }, "host": { "median": 5.093750000e-4, "min": 4.334590000e-4, "max": 5.999590000e-4, "q1": 4.986045000e-4, "q3": 5.409170000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 7.750000000e-6, "min": 7.542000000e-6, "max": 7.917000000e-6, "q1": 7.625000000e-6, "q3": 7.771000000e-6, "reps": 7 }, "library": { "median": 1.133300000e-5, "min": 1.100000000e-5, "max": 1.158300000e-5, "q1": 1.127100000e-5, "q3": 1.141650000e-5, "reps": 7 }, "pipeline": { "median": 2.691600000e-5, "min": 2.641700000e-5, "max": 2.754200000e-5, "q1": 2.679150000e-5, "q3": 2.706200000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.000002031e-6, "max": 6.166665116e-6, "q1": 6.104164640e-6, "q3": 6.125002983e-6, "reps": 7 }, "host": { "median": 5.265000000e-4, "min": 4.912500000e-4, "max": 5.496250000e-4, "q1": 5.206460000e-4, "q3": 5.289170000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 7.708000000e-6, "min": 7.583000000e-6, "max": 7.917000000e-6, "q1": 7.625000000e-6, "q3": 7.771000000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.091600000e-5, "max": 1.170900000e-5, "q1": 1.104150000e-5, "q3": 1.127100000e-5, "reps": 7 }, "pipeline": { "median": 2.662500000e-5, "min": 2.637500000e-5, "max": 2.679100000e-5, "q1": 2.652050000e-5, "q3": 2.666650000e-5, "reps": 7 }, "gpu": { "median": 6.000002031e-6, "min": 5.999994755e-6, "max": 6.124995707e-6, "q1": 6.000002031e-6, "q3": 6.020833098e-6, "reps": 7 }, "host": { "median": 5.137080000e-4, "min": 5.058750000e-4, "max": 5.431250000e-4, "q1": 5.129375000e-4, "q3": 5.265415000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 7.542000000e-6, "min": 7.416000000e-6, "max": 1.337500000e-5, "q1": 7.458500000e-6, "q3": 7.645500000e-6, "reps": 7 }, "library": { "median": 1.125000000e-5, "min": 1.091700000e-5, "max": 1.137500000e-5, "q1": 1.100000000e-5, "q3": 1.127100000e-5, "reps": 7 }, "pipeline": { "median": 2.658300000e-5, "min": 2.641700000e-5, "max": 2.945900000e-5, "q1": 2.652100000e-5, "q3": 2.668750000e-5, "reps": 7 }, "gpu": { "median": 6.250003935e-6, "min": 6.166665116e-6, "max": 6.250003935e-6, "q1": 6.229165592e-6, "q3": 6.250003935e-6, "reps": 7 }, "host": { "median": 5.196250000e-4, "min": 4.705420000e-4, "max": 5.796250000e-4, "q1": 4.989585000e-4, "q3": 5.451670000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 7.583000000e-6, "min": 7.458000000e-6, "max": 7.625000000e-6, "q1": 7.541500000e-6, "q3": 7.604500000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.100000000e-5, "max": 1.129200000e-5, "q1": 1.114600000e-5, "q3": 1.127050000e-5, "reps": 7 }, "pipeline": { "median": 2.725000000e-5, "min": 2.645900000e-5, "max": 3.054200000e-5, "q1": 2.693750000e-5, "q3": 2.866700000e-5, "reps": 7 }, "gpu": { "median": 6.208334526e-6, "min": 6.166672392e-6, "max": 6.333335477e-6, "q1": 6.208330888e-6, "q3": 6.250003935e-6, "reps": 7 }, "host": { "median": 5.233330000e-4, "min": 4.921660000e-4, "max": 5.424170000e-4, "q1": 5.017080000e-4, "q3": 5.346455000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "float-exact",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 9.125000000e-6, "min": 8.667000000e-6, "max": 1.658300000e-5, "q1": 8.812500000e-6, "q3": 1.385400000e-5, "reps": 7 }, "library": { "median": 1.208400000e-5, "min": 1.141600000e-5, "max": 1.837500000e-5, "q1": 1.166650000e-5, "q3": 1.229150000e-5, "reps": 7 }, "pipeline": { "median": 2.712500000e-5, "min": 2.662500000e-5, "max": 2.866700000e-5, "q1": 2.677050000e-5, "q3": 2.743750000e-5, "reps": 7 }, "gpu": { "median": 6.166665116e-6, "min": 5.958332622e-6, "max": 6.250003935e-6, "q1": 6.125002983e-6, "q3": 6.229165592e-6, "reps": 7 }, "host": { "median": 5.106660000e-4, "min": 4.910840000e-4, "max": 6.143750000e-4, "q1": 5.022500000e-4, "q3": 5.370625000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 8.583000000e-6, "min": 8.541000000e-6, "max": 1.425000000e-5, "q1": 8.583000000e-6, "q3": 8.687500000e-6, "reps": 7 }, "library": { "median": 1.145800000e-5, "min": 1.116700000e-5, "max": 1.187500000e-5, "q1": 1.131200000e-5, "q3": 1.164600000e-5, "reps": 7 }, "pipeline": { "median": 2.650000000e-5, "min": 2.620800000e-5, "max": 2.725000000e-5, "q1": 2.631300000e-5, "q3": 2.700000000e-5, "reps": 7 }, "gpu": { "median": 6.041671440e-6, "min": 5.916670489e-6, "max": 6.125002983e-6, "q1": 6.041664165e-6, "q3": 6.104164640e-6, "reps": 7 }, "host": { "median": 5.237920000e-4, "min": 4.042920000e-4, "max": 5.358750000e-4, "q1": 5.191665000e-4, "q3": 5.336665000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 8.583000000e-6, "min": 8.500000000e-6, "max": 8.834000000e-6, "q1": 8.562000000e-6, "q3": 8.708500000e-6, "reps": 7 }, "library": { "median": 1.112500000e-5, "min": 1.091600000e-5, "max": 1.129200000e-5, "q1": 1.110450000e-5, "q3": 1.120850000e-5, "reps": 7 }, "pipeline": { "median": 2.645900000e-5, "min": 2.629200000e-5, "max": 2.658400000e-5, "q1": 2.641650000e-5, "q3": 2.652100000e-5, "reps": 7 }, "gpu": { "median": 6.041664165e-6, "min": 5.999994755e-6, "max": 6.083333574e-6, "q1": 6.000002031e-6, "q3": 6.083333574e-6, "reps": 7 }, "host": { "median": 5.149170000e-4, "min": 5.000000000e-4, "max": 5.907500000e-4, "q1": 5.053955000e-4, "q3": 5.300000000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 8.667000000e-6, "min": 8.500000000e-6, "max": 8.792000000e-6, "q1": 8.583500000e-6, "q3": 8.791500000e-6, "reps": 7 }, "library": { "median": 1.112500000e-5, "min": 1.104100000e-5, "max": 1.120900000e-5, "q1": 1.106250000e-5, "q3": 1.114600000e-5, "reps": 7 }, "pipeline": { "median": 2.629200000e-5, "min": 2.612500000e-5, "max": 2.637500000e-5, "q1": 2.625000000e-5, "q3": 2.635400000e-5, "reps": 7 }, "gpu": { "median": 6.208327250e-6, "min": 6.000002031e-6, "max": 6.250003935e-6, "q1": 6.145830412e-6, "q3": 6.229169230e-6, "reps": 7 }, "host": { "median": 5.206670000e-4, "min": 5.023330000e-4, "max": 5.300840000e-4, "q1": 5.051045000e-4, "q3": 5.258955000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 8.667000000e-6, "min": 8.458000000e-6, "max": 8.750000000e-6, "q1": 8.542000000e-6, "q3": 8.687500000e-6, "reps": 7 }, "library": { "median": 1.116700000e-5, "min": 1.100000000e-5, "max": 1.133400000e-5, "q1": 1.108350000e-5, "q3": 1.125000000e-5, "reps": 7 }, "pipeline": { "median": 2.645800000e-5, "min": 2.595900000e-5, "max": 2.691600000e-5, "q1": 2.641700000e-5, "q3": 2.658350000e-5, "reps": 7 }, "gpu": { "median": 6.250003935e-6, "min": 6.166665116e-6, "max": 6.375004887e-6, "q1": 6.250000297e-6, "q3": 6.333331839e-6, "reps": 7 }, "host": { "median": 5.146670000e-4, "min": 4.975000000e-4, "max": 5.337500000e-4, "q1": 5.105415000e-4, "q3": 5.209795000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
]
}
]
}
@@ -1,18 +0,0 @@
{
"run_id": "run-1795352394",
"timestamp": "unix:1795352394",
"device": "Apple M5",
"host_arch": "aarch64",
"os_version": "27.3",
"os_build": "26C5047e",
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew)",
"xcode": "Xcode 27.2",
"commit": "cc0daa79e63c468e748f0333bd1314224752893a",
"profile": "release",
"api_validation": "0",
"shader_validation": "0",
"power": "AC Power",
"thermal": "no warnings recorded",
"reps": 21,
"warmup": 2
}
@@ -1,51 +0,0 @@
# Xenora benchmark report
Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol.
## Environment
| Field | Value |
| --- | --- |
| Device | Apple M5 |
| Host arch | aarch64 |
| macOS | 27.3 |
| Build | 26C5047e |
| Rust | rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew) |
| Xcode | Xcode 27.2 |
| Commit | cc0daa79e63c468e748f0333bd1314224752893a |
| Profile | release |
| API validation | 0 |
| Shader validation | 0 |
| Power source | AC Power |
| Thermal | no warnings recorded |
| Repetitions | 21 measured, 2 warm-up |
## Coverage
| Fixture | Stage | Source | Status |
| --- | --- | --- | --- |
| add | compute | translated-rdna | benchmarked |
| bitwise-branch | compute | translated-rdna | benchmarked |
| float-exact | compute | translated-rdna | benchmarked |
## Timings
Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, `library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer GPU time, and `host` is the wall time of one dispatch. Values are medians with interquartile range; minimum and maximum are in `results.json`.
| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| add | 4 | 5.08 | 13.42 | 32.50 | 87.62 | 375.33 | 103.62 | 0% |
| add | 64 | 4.42 | 11.79 | 28.25 | 3.63 | 407.79 | 36.54 | 0% |
| add | 256 | 4.17 | 10.96 | 26.79 | 1.38 | 231.25 | 2.25 | 0% |
| add | 1024 | 4.25 | 11.17 | 26.54 | 1.46 | 218.25 | 0.08 | 0% |
| add | 4096 | 4.46 | 11.67 | 27.62 | 3.38 | 237.71 | 17.63 | 0% |
| bitwise-branch | 4 | 7.71 | 11.04 | 26.29 | 1.33 | 214.29 | 0.08 | 0% |
| bitwise-branch | 64 | 8.71 | 11.92 | 27.83 | 2.08 | 213.12 | 4.25 | 0% |
| bitwise-branch | 256 | 7.58 | 10.71 | 26.00 | 1.37 | 216.38 | 0.04 | 0% |
| bitwise-branch | 1024 | 7.62 | 10.67 | 26.08 | 1.42 | 212.58 | 0.08 | 0% |
| bitwise-branch | 4096 | 7.62 | 11.12 | 26.58 | 1.58 | 236.17 | 25.75 | 0% |
| float-exact | 4 | 8.54 | 10.88 | 25.62 | 1.33 | 212.00 | 0.08 | 0% |
| float-exact | 64 | 8.71 | 11.00 | 26.21 | 1.38 | 215.33 | 1.25 | 0% |
| float-exact | 256 | 8.62 | 10.83 | 25.83 | 1.37 | 213.88 | 0.08 | 0% |
| float-exact | 1024 | 8.54 | 11.00 | 25.92 | 1.50 | 213.67 | 0.04 | 0% |
| float-exact | 4096 | 8.54 | 10.88 | 26.04 | 1.50 | 228.00 | 30.25 | 0% |
@@ -1,46 +0,0 @@
{
"fixtures": [
{
"name": "add",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 5.083000000e-6, "min": 4.167000000e-6, "max": 4.425000000e-5, "q1": 4.375000000e-6, "q3": 7.458000000e-6, "reps": 21 }, "library": { "median": 1.341700000e-5, "min": 1.087500000e-5, "max": 3.879200000e-5, "q1": 1.150000000e-5, "q3": 1.762500000e-5, "reps": 21 }, "pipeline": { "median": 3.250000000e-5, "min": 2.666700000e-5, "max": 5.920800000e-5, "q1": 2.979200000e-5, "q3": 4.262500000e-5, "reps": 21 }, "gpu": { "median": 8.762499965e-5, "min": 5.625000085e-6, "max": 2.230416667e-4, "q1": 1.562500074e-5, "q3": 1.192500004e-4, "reps": 21 }, "host": { "median": 3.753330000e-4, "min": 2.814590000e-4, "max": 5.746250000e-4, "q1": 3.609170000e-4, "q3": 4.326250000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 4.416000000e-6, "min": 4.083000000e-6, "max": 5.792000000e-6, "q1": 4.292000000e-6, "q3": 4.542000000e-6, "reps": 21 }, "library": { "median": 1.179100000e-5, "min": 1.075000000e-5, "max": 1.741600000e-5, "q1": 1.116700000e-5, "q3": 1.312500000e-5, "reps": 21 }, "pipeline": { "median": 2.825000000e-5, "min": 2.591700000e-5, "max": 3.758400000e-5, "q1": 2.770800000e-5, "q3": 3.100000000e-5, "reps": 21 }, "gpu": { "median": 3.625000318e-6, "min": 3.125000148e-6, "max": 3.708750000e-4, "q1": 3.208333510e-6, "q3": 3.974999981e-5, "reps": 21 }, "host": { "median": 4.077910000e-4, "min": 2.125000000e-4, "max": 8.305420000e-4, "q1": 3.319170000e-4, "q3": 4.473340000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 4.167000000e-6, "min": 4.083000000e-6, "max": 4.333000000e-6, "q1": 4.166000000e-6, "q3": 4.208000000e-6, "reps": 21 }, "library": { "median": 1.095800000e-5, "min": 1.054200000e-5, "max": 1.154200000e-5, "q1": 1.062500000e-5, "q3": 1.116600000e-5, "reps": 21 }, "pipeline": { "median": 2.679200000e-5, "min": 2.583400000e-5, "max": 3.391600000e-5, "q1": 2.612500000e-5, "q3": 2.716600000e-5, "reps": 21 }, "gpu": { "median": 1.375000465e-6, "min": 1.291666194e-6, "max": 5.875000170e-6, "q1": 1.374999556e-6, "q3": 3.625000318e-6, "reps": 21 }, "host": { "median": 2.312500000e-4, "min": 2.123750000e-4, "max": 7.405830000e-4, "q1": 2.190830000e-4, "q3": 6.997080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 4.250000000e-6, "min": 4.083000000e-6, "max": 6.292000000e-6, "q1": 4.167000000e-6, "q3": 4.333000000e-6, "reps": 21 }, "library": { "median": 1.116700000e-5, "min": 1.054200000e-5, "max": 1.583400000e-5, "q1": 1.075000000e-5, "q3": 1.133300000e-5, "reps": 21 }, "pipeline": { "median": 2.654200000e-5, "min": 2.566700000e-5, "max": 3.695800000e-5, "q1": 2.583300000e-5, "q3": 2.758300000e-5, "reps": 21 }, "gpu": { "median": 1.458333827e-6, "min": 1.375000465e-6, "max": 5.999999303e-6, "q1": 1.416667146e-6, "q3": 1.500000508e-6, "reps": 21 }, "host": { "median": 2.182500000e-4, "min": 2.122920000e-4, "max": 5.624590000e-4, "q1": 2.162090000e-4, "q3": 2.354590000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 4.458000000e-6, "min": 4.125000000e-6, "max": 1.104100000e-5, "q1": 4.250000000e-6, "q3": 4.833000000e-6, "reps": 21 }, "library": { "median": 1.166700000e-5, "min": 1.083300000e-5, "max": 7.970800000e-5, "q1": 1.120900000e-5, "q3": 1.337500000e-5, "reps": 21 }, "pipeline": { "median": 2.762500000e-5, "min": 2.645800000e-5, "max": 7.595800000e-5, "q1": 2.683300000e-5, "q3": 3.045800000e-5, "reps": 21 }, "gpu": { "median": 3.375000233e-6, "min": 1.375000465e-6, "max": 3.787499918e-5, "q1": 1.499999598e-6, "q3": 1.912500011e-5, "reps": 21 }, "host": { "median": 2.377080000e-4, "min": 2.014170000e-4, "max": 5.690830000e-4, "q1": 2.298750000e-4, "q3": 3.332910000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "bitwise-branch",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 7.709000000e-6, "min": 7.416000000e-6, "max": 1.133300000e-5, "q1": 7.542000000e-6, "q3": 8.083000000e-6, "reps": 21 }, "library": { "median": 1.104100000e-5, "min": 1.054100000e-5, "max": 1.454200000e-5, "q1": 1.079200000e-5, "q3": 1.112500000e-5, "reps": 21 }, "pipeline": { "median": 2.629200000e-5, "min": 2.554100000e-5, "max": 3.658400000e-5, "q1": 2.612500000e-5, "q3": 2.637500000e-5, "reps": 21 }, "gpu": { "median": 1.333332875e-6, "min": 1.291666194e-6, "max": 1.926666664e-4, "q1": 1.291667104e-6, "q3": 1.374999556e-6, "reps": 21 }, "host": { "median": 2.142920000e-4, "min": 2.040840000e-4, "max": 4.722500000e-4, "q1": 2.110840000e-4, "q3": 2.197500000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 8.708000000e-6, "min": 7.584000000e-6, "max": 4.979100000e-5, "q1": 7.834000000e-6, "q3": 1.245800000e-5, "reps": 21 }, "library": { "median": 1.191700000e-5, "min": 1.075000000e-5, "max": 7.475000000e-5, "q1": 1.141700000e-5, "q3": 1.362500000e-5, "reps": 21 }, "pipeline": { "median": 2.783400000e-5, "min": 2.591700000e-5, "max": 5.308300000e-5, "q1": 2.716700000e-5, "q3": 2.954100000e-5, "reps": 21 }, "gpu": { "median": 2.083333129e-6, "min": 1.249999514e-6, "max": 4.854166673e-5, "q1": 1.333333785e-6, "q3": 5.583333405e-6, "reps": 21 }, "host": { "median": 2.131250000e-4, "min": 1.608750000e-4, "max": 4.971250000e-4, "q1": 1.936660000e-4, "q3": 2.450420000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 7.583000000e-6, "min": 7.416000000e-6, "max": 7.750000000e-6, "q1": 7.500000000e-6, "q3": 7.625000000e-6, "reps": 21 }, "library": { "median": 1.070900000e-5, "min": 1.050000000e-5, "max": 1.104100000e-5, "q1": 1.062500000e-5, "q3": 1.079200000e-5, "reps": 21 }, "pipeline": { "median": 2.600000000e-5, "min": 2.541700000e-5, "max": 2.670800000e-5, "q1": 2.583300000e-5, "q3": 2.625000000e-5, "reps": 21 }, "gpu": { "median": 1.374999556e-6, "min": 1.291666194e-6, "max": 1.458333827e-6, "q1": 1.333332875e-6, "q3": 1.375000465e-6, "reps": 21 }, "host": { "median": 2.163750000e-4, "min": 2.042920000e-4, "max": 2.393750000e-4, "q1": 2.125830000e-4, "q3": 2.197080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 7.625000000e-6, "min": 7.500000000e-6, "max": 7.875000000e-6, "q1": 7.500000000e-6, "q3": 7.625000000e-6, "reps": 21 }, "library": { "median": 1.066700000e-5, "min": 1.050000000e-5, "max": 1.091700000e-5, "q1": 1.058400000e-5, "q3": 1.083400000e-5, "reps": 21 }, "pipeline": { "median": 2.608300000e-5, "min": 2.533300000e-5, "max": 3.291700000e-5, "q1": 2.558300000e-5, "q3": 2.620800000e-5, "reps": 21 }, "gpu": { "median": 1.416667146e-6, "min": 1.374999556e-6, "max": 9.749999663e-6, "q1": 1.375000465e-6, "q3": 1.458332918e-6, "reps": 21 }, "host": { "median": 2.125830000e-4, "min": 1.951250000e-4, "max": 4.068340000e-4, "q1": 2.102090000e-4, "q3": 2.148750000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 7.625000000e-6, "min": 7.417000000e-6, "max": 3.583300000e-5, "q1": 7.584000000e-6, "q3": 8.375000000e-6, "reps": 21 }, "library": { "median": 1.112500000e-5, "min": 1.062500000e-5, "max": 4.820800000e-5, "q1": 1.079200000e-5, "q3": 1.212500000e-5, "reps": 21 }, "pipeline": { "median": 2.658400000e-5, "min": 2.570900000e-5, "max": 1.125830000e-4, "q1": 2.595800000e-5, "q3": 2.954200000e-5, "reps": 21 }, "gpu": { "median": 1.583332960e-6, "min": 1.374999556e-6, "max": 6.262500028e-5, "q1": 1.416667146e-6, "q3": 2.716666677e-5, "reps": 21 }, "host": { "median": 2.361670000e-4, "min": 1.970840000e-4, "max": 5.112080000e-4, "q1": 2.251670000e-4, "q3": 2.410000000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "float-exact",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.233400000e-5, "q1": 8.417000000e-6, "q3": 8.875000000e-6, "reps": 21 }, "library": { "median": 1.087500000e-5, "min": 1.050000000e-5, "max": 1.500000000e-5, "q1": 1.079100000e-5, "q3": 1.120800000e-5, "reps": 21 }, "pipeline": { "median": 2.562500000e-5, "min": 2.520900000e-5, "max": 3.454100000e-5, "q1": 2.554200000e-5, "q3": 2.575000000e-5, "reps": 21 }, "gpu": { "median": 1.333333785e-6, "min": 1.291666194e-6, "max": 1.797083332e-4, "q1": 1.291667104e-6, "q3": 1.374999556e-6, "reps": 21 }, "host": { "median": 2.120000000e-4, "min": 2.052920000e-4, "max": 4.474160000e-4, "q1": 2.097500000e-4, "q3": 2.153330000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 8.708000000e-6, "min": 8.416000000e-6, "max": 3.125000000e-5, "q1": 8.500000000e-6, "q3": 9.625000000e-6, "reps": 21 }, "library": { "median": 1.100000000e-5, "min": 1.058400000e-5, "max": 5.441600000e-5, "q1": 1.075000000e-5, "q3": 1.225000000e-5, "reps": 21 }, "pipeline": { "median": 2.620800000e-5, "min": 2.516700000e-5, "max": 7.550000000e-5, "q1": 2.533300000e-5, "q3": 2.858300000e-5, "reps": 21 }, "gpu": { "median": 1.375000465e-6, "min": 1.291666194e-6, "max": 4.275000083e-5, "q1": 1.375000465e-6, "q3": 2.625000889e-6, "reps": 21 }, "host": { "median": 2.153330000e-4, "min": 1.642920000e-4, "max": 4.004580000e-4, "q1": 2.005830000e-4, "q3": 2.202080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 8.625000000e-6, "min": 8.208000000e-6, "max": 8.750000000e-6, "q1": 8.459000000e-6, "q3": 8.667000000e-6, "reps": 21 }, "library": { "median": 1.083400000e-5, "min": 1.066700000e-5, "max": 1.120900000e-5, "q1": 1.075000000e-5, "q3": 1.104200000e-5, "reps": 21 }, "pipeline": { "median": 2.583300000e-5, "min": 2.504200000e-5, "max": 3.329200000e-5, "q1": 2.529100000e-5, "q3": 2.595900000e-5, "reps": 21 }, "gpu": { "median": 1.374999556e-6, "min": 1.291666194e-6, "max": 7.387500045e-5, "q1": 1.291666194e-6, "q3": 1.375000465e-6, "reps": 21 }, "host": { "median": 2.138750000e-4, "min": 1.780830000e-4, "max": 2.769590000e-4, "q1": 1.977920000e-4, "q3": 2.193750000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.145900000e-5, "q1": 8.458000000e-6, "q3": 8.666000000e-6, "reps": 21 }, "library": { "median": 1.100000000e-5, "min": 1.062500000e-5, "max": 1.925000000e-5, "q1": 1.083400000e-5, "q3": 1.108300000e-5, "reps": 21 }, "pipeline": { "median": 2.591600000e-5, "min": 2.516700000e-5, "max": 3.541700000e-5, "q1": 2.579200000e-5, "q3": 2.612500000e-5, "reps": 21 }, "gpu": { "median": 1.499999598e-6, "min": 1.374999556e-6, "max": 1.624999641e-6, "q1": 1.458332918e-6, "q3": 1.500000508e-6, "reps": 21 }, "host": { "median": 2.136670000e-4, "min": 1.936670000e-4, "max": 4.228330000e-4, "q1": 2.092920000e-4, "q3": 2.170420000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.158300000e-5, "q1": 8.459000000e-6, "q3": 8.750000000e-6, "reps": 21 }, "library": { "median": 1.087500000e-5, "min": 1.066700000e-5, "max": 3.562500000e-5, "q1": 1.083400000e-5, "q3": 1.145800000e-5, "reps": 21 }, "pipeline": { "median": 2.604200000e-5, "min": 2.508300000e-5, "max": 1.914590000e-4, "q1": 2.550000000e-5, "q3": 2.625000000e-5, "reps": 21 }, "gpu": { "median": 1.500000508e-6, "min": 1.416666237e-6, "max": 6.304166618e-5, "q1": 1.458332918e-6, "q3": 3.170833315e-5, "reps": 21 }, "host": { "median": 2.280000000e-4, "min": 1.988340000e-4, "max": 8.358750000e-4, "q1": 2.237090000e-4, "q3": 2.523330000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
]
}
]
}
-980
View File
@@ -1,980 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Correctness-gated benchmark harness for the Phase 01 corpus.
//!
//! Reads `benchmarks/manifest.toml`, verifies every fixture against the
//! independent reference and the native GPU before timing it, then writes
//! metadata, raw JSON and a generated markdown report. A fixture that fails
//! correctness is excluded and listed as such; it is never timed.
use std::error::Error;
use std::fmt::Write as _;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use xenora_metal::{NativeCompute, RunProfile};
use xenora_shader::{Architecture, ENTRY_POINT, compile};
const WARMUP_REPS: usize = 2;
const DEFAULT_REPS: usize = 7;
const BATCH: usize = 8;
#[derive(Debug, Clone)]
struct Fixture {
name: String,
stage: String,
source: String,
path: String,
input: Vec<u32>,
expected: Vec<u32>,
sizes: Vec<usize>,
}
#[derive(Debug, Clone, Default)]
struct Stats {
median: f64,
min: f64,
max: f64,
q1: f64,
q3: f64,
reps: usize,
}
impl Stats {
fn from_samples(mut samples: Vec<f64>) -> Self {
if samples.is_empty() {
return Self::default();
}
samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let n = samples.len();
let median = percentile(&samples, 0.5);
Self {
median,
min: samples[0],
max: samples[n - 1],
q1: percentile(&samples, 0.25),
q3: percentile(&samples, 0.75),
reps: n,
}
}
}
fn percentile(sorted: &[f64], fraction: f64) -> f64 {
if sorted.is_empty() {
return 0.0;
}
let position = fraction * (sorted.len() - 1) as f64;
let lower = position.floor() as usize;
let upper = position.ceil() as usize;
if lower == upper {
sorted[lower]
} else {
let weight = position - lower as f64;
sorted[lower] * (1.0 - weight) + sorted[upper] * weight
}
}
#[derive(Debug, Clone)]
struct SizeResult {
words: usize,
compile: Stats,
library: Stats,
pipeline: Stats,
gpu: Stats,
host: Stats,
/// Host submission stages inside `host`, plus readback after it.
submit: SubmitStats,
/// Fraction of samples whose GPU timestamp delta was zero.
gpu_zero_fraction: f64,
}
/// Host-side split of one dispatch's submission path.
///
/// `other` is `host` minus library, pipeline and the four stages below it,
/// per sample: compile options, function lookup, bounds and validation checks.
#[derive(Debug, Clone, Default)]
struct SubmitStats {
alloc: Stats,
encode: Stats,
commit: Stats,
wait: Stats,
readback: Stats,
other: Stats,
}
#[derive(Debug, Clone, Default)]
struct SubmitSamples {
alloc: Vec<f64>,
encode: Vec<f64>,
commit: Vec<f64>,
wait: Vec<f64>,
readback: Vec<f64>,
other: Vec<f64>,
}
impl SubmitSamples {
fn push(&mut self, profile: &RunProfile) {
self.alloc.push(profile.alloc_seconds);
self.encode.push(profile.encode_seconds);
self.commit.push(profile.commit_seconds);
self.wait.push(profile.wait_seconds);
self.readback.push(profile.readback_seconds);
self.other.push(
profile.host_seconds
- profile.library_seconds
- profile.pipeline_seconds
- profile.alloc_seconds
- profile.encode_seconds
- profile.commit_seconds
- profile.wait_seconds,
);
}
fn stats(self) -> SubmitStats {
SubmitStats {
alloc: Stats::from_samples(self.alloc),
encode: Stats::from_samples(self.encode),
commit: Stats::from_samples(self.commit),
wait: Stats::from_samples(self.wait),
readback: Stats::from_samples(self.readback),
other: Stats::from_samples(self.other),
}
}
}
#[derive(Debug, Clone)]
struct FixtureResult {
name: String,
stage: String,
source: String,
status: String,
reason: String,
sizes: Vec<SizeResult>,
batch: Option<BatchResult>,
}
#[derive(Debug, Clone)]
struct BatchResult {
words: usize,
sync: Stats,
pipelined: Stats,
}
mod startup;
mod startup_report;
fn main() -> Result<(), Box<dyn Error>> {
// Taken before anything else so a fresh startup child can report the time
// from its parent's spawn to `main`.
let entered = SystemTime::now();
let mut args = std::env::args().skip(1).peekable();
match args.peek().map(String::as_str) {
Some("startup") => return startup::run(args.skip(1)),
Some("startup-child") => return startup::child(entered, args.skip(1)),
_ => {}
}
let mut output = PathBuf::from("benchmarks/results");
let mut reps = DEFAULT_REPS;
while let Some(arg) = args.next() {
match arg.as_str() {
"--output" => {
output = PathBuf::from(args.next().ok_or("--output needs a path")?);
}
"--reps" => {
reps = args
.next()
.ok_or("--reps needs a count")?
.parse()
.map_err(|_| "--reps must be a positive integer")?;
}
"--help" | "-h" => {
println!(
"usage: xenora-bench [--output DIR] [--reps N]\n \
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
[--reps N] [--output DIR]"
);
return Ok(());
}
other => return Err(format!("unknown argument {other}").into()),
}
}
if reps == 0 {
return Err("--reps must be at least 1".into());
}
let manifest_text = fs::read_to_string("benchmarks/manifest.toml")?;
let fixtures = parse_manifest(&manifest_text)?;
if fixtures.is_empty() {
return Err("manifest lists no fixtures".into());
}
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
let device = metal.device_name();
let metadata = Metadata::collect(&device, reps);
let mut results = Vec::with_capacity(fixtures.len());
for fixture in &fixtures {
results.push(run_fixture(&metal, fixture, reps));
}
let run_id = metadata.run_id.clone();
let hardware_dir = slug(&device);
let run_dir = output.join(&hardware_dir).join(&run_id);
fs::create_dir_all(&run_dir)?;
fs::write(run_dir.join("metadata.json"), metadata.to_json())?;
fs::write(run_dir.join("results.json"), results_json(&results))?;
fs::write(
run_dir.join("report.md"),
report_markdown(&metadata, &results),
)?;
println!("Benchmark results written to {}", run_dir.display());
for result in &results {
println!(
" {:<16} {:<10} {}",
result.name,
result.status,
if result.reason.is_empty() {
String::new()
} else {
format!("({})", result.reason)
}
);
}
let excluded = results.iter().filter(|r| r.status != "benchmarked").count();
if excluded > 0 {
return Err(format!("{excluded} fixture(s) excluded from timing").into());
}
Ok(())
}
fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> FixtureResult {
let mut result = FixtureResult {
name: fixture.name.clone(),
stage: fixture.stage.clone(),
source: fixture.source.clone(),
status: "not-implemented".to_string(),
reason: String::new(),
sizes: Vec::new(),
batch: None,
};
let code = match fs::read(&fixture.path) {
Ok(code) => code,
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("cannot read {}: {error}", fixture.path);
return result;
}
};
let compiled = match compile(Architecture::Gfx1030, &code) {
Ok(compiled) => compiled,
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("compile failed: {error}");
return result;
}
};
// Independent reference on the declared base input.
let reference = match xenora_ref::execute(&code, &fixture.input) {
Ok(reference) => reference,
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("reference execution failed: {error}");
return result;
}
};
if reference != fixture.expected {
result.status = "excluded".to_string();
result.reason = "reference disagrees with hand-derived expected values".to_string();
return result;
}
// Native correctness at the smallest declared size before any timing.
let base_words = *fixture.sizes.first().unwrap_or(&fixture.input.len());
let base_input = expand(&fixture.input, base_words);
let base_expected = expand(&fixture.expected, base_words);
match metal.run_words(&compiled.msl, ENTRY_POINT, &base_input) {
Ok(actual) if actual == base_expected => {}
Ok(_) => {
result.status = "excluded".to_string();
result.reason = "GPU output disagrees with known answers".to_string();
return result;
}
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("GPU execution failed: {error}");
return result;
}
}
let mut sizes = Vec::with_capacity(fixture.sizes.len());
for &words in &fixture.sizes {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let mut compile_samples = Vec::with_capacity(reps);
let mut library_samples = Vec::with_capacity(reps);
let mut pipeline_samples = Vec::with_capacity(reps);
let mut gpu_samples = Vec::with_capacity(reps);
let mut host_samples = Vec::with_capacity(reps);
let mut submit_samples = SubmitSamples::default();
let mut gpu_zero = 0usize;
let mut mismatch = None;
for rep in 0..(WARMUP_REPS + reps) {
let compile_start = std::time::Instant::now();
let recompiled = match compile(Architecture::Gfx1030, &code) {
Ok(compiled) => compiled,
Err(error) => {
mismatch = Some(format!("compile failed at {words} words: {error}"));
break;
}
};
let compile_seconds = compile_start.elapsed().as_secs_f64();
let profile = match metal.run_words_profiled(&recompiled.msl, ENTRY_POINT, &input) {
Ok(profile) => profile,
Err(error) => {
mismatch = Some(format!("GPU run failed at {words} words: {error}"));
break;
}
};
if profile.output != expected {
mismatch = Some(format!("GPU mismatch at {words} words"));
break;
}
if rep < WARMUP_REPS {
continue;
}
compile_samples.push(compile_seconds);
library_samples.push(profile.library_seconds);
pipeline_samples.push(profile.pipeline_seconds);
gpu_samples.push(profile.gpu_seconds);
host_samples.push(profile.host_seconds);
submit_samples.push(&profile);
if profile.gpu_seconds <= 0.0 {
gpu_zero += 1;
}
}
if let Some(reason) = mismatch {
result.status = "excluded".to_string();
result.reason = reason;
return result;
}
let measured = gpu_samples.len();
sizes.push(SizeResult {
words,
compile: Stats::from_samples(compile_samples),
library: Stats::from_samples(library_samples),
pipeline: Stats::from_samples(pipeline_samples),
gpu: Stats::from_samples(gpu_samples),
host: Stats::from_samples(host_samples),
submit: submit_samples.stats(),
gpu_zero_fraction: if measured == 0 {
0.0
} else {
gpu_zero as f64 / measured as f64
},
});
}
let batch_words = fixture
.sizes
.iter()
.copied()
.min_by_key(|words| words.abs_diff(1024))
.unwrap_or(1024);
match measure_batch(metal, &code, fixture, batch_words, reps) {
Ok(batch) => result.batch = Some(batch),
Err(reason) => {
result.status = "excluded".to_string();
result.reason = reason;
return result;
}
}
result.sizes = sizes;
result.status = "benchmarked".to_string();
result
}
fn measure_batch(
metal: &NativeCompute,
code: &[u8],
fixture: &Fixture,
words: usize,
reps: usize,
) -> Result<BatchResult, String> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let mut sync = Vec::with_capacity(reps);
let mut pipelined = Vec::with_capacity(reps);
for rep in 0..(WARMUP_REPS + reps) {
for (samples, variant) in [(&mut sync, "sync"), (&mut pipelined, "pipelined")] {
let mut tokens = Vec::with_capacity(BATCH);
let mut outputs = Vec::with_capacity(BATCH);
let start = std::time::Instant::now();
for _ in 0..BATCH {
let compiled = compile(Architecture::Gfx1030, code).map_err(|error| {
format!("{variant} batch compile failed at {words} words: {error}")
})?;
if variant == "sync" {
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|error| {
format!("{variant} batch run failed at {words} words: {error}")
})?;
outputs.push(profile.output);
} else {
let token = metal
.submit_words(&compiled.msl, ENTRY_POINT, &input)
.map_err(|error| {
format!("{variant} batch submit failed at {words} words: {error}")
})?;
tokens.push(token);
}
}
for token in tokens {
let profile = metal.wait(token).map_err(|error| {
format!("{variant} batch wait failed at {words} words: {error}")
})?;
outputs.push(profile.output);
}
let per_dispatch = start.elapsed().as_secs_f64() / BATCH as f64;
if outputs.iter().any(|output| *output != expected) {
return Err(format!("{variant} batch GPU mismatch at {words} words"));
}
if rep >= WARMUP_REPS {
samples.push(per_dispatch);
}
}
}
Ok(BatchResult {
words,
sync: Stats::from_samples(sync),
pipelined: Stats::from_samples(pipelined),
})
}
fn expand(base: &[u32], words: usize) -> Vec<u32> {
(0..words).map(|i| base[i % base.len()]).collect()
}
// --- Manifest parsing (documented subset: [[fixture]] tables, string and int arrays) ---
fn parse_manifest(text: &str) -> Result<Vec<Fixture>, String> {
let mut fixtures = Vec::new();
let mut current: Option<Fixture> = None;
for (line_no, raw) in text.lines().enumerate() {
let line = raw.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
if line == "[[fixture]]" {
if let Some(fixture) = current.take() {
fixtures.push(finish(fixture, line_no)?);
}
current = Some(Fixture {
name: String::new(),
stage: String::new(),
source: String::new(),
path: String::new(),
input: Vec::new(),
expected: Vec::new(),
sizes: Vec::new(),
});
continue;
}
let Some(fixture) = current.as_mut() else {
return Err(format!(
"line {}: key outside a [[fixture]] table",
line_no + 1
));
};
let (key, value) = line
.split_once('=')
.ok_or_else(|| format!("line {}: expected key = value", line_no + 1))?;
let key = key.trim();
let value = value.trim();
match key {
"name" => fixture.name = parse_string(value)?,
"stage" => fixture.stage = parse_string(value)?,
"source" => fixture.source = parse_string(value)?,
"path" => fixture.path = parse_string(value)?,
"input" => fixture.input = parse_int_array(value)?,
"expected" => fixture.expected = parse_int_array(value)?,
"sizes" => {
fixture.sizes = parse_int_array(value)?
.into_iter()
.map(|n| n as usize)
.collect();
}
other => return Err(format!("line {}: unknown key {other}", line_no + 1)),
}
}
if let Some(fixture) = current.take() {
fixtures.push(finish(fixture, 0)?);
}
Ok(fixtures)
}
fn finish(fixture: Fixture, line_no: usize) -> Result<Fixture, String> {
let context = if fixture.name.is_empty() {
format!("fixture ending near line {line_no}")
} else {
format!("fixture {}", fixture.name)
};
if fixture.name.is_empty()
|| fixture.stage.is_empty()
|| fixture.source.is_empty()
|| fixture.path.is_empty()
{
return Err(format!("{context}: missing required string field"));
}
if fixture.input.is_empty() || fixture.expected.len() != fixture.input.len() {
return Err(format!(
"{context}: input and expected must be equal-length"
));
}
if fixture.sizes.is_empty() || fixture.sizes.contains(&0) {
return Err(format!(
"{context}: sizes must be a nonempty list of positive integers"
));
}
Ok(fixture)
}
fn parse_string(value: &str) -> Result<String, String> {
let trimmed = value.trim();
let inner = trimmed
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.ok_or_else(|| format!("expected a quoted string, got {trimmed}"))?;
Ok(inner.to_string())
}
fn parse_int_array(value: &str) -> Result<Vec<u32>, String> {
let trimmed = value.trim();
let inner = trimmed
.strip_prefix('[')
.and_then(|v| v.strip_suffix(']'))
.ok_or_else(|| format!("expected an integer array, got {trimmed}"))?;
if inner.trim().is_empty() {
return Ok(Vec::new());
}
inner
.split(',')
.map(|item| {
item.trim()
.parse::<u32>()
.map_err(|_| format!("invalid integer {}", item.trim()))
})
.collect()
}
// --- Metadata and output ---
struct Metadata {
run_id: String,
timestamp: String,
device: String,
host_arch: String,
os_version: String,
os_build: String,
rustc: String,
xcode: String,
commit: String,
profile: String,
api_validation: String,
shader_validation: String,
power: String,
thermal: String,
reps: usize,
warmup: usize,
}
impl Metadata {
fn collect(device: &str, reps: usize) -> Self {
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
Self {
run_id: format!("run-{seconds}"),
timestamp: format!("unix:{seconds}"),
device: device.to_string(),
host_arch: std::env::consts::ARCH.to_string(),
os_version: command_line("sw_vers", &["-productVersion"]),
os_build: command_line("sw_vers", &["-buildVersion"]),
rustc: command_line("rustc", &["-vV"])
.lines()
.next()
.unwrap_or("unknown")
.to_string(),
xcode: command_line("xcodebuild", &["-version"])
.lines()
.next()
.unwrap_or("unknown")
.to_string(),
commit: command_line("git", &["rev-parse", "HEAD"]),
profile: if cfg!(debug_assertions) {
"debug"
} else {
"release"
}
.to_string(),
api_validation: env_or("MTL_DEBUG_LAYER"),
shader_validation: env_or("MTL_SHADER_VALIDATION"),
power: power_source(),
thermal: thermal_state(),
reps,
warmup: WARMUP_REPS,
}
}
fn to_json(&self) -> String {
format!(
"{{\n \"run_id\": {},\n \"timestamp\": {},\n \"device\": {},\n \"host_arch\": {},\n \"os_version\": {},\n \"os_build\": {},\n \"rustc\": {},\n \"xcode\": {},\n \"commit\": {},\n \"profile\": {},\n \"api_validation\": {},\n \"shader_validation\": {},\n \"power\": {},\n \"thermal\": {},\n \"reps\": {},\n \"warmup\": {}\n}}\n",
json_str(&self.run_id),
json_str(&self.timestamp),
json_str(&self.device),
json_str(&self.host_arch),
json_str(&self.os_version),
json_str(&self.os_build),
json_str(&self.rustc),
json_str(&self.xcode),
json_str(&self.commit),
json_str(&self.profile),
json_str(&self.api_validation),
json_str(&self.shader_validation),
json_str(&self.power),
json_str(&self.thermal),
self.reps,
self.warmup
)
}
}
fn command_line(program: &str, args: &[&str]) -> String {
match Command::new(program).args(args).output() {
Ok(output) if output.status.success() => {
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
_ => "unavailable".to_string(),
}
}
fn env_or(key: &str) -> String {
std::env::var(key).unwrap_or_else(|_| "unset".to_string())
}
/// Report the power source line from `pmset`, or `unavailable` off macOS.
fn power_source() -> String {
let output = command_line("pmset", &["-g", "batt"]);
for line in output.lines() {
let line = line.trim();
if line.contains("AC Power") {
return "AC Power".to_string();
}
if line.contains("Battery Power") {
return "Battery Power".to_string();
}
}
"unavailable".to_string()
}
/// Report the CPU thermal and speed limits from `pmset`, compactly.
fn thermal_state() -> String {
let output = command_line("pmset", &["-g", "therm"]);
let mut parts = Vec::new();
for line in output.lines() {
let line = line.trim();
for key in ["CPU_Scheduler_Limit", "CPU_Speed_Limit"] {
if let Some(value) = line.strip_prefix(key) {
parts.push(format!("{key}{}", value.trim()));
}
}
}
if !parts.is_empty() {
parts.join(", ")
} else if output.contains("No thermal warning level has been recorded") {
"no warnings recorded".to_string()
} else {
"unavailable".to_string()
}
}
fn slug(device: &str) -> String {
device
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect::<String>()
.trim_matches('-')
.to_string()
}
fn json_str(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for c in value.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn stats_json(stats: &Stats) -> String {
format!(
"{{ \"median\": {:.9e}, \"min\": {:.9e}, \"max\": {:.9e}, \"q1\": {:.9e}, \"q3\": {:.9e}, \"reps\": {} }}",
stats.median, stats.min, stats.max, stats.q1, stats.q3, stats.reps
)
}
fn results_json(results: &[FixtureResult]) -> String {
let mut out = String::from("{\n \"fixtures\": [\n");
for (index, result) in results.iter().enumerate() {
let _ = writeln!(
out,
" {{\n \"name\": {},\n \"stage\": {},\n \"source\": {},\n \"status\": {},\n \"reason\": {},\n \"sizes\": [",
json_str(&result.name),
json_str(&result.stage),
json_str(&result.source),
json_str(&result.status),
json_str(&result.reason)
);
for (size_index, size) in result.sizes.iter().enumerate() {
let _ = writeln!(
out,
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"alloc\": {}, \"encode\": {}, \"commit\": {}, \"wait\": {}, \"readback\": {}, \"host_other\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
size.words,
stats_json(&size.compile),
stats_json(&size.library),
stats_json(&size.pipeline),
stats_json(&size.gpu),
stats_json(&size.host),
stats_json(&size.submit.alloc),
stats_json(&size.submit.encode),
stats_json(&size.submit.commit),
stats_json(&size.submit.wait),
stats_json(&size.submit.readback),
stats_json(&size.submit.other),
size.gpu_zero_fraction,
if size_index + 1 == result.sizes.len() {
""
} else {
","
}
);
}
out.push_str(" ]");
if let Some(batch) = &result.batch {
let _ = write!(
out,
",\n \"batch\": {{ \"dispatches\": {BATCH}, \"words\": {}, \"sync\": {}, \"pipelined\": {} }}",
batch.words,
stats_json(&batch.sync),
stats_json(&batch.pipelined)
);
}
let _ = writeln!(
out,
"\n }}{}",
if index + 1 == results.len() { "" } else { "," }
);
}
out.push_str(" ]\n}\n");
out
}
fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
let mut out = String::new();
let _ = writeln!(out, "# Xenora benchmark report");
let _ = writeln!(out);
let _ = writeln!(
out,
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
See `docs/testing/benchmarks.md` for the single-dispatch protocol."
);
let _ = writeln!(out);
let _ = writeln!(out, "## Environment");
let _ = writeln!(out);
let _ = writeln!(out, "| Field | Value |");
let _ = writeln!(out, "| --- | --- |");
for (key, value) in [
("Device", metadata.device.as_str()),
("Host arch", metadata.host_arch.as_str()),
("macOS", metadata.os_version.as_str()),
("Build", metadata.os_build.as_str()),
("Rust", metadata.rustc.as_str()),
("Xcode", metadata.xcode.as_str()),
("Commit", metadata.commit.as_str()),
("Profile", metadata.profile.as_str()),
("API validation", metadata.api_validation.as_str()),
("Shader validation", metadata.shader_validation.as_str()),
("Power source", metadata.power.as_str()),
("Thermal", metadata.thermal.as_str()),
] {
let _ = writeln!(out, "| {key} | {} |", value.replace('|', "\\|"));
}
let _ = writeln!(
out,
"| Repetitions | {} measured, {} warm-up |",
metadata.reps, metadata.warmup
);
if metadata.power != "AC Power" {
let _ = writeln!(out);
let _ = writeln!(
out,
"> **Protocol note.** The machine was not confirmed on AC power. \
The benchmark protocol in `docs/testing/benchmarks.md` requires AC power, \
so these timings are not protocol-compliant release evidence."
);
}
let _ = writeln!(out);
let _ = writeln!(out, "## Coverage");
let _ = writeln!(out);
let _ = writeln!(out, "| Fixture | Stage | Source | Status |");
let _ = writeln!(out, "| --- | --- | --- | --- |");
for result in results {
let status = if result.reason.is_empty() {
result.status.clone()
} else {
format!("{} ({})", result.status, result.reason)
};
let _ = writeln!(
out,
"| {} | {} | {} | {} |",
result.name,
result.stage,
result.source,
status.replace('|', "\\|")
);
}
let _ = writeln!(out);
let _ = writeln!(out, "## Timings");
let _ = writeln!(out);
let _ = writeln!(
out,
"Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, \
`library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer \
GPU time, and `host` is the wall time of one dispatch. Values are medians with \
interquartile range; minimum and maximum are in `results.json`."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |"
);
let _ = writeln!(
out,
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
);
for result in results.iter().filter(|r| r.status == "benchmarked") {
for size in &result.sizes {
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.0}% |",
result.name,
size.words,
size.compile.median * 1e6,
size.library.median * 1e6,
size.pipeline.median * 1e6,
size.gpu.median * 1e6,
size.host.median * 1e6,
(size.gpu.q3 - size.gpu.q1) * 1e6,
size.gpu_zero_fraction * 100.0
);
}
}
let _ = writeln!(out);
let _ = writeln!(out, "## Submission split");
let _ = writeln!(out);
let _ = writeln!(
out,
"Medians in microseconds of the host stages inside `host`: `alloc` creates the input and \
output shared buffers, `encode` creates the command buffer and encodes the dispatch, \
`commit` and `wait` time `commit` and `waitUntilCompleted`, and `other` is the per-sample \
remainder of `host` after library, pipeline and these four stages. `readback` copies \
the output after `host` ends."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | host | alloc | encode | commit | wait | other | readback |"
);
let _ = writeln!(
out,
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
);
for result in results.iter().filter(|r| r.status == "benchmarked") {
for size in &result.sizes {
let stages = &size.submit;
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} |",
result.name,
size.words,
size.host.median * 1e6,
stages.alloc.median * 1e6,
stages.encode.median * 1e6,
stages.commit.median * 1e6,
stages.wait.median * 1e6,
stages.other.median * 1e6,
stages.readback.median * 1e6
);
}
}
let _ = writeln!(out);
let _ = writeln!(out, "## Batched submission");
let _ = writeln!(out);
let _ = writeln!(
out,
"Median host microseconds per dispatch in batches of {BATCH}, including recompilation."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | Sync (µs) | Pipelined (µs) | Sync / pipelined |"
);
let _ = writeln!(out, "| --- | --- | --- | --- | --- |");
for result in results {
if let Some(batch) = &result.batch {
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2}× |",
result.name,
batch.words,
batch.sync.median * 1e6,
batch.pipelined.median * 1e6,
batch.sync.median / batch.pipelined.median
);
}
}
out
}
-405
View File
@@ -1,405 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
//!
//! `xenora-bench startup` checks one manifest fixture against the independent
//! reference, then measures it two ways:
//!
//! - **Fresh process.** It launches its own executable `--processes` times. Each
//! child creates the Metal device and queue, translates the fixture, runs it
//! once with `run_words_profiled`, checks the output and prints one sample line.
//! - **Repeated.** In this process it creates one device, then translates and runs
//! the same fixture `--reps` times. The first run is reported on its own.
//!
//! Every sample must produce the expected words. One wrong output, failed child or
//! unparsable sample line stops the run before anything is written. The
//! numbers describe this host only; two distributions do not explain each other.
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
use crate::startup_report::Report;
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
const DEFAULT_PROCESSES: usize = 30;
const DEFAULT_REPS: usize = 100;
/// A fresh process that has not exited by then is killed and fails the run.
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
pub(crate) const PHASES: [&str; 8] = [
"spawn_to_main",
"device",
"translate",
"library",
"pipeline",
"submit",
"gpu",
"readback",
];
/// One run's phase timings, indexed like [`PHASES`].
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
impl Sample {
fn line(&self) -> String {
let fields: Vec<String> = PHASES
.iter()
.zip(self.0)
.map(|(name, value)| format!("{name}={value:e}"))
.collect();
format!("startup-sample {}", fields.join(" "))
}
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
pub(crate) fn parse(line: &str) -> Result<Self, String> {
let rest = line
.strip_prefix("startup-sample ")
.ok_or("missing startup-sample prefix")?;
let fields: Vec<&str> = rest.split(' ').collect();
if fields.len() != PHASES.len() {
return Err(format!(
"expected {} fields, got {}",
PHASES.len(),
fields.len()
));
}
let mut sample = Self::default();
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
let value = field
.strip_prefix(name)
.and_then(|v| v.strip_prefix('='))
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
if !value.is_finite() || value < 0.0 {
return Err(format!("{name} must be finite and non-negative"));
}
sample.0[i] = value;
}
Ok(sample)
}
}
/// Median, tail and extremes of one phase.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Summary {
pub(crate) n: usize,
pub(crate) min: f64,
pub(crate) median: f64,
pub(crate) p90: f64,
pub(crate) p99: f64,
pub(crate) max: f64,
}
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
if values.is_empty() {
return None;
}
let mut sorted = values.to_vec();
sorted.sort_by(f64::total_cmp);
Some(Summary {
n: sorted.len(),
min: sorted[0],
median: percentile(&sorted, 0.5),
p90: percentile(&sorted, 0.9),
p99: percentile(&sorted, 0.99),
max: sorted[sorted.len() - 1],
})
}
struct Options {
fixture: Option<String>,
words: Option<usize>,
processes: usize,
reps: usize,
output: PathBuf,
}
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
let n: usize = value
.ok_or_else(|| format!("{flag} needs a count"))?
.parse()
.map_err(|_| format!("{flag} must be a positive integer"))?;
if n == 0 {
return Err(format!("{flag} must be at least 1"));
}
Ok(n)
}
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
let mut options = Options {
fixture: None,
words: None,
processes: DEFAULT_PROCESSES,
reps: DEFAULT_REPS,
output: PathBuf::from("artifacts/startup"),
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
"--words" => options.words = Some(count(args.next(), "--words")?),
"--processes" => options.processes = count(args.next(), "--processes")?,
"--reps" => options.reps = count(args.next(), "--reps")?,
"--output" => {
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
}
other => return Err(format!("unknown startup argument {other}")),
}
}
Ok(options)
}
/// The fixture to time and its word count, after the reference agrees with it.
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
let fixture = match &options.fixture {
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
None => fixtures.into_iter().next(),
}
.ok_or("fixture not found in benchmarks/manifest.toml")?;
let code = fs::read(&fixture.path)?;
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
if reference != fixture.expected {
return Err("reference disagrees with hand-derived expected values".into());
}
let words = options
.words
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
Ok((fixture, words))
}
/// Translates and runs the fixture once on `metal`, checking the output.
fn run_once(
metal: &NativeCompute,
fixture: &Fixture,
words: usize,
sample: &mut Sample,
) -> Result<(), Box<dyn Error>> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let start = Instant::now();
let code = fs::read(&fixture.path)?;
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
sample.0[2] = start.elapsed().as_secs_f64();
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|e| e.to_string())?;
if profile.output != expected {
return Err(format!("{} output disagrees with known answers", fixture.name).into());
}
sample.0[3] = profile.library_seconds;
sample.0[4] = profile.pipeline_seconds;
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
sample.0[6] = profile.gpu_seconds;
sample.0[7] = profile.readback_seconds;
Ok(())
}
fn unix_nanos(time: SystemTime) -> u128 {
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
}
/// Entry point of one fresh child process, called first thing in `main`.
///
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
/// time just before it spawned this process.
pub(crate) fn child(
entered: SystemTime,
mut args: impl Iterator<Item = String>,
) -> Result<(), Box<dyn Error>> {
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let mut sample = Sample::default();
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
sample.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut sample)?;
println!("{}", sample.line());
Ok(())
}
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
vec![
"--fixture".into(),
fixture.name.clone(),
"--words".into(),
words.to_string(),
]
}
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
///
/// The child inherits this process's environment on purpose, so its `MTL_*`
/// validation settings are the ones the run's metadata records.
fn spawn_child(
exe: &std::path::Path,
fixture: &Fixture,
words: usize,
) -> Result<(f64, String), Box<dyn Error>> {
let started = Instant::now();
let spawned = unix_nanos(SystemTime::now());
let mut child = Command::new(exe)
.arg("startup-child")
.arg(spawned.to_string())
.args(forwarded(fixture, words))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
// Drain both pipes while waiting, so a child that writes more than a pipe
// buffer (validation logs, for example) cannot block and look like a hang.
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut pipe) = pipe {
let _ = pipe.read_to_string(&mut text);
}
text
})
};
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > CHILD_TIMEOUT {
child.kill()?;
child.wait()?;
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
}
std::thread::sleep(Duration::from_millis(1));
};
let seconds = started.elapsed().as_secs_f64();
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
if !status.success() {
return Err(format!("{status}: {}", stderr.trim()).into());
}
Ok((seconds, stdout))
}
/// Runs both regimes and writes `startup.json` and `report.md`.
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let exe = std::env::current_exe()?;
let mut fresh = Vec::with_capacity(options.processes);
let mut wall = Vec::with_capacity(options.processes);
for i in 0..options.processes {
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
wall.push(seconds);
let line = stdout
.lines()
.find(|l| l.starts_with("startup-sample "))
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
}
let mut first = Sample::default();
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
first.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut first)?;
let mut repeated = Vec::with_capacity(options.reps);
for _ in 0..options.reps {
let mut sample = Sample::default();
run_once(&metal, &fixture, words, &mut sample)?;
repeated.push(sample);
}
let metadata = Metadata::collect(&metal.device_name(), options.reps);
let dir = options
.output
.join(slug(&metadata.device))
.join(&metadata.run_id);
fs::create_dir_all(&dir)?;
fs::write(dir.join("metadata.json"), metadata.to_json())?;
let report = Report {
fixture: &fixture.name,
words,
fresh: &fresh,
wall: &wall,
first: &first,
repeated: &repeated,
};
fs::write(dir.join("startup.json"), report.json())?;
let markdown = report.markdown(&metadata);
fs::write(dir.join("report.md"), &markdown)?;
println!("{markdown}");
println!("Startup results written to {}", dir.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_lines_round_trip() {
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
}
#[test]
fn sample_lines_reject_damaged_input() {
let line = Sample([1.0; PHASES.len()]).line();
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
// Phases out of order are refused even when every name is present.
let swapped = line
.replacen("device=", "TMP=", 1)
.replacen("translate=", "device=", 1)
.replacen("TMP=", "translate=", 1);
assert!(Sample::parse(&swapped).is_err());
}
#[test]
fn summary_uses_interpolated_percentiles() {
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
// 0.99 * 99 = 98.01 between 99 and 100.
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
let s = summarize(&values).unwrap();
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
assert!((s.median - 50.5).abs() < 1e-9);
assert!((s.p90 - 90.1).abs() < 1e-9);
assert!((s.p99 - 99.01).abs() < 1e-9);
assert_eq!(summarize(&[]), None);
let one = summarize(&[3.0]).unwrap();
assert_eq!(
(one.median, one.p90, one.p99, one.max),
(3.0, 3.0, 3.0, 3.0)
);
}
#[test]
fn options_reject_bad_counts_and_flags() {
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
let defaults = parse(&[]).unwrap();
assert_eq!(
(defaults.processes, defaults.reps),
(DEFAULT_PROCESSES, DEFAULT_REPS)
);
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
assert!(parse(&["--processes", "0"]).is_err());
assert!(parse(&["--reps", "-1"]).is_err());
assert!(parse(&["--words"]).is_err());
assert!(parse(&["--fast"]).is_err());
}
}
-146
View File
@@ -1,146 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! JSON and markdown output of `xenora-bench startup` (#178).
use std::fmt::Write as _;
use crate::startup::{PHASES, Sample, Summary, summarize};
use crate::{Metadata, json_str};
pub(crate) struct Report<'a> {
pub(crate) fixture: &'a str,
pub(crate) words: usize,
pub(crate) fresh: &'a [Sample],
pub(crate) wall: &'a [f64],
pub(crate) first: &'a Sample,
pub(crate) repeated: &'a [Sample],
}
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
samples.iter().map(|s| s.0[phase]).collect()
}
fn summary_json(summary: Option<Summary>) -> String {
summary.map_or_else(
|| "null".to_string(),
|s| {
format!(
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
s.n, s.min, s.median, s.p90, s.p99, s.max
)
},
)
}
impl Report<'_> {
pub(crate) fn json(&self) -> String {
let mut out = format!(
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
json_str(self.fixture),
self.words,
summary_json(summarize(self.wall))
);
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
let _ = writeln!(out, " \"{regime}\": {{");
for (i, phase) in PHASES.iter().enumerate() {
let comma = if i + 1 < PHASES.len() { "," } else { "" };
let summary = if regime == "repeated" && i < 2 {
None
} else {
summarize(&column(samples, i))
};
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
}
out.push_str(" },\n");
}
let first: Vec<String> = PHASES
.iter()
.zip(self.first.0)
.skip(1)
.map(|(p, v)| format!("\"{p}\": {v:e}"))
.collect();
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
// Raw fresh-process samples in launch order, so a cold first process
// (for example an empty Metal shader cache) stays visible.
let rows: Vec<String> = self
.fresh
.iter()
.zip(self.wall)
.map(|(sample, wall)| {
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
format!("[{}, {wall:e}]", phases.join(", "))
})
.collect();
let _ = writeln!(
out,
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
PHASES
.iter()
.map(|p| json_str(p))
.collect::<Vec<_>>()
.join(", "),
rows.join(",\n ")
);
out
}
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
let ms = |v: f64| format!("{:.3}", v * 1e3);
let mut out = format!(
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
self.fixture,
self.words,
metadata.device,
metadata.profile,
metadata.commit,
metadata.api_validation,
metadata.shader_validation,
metadata.power,
metadata.thermal,
self.fresh.len(),
self.repeated.len(),
);
for (i, phase) in PHASES.iter().enumerate() {
let fresh = summarize(&column(self.fresh, i));
let repeated = (i >= 2)
.then(|| summarize(&column(self.repeated, i)))
.flatten();
let cells = |s: Option<Summary>| {
s.map_or_else(
|| "– | – | – | –".to_string(),
|s| {
format!(
"{} | {} | {} | {}",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
)
},
)
};
let first = if i == 0 {
"–".to_string()
} else {
ms(self.first.0[i])
};
let _ = writeln!(
out,
"| `{phase}` | {} | {first} | {} |",
cells(fresh),
cells(repeated)
);
}
if let Some(s) = summarize(self.wall) {
let _ = writeln!(
out,
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
);
}
out
}
}
-5
View File
@@ -1,5 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Exercise the benchmark's LLVM-derived fixture during ordinary workspace tests.
#[allow(dead_code)]
#[path = "../benches/gfx1030_identify.rs"]
mod benchmark;
-18
View File
@@ -1,18 +0,0 @@
[package]
name = "betterxen"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
xenora-decoder = { path = "../decoder" }
xenora-isa = { path = "../isa" }
xenora-metal = { path = "../metal" }
xenora-ref = { path = "../ref" }
xenora-shader = { path = "../shader" }
xenora-loader = { path = "../loader" }
xenora-import-gen = { path = "../import-gen" }
-67
View File
@@ -1,67 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::error::Error;
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
const INPUT: [u32; 4] = [0, 1, u32::MAX, 3_989_547_400];
struct Fixture {
name: &'static str,
code: &'static [u8],
expected: [u32; 4],
}
const FIXTURES: [Fixture; 3] = [
Fixture {
name: "add",
code: include_bytes!("../../../fixtures/rdna2/add.bin"),
expected: [305_419_896, 305_419_897, 305_419_895, 0],
},
Fixture {
name: "bitwise-branch",
code: include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin"),
expected: [305_419_896, 305_419_897, 315_315_847, 318_723_824],
},
Fixture {
name: "float-exact",
code: include_bytes!("../../../fixtures/rdna2/float-exact.bin"),
expected: [0x410c_0000, 0x410c_0000, 0x4120_0000, 0x4120_0000],
},
];
pub fn run() -> Result<(), Box<dyn Error>> {
let metal = NativeCompute::new()?;
println!("Metal device: {}", metal.device_name());
for fixture in FIXTURES {
run_fixture(&metal, fixture)?;
}
Ok(())
}
fn run_fixture(metal: &NativeCompute, fixture: Fixture) -> Result<(), Box<dyn Error>> {
let Fixture {
name,
code,
expected,
} = fixture;
println!("Fixture {name}");
let compiled = compile(Architecture::Gfx1030, code)?;
println!(
"Disassembly\n{}\nIR\n{}\nMSL\n{}",
compiled.disassembly, compiled.ir, compiled.msl
);
let reference = xenora_ref::execute(code, &INPUT)?;
if reference != expected {
return Err(format!("reference mismatch: {reference:?} != {expected:?}").into());
}
let actual = metal.run_words(&compiled.msl, ENTRY_POINT, &INPUT)?;
if actual != reference || actual != expected {
return Err(format!("Metal mismatch: {actual:?} != {expected:?}").into());
}
println!("Metal, reference and known answers match: {actual:?}");
Ok(())
}
-639
View File
@@ -1,639 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
mod demo;
mod runner;
mod shaders;
use std::process::ExitCode;
/// Where `probe` writes and `imports sync` reads without `--report`.
const DEFAULT_REPORT_DIR: &str = "diagnostics/probe";
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("info") => {
println!(
"BetterXen {} ({})",
env!("CARGO_PKG_VERSION"),
std::env::consts::ARCH
);
ExitCode::SUCCESS
}
Some("inspect") => {
let Some(file_path) = std::env::args().nth(2) else {
eprintln!("usage: betterxen inspect <path-to-pe-binary>");
return ExitCode::from(2);
};
match xenora_loader::triage_file(&file_path) {
Ok(report) => {
print!("{report}");
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("inspect failed: {err}");
ExitCode::FAILURE
}
}
}
Some("demo") => match demo::run() {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("demo: {error}");
ExitCode::FAILURE
}
},
Some("run") => runner::command(std::env::args_os().skip(2)),
Some("imports") => imports_command(std::env::args().skip(2).collect()),
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("probe") => {
let args: Vec<String> = std::env::args().collect();
let mut pe_path: Option<String> = None;
let mut mode = "static".to_string();
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
"--pe" => {
if i + 1 < args.len() {
pe_path = Some(args[i + 1].clone());
i += 2;
} else {
eprintln!("missing argument for --pe");
return ExitCode::from(2);
}
}
"--mode" => {
if i + 1 < args.len() {
mode = args[i + 1].clone();
i += 2;
} else {
eprintln!("missing argument for --mode");
return ExitCode::from(2);
}
}
"--report" => {
if i + 1 < args.len() {
report_dir = args[i + 1].clone();
i += 2;
} else {
eprintln!("missing argument for --report");
return ExitCode::from(2);
}
}
other => {
eprintln!("unknown probe argument: {other}");
return ExitCode::from(2);
}
}
}
let Some(pe) = pe_path else {
eprintln!(
"usage: betterxen probe --pe <path> [--mode <static>] [--report <output-dir>]"
);
return ExitCode::from(2);
};
if mode != "static" {
eprintln!("error: currently only --mode static is supported");
return ExitCode::from(2);
}
let bytes = match std::fs::read(&pe) {
Ok(b) => b,
Err(err) => {
eprintln!("error reading PE binary '{pe}': {err}");
return ExitCode::FAILURE;
}
};
let config = xenora_loader::ProbeConfig::default();
match xenora_loader::run_probe_and_export(&bytes, &report_dir, &config) {
Ok(report) => {
println!("BetterXen static PE probe complete.");
println!("Artifacts exported to: {report_dir}");
println!("Sections: {}", report.parsed.sections.len());
println!("Relocations: {}", report.relocations.total_entries);
println!("TLS Callbacks: {}", report.tls.callback_targets.len());
println!("Imported Thunks: {}", report.imports.len());
println!(
"Unresolved Standard Import Thunks: {}",
report
.imports
.iter()
.filter(|import| !import.is_supported)
.count()
);
if let Some(insn) = report.first_unsupported_dbt_insn {
println!("First DBT Blocker: RVA 0x{:08x} ({})", insn.rva, insn.notes);
}
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("probe failed: {err}");
ExitCode::FAILURE
}
}
}
_ => {
eprintln!("usage: betterxen <info|demo|inspect|probe|run|imports|shaders>");
ExitCode::from(2)
}
}
}
/// `betterxen imports sync [--report <dir>] [--check]`
/// `betterxen imports generate --pe <path> [--out <dir>]`
/// `betterxen imports metadata sync [--out <dir>]`
/// `betterxen imports verify`
fn imports_command(args: Vec<String>) -> ExitCode {
if args.is_empty() {
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
return ExitCode::from(2);
}
match args[0].as_str() {
"generate" => run_imports_generate_cli(&args[1..]),
"sync" => run_imports_sync_cli(&args[1..]),
"metadata" => run_imports_metadata_cli(&args[1..]),
"verify" => run_imports_verify_cli(&args[1..]),
other => {
eprintln!("unknown imports subcommand: {other}");
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
ExitCode::from(2)
}
}
}
fn run_imports_metadata_cli(args: &[String]) -> ExitCode {
let mut out_dir = "artifacts/metadata".to_string();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"sync" => {
i += 1;
}
"--out" => {
if i + 1 < args.len() {
out_dir = args[i + 1].clone();
i += 2;
} else {
eprintln!("missing argument for --out");
return ExitCode::from(2);
}
}
other => {
eprintln!("unknown metadata argument: {other}");
return ExitCode::from(2);
}
}
}
println!("Synchronizing offline API metadata catalog from public specifications...");
let catalog = xenora_import_gen::MetadataCatalog::builtin();
println!(
"Loaded version {} with {} entries.",
catalog.version,
catalog.entries.len()
);
let _ = std::fs::create_dir_all(&out_dir);
let out_file = format!("{out_dir}/api_catalog.json");
let mut json = String::from("{\n \"version\": 1,\n \"entries\": [\n");
let mut first = true;
for ((module, sym), sig) in &catalog.entries {
if !first {
json.push_str(",\n");
}
first = false;
json.push_str(&format!(
" {{\"module\": \"{}\", \"symbol\": \"{}\", \"header\": \"{}\", \"doc\": \"{}\"}}",
module, sym, sig.header_source, sig.doc
));
}
json.push_str("\n ]\n}\n");
if let Err(e) = std::fs::write(&out_file, json) {
eprintln!("failed to write metadata catalog: {e}");
return ExitCode::FAILURE;
}
println!("API metadata catalog synchronized to: {out_file}");
ExitCode::SUCCESS
}
fn run_imports_verify_cli(args: &[String]) -> ExitCode {
if !args.is_empty() {
eprintln!("warning: verify takes no additional arguments");
}
println!("Running automated behavioral verification for generated import bindings...");
match xenora_import_gen::run_verification() {
Ok(res) => {
for detail in &res.details {
println!(" {detail}");
}
println!(
"Verification summary: {}/{} tests passed.",
res.passed, res.total
);
if res.failed > 0 {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
Err(err) => {
eprintln!("verification failed: {err}");
ExitCode::FAILURE
}
}
}
fn run_imports_generate_cli(args: &[String]) -> ExitCode {
let mut pe_path: Option<String> = None;
let mut csv_path: Option<String> = None;
let mut out_dir = "crates/loader/src/generated".to_string();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--pe" => {
if i + 1 < args.len() {
pe_path = Some(args[i + 1].clone());
i += 2;
} else {
eprintln!("missing argument for --pe");
return ExitCode::from(2);
}
}
"--csv" => {
if i + 1 < args.len() {
csv_path = Some(args[i + 1].clone());
i += 2;
} else {
eprintln!("missing argument for --csv");
return ExitCode::from(2);
}
}
"--out" => {
if i + 1 < args.len() {
out_dir = args[i + 1].clone();
i += 2;
} else {
eprintln!("missing argument for --out");
return ExitCode::from(2);
}
}
other => {
eprintln!("unknown generate argument: {other}");
return ExitCode::from(2);
}
}
}
let mut records = if let Some(ref pe) = pe_path {
println!("Extracting imports from PE executable: {pe}");
let bytes = match std::fs::read(pe) {
Ok(b) => b,
Err(err) => {
eprintln!("error reading PE binary '{pe}': {err}");
return ExitCode::FAILURE;
}
};
let probe_cfg = xenora_loader::ProbeConfig::default();
let report = match xenora_loader::probe::probe_pe_bytes(&bytes, &probe_cfg) {
Ok(rep) => rep,
Err(err) => {
eprintln!("error probing PE binary: {err}");
return ExitCode::FAILURE;
}
};
report
.imports
.into_iter()
.map(|imp| xenora_import_gen::ImportRecord {
module: imp.dll,
symbol: imp.symbol,
ordinal: match imp.import_name {
xenora_loader::import_table::ImportName::Ordinal(ordinal) => Some(ordinal),
xenora_loader::import_table::ImportName::Name(_) => None,
},
iat_rva: imp.iat_rva as u64,
})
.collect::<Vec<_>>()
} else if let Some(ref csv) = csv_path {
match xenora_import_gen::parse_csv(csv) {
Ok(recs) => recs,
Err(err) => {
eprintln!("error reading CSV '{csv}': {err}");
return ExitCode::FAILURE;
}
}
} else {
eprintln!(
"usage: betterxen imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
);
return ExitCode::from(2);
};
records.sort();
records.dedup();
println!("Total imports extracted: {}", records.len());
let db = xenora_import_gen::SymbolDb::builtin();
let manifest = xenora_import_gen::Manifest::build(&records, &db);
let summary = manifest.summary();
println!("Catalog classification by import slot:");
for (tier, count) in &summary {
let pct = (*count as f64 / records.len() as f64 * 100.0) as u32;
println!(" - {tier}: {count} ({pct}%)");
}
println!("Emitted disposition by distinct import:");
for (disposition, count) in manifest.emission_summary() {
println!(" - {disposition}: {count}");
}
let files = xenora_import_gen::generate(&manifest, &db);
if let Err(err) = files.write_all(&out_dir) {
eprintln!("failed to write generated files: {err}");
return ExitCode::FAILURE;
}
let manifest_csv = format!("{out_dir}/generated_manifest.csv");
if let Err(err) = manifest.write_csv(&manifest_csv) {
eprintln!("failed to write manifest CSV: {err}");
return ExitCode::FAILURE;
}
println!("Successfully generated bindings in '{out_dir}':");
println!(" - {out_dir}/generated_crt.rs");
println!(" - {out_dir}/generated_stubs.rs");
println!(" - {out_dir}/generated_tests.rs");
println!(" - {out_dir}/generated_manifest.md");
println!(" - {out_dir}/generated_manifest.csv");
ExitCode::SUCCESS
}
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut check_mode = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--report" => {
if i + 1 < args.len() {
report_dir = args[i + 1].clone();
i += 2;
} else {
eprintln!("missing argument for --report");
return ExitCode::from(2);
}
}
"--check" => {
check_mode = true;
i += 1;
}
other => {
eprintln!("unknown sync argument: {other}");
return ExitCode::from(2);
}
}
}
match run_imports_sync(&report_dir, check_mode) {
Ok(changed) => {
if check_mode {
if changed {
eprintln!("imports sync --check: import_backlog.md is out of date");
ExitCode::FAILURE
} else {
println!("imports sync --check: import_backlog.md is up to date");
ExitCode::SUCCESS
}
} else {
println!("imports sync complete. Report written to: {report_dir}");
ExitCode::SUCCESS
}
}
Err(e) => {
eprintln!("imports sync failed: {e}");
ExitCode::FAILURE
}
}
}
fn run_imports_sync(
report_dir: &str,
check_mode: bool,
) -> Result<bool, Box<dyn std::error::Error>> {
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use xenora_loader::ImportRegistry;
use xenora_loader::import_table::ImportName;
use xenora_loader::imports::ServiceStatus;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
let imports_csv_path = std::path::Path::new(report_dir).join("imports.csv");
if !imports_csv_path.exists() {
return Err(format!(
"imports.csv not found in '{report_dir}'. Run `betterxen probe` first."
)
.into());
}
// Build the standard registry to get current implementation state.
let mut registry = ImportRegistry::new();
register_standard_services(
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
// Parse imports.csv (skip header line).
let csv_text = std::fs::read_to_string(&imports_csv_path)?;
let mut by_module: BTreeMap<String, Vec<(String, bool, Option<ServiceStatus>)>> =
BTreeMap::new();
let mut total = 0usize;
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut lines = csv_text.lines();
let header = lines.next().unwrap_or_default();
let has_import_kind = header.ends_with(",import_kind");
// Binding does not resolve delay-loaded imports, so the backlog omits them.
let table_column = header
.split(',')
.position(|column| column == "import_table");
for line in lines {
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
continue;
}
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
// We re-query the live registry rather than trusting cached status.
let fields: Vec<&str> = line.splitn(10, ',').collect();
if fields.len() < 2 {
continue;
}
let module = fields[0].trim_matches('"').to_string();
let symbol = fields[1].trim_matches('"').to_string();
if module.is_empty() || symbol.is_empty() {
continue;
}
let name = if has_import_kind && line.ends_with(",ordinal") {
let Some(ordinal) = symbol.strip_prefix("Ordinal#").and_then(|n| n.parse().ok()) else {
continue;
};
ImportName::Ordinal(ordinal)
} else {
ImportName::Name(symbol.clone())
};
let binding = registry.resolve(&module, &name);
let is_registered = binding.is_some();
let status = binding.map(|b| b.status);
let label: &'static str = match status {
Some(ServiceStatus::Implemented) => "implemented",
Some(ServiceStatus::Partial) => "partial",
Some(ServiceStatus::Stub) => "stub",
None => {
// Check explicit known-unsupported list
match (module.to_ascii_lowercase().as_str(), symbol.as_str()) {
(
"api-ms-win-core-processthreads-l1-1-0.dll",
"CreateThread" | "ResumeThread" | "SuspendThread" | "TerminateProcess",
)
| (
"api-ms-win-core-synch-l1-1-0.dll",
"WaitForSingleObject" | "WaitForSingleObjectEx",
)
| ("api-ms-win-core-synch-l1-2-1.dll", "WaitForMultipleObjects")
| ("api-ms-win-core-rtlsupport-l1-1-0.dll", "RtlVirtualUnwind") => {
"unsupported"
}
_ => "missing",
}
}
};
*counts.entry(label).or_default() += 1;
total += 1;
by_module
.entry(module.to_ascii_lowercase())
.or_default()
.push((symbol, is_registered, status));
}
// Build the refreshed import_backlog.md.
let mut md = String::new();
let _ = writeln!(md, "# BetterXen import compatibility backlog");
let _ = writeln!(md);
let _ = writeln!(
md,
"Generated by `betterxen imports sync`. Do not edit manually."
);
let _ = writeln!(
md,
"Re-run after adding service handlers to refresh this file."
);
let _ = writeln!(md);
let _ = writeln!(md, "## Summary");
let _ = writeln!(md);
let _ = writeln!(md, "| Status | Count |");
let _ = writeln!(md, "| --- | ---: |");
let _ = writeln!(md, "| **Total** | {total} |");
for (label, count) in &counts {
let _ = writeln!(md, "| {label} | {count} |");
}
let _ = writeln!(md);
let _ = writeln!(md, "## Missing handlers (highest value first)");
let _ = writeln!(md);
// Priority ordering: processthreads, synch, rtlsupport, memory, crt, file, graphics, other
fn priority_key(module: &str) -> u8 {
if module.contains("processthreads") || module.contains("core-handle") {
1
} else if module.contains("fibers") || module.contains("tls") {
2
} else if module.contains("core-synch") {
3
} else if module.contains("core-profile") || module.contains("core-sysinfo") {
4
} else if module.contains("core-memory")
|| module.contains("core-heap")
|| module == "xmem.dll"
{
5
} else if module.starts_with("api-ms-win-crt-")
|| module.contains("vcruntime")
|| module.contains("libraryloader")
{
6
} else if module.contains("rtlsupport") || module.contains("errorhandling") {
7
} else if module.contains("core-file") || module == "xcrdapi.dll" {
8
} else {
9
}
}
// Collect missing/unsupported into a prioritized list.
let mut missing_entries: Vec<(u8, String, String)> = Vec::new();
for (module, symbols) in &by_module {
for (symbol, is_registered, _status) in symbols {
if !is_registered {
missing_entries.push((priority_key(module), module.clone(), symbol.clone()));
}
}
}
missing_entries.sort();
let mut prev_priority = 255u8;
for (priority, module, symbol) in &missing_entries {
if *priority != prev_priority {
let _ = writeln!(md, "### Priority {priority}");
let _ = writeln!(md);
prev_priority = *priority;
}
let _ = writeln!(md, "- `{module}!{symbol}`");
}
let _ = writeln!(md);
let _ = writeln!(md, "## Registered handlers");
let _ = writeln!(md);
let _ = writeln!(md, "| Module | Symbol | Status |");
let _ = writeln!(md, "| --- | --- | --- |");
// Enumerate canonical registrations sorted by module, symbol
let mut registered: BTreeSet<(String, String, &'static str)> = BTreeSet::new();
for (module, symbol, status) in registry.iter_registered() {
registered.insert((
module.to_ascii_lowercase(),
symbol.to_string(),
status.as_str(),
));
}
for (module, symbol, status) in &registered {
let _ = writeln!(md, "| `{module}` | `{symbol}` | {status} |");
}
let out_path = std::path::Path::new(report_dir).join("import_backlog.md");
let existing = std::fs::read_to_string(&out_path).unwrap_or_default();
let changed = existing != md;
if !check_mode {
std::fs::write(&out_path, &md)?;
println!(
" Total imports: {total} | implemented: {} | partial: {} | stub: {} | missing: {}",
counts.get("implemented").copied().unwrap_or(0),
counts.get("partial").copied().unwrap_or(0),
counts.get("stub").copied().unwrap_or(0),
counts.get("missing").copied().unwrap_or(0),
);
}
Ok(changed)
}
use std::fmt::Write as _;
-473
View File
@@ -1,473 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::error::Error;
use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitCode, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use xenora_loader::startup::{StartupEvent, StartupLayout, run_synthetic_startup_with_observer};
use xenora_loader::{
ExitReason, ImportRegistry, Register, ServicesState, SystemClock, register_standard_services,
};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
#[path = "startup_report.rs"]
mod startup_report;
use startup_report::{Events, JOURNAL_ERROR_EXIT, Journal, Termination, WATCHDOG_EXIT};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe");
const WALL_LIMIT: Duration = Duration::from_secs(15);
const DEFAULT_STEPS: usize = 100;
const MAX_STEPS: usize = 10_000;
const IMAGE_BASE: u64 = 0x150000000;
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
const TICKET: u64 = 17;
const DRAW_RESULT: u64 = 0x42;
const EXTENT: [usize; 2] = [4, 3];
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report <path>]";
struct Options {
path: PathBuf,
max_steps: usize,
worker: bool,
trace: bool,
hud: bool,
report: Option<PathBuf>,
journal: Option<PathBuf>,
}
impl Options {
fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Self, String> {
let mut args = args.into_iter();
let mut path = None;
let mut max_steps = None;
let mut report = None;
let mut journal = None;
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
while let Some(arg) = args.next() {
match arg.to_str() {
Some("--pe") if path.is_none() => {
path = Some(PathBuf::from(args.next().ok_or("missing --pe path")?));
}
Some("--max-steps") if max_steps.is_none() => {
max_steps = Some(
args.next()
.and_then(|arg| arg.to_str()?.parse::<usize>().ok())
.filter(|steps| (1..=MAX_STEPS).contains(steps))
.ok_or("--max-steps must be in 1..=10000")?,
);
}
Some("--startup-report") if report.is_none() => {
report = Some(PathBuf::from(
args.next().ok_or("missing --startup-report path")?,
));
}
Some("--startup-journal") if journal.is_none() => {
journal = Some(PathBuf::from(
args.next().ok_or("missing worker journal path")?,
));
}
Some("--experimental") if !experimental => experimental = true,
Some("--trace") if !trace => trace = true,
Some("--metal-hud") if !hud => hud = true,
Some("--worker") if !worker => worker = true,
_ => return Err(format!("unknown or repeated run argument {arg:?}")),
}
}
if !experimental {
return Err("run requires --experimental".into());
}
if (worker && report.is_some()) || (!worker && journal.is_some()) {
return Err("invalid startup report option for this process".into());
}
Ok(Self {
path: path.ok_or("missing --pe path")?,
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
worker,
trace,
hud,
report,
journal,
})
}
}
pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
let options = match Options::parse(args) {
Ok(options) => options,
Err(error) => {
eprintln!("{error}\n{USAGE}");
return ExitCode::from(2);
}
};
let result = if options.worker {
worker_command(&options)
} else {
launch_worker(&options)
};
match result {
Ok(code) => code,
Err(error) => {
eprintln!("run failed: {error}");
ExitCode::FAILURE
}
}
}
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
let journal = options
.report
.as_ref()
.map(|_| Journal::create())
.transpose()?;
let executable = std::env::current_exe()?;
let destination = options
.report
.as_ref()
.map(|path| {
OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| format!("could not create startup report: {error}"))
})
.transpose()?;
let started = Instant::now();
let mut command = Command::new(executable);
command
.args([
"run",
"--experimental",
"--trace",
"--metal-hud",
"--worker",
])
.arg("--max-steps")
.arg(options.max_steps.to_string())
.arg("--pe")
.arg(&options.path)
.stdin(Stdio::null());
if let Some(journal) = &journal {
command.arg("--startup-journal").arg(journal.path());
}
let termination = command
.spawn()
.and_then(|child| supervise(child, started, WALL_LIMIT));
if let (Some(journal), Some(destination)) = (&journal, destination)
&& let Err(error) = journal.finish(destination, &termination)
{
eprintln!("could not write startup report: {error}");
if matches!(&termination, Ok(Termination::Exited(status)) if status.success()) {
return Ok(ExitCode::FAILURE);
}
}
match termination? {
Termination::Exited(status) => match status.code() {
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
None => Err(format!("worker terminated: {status}").into()),
},
Termination::Deadline => {
Err("experimental worker exceeded its 15 second wall deadline".into())
}
}
}
fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Result<Termination> {
loop {
match child.try_wait() {
Ok(Some(status)) => return Ok(Termination::Exited(status)),
Ok(None) if started.elapsed() < limit => {
std::thread::sleep(Duration::from_millis(10));
}
status => {
let _ = child.kill();
child.wait()?;
status?;
return Ok(Termination::Deadline);
}
}
}
}
fn worker_command(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
let mut events = match options.journal.as_deref().map(Events::open).transpose() {
Ok(events) => events,
Err(error) => {
eprintln!("could not open startup journal: {error}");
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
}
};
let result = run_worker(options, events.as_mut());
if let Some(events) = events.as_mut() {
if let Err(error) = &result {
events.failure(error.as_ref());
}
if let Some(error) = events.write_error() {
if let Err(error) = result {
eprintln!("run failed: {error}");
}
eprintln!("could not write startup journal: {error}");
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
}
}
result.map(|()| ExitCode::SUCCESS)
}
fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
let valid_metadata =
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
let rejection =
"execution denied: input must match an embedded trusted PE fixture byte for byte";
// Check size before opening and again on the descriptor. Bound the read
// even if another process changes the file after the metadata checks.
if !valid_metadata(fs::metadata(path)?) {
return Err(rejection.into());
}
let file = File::open(path)?;
if !valid_metadata(file.metadata()?) {
return Err(rejection.into());
}
let mut bytes = Vec::with_capacity(FIXTURE.len() + 1);
file.take(FIXTURE.len() as u64 + 1)
.read_to_end(&mut bytes)?;
[FIXTURE, SERVICES_FIXTURE]
.into_iter()
.find(|fixture| *fixture == bytes)
.ok_or_else(|| rejection.into())
}
fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), Box<dyn Error>> {
std::thread::Builder::new()
.name("xenora-deadline".into())
.spawn(|| {
std::thread::sleep(WALL_LIMIT);
// The supervisor also enforces this deadline. The worker retains
// its own deadline if it is invoked directly.
std::process::exit(i32::from(WATCHDOG_EXIT));
})?;
let fixture = verify_fixture(&options.path)?;
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
("runtime-services", 23, 3)
} else {
("trusted-runner", TICKET, 1)
};
if options.trace {
println!(
"trace fixture={name} policy=exact-bytes entry_step_limit={} wall_limit_ms=15000",
options.max_steps
);
}
let capture = Arc::new(Mutex::new(None));
let draw_capture = Arc::clone(&capture);
let mut imports = ImportRegistry::new();
register_standard_services(
&mut imports,
Arc::new(ServicesState::new(Arc::new(SystemClock))),
);
let trace = options.trace;
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
let ticket_address = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
let mut result = draw_capture
.lock()
.map_err(|_| ExitReason::IllegalInstruction(0xff))?;
if result.is_some() {
return Err(ExitReason::IllegalInstruction(0xff));
}
if ticket_address != TICKET_ADDRESS
|| memory
.read_u64(ticket_address)
.map_err(ExitReason::MemoryFault)?
!= ticket
{
*result = Some(Err(
"guest draw ticket differed from the expected value".into()
));
return Err(ExitReason::IllegalInstruction(0xff));
}
if trace {
println!("trace import=xenora.dll!fixture_draw tls_ticket={ticket}");
}
let frame = draw().map_err(|error| error.to_string());
let drawn = frame.is_ok();
*result = Some(frame);
if drawn {
Ok(DRAW_RESULT)
} else {
Err(ExitReason::IllegalInstruction(0xff))
}
});
let started = Instant::now();
// Use only the embedded snapshot. The file is solely an exact-byte gate.
let startup = run_synthetic_startup_with_observer(
fixture,
StartupLayout {
image_base: IMAGE_BASE,
stack_top: 0x200010000,
tls_base: 0x300000000,
},
imports,
options.max_steps,
|event| {
if let Some(events) = events.as_deref_mut() {
events.stage(match &event {
StartupEvent::Parsed { .. } => "parsed",
StartupEvent::Mapped { .. } => "mapped",
StartupEvent::Relocated { .. } => "relocated",
StartupEvent::ImportsBound { .. } => "imports_bound",
StartupEvent::TlsCompleted { .. } => "tls_completed",
StartupEvent::Entering { .. } => "entry",
});
}
if options.trace {
trace_startup(event);
}
},
)?;
let host_ms = started.elapsed().as_secs_f64() * 1000.0;
let result = capture
.lock()
.map_err(|_| "fixture draw result lock failed")?
.take();
let exit = startup.execution.exit_reason;
let rax = startup.execution.final_state.get(Register::Rax);
if exit == ExitReason::Halt
&& let Some(events) = events.as_deref_mut()
{
events.stage("exit");
}
if options.trace {
println!(
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
startup.execution.instructions_executed,
);
}
if let Some(Err(error)) = &result {
return Err(format!("fixture draw failed: {error}").into());
}
if exit != ExitReason::Halt {
return Err(exit.into());
}
if startup.relocations.applied_dir64 != 4
|| startup.bound_imports != bound_imports
|| startup.tls_callbacks != 1
|| rax != DRAW_RESULT
{
return Err("trusted fixture startup or result differs from the expected values".into());
}
let frame = result.ok_or("guest halted without a draw")??;
if let Some(events) = events {
events.stage("framebuffer");
}
if options.trace {
println!(
"trace stage=framebuffer extent={}x{} verified_pixels={}",
EXTENT[0],
EXTENT[1],
EXTENT[0] * EXTENT[1],
);
}
if options.hud {
let gpu_time = frame.gpu_seconds.map_or_else(
|| "unavailable".to_owned(),
|seconds| format!("{:.3}", seconds * 1000.0),
);
println!(
"Metal HUD | device={} | offscreen={}x{} | draw_calls=1 | verified_pixels={} | host_render_readback_ms={:.3} | host_startup_ms={host_ms:.3} | gpu_command_ms={gpu_time}",
frame.device,
EXTENT[0],
EXTENT[1],
EXTENT[0] * EXTENT[1],
frame.host_render_readback_ms,
);
let metrics = startup.dbt_metrics;
println!(
"DBT | entry_steps={} | native_steps_tls_and_entry={} | blocks_compiled={} | native_bytes={} | native_dispatches={} | service_calls={} | interpreter_fallbacks={}",
startup.execution.instructions_executed,
metrics.instructions_executed,
metrics.blocks_compiled,
metrics.native_bytes_emitted,
metrics.dbt_dispatches,
metrics.service_calls,
metrics.interpreter_fallbacks,
);
}
println!("Trusted fixture completed one verified offscreen Metal draw.");
Ok(())
}
fn trace_startup(event: StartupEvent) {
match event {
StartupEvent::Parsed {
sections,
entry_rva,
} => {
println!("trace stage=parsed sections={sections} entry_rva={entry_rva:#x}");
}
StartupEvent::Mapped { entry_va } => {
println!("trace stage=mapped base={IMAGE_BASE:#x} entry_va={entry_va:#x}");
}
StartupEvent::Relocated { applied_dir64 } => {
println!("trace stage=relocated dir64_applied={applied_dir64}");
}
StartupEvent::ImportsBound { count } => {
println!("trace stage=imports_bound bound_imports={count}");
}
StartupEvent::TlsCompleted {
callbacks,
native_steps,
} => {
println!(
"trace stage=tls_completed tls_callbacks={callbacks} native_steps={native_steps}"
);
}
StartupEvent::Entering { step_limit } => {
println!("trace stage=entry step_limit={step_limit}");
}
}
}
struct Frame {
device: String,
host_render_readback_ms: f64,
gpu_seconds: Option<f64>,
}
fn draw() -> Result<Frame, Box<dyn Error>> {
let shader = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
)?;
let gpu = NativeCompute::new()?;
let started = Instant::now();
let (pixels, gpu_seconds) = gpu.render_rgba8_profiled(
&shader.msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&[
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
],
&[[0.0; 4]; 3],
EXTENT,
[19, 43, 93, 251],
)?;
let host_render_readback_ms = started.elapsed().as_secs_f64() * 1000.0;
if pixels != EXPECTED_PIXEL.repeat(EXTENT[0] * EXTENT[1]) {
return Err("offscreen readback did not match opaque red at every pixel".into());
}
Ok(Frame {
device: gpu.device_name().to_owned(),
host_render_readback_ms,
gpu_seconds,
})
}
-288
View File
@@ -1,288 +0,0 @@
//! `betterxen shaders`: instruction inventory and stream inspection.
use std::process::ExitCode;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at};
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
const USAGE: &str = "usage: betterxen shaders <coverage [--json] | inspect <gfx1030.bin>>";
pub fn command(args: &[String]) -> ExitCode {
match args.first().map(String::as_str) {
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
Some("inspect") => match args.get(1) {
Some(path) => inspect(path),
None => usage(),
},
_ => usage(),
}
}
fn usage() -> ExitCode {
eprintln!("{USAGE}");
ExitCode::from(2)
}
fn semantic(family: EncodingFamily) -> usize {
SEMANTIC_FORMS
.iter()
.filter(|(_, form_family)| *form_family == family)
.count()
}
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
/// with their length; "semantic" forms decode into executable instructions.
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
fn coverage(json: bool) -> ExitCode {
print!("{}", coverage_report(json));
ExitCode::SUCCESS
}
fn coverage_report(json: bool) -> String {
use std::fmt::Write as _;
let rows: Vec<_> = meta::inventory()
.into_iter()
.map(|(family, discovered)| (family, discovered, semantic(family)))
.collect();
let total: usize = rows.iter().map(|row| row.1).sum();
let supported: usize = rows.iter().map(|row| row.2).sum();
let mut out = String::new();
if json {
let families: Vec<String> = rows
.iter()
.map(|(family, discovered, semantic)| {
format!(
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
family.name()
)
})
.collect();
writeln!(
out,
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
meta::SOURCE_SHA256,
families.join(",")
)
.unwrap();
} else {
writeln!(
out,
"{:<10} {:>10} {:>9}",
"family", "discovered", "semantic"
)
.unwrap();
for (family, discovered, semantic) in &rows {
writeln!(out, "{:<10} {discovered:>10} {semantic:>9}", family.name()).unwrap();
}
writeln!(out, "{:<10} {total:>10} {supported:>9}", "total").unwrap();
writeln!(
out,
"Semantic forms decode for the operand subsets in docs/status.toml only."
)
.unwrap();
}
out
}
fn inspect(path: &str) -> ExitCode {
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) => {
eprintln!("{path}: {error}");
return ExitCode::FAILURE;
}
};
let listing = listing(&bytes);
for row in &listing.rows {
println!("{row}");
}
if let Some(failure) = listing.failure {
println!("{failure}");
return ExitCode::FAILURE;
}
println!(
"{} instructions inspected against {} gfx1030 forms; {} without semantic decoding",
listing.rows.len(),
FORMS.len(),
listing.unsupported
);
ExitCode::SUCCESS
}
/// The printed rows of `betterxen shaders inspect`, the number of rows that do
/// not decode into executable instructions and the identification failure
/// that ended the stream early, if any.
struct Listing {
rows: Vec<String>,
unsupported: usize,
failure: Option<String>,
}
fn listing(bytes: &[u8]) -> Listing {
let mut listing = Listing {
rows: Vec::new(),
unsupported: 0,
failure: None,
};
// Identify every instruction first: a branch target is valid only if it
// lands on one of these boundaries, which no single instruction can show.
let mut forms = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
match identify(&bytes[offset..]) {
Ok(found) => {
forms.push((offset, found));
offset += found.len;
}
Err(error) => {
listing.failure = Some(format!("{offset:#06x} decode failure: {error}"));
break;
}
}
}
let boundary = |target: usize| forms.binary_search_by_key(&target, |form| form.0).is_ok();
// Past the last identified instruction the boundaries are unknown.
let identified = forms
.last()
.map_or(0, |&(offset, found)| offset + found.len);
for &(offset, found) in &forms {
let instruction = &bytes[offset..offset + found.len];
let words: Vec<String> = instruction
.chunks(4)
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
.collect();
let status = match decode_at(Architecture::Gfx1030, &bytes[..offset + found.len], offset) {
Ok(decoded) => match decoded.branch_target() {
Some(target) if listing.failure.is_some() && target >= identified => {
format!("branch target {target:#04x} unverified: stream not identified there")
}
Some(target) if !boundary(target) => {
format!("invalid branch target {target:#04x}")
}
_ => "semantic".to_owned(),
},
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
format!("unsupported operands: {error}")
}
Err(_) => "unsupported instruction semantics".to_owned(),
};
if status != "semantic" {
listing.unsupported += 1;
}
listing.rows.push(format!(
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
found.form.family.name(),
found.form.name.to_ascii_lowercase(),
words.join(" ")
));
}
listing
}
#[cfg(test)]
mod tests {
use super::{coverage_report, listing};
use xenora_decoder::SEMANTIC_FORMS;
use xenora_isa::meta::{EncodingFamily, FORMS};
#[test]
fn coverage_totals_match_the_generated_table() {
let json = coverage_report(true);
assert!(json.starts_with("{\"architecture\":\"gfx1030\""), "{json}");
assert!(json.ends_with("}]}\n"), "{json}");
assert_eq!(json.matches('{').count(), json.matches('}').count());
let totals = format!(
"\"discovered\":{},\"semantic\":{},\"families\":[",
FORMS.len(),
SEMANTIC_FORMS.len()
);
assert!(json.contains(&totals), "{json}");
let families: Vec<usize> = json
.split("{\"family\":")
.skip(1)
.map(|row| {
let count = row.split("\"discovered\":").nth(1).unwrap();
count[..count.find(',').unwrap()].parse().unwrap()
})
.collect();
assert_eq!(families.len(), EncodingFamily::ALL.len());
assert_eq!(families.iter().sum::<usize>(), FORMS.len());
let text = coverage_report(false);
let total = format!(
"{:<10} {:>10} {:>9}\n",
"total",
FORMS.len(),
SEMANTIC_FORMS.len()
);
assert!(text.contains(&total), "{text}");
}
fn program(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
#[test]
fn branches_in_a_valid_program_are_semantic() {
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
let listing = listing(fixture);
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 15);
let branches: Vec<_> = listing
.rows
.iter()
.filter(|row| row.contains("branch"))
.collect();
assert_eq!(branches.len(), 3);
for row in &branches {
assert!(row.ends_with(" semantic"), "{row}");
}
assert_eq!(listing.unsupported, 0);
}
#[test]
fn targets_past_an_identification_failure_are_unverified() {
// s_branch 1 targets 0x08; 0xbfff0000 is not a gfx1030 form, so
// nothing past 0x04 is identified; s_endpgm.
let listing = listing(&program(&[0xbf82_0001, 0xbfff_0000, 0xbf81_0000]));
assert!(listing.failure.as_deref().unwrap().starts_with("0x0004"));
assert_eq!(listing.rows.len(), 1);
assert!(
listing.rows[0].ends_with("branch target 0x08 unverified: stream not identified there"),
"{}",
listing.rows[0]
);
}
#[test]
fn add_fixture_is_fully_semantic() {
let listing = listing(include_bytes!("../../../fixtures/rdna2/add.bin"));
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 7);
assert_eq!(listing.unsupported, 0);
}
#[test]
fn branch_targets_are_checked_against_the_whole_stream() {
// s_branch 1 skips one word; s_cbranch_scc0 1 lands inside the
// two-word v_mov_b32 literal form; s_endpgm.
let listing = listing(&program(&[
0xbf82_0001,
0xbf84_0001,
0x7e04_02ff,
0x00ff_00ff,
0xbf81_0000,
]));
assert_eq!(listing.failure, None);
assert!(
listing.rows[0].ends_with(" semantic"),
"{}",
listing.rows[0]
);
assert!(
listing.rows[1].ends_with("invalid branch target 0x0c"),
"{}",
listing.rows[1]
);
assert_eq!(listing.unsupported, 1);
}
}
-399
View File
@@ -1,399 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::fmt::Write as _;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use std::process::ExitStatus;
use std::sync::atomic::{AtomicUsize, Ordering};
pub(super) const WATCHDOG_EXIT: u8 = 124;
pub(super) const JOURNAL_ERROR_EXIT: u8 = 125;
const VERSION: &str = "1";
const RECORD_SEPARATOR: char = '\t';
const MAX_BYTES: usize = 8192;
const MAX_ERROR_BYTES: usize = 2048;
const STAGES: [&str; 8] = [
"parsed",
"mapped",
"relocated",
"imports_bound",
"tls_completed",
"entry",
"exit",
"framebuffer",
];
pub(super) struct Journal(PathBuf);
impl Journal {
pub(super) fn create() -> io::Result<Self> {
static NEXT: AtomicUsize = AtomicUsize::new(0);
loop {
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let directory =
std::env::temp_dir().join(format!("betterxen-startup-{}-{id}", std::process::id()));
match fs::DirBuilder::new().mode(0o700).create(&directory) {
Ok(()) => return Ok(Self(directory)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
pub(super) fn path(&self) -> PathBuf {
self.0.join("events")
}
fn read(&self) -> Report {
let mut bytes = Vec::new();
match File::open(self.path())
.and_then(|file| file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes))
{
Ok(_) => Report::parse(&bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => Report::default(),
Err(_) => Report {
integrity: "unreadable",
..Report::default()
},
}
}
pub(super) fn finish(
&self,
mut destination: File,
termination: &io::Result<Termination>,
) -> io::Result<()> {
destination.write_all(self.read().json(termination).as_bytes())
}
}
impl Drop for Journal {
fn drop(&mut self) {
let _ = fs::remove_file(self.path());
let _ = fs::remove_dir(&self.0);
}
}
pub(super) struct Events(File, Option<io::Error>);
impl Events {
pub(super) fn open(path: &Path) -> io::Result<Self> {
OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map(|file| Self(file, None))
}
pub(super) fn stage(&mut self, stage: &str) {
self.record(format_args!("{VERSION}\t{stage}"));
}
pub(super) fn failure(&mut self, error: &dyn std::error::Error) {
let message = error.to_string();
let end = message.floor_char_boundary(MAX_ERROR_BYTES);
let mut encoded = String::with_capacity(end * 2);
for byte in message[..end].bytes() {
write!(encoded, "{byte:02x}").unwrap();
}
self.record(format_args!(
"{VERSION}\tfailure\t{}\t{encoded}",
u8::from(end < message.len())
));
}
fn record(&mut self, arguments: std::fmt::Arguments<'_>) {
if self.1.is_none() {
self.1 = writeln!(self.0, "{arguments}").err();
}
}
pub(super) fn write_error(&self) -> Option<&io::Error> {
self.1.as_ref()
}
}
pub(super) enum Termination {
Exited(ExitStatus),
Deadline,
}
struct Report {
completed: usize,
error: Option<String>,
error_truncated: bool,
integrity: &'static str,
}
impl Default for Report {
fn default() -> Self {
Self {
completed: 0,
error: None,
error_truncated: false,
integrity: "complete",
}
}
}
impl Report {
fn parse(bytes: &[u8]) -> Self {
let mut report = Self::default();
let bounded = &bytes[..bytes.len().min(MAX_BYTES)];
for line in bounded.split_inclusive(|&byte| byte == b'\n') {
let Some(line) = line.strip_suffix(b"\n") else {
report.integrity = "truncated";
break;
};
if !std::str::from_utf8(line).is_ok_and(|line| report.record(line)) {
report.integrity = "malformed";
break;
}
}
if bytes.len() > MAX_BYTES {
report.integrity = "oversized";
}
report
}
fn record(&mut self, line: &str) -> bool {
let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else {
return false;
};
if self.error.is_some() {
return false;
}
if STAGES.get(self.completed) == Some(&record) {
self.completed += 1;
return true;
}
let Some((truncated, encoded)) = record
.strip_prefix("failure\t")
.and_then(|s| s.split_once('\t'))
else {
return false;
};
if !matches!(truncated, "0" | "1")
|| encoded.len() > MAX_ERROR_BYTES * 2
|| !encoded.len().is_multiple_of(2)
|| !encoded.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return false;
}
let (pairs, _) = encoded.as_bytes().as_chunks::<2>();
let Some(message) = pairs
.iter()
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
.collect::<Option<Vec<_>>>()
.and_then(|bytes| String::from_utf8(bytes).ok())
else {
return false;
};
self.error = Some(message);
self.error_truncated = truncated == "1";
true
}
fn json(&self, termination: &io::Result<Termination>) -> String {
let unwritable = matches!(termination, Ok(Termination::Exited(status))
if status.code() == Some(i32::from(JOURNAL_ERROR_EXIT)));
let integrity = if unwritable {
"unwritable"
} else {
self.integrity
};
let (outcome, status, detail) = match termination {
Ok(Termination::Deadline) => (
"timeout",
None,
Some("worker exceeded the wall deadline".into()),
),
Err(error) => ("unknown", None, Some(error.to_string())),
Ok(Termination::Exited(status)) if status.code() == Some(i32::from(WATCHDOG_EXIT)) => (
"timeout",
Some(status),
Some("worker watchdog expired".into()),
),
Ok(Termination::Exited(status)) if unwritable => (
"unknown",
Some(status),
Some("worker could not write its startup journal".into()),
),
Ok(Termination::Exited(status))
if status.success()
&& self.error.is_none()
&& self.completed == STAGES.len()
&& self.integrity == "complete" =>
{
("verified", Some(status), None)
}
Ok(Termination::Exited(status))
if status.code().is_some() && !status.success() && self.error.is_some() =>
{
("stage_failure", Some(status), None)
}
Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => {
("early_exit", Some(status), Some(status.to_string()))
}
Ok(Termination::Exited(status)) => ("unknown", Some(status), Some(status.to_string())),
};
let stages = &STAGES[..self.completed];
let records = stages
.iter()
.map(|stage| format!(r#"{{"schema_version":{VERSION},"stage":"{stage}"}}"#))
.collect::<Vec<_>>()
.join(",");
let last = json_string(stages.last().copied());
let error = json_string(self.error.as_deref());
let detail = json_string(detail.as_deref());
let code = status
.and_then(|status| status.code())
.map_or("null".into(), |code| code.to_string());
format!(
"{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n",
integrity, self.error_truncated
)
}
}
fn json_string(value: Option<&str>) -> String {
let Some(value) = value else {
return String::from("null");
};
let mut escaped = String::from("\"");
for ch in value.chars() {
match ch {
'"' => escaped.push_str("\\\""),
'\\' => escaped.push_str("\\\\"),
'\0'..='\u{1f}' => write!(escaped, "\\u{:04x}", u32::from(ch)).unwrap(),
_ => escaped.push(ch),
}
}
escaped.push('"');
escaped
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
use std::time::{Duration, Instant};
#[test]
fn journal_write_error_surfaces_in_report() {
use std::os::unix::process::ExitStatusExt;
let journal = Journal::create().unwrap();
fs::write(journal.path(), b"1\tparsed\n").unwrap();
let mut events = Events(File::open(journal.path()).unwrap(), None);
events.stage("mapped");
assert!(events.write_error().is_some());
let status = ExitStatus::from_raw(i32::from(JOURNAL_ERROR_EXIT) << 8);
let result = journal.read().json(&Ok(Termination::Exited(status)));
assert!(
result.contains(r#""record_integrity":"unwritable""#),
"{result}"
);
assert!(
result.contains(r#""last_completed_stage":"parsed""#),
"{result}"
);
}
#[test]
fn terminal_failure_keeps_signal_detail_after_all_stages() {
use std::os::unix::process::ExitStatusExt;
let journal = Journal::create().unwrap();
let mut events = Events::open(&journal.path()).unwrap();
for stage in STAGES {
events.stage(stage);
}
events.failure(&io::Error::other("late error"));
let report = journal.read();
assert_eq!(report.integrity, "complete");
let result = report.json(&Ok(Termination::Exited(ExitStatus::from_raw(15))));
assert!(result.contains(r#""outcome":"unknown""#), "{result}");
assert!(result.contains(r#""error":"late error""#), "{result}");
assert!(result.contains("signal: 15"), "{result}");
}
#[test]
fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() {
for (script, limit, outcome, code) in [
("exit 9", Duration::from_secs(2), "early_exit", "9"),
("exit 124", Duration::from_secs(2), "timeout", "124"),
("kill -TERM $$", Duration::from_secs(2), "unknown", "null"),
(
"exec sleep 5",
Duration::from_millis(250),
"timeout",
"null",
),
] {
let journal = Journal::create().unwrap();
let started = Instant::now();
let child = Command::new("/bin/sh")
.args([
"-c",
&format!("printf '1\\tparsed\\n' > \"$1\"; {script}"),
"worker",
])
.arg(journal.path())
.spawn()
.unwrap();
let termination = super::super::supervise(child, started, limit);
let report = journal.read().json(&termination);
assert!(
report.contains(&format!(r#""outcome":"{outcome}""#)),
"{report}"
);
assert!(
report.contains(&format!(r#""worker_exit_code":{code}"#)),
"{report}"
);
assert!(
report.contains(r#""last_completed_stage":"parsed""#),
"{report}"
);
}
}
#[test]
fn invalid_records_keep_only_the_valid_prefix() {
let mut oversized = b"1\tparsed\n1\tmapped".to_vec();
oversized.resize(MAX_BYTES + 1, b'x');
for (bytes, integrity) in [
(&b"1\tparsed\n1\tmapped"[..], "truncated"),
(&b"1\tparsed\n1\tentry\n1\tmapped\n"[..], "malformed"),
(&b"1\tparsed\n1\tfailure\t0\tqq\n"[..], "malformed"),
(oversized.as_slice(), "oversized"),
] {
let journal = Journal::create().unwrap();
fs::write(journal.path(), bytes).unwrap();
let report = journal.read();
assert_eq!(report.completed, 1);
assert_eq!(report.integrity, integrity);
assert!(report.error.is_none());
}
}
#[test]
fn failure_preserves_original_context_with_bounded_utf8() {
let journal = Journal::create().unwrap();
let mut events = Events::open(&journal.path()).unwrap();
events.stage("parsed");
let message = format!("line\nwith \"quote\" and \\{}", "é".repeat(MAX_ERROR_BYTES));
events.failure(&io::Error::other(&message[..]));
let report = journal.read();
assert_eq!(
report.error.as_deref(),
Some(&message[..message.floor_char_boundary(MAX_ERROR_BYTES)])
);
assert!(report.error_truncated);
let json = report.json(&Ok(Termination::Deadline));
assert!(
json.contains(r#"line\u000awith \"quote\" and \\"#),
"{json}"
);
}
}
-27
View File
@@ -1,27 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Default report folder of `betterxen probe` and `betterxen imports sync`.
use std::process::Command;
#[test]
fn probe_and_sync_use_the_same_default_folder() {
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/delay-imports.exe"
);
let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id()));
std::fs::create_dir(&folder).unwrap();
for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] {
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args(arguments)
.current_dir(&folder)
.status()
.unwrap();
assert!(status.success(), "{arguments:?}");
}
let written = ["imports.csv", "import_backlog.md"]
.map(|name| folder.join("diagnostics/probe").join(name).is_file());
std::fs::remove_dir_all(folder).unwrap();
assert_eq!(written, [true, true]);
}
-35
View File
@@ -1,35 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! `betterxen imports sync` over a probe report that lists delay-loaded imports.
use std::process::Command;
#[test]
fn backlog_leaves_out_delay_loaded_imports() {
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/delay-imports.exe"
);
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
let betterxen = |arguments: &[&str]| {
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args(arguments)
.arg("--report")
.arg(&report)
.status()
.unwrap();
assert!(status.success(), "{arguments:?}");
};
betterxen(&["probe", "--pe", fixture]);
betterxen(&["imports", "sync"]);
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
std::fs::remove_dir_all(report).unwrap();
assert_eq!(listed.matches(",delayed,").count(), 3);
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
assert!(!backlog.contains("fixture-delay"), "{backlog}");
}
-57
View File
@@ -1,57 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The import generator skips emitting an adapter for a symbol it classifies
//! as a standard service, so every such classification must name a handler
//! the standard loader registry actually provides.
use std::sync::Arc;
use xenora_import_gen::{Classification, SymbolDb};
use xenora_loader::import_table::ImportName;
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
#[test]
fn every_standard_service_classification_resolves_to_a_registered_handler() {
let mut registry = ImportRegistry::new();
let state = ServicesState::new(Arc::new(MockClock::new(0)));
register_standard_services(&mut registry, Arc::new(state));
let db = SymbolDb::builtin();
let mut checked = 0;
let mut missing = Vec::new();
for (module, symbol, class) in db.entries() {
if !matches!(class, Classification::StandardService) {
continue;
}
checked += 1;
match registry.resolve(module, &ImportName::Name(symbol.to_string())) {
Some(service) if service.status != ServiceStatus::Stub => {}
_ => missing.push(format!("{module}!{symbol}")),
}
}
assert!(missing.is_empty(), "unregistered: {missing:?}");
assert!(checked > 100, "{checked}");
}
#[test]
fn registered_synchronization_services_are_not_classified_as_stubs() {
let db = SymbolDb::builtin();
for module in ["api-ms-win-core-synch-l1-1-0.dll", "kernel32.dll"] {
for symbol in [
"CreateSemaphoreW",
"ReleaseSemaphore",
"CreateMutexW",
"EnterCriticalSection",
"TryEnterCriticalSection",
"AcquireSRWLockExclusive",
] {
assert!(
matches!(
db.get(module, symbol),
Some(Classification::StandardService)
),
"{module}!{symbol}"
);
}
}
}
-109
View File
@@ -1,109 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::process::Command;
const STARTUP_STAGES: &[&str] = &[
"parsed",
"mapped",
"relocated",
"imports_bound",
"tls_completed",
"entry",
];
#[test]
fn trusted_fixture_preserves_step_failure() {
let report = run_fixture("1", false);
assert!(report.contains(r#""outcome":"stage_failure""#), "{report}");
assert!(
report.contains(r#""last_completed_stage":"entry""#),
"{report}"
);
assert!(report.contains("step budget exhausted"), "{report}");
assert_stages(&report, STARTUP_STAGES);
assert!(!report.contains(r#""stage":"exit""#), "{report}");
}
#[test]
#[ignore = "requires a native Metal device with Apple family 7 capabilities"]
fn trusted_fixture_reports_verified_progress() {
let report = run_fixture("100", true);
assert!(report.contains(r#""outcome":"verified""#), "{report}");
assert!(
report.contains(r#""last_completed_stage":"framebuffer""#),
"{report}"
);
let stages = [STARTUP_STAGES, &["exit", "framebuffer"]].concat();
assert_stages(&report, &stages);
}
fn run_fixture(steps: &str, success: bool) -> String {
let path = std::env::temp_dir().join(format!(
"betterxen-report-test-{}-{steps}.json",
std::process::id()
));
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let output = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args([
"run",
"--experimental",
"--pe",
fixture,
"--max-steps",
steps,
"--startup-report",
])
.arg(&path)
.output()
.unwrap();
let report = std::fs::read_to_string(&path);
if report.is_ok() {
std::fs::remove_file(&path).unwrap();
}
assert_eq!(output.status.success(), success, "{output:?}, {report:?}");
report.unwrap()
}
fn assert_stages(report: &str, stages: &[&str]) {
assert!(report.contains(r#""schema_version":1"#), "{report}");
let mut remaining = report;
for stage in stages {
remaining = remaining
.split_once(&format!(r#""stage":"{stage}""#))
.unwrap()
.1;
}
}
#[test]
fn existing_report_path_prevents_worker_launch() {
let path = std::env::temp_dir().join(format!(
"betterxen-report-existing-{}.json",
std::process::id()
));
std::fs::write(&path, "previous report").unwrap();
let result = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args([
"run",
"--experimental",
"--pe",
"missing-fixture",
"--startup-report",
])
.arg(&path)
.output()
.unwrap();
let contents = std::fs::read_to_string(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(contents, "previous report");
assert!(!result.status.success());
let stderr = String::from_utf8(result.stderr).unwrap();
assert!(
stderr.contains("could not create startup report"),
"{stderr}"
);
assert!(!stderr.contains("No such file or directory"), "{stderr}");
}
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "xenora-decoder"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
publish = false
[dependencies]
xenora-isa = { path = "../isa" }
[dev-dependencies]
xenora-ref = { path = "../ref" }
[lints]
workspace = true
-791
View File
@@ -1,791 +0,0 @@
//! Decoder for Xenora's bounded little-endian gfx1030 instruction stream.
use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
VectorSource, VectorSwapOp, VectorUnaryOp,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
};
use xenora_isa::meta::EncodingFamily;
use xenora_isa::semantics::{FORM_IDS, OperandRule};
pub use xenora_isa::semantics::{VectorBinary, VectorLowering, VectorUnary, VectorVcc};
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination: the hand-written forms below followed by every form of
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
/// restrictions are listed in docs/status.toml; every other form in
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
concat_forms();
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
let mut forms = [("", EncodingFamily::Sop2); N];
let mut index = 0;
while index < N {
forms[index] = if index < HANDWRITTEN_FORMS.len() {
HANDWRITTEN_FORMS[index]
} else {
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
};
index += 1;
}
forms
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 10] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("V_ADD_F32", EncodingFamily::Vop2),
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
("V_MOV_B32", EncodingFamily::Vop1),
("V_MUL_F32", EncodingFamily::Vop2),
];
/// A successfully decoded instruction and its location in the input stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodedInstruction {
/// Byte offset from the start of the stream.
pub offset: usize,
/// Total size in bytes, including any literal word.
pub byte_len: u8,
/// The decoded instruction and operand fields.
pub instruction: Instruction,
}
impl DecodedInstruction {
/// Destination byte offset of a branch, from the start of the stream.
#[must_use]
pub fn branch_target(&self) -> Option<usize> {
match self.instruction {
Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } => Some(target),
_ => None,
}
}
}
impl fmt::Display for DecodedInstruction {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
}
}
/// Decoder failures classified for callers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DecodeErrorKind {
/// An instruction, second word or literal extends past the available input.
Truncated {
/// Number of bytes required at the instruction start.
needed: u8,
/// Number of bytes available at the instruction start.
available: usize,
},
/// No supported opcode pattern matches the first word.
UnsupportedOpcode {
/// First instruction word in host integer order.
word: u32,
},
/// A supported opcode uses an operand or modifier outside the subset.
UnsupportedForm {
/// Opcode mnemonic.
mnemonic: &'static str,
/// Details of the unsupported or reserved fields.
detail: &'static str,
},
/// A forward branch leaves the stream or lands inside an instruction.
InvalidBranchTarget {
/// Destination byte offset from the start of the stream.
target: usize,
},
}
/// A decoder error and the offset of the offending instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodeError {
/// Byte offset from the start of the stream.
pub offset: usize,
/// Decoder-specific failure.
pub kind: DecodeErrorKind,
}
impl fmt::Display for DecodeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "gfx1030 decode at byte 0x{:x}: ", self.offset)?;
match self.kind {
DecodeErrorKind::Truncated { needed, available } => {
write!(
formatter,
"instruction requires {needed} bytes, found {available}"
)
}
DecodeErrorKind::UnsupportedOpcode { word } => {
write!(formatter, "unsupported opcode in 0x{word:08x}")
}
DecodeErrorKind::UnsupportedForm { mnemonic, detail } => {
write!(formatter, "unsupported {mnemonic} form: {detail}")
}
DecodeErrorKind::InvalidBranchTarget { target } => {
write!(
formatter,
"branch target 0x{target:x} is outside instruction boundaries"
)
}
}
}
}
impl std::error::Error for DecodeError {}
/// Decodes a stream of instructions. Program termination, memory hazards and
/// register initialization are checked by later stages.
///
/// # Errors
///
/// Returns the failing byte offset for a truncated instruction, unsupported
/// opcode, unsupported form or invalid branch target. An empty stream
/// decodes to an empty list.
pub fn decode(
architecture: Architecture,
bytes: &[u8],
) -> Result<Vec<DecodedInstruction>, DecodeError> {
let mut result = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
let decoded = decode_at(architecture, bytes, offset)?;
offset += usize::from(decoded.byte_len);
result.push(decoded);
}
for decoded in &result {
if let Some(target) = decoded.branch_target()
&& result
.binary_search_by_key(&target, |item| item.offset)
.is_err()
{
return Err(DecodeError {
offset: decoded.offset,
kind: DecodeErrorKind::InvalidBranchTarget { target },
});
}
}
Ok(result)
}
/// Decodes the one instruction that starts at `offset` in `bytes`. Branch
/// targets are stream offsets, but whether they land on an instruction
/// boundary is left to the caller, which knows the rest of the stream.
///
/// # Errors
///
/// Returns `offset` with a truncated instruction, unsupported opcode or
/// unsupported form. An `offset` at or past the end is truncated.
pub fn decode_at(
architecture: Architecture,
bytes: &[u8],
offset: usize,
) -> Result<DecodedInstruction, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let rest = bytes.get(offset..).unwrap_or_default();
let (instruction, byte_len) =
decode_instruction(rest, offset).map_err(|kind| DecodeError { offset, kind })?;
Ok(DecodedInstruction {
offset,
byte_len,
instruction,
})
}
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
let end_index = usize::from(end);
let Some(word) = bytes
.get(end_index - 4..end_index)
.and_then(|word| <[u8; 4]>::try_from(word).ok())
else {
return Err(DecodeErrorKind::Truncated {
needed: end,
available: bytes.len(),
});
};
Ok(u32::from_le_bytes(word))
}
fn unsupported(mnemonic: &'static str, detail: &'static str) -> DecodeErrorKind {
DecodeErrorKind::UnsupportedForm { mnemonic, detail }
}
fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), DecodeErrorKind> {
let first = word(bytes, 4)?;
if BUFFER_LOAD_DWORD.matches(first) {
let len = BUFFER_LOAD_DWORD.byte_len();
let second = word(bytes, len)?;
let (data, index, resource) = buffer_operands(first, second, "buffer_load_dword")?;
return Ok((
Instruction::BufferLoadDword {
data,
index,
resource,
},
len,
));
}
if BUFFER_STORE_DWORD.matches(first) {
let len = BUFFER_STORE_DWORD.byte_len();
let second = word(bytes, len)?;
let (data, index, resource) = buffer_operands(first, second, "buffer_store_dword")?;
return Ok((
Instruction::BufferStoreDword {
data,
index,
resource,
},
len,
));
}
if EXP.matches(first) {
let len = EXP.byte_len();
let sources = word(bytes, len)?.to_le_bytes();
// RDNA 2 ISA Table 56. Match all operand and reserved bits, including
// the four enable bits, compression, DONE and valid-mask flags.
let target = match first & 0x03ff_ffff {
0x08cf => ExportTarget::Position0,
0x020f => ExportTarget::Parameter0,
0x180f => ExportTarget::RenderTarget0,
_ => {
return Err(unsupported(
"exp",
"expected full uncompressed POS0 done, PARAM0, or MRT0 done vm",
));
}
};
return Ok((Instruction::Export { target, sources }, len));
}
if IMAGE_SAMPLE_LZ.matches(first) {
let len = IMAGE_SAMPLE_LZ.byte_len();
let second = word(bytes, len)?;
let (dst, coord, resource, sampler) =
image_sample_operands(first, second, "image_sample_lz")?;
return Ok((
Instruction::ImageSampleLz {
dst,
coord,
resource,
sampler,
},
len,
));
}
for (opcode, phase) in [
(V_INTERP_P1_F32, InterpolationPhase::First),
(V_INTERP_P2_F32, InterpolationPhase::Second),
] {
if opcode.matches(first) {
return Ok((
Instruction::Interpolate {
phase,
dst: (first >> 18) as u8,
coordinate: first as u8,
attribute: ((first >> 10) & 0x3f) as u8,
component: ((first >> 8) & 3) as u8,
},
opcode.byte_len(),
));
}
}
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
// AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8.
if let Some(op) = VectorUnaryOp::from_word(first) {
let dst = (first >> 17) as u8;
let (src, len) = vector_src0(first, bytes, op.assembly_name())?;
return Ok((Instruction::VectorUnary { op, dst, src }, len));
}
if let Some(op) = VectorSwapOp::from_word(first) {
if first & 0x100 == 0 {
return Err(unsupported(
op.assembly_name(),
"expected a VGPR SRC0 for writeback",
));
}
let dst = (first >> 17) as u8;
let src = first as u8;
return Ok((Instruction::VectorSwap { op, dst, src }, 4));
}
if let Some(op) = VectorCompareOp::from_word(first) {
return vector_compare(op, first, bytes);
}
if let Some(op) = VectorCompareVop3Op::from_word(first) {
let second = word(bytes, 8)?;
let sdst = first as u8;
if sdst > VCC_LO {
return Err(unsupported(
op.assembly_name(),
"expected a destination of s0-s105 or vcc_lo",
));
}
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
return Ok((
Instruction::VectorCompareVop3 {
op,
sdst,
src0,
src1,
},
8,
));
}
if let Some(op) = VectorAluVop3Op::from_word(first) {
let second = word(bytes, 8)?;
return Ok((vop3_vgpr2(op, first, second)?, 8));
}
if let Some(op) = ScalarUnaryOp::from_word(first) {
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
match op.semantics().operands {
OperandRule::Sop1Move if !matches!(dst, 0..=107 | 126..=127) => {
return Err(unsupported(
mnemonic,
"expected a normal SGPR or EXEC/VCC destination",
));
}
OperandRule::Sop1Sgpr if dst > 105 => {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
_ => {}
}
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
}
if let Some(op) = ScalarCompareOp::from_word(first) {
let mnemonic = op.mnemonic();
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
mnemonic,
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
return Ok((
Instruction::ScalarCompare { op, src0, src1 },
len0.max(len1),
));
}
if let Some(op) = ScalarImmediateOp::from_word(first) {
// SOPK: SIMM16 in bits 0-15, SDST in bits 16-22; the word has no literal.
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(
op.mnemonic(),
"expected a normal SGPR destination",
));
}
let simm16 = first as u16;
return Ok((Instruction::ScalarImmediate { op, dst, simm16 }, 4));
}
if let Some(op) = ScalarImmediateCompareOp::from_word(first) {
let src = ((first >> 16) & 0x7f) as u8;
if src > 105 {
return Err(unsupported(op.mnemonic(), "expected a normal SGPR operand"));
}
let simm16 = first as u16;
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
}
if let Some(op) = SoppControlOp::from_word(first) {
let immediate = first as u16;
if op
.required_immediate()
.is_some_and(|exact| immediate != exact)
{
let detail = if op == SoppControlOp::EndProgram {
"expected zero immediate"
} else {
"expected vmcnt(0) alone"
};
return Err(unsupported(op.mnemonic(), detail));
}
let instruction = op.decode(|| branch_target(immediate, offset, op.mnemonic()))?;
return Ok((instruction, 4));
}
if let Some(op) = ScalarAluOp::from_word(first) {
return scalar_alu(op, first, bytes);
}
if let Some(op) = VectorAluOp::from_word(first) {
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
let dst = ((first >> 17) & 0xff) as u8;
let src1 = ((first >> 9) & 0xff) as u8;
let (src0, len) = match op.operand_rule() {
// Operand rule `vop2_vgpr2`: SRC0 must select a VGPR (256-511).
OperandRule::Vop2Vgpr2 => {
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
(VectorSource::Register(src0), 4)
}
OperandRule::Vop2Vgpr | OperandRule::Vop2Vcc => {
vector_src0(first, bytes, op.assembly_name())?
}
_ => unreachable!("non-VOP2 operand rule for VOP2 instruction"),
};
return Ok((
Instruction::VectorAlu {
op,
dst,
src0,
src1,
},
len,
));
}
if V_ADD_F32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_add_f32_e32")?;
return Ok((
Instruction::VectorAddF32 { dst, src0, src1 },
V_ADD_F32.byte_len(),
));
}
if V_MUL_F32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_mul_f32_e32")?;
return Ok((
Instruction::VectorMulF32 { dst, src0, src1 },
V_MUL_F32.byte_len(),
));
}
if S_WAITCNT_VSCNT.matches(first) {
return scalar_form(
first,
S_WAITCNT_VSCNT.byte_len(),
0xbbfd_0000,
Instruction::WaitStore,
"expected null, 0",
);
}
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
}
/// SOP2: SSRC0 in bits 0-7, SSRC1 in bits 8-15, SDST in bits 16-22.
/// Other SOP2 opcodes stay unsupported.
fn scalar_alu(
op: ScalarAluOp,
first: u32,
bytes: &[u8],
) -> Result<(Instruction, u8), DecodeErrorKind> {
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
mnemonic,
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
Ok((
Instruction::ScalarAlu {
op,
dst,
src0,
src1,
},
len0.max(len1),
))
}
fn scalar_source(
bits: u8,
bytes: &[u8],
mnemonic: &'static str,
) -> Result<(ScalarSource, u8), DecodeErrorKind> {
let value = u32::from(bits);
match bits {
0..=105 => Ok((ScalarSource::Register(bits), 4)),
128..=192 => Ok((ScalarSource::Immediate(value - 128), 4)),
193..=208 => Ok((ScalarSource::Immediate(192u32.wrapping_sub(value)), 4)),
255 => Ok((ScalarSource::Immediate(word(bytes, 8)?), 8)),
_ => Err(unsupported(
mnemonic,
"expected a normal SGPR, inline integer or literal",
)),
}
}
fn branch_target(
immediate: u16,
offset: usize,
mnemonic: &'static str,
) -> Result<usize, DecodeErrorKind> {
let displacement = immediate as i16;
let words = usize::try_from(displacement)
.map_err(|_| unsupported(mnemonic, "expected a forward branch"))?;
offset
.checked_add(4 + words * 4)
.ok_or_else(|| unsupported(mnemonic, "target byte offset overflowed"))
}
fn vop2_registers(first: u32, mnemonic: &'static str) -> Result<(u8, u8, u8), DecodeErrorKind> {
if first & 0x100 == 0 {
return Err(unsupported(
mnemonic,
"expected two unmodified VGPR sources",
));
}
Ok(((first >> 17) as u8, first as u8, (first >> 9) as u8))
}
fn image_sample_operands(
first: u32,
second: u32,
mnemonic: &'static str,
) -> Result<(u8, u8, u8, u8), DecodeErrorKind> {
// In word 0:
// Bits 1..2: NSA (must be 0 for contiguous VADDR)
// Bits 3..5: DIM (1 = SQ_RSRC_IMG_2D)
// Bit 7: DLC (0)
// Bits 8..11: DMASK (0xf for RGBA 4-component return)
// Bit 12: UNORM (0)
// Bit 13: GLC (0)
// Bit 14: DA (0)
// Bit 15: R128 (0)
// Bit 16: TFE (0)
// Bit 25: SLC (0)
// Bit 0 & Bits 18..24: OP (0x27 / 39)
// Bits 26..31: ENCODING (0x3c)
// Mask off OP and ENCODING (bits 0, 18..24, 26..31).
// The expected variable bits for 2D RGBA8 sampling:
// dim = 1 (bits 3..5 = 1 << 3 = 0x8), dmask = 0xf (bits 8..11 = 0xf << 8 = 0xf00).
// All other modifier flags (NSA, DLC, UNORM, GLC, DA, R128, TFE, SLC) must be zero.
const MODIFIER_MASK: u32 = 0x0203_fffe;
const EXPECTED_2D_RGBA: u32 = 0x0000_0f08;
if first & MODIFIER_MASK != EXPECTED_2D_RGBA {
return Err(unsupported(
mnemonic,
"expected dim:SQ_RSRC_IMG_2D and dmask:0xf with zero modifier flags",
));
}
// In word 1:
// Bits 0..7: VADDR (u8)
// Bits 8..15: VDATA (u8)
// Bits 16..20: SRSRC >> 2 (5 bits)
// Bits 21..25: SSAMP >> 2 (5 bits)
// Bits 26..29: reserved (must be 0)
// Bit 30: A16 (0)
// Bit 31: D16 (0)
if second & 0xfc00_0000 != 0 {
return Err(unsupported(
mnemonic,
"expected 32-bit float coordinates and data without A16/D16",
));
}
let coord = (second & 0xff) as u8;
let dst = ((second >> 8) & 0xff) as u8;
let resource = (((second >> 16) & 0x1f) * 4) as u8;
let sampler = (((second >> 21) & 0x1f) * 4) as u8;
// RDNA 2 resource descriptor (T#) requires 8 SGPRs; sampler (S#) requires 4 SGPRs.
// SGPR range is 0..=105 for normal allocatable registers.
if resource > 98 {
return Err(unsupported(
mnemonic,
"resource descriptor must fit in normal SGPRs s[0:105]",
));
}
if sampler > 102 {
return Err(unsupported(
mnemonic,
"sampler descriptor must fit in normal SGPRs s[0:105]",
));
}
Ok((dst, coord, resource, sampler))
}
fn buffer_operands(
first: u32,
second: u32,
mnemonic: &'static str,
) -> Result<(u8, u8, u8), DecodeErrorKind> {
// OFFSET, OFFEN, IDXEN, GLC, DLC, LDS and the reserved bit before OP.
const ADDRESS_MODE_MASK: u32 = 0x0003_ffff;
const IDXEN: u32 = 1 << 13;
// SOFFSET is inline zero. TFE, SLC and the reserved high operand bit are zero.
if first & ADDRESS_MODE_MASK != IDXEN || second & 0xffe0_0000 != 0x8000_0000 {
return Err(unsupported(
mnemonic,
"expected idxen alone with zero offsets",
));
}
let index = second as u8;
let data = (second >> 8) as u8;
let resource = ((second >> 16) & 0x1f) as u8 * 4;
// AMD RDNA 2 ISA §3.6.2. A resource descriptor requires four normal SGPRs.
if resource > 102 {
return Err(unsupported(
mnemonic,
"resource descriptor must fit in normal SGPRs",
));
}
Ok((data, index, resource))
}
/// VOPC: SRC0 in bits 0-8, VSRC1 in bits 9-16 (RDNA 2 ISA section 12.9). The
/// destination is implicitly `vcc_lo`. SRC0 excludes inline float constants,
/// `vcc_hi`, EXEC, M0, TTMPs and the condition selectors (SDWA 249, DPP 250/233).
fn vector_compare(
op: VectorCompareOp,
first: u32,
bytes: &[u8],
) -> Result<(Instruction, u8), DecodeErrorKind> {
let src1 = ((first >> 9) & 0xff) as u8;
let mnemonic = op.assembly_name();
if op.semantics().width == 64 {
// Guide §3.6.3 requires even SGPR bases. Reject invalid selectors
// before reading a literal word or considering the execution mask.
let source = first & 0x1ff;
if src1 == 255
|| !matches!(source, 0..=104 | 128..=208 | 256..=510)
|| (source <= 104 && !source.is_multiple_of(2))
{
return Err(unsupported(mnemonic, "invalid 64-bit compare source"));
}
}
if op.semantics().width == 16 && first & 0x1ff == 255 {
return Err(unsupported(mnemonic, "literal in 16-bit compare"));
}
let (src0, len) = vector_src0(first, bytes, mnemonic)?;
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
}
/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an
/// inline integer -16..64 or a literal word; everything else is unsupported.
fn vector_src0(
first: u32,
bytes: &[u8],
mnemonic: &'static str,
) -> Result<(VectorSource, u8), DecodeErrorKind> {
let source = first & 0x1ff;
let base_len = 4;
Ok(match source {
0..=106 => (VectorSource::Scalar(source as u8), base_len),
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
VectorSource::Immediate(192u32.wrapping_sub(source)),
base_len,
),
255 => {
let len = base_len + 4;
(VectorSource::Immediate(word(bytes, len)?), len)
}
256..=511 => (VectorSource::Register(source as u8), base_len),
_ => {
return Err(unsupported(
mnemonic,
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
));
}
})
}
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
let dst = (first >> 17) as u8;
let source = first & 0x1ff;
let base_len = V_MOV_B32.byte_len();
let (src, len) = match source {
0..=105 => (VectorSource::Scalar(source as u8), base_len),
// vcc_lo, which may hold a lane-derived compare mask (docs/shaders/vector-compare.md).
106 => (VectorSource::Scalar(VCC_LO), base_len),
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
VectorSource::Immediate(192u32.wrapping_sub(source)),
base_len,
),
// AMD RDNA 2 ISA Table 77: VOP1 source selector 242 supplies +1.0f.
242 => (VectorSource::Immediate(0x3f80_0000), base_len),
255 => {
let len = base_len + 4;
(VectorSource::Immediate(word(bytes, len)?), len)
}
256..=511 => (VectorSource::Register(source as u8), base_len),
_ => {
return Err(unsupported(
"v_mov_b32_e32",
"expected a VGPR, normal SGPR, vcc_lo, inline integer, inline +1.0f or literal",
));
}
};
Ok((Instruction::MoveB32 { dst, src }, len))
}
fn vop3_vgpr2(
op: VectorAluVop3Op,
first: u32,
second: u32,
) -> Result<Instruction, DecodeErrorKind> {
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
Ok(Instruction::VectorAluVop3 {
op,
dst: first as u8,
src0,
src1,
})
}
/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4).
/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL,
/// CLAMP, OMOD and NEG are clear.
fn vop3_vgpr2_sources(
mnemonic: &'static str,
first: u32,
second: u32,
) -> Result<(u8, u8), DecodeErrorKind> {
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(unsupported(
mnemonic,
"expected two VGPR sources and no modifiers",
));
}
Ok((src0 as u8, src1 as u8))
}
fn scalar_form(
word: u32,
byte_len: u8,
expected: u32,
instruction: Instruction,
detail: &'static str,
) -> Result<(Instruction, u8), DecodeErrorKind> {
if word == expected {
Ok((instruction, byte_len))
} else {
Err(unsupported(instruction.mnemonic(), detail))
}
}
File diff suppressed because it is too large. Load diff
-86
View File
@@ -1,86 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_decoder::{
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, ExportTarget, Instruction,
InterpolationPhase, decode,
};
#[test]
fn decodes_export_registers_and_interpolation_fields_in_byte_order() {
// Derived with llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding:
// exp param0, v255, v128, v15, v1
// v_interp_p1_f32 v255, v254, attr31.z
// v_interp_p2_f32 v128, v255, attr1.w
let bytes = [
0x0f, 0x02, 0x00, 0xf8, 0xff, 0x80, 0x0f, 0x01, 0xfe, 0x7e, 0xfc, 0xcb, 0xff, 0x07, 0x01,
0xca,
];
assert_eq!(
decode(Architecture::Gfx1030, &bytes).unwrap(),
[
DecodedInstruction {
offset: 0,
byte_len: 8,
instruction: Instruction::Export {
target: ExportTarget::Parameter0,
sources: [255, 128, 15, 1],
},
},
DecodedInstruction {
offset: 8,
byte_len: 4,
instruction: Instruction::Interpolate {
phase: InterpolationPhase::First,
dst: 255,
coordinate: 254,
attribute: 31,
component: 2,
},
},
DecodedInstruction {
offset: 12,
byte_len: 4,
instruction: Instruction::Interpolate {
phase: InterpolationPhase::Second,
dst: 128,
coordinate: 255,
attribute: 1,
component: 3,
},
},
],
);
}
#[test]
fn rejects_truncated_export_and_each_invalid_operand_field() {
let valid = 0xf800_180fu32;
let bytes = valid.to_le_bytes();
assert_eq!(
decode(Architecture::Gfx1030, &bytes).unwrap_err(),
DecodeError {
offset: 0,
kind: DecodeErrorKind::Truncated {
needed: 8,
available: 4
},
},
);
for bit in 0..26 {
let mut bytes = [0; 8];
bytes[..4].copy_from_slice(&(valid ^ (1 << bit)).to_le_bytes());
assert!(
matches!(
decode(Architecture::Gfx1030, &bytes),
Err(DecodeError {
offset: 0,
kind: DecodeErrorKind::UnsupportedForm {
mnemonic: "exp",
..
},
}),
),
"export bit {bit}"
);
}
}
-59
View File
@@ -1,59 +0,0 @@
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
use xenora_isa::meta::{FORMS, identify};
#[test]
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
let mut decoded = BTreeSet::new();
for entry in fs::read_dir(directory).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "bin") {
continue;
}
let binary = fs::read(&path).unwrap();
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
let found = identify(&binary[instruction.offset..]).unwrap();
assert_eq!(
found.len,
usize::from(instruction.byte_len),
"{}",
path.display()
);
decoded.insert((found.form.name, found.form.family));
}
}
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert!(
decoded.is_subset(&declared),
"{:?}",
decoded.difference(&declared)
);
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
let inline_only: BTreeSet<_> = declared
.difference(&decoded)
.map(|(name, _)| *name)
.collect();
assert_eq!(inline_only, BTreeSet::from(["IMAGE_SAMPLE_LZ"]));
for (name, family) in SEMANTIC_FORMS {
assert!(
FORMS
.iter()
.any(|form| form.name == name && form.family == family),
"{name}"
);
}
}
#[test]
fn registry_forms_do_not_duplicate_hand_written_forms() {
// A form declared in the semantic registry and also decoded by hand-written
// code would have two implementations; the hand-written one would win.
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
}
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "xenora-ffi"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
description = "Versioned C interface between the native macOS application and the Xenora runtime"
[lib]
crate-type = ["staticlib", "rlib"]
[lints]
workspace = true
[features]
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
gpu-tests = []
[dependencies]
xenora-loader = { path = "../loader" }
xenora-metal = { path = "../metal" }
xenora-shader = { path = "../shader" }
-397
View File
@@ -1,397 +0,0 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Xenora native application interface, version 1.
*
* Every function returns a xenora_status. Sessions are identified by opaque
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
* handle stays invalid even if its slot is reused. Output pointers are owned
* by the caller and are written only when the call returns XENORA_OK.
* All functions are thread-safe. No Rust panic crosses this boundary: one is
* reported as XENORA_INTERNAL_ERROR.
*/
#ifndef XENORA_H
#define XENORA_H
#include <stdint.h>
#define XENORA_ABI_VERSION 1u
typedef int32_t xenora_status;
enum {
XENORA_OK = 0,
XENORA_INVALID_ARGUMENT = 1,
XENORA_INVALID_HANDLE = 2,
XENORA_VERSION_MISMATCH = 3,
XENORA_INTERNAL_ERROR = 4,
XENORA_PE_ERROR = 5,
XENORA_LIMIT_EXCEEDED = 6,
XENORA_BUFFER_TOO_SMALL = 7,
XENORA_EXECUTION_FAILED = 8,
XENORA_INVALID_STATE = 9,
XENORA_FILE_NOT_FOUND = 10,
XENORA_ACCESS_DENIED = 11,
XENORA_IO_ERROR = 12,
};
/* Frame-loop states reported by xenora_session_frame_loop_status. */
enum {
XENORA_LOOP_NONE = 0,
XENORA_LOOP_RUNNING = 1,
XENORA_LOOP_PAUSED = 2,
XENORA_LOOP_FINISHED = 3,
XENORA_LOOP_STOPPED = 4,
XENORA_LOOP_FAILED = 5,
};
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
/* Frame id reported when no frame has been completed yet. */
#define XENORA_NO_FRAME 0xFFFFFFFFu
/* Input snapshot delivered to guest runtime services (Gate 4, #276). */
typedef struct {
uint32_t buttons;
int16_t stick_x;
int16_t stick_y;
int16_t mouse_dx;
int16_t mouse_dy;
uint8_t mouse_buttons;
uint8_t connected;
uint16_t reserved;
} xenora_input_state;
/* Extended controller snapshot. Trigger values span 0 to 65535. */
typedef struct {
xenora_input_state state;
uint16_t left_trigger;
uint16_t right_trigger;
} xenora_controller_input;
#define XENORA_INPUT_NONE 0u
#define XENORA_INPUT_RIGHT (1u << 0)
#define XENORA_INPUT_LEFT (1u << 1)
#define XENORA_INPUT_UP (1u << 2)
#define XENORA_INPUT_DOWN (1u << 3)
#define XENORA_INPUT_ACTION_A (1u << 4)
#define XENORA_INPUT_ACTION_B (1u << 5)
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
#define XENORA_FIXTURE_FRAME_WIDTH 4u
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
typedef uint64_t xenora_session;
/* The interface version this library implements. */
uint32_t xenora_abi_version(void);
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
xenora_status xenora_session_destroy(xenora_session session);
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
xenora_status xenora_session_inspect_trusted_fixture(
xenora_session session,
uint32_t *out_section_count,
uint32_t *out_entry_rva);
/*
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
* checked against the fixture shader's known output. `capacity` is the size of
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
* Only the embedded fixture can run; no caller-supplied executable is accepted.
*/
xenora_status xenora_session_run_trusted_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height);
/*
* Persistent rendering (one frame loop per session). Start runs the embedded
* frame-loop fixture on a session-owned guest thread: the guest submits frames
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
* becomes the latest frame. The guest stops after `frame_count` frames
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
* submission; resume continues it; stop makes it leave its loop and halt, and
* waits for its thread. Destroying the session stops the loop first. Starting a
* second loop on the same session returns XENORA_INVALID_STATE.
*/
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count);
xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input);
xenora_status xenora_session_send_controller_input(xenora_session session, const xenora_controller_input *input);
xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input);
xenora_status xenora_session_pause_frame_loop(xenora_session session);
xenora_status xenora_session_resume_frame_loop(xenora_session session);
xenora_status xenora_session_stop_frame_loop(xenora_session session);
/*
* Retrieve a previously completed frame by sequence index (0 <= frame_index < completed).
* Used for deterministic replay verification and frame inspection.
*/
xenora_status xenora_session_get_recorded_frame(
xenora_session session,
uint32_t frame_index,
uint32_t *out_frame_id,
uint8_t *out_rgba,
uint64_t capacity
);
/*
* Report the loop's state, the number of completed frames, and the latest
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
*/
xenora_status xenora_session_frame_loop_status(
xenora_session session,
uint32_t *out_state,
uint32_t *out_completed,
uint32_t *out_frame_id,
uint8_t *out_rgba,
uint64_t capacity);
/* 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.
* byte_count must contain a whole number of interleaved sample frames.
*/
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.
* Only whole frames are returned. Any remaining output bytes are untouched.
*/
xenora_status xenora_session_audio_read(
xenora_session session,
uint8_t *out_pcm,
uint64_t capacity,
uint64_t *out_bytes_read
);
/*
* Fill one playback block with whole frames, padding a shortfall with silence.
* out_source_bytes reports how much PCM was supplied before padding.
*/
xenora_status xenora_session_audio_render(
xenora_session session,
uint8_t *out_pcm,
uint64_t byte_count,
uint64_t *out_source_bytes
);
/*
* Query queued bytes, render calls that ran short, and total bytes 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.
* Missing files return XENORA_FILE_NOT_FOUND. Host permission failures return
* XENORA_ACCESS_DENIED. Other host I/O failures return XENORA_IO_ERROR.
*/
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.
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
* XENORA_LIMIT_EXCEEDED.
*/
xenora_status xenora_inspect_executable(
const uint8_t *bytes,
uint64_t length,
char *out_report,
uint64_t capacity,
uint64_t *out_required);
#endif
-407
View File
@@ -1,407 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Persistent guest rendering for one session (Gate 3, #266).
//!
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
//! its own thread for the session's lifetime. Pause, resume and stop act at the
//! frame-submit boundary: a paused guest waits inside that call with its
//! architectural state untouched, and a stop request makes the call return 0 so
//! the guest leaves its loop and halts.
use std::cell::RefCell;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::thread::JoinHandle;
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
use xenora_loader::{ExitReason, ImportRegistry, Register};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe");
pub const WIDTH: usize = 4;
pub const HEIGHT: usize = 3;
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
pub const MAX_FRAMES: u32 = 100_000;
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
const STEPS_PER_FRAME: usize = 8;
const STEPS_PER_INTERACTIVE_FRAME: usize = 24;
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
const RED: [u8; 4] = [255, 0, 0, 255];
const CLEAR: [u8; 4] = [19, 43, 93, 251];
pub const RUNNING: u32 = 1;
pub const PAUSED: u32 = 2;
pub const FINISHED: u32 = 3;
pub const STOPPED: u32 = 4;
pub const FAILED: u32 = 5;
#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct InputState {
pub buttons: u32,
pub stick_x: i16,
pub stick_y: i16,
pub mouse_dx: i16,
pub mouse_dy: i16,
pub mouse_buttons: u8,
pub connected: u8,
pub reserved: u16,
}
#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct ControllerInput {
pub state: InputState,
pub left_trigger: u16,
pub right_trigger: u16,
}
impl ControllerInput {
fn guest_bytes(self) -> [u8; 20] {
let mut bytes = [0; 20];
bytes[..4].copy_from_slice(&self.state.buttons.to_le_bytes());
for (slot, value) in bytes[4..12].as_chunks_mut::<2>().0.iter_mut().zip([
self.state.stick_x,
self.state.stick_y,
self.state.mouse_dx,
self.state.mouse_dy,
]) {
*slot = value.to_le_bytes();
}
bytes[12] = self.state.mouse_buttons;
bytes[13] = self.state.connected;
bytes[16..18].copy_from_slice(&self.left_trigger.to_le_bytes());
bytes[18..20].copy_from_slice(&self.right_trigger.to_le_bytes());
bytes
}
}
#[derive(Default)]
struct State {
status: u32,
paused: bool,
stop: bool,
interactive: bool,
limit: u32,
completed: u32,
input: ControllerInput,
input_queue: std::collections::VecDeque<InputState>,
recorded_frames: Vec<(u32, Vec<u8>)>,
/// Every `frame_submit` call the guest made, including the one answered with 0.
calls: u64,
latest: Option<(u32, Vec<u8>)>,
}
#[derive(Default)]
pub struct FrameLoop {
state: Mutex<State>,
wake: Condvar,
thread: Mutex<Option<JoinHandle<()>>>,
}
pub struct Snapshot {
pub status: u32,
pub completed: u32,
pub latest: Option<(u32, Vec<u8>)>,
}
impl FrameLoop {
fn lock(&self) -> MutexGuard<'_, State> {
self.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
let shared = Arc::new(Self::default());
{
let mut state = shared.lock();
state.status = RUNNING;
state.limit = limit;
state.interactive = interactive;
}
let guest = Arc::clone(&shared);
let handle = std::thread::Builder::new()
.name("xenora-guest".into())
.spawn(move || guest.run())
.ok();
if handle.is_none() {
shared.lock().status = FAILED;
}
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
shared
}
/// Pause or resume. Returns false unless the loop is running or paused.
pub fn set_paused(&self, paused: bool) -> bool {
let mut state = self.lock();
if !matches!(state.status, RUNNING | PAUSED) {
return false;
}
state.paused = paused;
state.status = if paused { PAUSED } else { RUNNING };
self.wake.notify_all();
true
}
/// Ask the guest to stop at its next frame submission and wait for its thread.
pub fn stop(&self) {
{
let mut state = self.lock();
state.stop = true;
self.wake.notify_all();
}
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
let _ = handle.join();
}
}
pub fn send_input(&self, input: InputState) {
self.send_controller_input(ControllerInput {
state: input,
..ControllerInput::default()
});
}
pub fn send_controller_input(&self, input: ControllerInput) {
let mut state = self.lock();
state.input = input;
}
pub fn queue_input(&self, input: InputState) {
let mut state = self.lock();
state.input_queue.push_back(input);
}
pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec<u8>)> {
let state = self.lock();
state.recorded_frames.get(index).cloned()
}
pub fn snapshot(&self) -> Snapshot {
let state = self.lock();
Snapshot {
status: state.status,
completed: state.completed,
latest: state.latest.clone(),
}
}
fn run(self: Arc<Self>) {
let outcome = self.execute();
let mut state = self.lock();
state.status = match outcome {
Err(_) => FAILED,
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
Ok(()) => FINISHED,
};
}
fn execute(self: &Arc<Self>) -> Result<(), String> {
let shader = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
)
.map_err(|e| format!("shader translation: {e}"))?;
let gpu = shared_gpu()?;
// The import runs on the guest thread, so the session's shader lives there too.
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
let shared = Arc::clone(self);
let mut imports = ImportRegistry::new();
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
shared
.submit(index)
.ok_or(ExitReason::IllegalInstruction(0xff))
});
if self.lock().interactive {
let shared_poll = Arc::clone(self);
imports.register("xenora.dll", "input_poll", move |_args, _, _memory| {
let mut state = shared_poll.lock();
let input = state.input_queue.pop_front().unwrap_or(state.input.state);
let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
1u64
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
2u64
} else {
0u64
};
Ok(cmd)
});
let snapshot = Arc::clone(self);
imports.register(
"xenora.dll",
"input_poll_snapshot",
move |args, _, memory| {
let input = snapshot.lock().input;
memory
.write_bytes(args.rcx, &input.guest_bytes())
.map_err(ExitReason::MemoryFault)?;
Ok(1)
},
);
}
let limit = self.lock().limit as usize;
let is_interactive = self.lock().interactive;
let fixture_bytes = if is_interactive {
INTERACTIVE_FIXTURE
} else {
FIXTURE
};
let steps_per_frame = if is_interactive {
STEPS_PER_INTERACTIVE_FRAME
} else {
STEPS_PER_FRAME
};
let startup = run_synthetic_startup(
fixture_bytes,
StartupLayout {
image_base: 0x1_4000_0000,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
},
imports,
(limit + 1) * steps_per_frame + 32,
)
.map_err(|e| format!("startup: {e}"));
GPU.with(|slot| slot.borrow_mut().take());
let startup = startup?;
let calls = self.lock().calls;
let rbx = startup.execution.final_state.get(Register::Rbx);
if startup.execution.exit_reason != ExitReason::Halt {
return Err(format!(
"guest ended with {:?}",
startup.execution.exit_reason
));
}
if !is_interactive && rbx != calls {
return Err(format!("guest ended with rbx={rbx}, calls={calls}"));
}
Ok(())
}
/// Handle one `frame_submit`: wait while paused, then render and verify the
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
fn submit(&self, index: u64) -> Option<u64> {
let mut state = self.lock();
state.calls += 1;
while state.paused && !state.stop {
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
}
if state.stop || state.completed >= state.limit {
return Some(0);
}
if state.interactive {
if index >= WIDTH as u64 {
return None; // column must be inside 0..WIDTH
}
} else if index != u64::from(state.completed) {
return None; // frame identities must arrive in order
}
drop(state);
let pixels = render(index as u32)?;
let mut state = self.lock();
state.completed += 1;
state.latest = Some((index as u32, pixels.clone()));
if state.interactive {
state.recorded_frames.push((index as u32, pixels));
}
Some(u64::from(state.completed < state.limit && !state.stop))
}
}
thread_local! {
static GPU: RefCell<Option<(&'static NativeCompute, String)>> = const { RefCell::new(None) };
}
/// One Metal device and command queue shared by every frame-loop session (#290).
///
/// The first command buffer submitted on a queue makes the GPU driver allocate a
/// working set for it (about 45 MiB on an Apple M5 with Metal validation), and the
/// driver frees that memory asynchronously, 10–50 ms after the queue is released.
/// A queue per session therefore allocated and freed it once per session, and the
/// process footprint depended on how far that release had progressed. One queue
/// for the process allocates the working set once and keeps it: bounded caching,
/// not per-session churn. `NativeCompute` is `Send + Sync`, and rendering takes
/// `&self`, so concurrent sessions can share it. A device that cannot be opened
/// is reported to every session that asks.
fn shared_gpu() -> Result<&'static NativeCompute, String> {
static SHARED: OnceLock<Result<NativeCompute, String>> = OnceLock::new();
SHARED
.get_or_init(|| NativeCompute::new().map_err(|e| format!("Metal device: {e}")))
.as_ref()
.map_err(Clone::clone)
}
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
///
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
/// column's left edge, covers that column's pixel centres in all three rows and
/// none of its neighbours'.
fn render(index: u32) -> Option<Vec<u8>> {
let column = (index as usize % WIDTH) as f32;
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
let pixels = GPU.with(|slot| {
let slot = slot.borrow();
let (gpu, msl) = slot.as_ref()?;
gpu.render_rgba8(
msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&[
[x0, -10.0, 0.5, 1.0],
[x0 + 0.7, 0.0, 0.5, 1.0],
[x0, 10.0, 0.5, 1.0],
],
&[[0.0; 4]; 3],
[WIDTH, HEIGHT],
CLEAR,
)
.ok()
})?;
(pixels == expected(index)).then_some(pixels)
}
/// The expected frame for `index`, from the strip rule alone.
pub fn expected(index: u32) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| {
if pixel % WIDTH == index as usize % WIDTH {
RED
} else {
CLEAR
}
})
.collect()
}
#[cfg(test)]
#[test]
fn extended_controller_snapshot_retains_trigger_bytes_and_legacy_input_resets_them() {
let running = FrameLoop::default();
running.send_controller_input(ControllerInput {
state: InputState {
buttons: 0x10,
stick_x: -32767,
stick_y: 9,
connected: 1,
reserved: u16::MAX,
..InputState::default()
},
left_trigger: 0x1234,
right_trigger: u16::MAX,
});
let bytes = running.lock().input.guest_bytes();
assert_eq!(std::mem::size_of::<ControllerInput>(), 20);
assert_eq!(
bytes,
[
16, 0, 0, 0, 1, 128, 9, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0x34, 0x12, 255, 255
]
);
running.send_input(InputState::default());
assert_eq!(running.lock().input.guest_bytes(), [0; 20]);
}
File diff suppressed because it is too large. Load diff
-379
View File
@@ -1,379 +0,0 @@
// 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",
"",
] {
let bad_c = std::ffi::CString::new(*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
);
}
let missing = std::ffi::CString::new("missing-xenora-test-asset.bin").unwrap();
assert_eq!(
unsafe { xenora_session_vfs_open(sess, missing.as_ptr(), 0, &mut file) },
XENORA_FILE_NOT_FOUND
);
assert_eq!(file, XENORA_NO_FILE);
// 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);
}
-396
View File
@@ -1,396 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 3 acceptance on a native Metal device: persistent guest rendering through
//! the C interface. Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use std::time::{Duration, Instant};
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
/// Expected frame `id`, derived only from the geometry: the guest's frame index picks
/// column `id % 4`, which is opaque red (x9-constant-ps exports (1, 0, 0, 1)); the
/// other columns keep the clear colour (19, 43, 93, 251).
fn expected(id: u32) -> Vec<u8> {
let mut frame = Vec::new();
for _row in 0..3 {
for column in 0..4 {
if column == id % 4 {
frame.extend([255, 0, 0, 255]);
} else {
frame.extend([19, 43, 93, 251]);
}
}
}
frame
}
struct Status {
state: u32,
completed: u32,
frame_id: u32,
rgba: [u8; 48],
}
fn status(session: u64) -> Status {
let mut s = Status {
state: 99,
completed: 0,
frame_id: 0,
rgba: [0; 48],
};
let code = unsafe {
xenora_session_frame_loop_status(
session,
&mut s.state,
&mut s.completed,
&mut s.frame_id,
s.rgba.as_mut_ptr(),
48,
)
};
assert_eq!(code, XENORA_OK);
s
}
fn session() -> u64 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
session
}
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let s = status(session);
if done(&s) {
return s;
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what} (state {}, completed {})",
s.state,
s.completed
);
std::thread::sleep(Duration::from_millis(2));
}
}
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
fn footprint() -> u64 {
unsafe extern "C" {
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut [u64; 32]) -> i32;
}
let mut info = [0u64; 32];
assert_eq!(
unsafe { proc_pid_rusage(std::process::id() as i32, 2, &mut info) },
0
);
info[9] // after the 16-byte UUID: user, system, idle wakeups, interrupts, pageins, wired, resident, footprint
}
#[test]
fn three_hundred_guest_frames_arrive_verified_and_in_order() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
assert_eq!(
xenora_session_start_frame_loop(session, 300),
XENORA_INVALID_STATE
);
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!(s.state, XENORA_LOOP_FINISHED);
assert_eq!(s.completed, 300);
assert_eq!(s.frame_id, 299);
assert_eq!(s.rgba.to_vec(), expected(299));
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn observed_frame_ids_never_go_backwards_and_match_their_pixels() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 2_000), XENORA_OK);
let mut previous = None;
let mut samples = 0;
loop {
let s = status(session);
if s.frame_id != XENORA_NO_FRAME {
if let Some(p) = previous {
assert!(s.frame_id >= p, "frame id went from {p} to {}", s.frame_id);
}
assert!(
s.frame_id < s.completed,
"id {} not below completed {}",
s.frame_id,
s.completed
);
assert_eq!(
s.rgba.to_vec(),
expected(s.frame_id),
"frame {}",
s.frame_id
);
previous = Some(s.frame_id);
samples += 1;
}
if s.state != XENORA_LOOP_RUNNING {
assert_eq!(s.state, XENORA_LOOP_FINISHED);
assert_eq!((s.completed, s.frame_id), (2_000, 1_999));
break;
}
}
assert!(samples > 1);
xenora_session_destroy(session);
}
#[test]
fn pause_holds_the_guest_resume_continues_and_stop_halts_it() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "10 frames", |s| s.completed >= 10);
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
// At most the frame already being rendered can still complete after pausing.
std::thread::sleep(Duration::from_millis(50));
let held = status(session);
std::thread::sleep(Duration::from_millis(200));
let later = status(session);
assert_eq!(later.state, XENORA_LOOP_PAUSED);
assert_eq!(later.completed, held.completed, "no frames while paused");
assert_eq!(later.frame_id, held.completed - 1);
assert_eq!(later.rgba.to_vec(), expected(later.frame_id));
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
let resumed = wait_until(session, "progress after resume", |s| {
s.completed >= held.completed + 10
});
assert_eq!(resumed.state, XENORA_LOOP_RUNNING);
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
let stopped = status(session);
assert_eq!(stopped.state, XENORA_LOOP_STOPPED);
assert!(stopped.completed < XENORA_FRAME_LOOP_MAX_FRAMES);
assert_eq!(stopped.frame_id, stopped.completed - 1);
assert_eq!(stopped.rgba.to_vec(), expected(stopped.frame_id));
// Pause and resume are refused once the guest has halted.
assert_eq!(
xenora_session_pause_frame_loop(session),
XENORA_INVALID_STATE
);
assert_eq!(
xenora_session_resume_frame_loop(session),
XENORA_INVALID_STATE
);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn destroying_a_running_or_paused_session_stops_it() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
for pause_first in [false, true] {
let session = session();
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "a frame", |s| s.completed >= 1);
if pause_first {
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
}
let started = Instant::now();
assert_eq!(xenora_session_destroy(session), XENORA_OK);
assert!(
started.elapsed() < Duration::from_secs(5),
"destroy joined promptly"
);
let mut x = 0;
let mut rgba = [0u8; 48];
assert_eq!(
unsafe {
xenora_session_frame_loop_status(
session,
&mut x,
&mut x,
&mut x,
rgba.as_mut_ptr(),
48,
)
},
XENORA_INVALID_HANDLE
);
}
}
#[test]
fn repeated_sessions_do_not_grow_the_memory_footprint() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let run = || {
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 300));
assert_eq!(xenora_session_destroy(session), XENORA_OK);
};
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
run();
run();
let baseline = footprint();
for _ in 0..5 {
run();
}
let after = footprint();
let growth = after.saturating_sub(baseline);
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
assert!(
growth < 16 << 20,
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
);
}
/// Regression test for #290: the footprint read right after each destroy must stay
/// flat across many sessions. Each session used to open its own Metal command queue,
/// and the GPU driver frees a queue's working set (about 45 MiB on an Apple M5 with
/// validation) asynchronously after release, so these readings swung by about 50 MiB
/// from session to session. Sessions now share one queue. The mix of sessions covers
/// normal completion, pause and resume, and destruction while running.
#[test]
fn fifty_sessions_keep_a_flat_footprint_after_each_destroy() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let one = |kind: usize| {
let session = session();
match kind {
0 => {
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
}
1 => {
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
wait_until(session, "10 frames", |s| s.completed >= 10);
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
}
_ => {
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "a frame", |s| s.completed >= 1);
}
}
assert_eq!(xenora_session_destroy(session), XENORA_OK);
footprint()
};
one(0); // the first session allocates the shared queue's working set
let readings: Vec<u64> = (0..50).map(|i| one(i % 3)).collect();
let mib: Vec<u64> = readings.iter().map(|r| r >> 20).collect();
println!("footprint after each destroy (MiB): {mib:?}");
let median = |values: &[u64]| {
let mut sorted = values.to_vec();
sorted.sort_unstable();
sorted[sorted.len() / 2]
};
// Sustained growth: the typical reading at the end against the start.
let (start, end) = (median(&readings[..10]), median(&readings[40..]));
assert!(
end.saturating_sub(start) < 16 << 20,
"footprint grew from {start} to {end} bytes (median of first and last ten sessions)"
);
// Per-session churn, the cause fixed in #290: with a queue per session, about half
// of all readings sat some 45 MiB away from the median. With the shared queue,
// a reading is still occasionally caught while the driver frees a batch of
// per-frame render resources: graphics-tagged memory only, 16 to 44 MiB, gone
// within about 100 ms, measured in 13 of 6,000 sessions (0.22%). Allowing two such
// readings in 50 keeps a false failure near 1 in 5,000 runs while per-session
// churn would exceed it every time.
let centre = median(&readings);
let outliers: Vec<u64> = readings
.iter()
.filter(|&&r| r.abs_diff(centre) >= 16 << 20)
.map(|r| r >> 20)
.collect();
assert!(
outliers.len() <= 2,
"{} of 50 readings were 16 MiB or more from the median {} MiB: {outliers:?}",
outliers.len(),
centre >> 20
);
}
/// Two sessions render at the same time through the shared Metal queue (#290). Each
/// must keep its own frame sequence and pixels, pausing one must not stop the other,
/// and destroying one mid-run must not disturb the other.
#[test]
fn concurrent_sessions_share_the_queue_but_stay_isolated() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let (a, b) = (session(), session());
assert_eq!(xenora_session_start_frame_loop(a, 400), XENORA_OK);
assert_eq!(xenora_session_start_frame_loop(b, 250), XENORA_OK);
wait_until(a, "session A started", |s| s.completed >= 5);
wait_until(b, "session B started", |s| s.completed >= 5);
// Pausing A holds only A.
assert_eq!(xenora_session_pause_frame_loop(a), XENORA_OK);
let a_held = wait_until(a, "session A paused", |s| s.state == XENORA_LOOP_PAUSED);
let b_before = status(b).completed;
let b_moving = wait_until(b, "session B progress while A is paused", |s| {
s.completed >= b_before + 20 || s.state != XENORA_LOOP_RUNNING
});
assert!(
b_moving.completed > b_before,
"B kept rendering while A was paused"
);
let a_still = status(a);
assert_eq!(a_still.state, XENORA_LOOP_PAUSED);
// At most the frame A was rendering when paused can still complete.
assert!(a_still.completed <= a_held.completed + 1);
assert_eq!(a_still.rgba.to_vec(), expected(a_still.frame_id));
assert_eq!(xenora_session_resume_frame_loop(a), XENORA_OK);
// Both finish with their own counts and their own final frames.
let a_done = wait_until(a, "session A finished", |s| s.state != XENORA_LOOP_RUNNING);
let b_done = wait_until(b, "session B finished", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!(
(a_done.state, a_done.completed, a_done.frame_id),
(XENORA_LOOP_FINISHED, 400, 399)
);
assert_eq!(
(b_done.state, b_done.completed, b_done.frame_id),
(XENORA_LOOP_FINISHED, 250, 249)
);
assert_eq!(a_done.rgba.to_vec(), expected(399));
assert_eq!(b_done.rgba.to_vec(), expected(249));
assert_eq!(xenora_session_destroy(a), XENORA_OK);
assert_eq!(xenora_session_destroy(b), XENORA_OK);
// Destroying one running session leaves the other running to completion.
let (c, d) = (session(), session());
assert_eq!(
xenora_session_start_frame_loop(c, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
assert_eq!(xenora_session_start_frame_loop(d, 300), XENORA_OK);
wait_until(c, "session C started", |s| s.completed >= 5);
wait_until(d, "session D started", |s| s.completed >= 5);
assert_eq!(xenora_session_destroy(c), XENORA_OK);
let d_done = wait_until(d, "session D finished", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!(
(d_done.state, d_done.completed, d_done.frame_id),
(XENORA_LOOP_FINISHED, 300, 299)
);
assert_eq!(d_done.rgba.to_vec(), expected(299));
assert_eq!(xenora_session_destroy(d), XENORA_OK);
}
-298
View File
@@ -1,298 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 4 acceptance on a native Metal device: interactive guest execution with
//! dynamic input handling and rendering through the C interface.
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use std::time::{Duration, Instant};
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255);
/// all other columns keep the clear colour (19, 43, 93, 251).
fn expected(column: u32) -> Vec<u8> {
let mut frame = Vec::new();
for _row in 0..3 {
for col in 0..4 {
if col == column % 4 {
frame.extend([255, 0, 0, 255]);
} else {
frame.extend([19, 43, 93, 251]);
}
}
}
frame
}
struct Status {
state: u32,
completed: u32,
frame_id: u32,
rgba: [u8; 48],
}
fn status(session: u64) -> Status {
let mut s = Status {
state: 99,
completed: 0,
frame_id: 0,
rgba: [0; 48],
};
let code = unsafe {
xenora_session_frame_loop_status(
session,
&mut s.state,
&mut s.completed,
&mut s.frame_id,
s.rgba.as_mut_ptr(),
48,
)
};
assert_eq!(code, XENORA_OK);
s
}
fn session() -> u64 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
session
}
fn send_buttons(session: u64, buttons: u32) {
let input = xenora_input_state {
buttons,
stick_x: 0,
stick_y: 0,
mouse_dx: 0,
mouse_dy: 0,
mouse_buttons: 0,
connected: 1,
reserved: 0,
};
assert_eq!(
unsafe { xenora_session_send_input(session, &input) },
XENORA_OK
);
}
fn queue_buttons(session: u64, buttons: u32) {
let input = xenora_input_state {
buttons,
stick_x: 0,
stick_y: 0,
mouse_dx: 0,
mouse_dy: 0,
mouse_buttons: 0,
connected: 1,
reserved: 0,
};
assert_eq!(
unsafe { xenora_session_queue_input(session, &input) },
XENORA_OK
);
}
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let s = status(session);
if done(&s) {
return s;
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what} (state {}, completed {})",
s.state,
s.completed
);
std::thread::sleep(Duration::from_millis(2));
}
}
#[test]
fn interactive_input_moves_guest_column_and_updates_pixels() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
// Start interactive loop with 120 frames
assert_eq!(
xenora_session_start_interactive_loop(session, 120),
XENORA_OK
);
// Initial frames without input stay at column 0
let s = wait_until(session, "initial frames", |s| s.completed >= 5);
assert_eq!(s.frame_id, 0);
assert_eq!(s.rgba.to_vec(), expected(0));
// Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0
send_buttons(session, XENORA_INPUT_RIGHT);
let s_right = wait_until(session, "column moves right", |s| {
s.completed >= 15 && s.frame_id != 0
});
assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id));
// Release input: position stops moving
send_buttons(session, XENORA_INPUT_NONE);
let s_hold_start = wait_until(session, "wait for release frame", |s| {
s.completed >= s_right.completed + 2
});
let hold_col = s_hold_start.frame_id;
let s_hold = wait_until(session, "position holds on release", |s| {
s.completed >= s_hold_start.completed + 10
});
assert_eq!(s_hold.frame_id, hold_col);
assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id));
// Send Left input: column should move left
send_buttons(session, XENORA_INPUT_LEFT);
let s_left = wait_until(session, "column moves left", |s| {
s.completed >= s_hold.completed + 10 && s.frame_id != hold_col
});
assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id));
// Wait until finished
let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED);
assert_eq!(s_end.completed, 120);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn deterministic_input_replay_produces_identical_frames() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
// Timeline of inputs across 60 frames:
// frames 0..15: Right
// frames 15..30: None
// frames 30..45: Left
// frames 45..60: Right
let replay_sequence: Vec<u32> = (0..60)
.map(|f| {
if f < 15 {
XENORA_INPUT_RIGHT
} else if f < 30 {
XENORA_INPUT_NONE
} else if f < 45 {
XENORA_INPUT_LEFT
} else {
XENORA_INPUT_RIGHT
}
})
.collect();
let run_replay = || {
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 60),
XENORA_OK
);
// Pre-queue the complete input sequence
for &btn in &replay_sequence {
queue_buttons(session, btn);
}
// Wait until all 60 frames are rendered
let s = wait_until(session, "replay completion", |s| {
s.state == XENORA_LOOP_FINISHED && s.completed == 60
});
assert_eq!(s.completed, 60);
// Inspect all 60 recorded frames
let mut frames = Vec::with_capacity(60);
for i in 0..60 {
let mut id = 0u32;
let mut rgba = [0u8; 48];
let code = unsafe {
xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48)
};
assert_eq!(code, XENORA_OK);
assert_eq!(rgba.to_vec(), expected(id));
frames.push((id, rgba));
}
assert_eq!(xenora_session_destroy(session), XENORA_OK);
frames
};
let run1 = run_replay();
let run2 = run_replay();
assert_eq!(run1.len(), 60);
assert_eq!(run2.len(), 60);
for i in 0..60 {
assert_eq!(
run1[i].0, run2[i].0,
"frame {} column mismatch: {} vs {}",
i, run1[i].0, run2[i].0
);
assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i);
}
}
#[test]
fn focus_loss_and_release_resets_input_cleanly() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 100),
XENORA_OK
);
// Send Right
send_buttons(session, XENORA_INPUT_RIGHT);
let s1 = wait_until(session, "moving right", |s| s.completed >= 10);
// Simulate focus loss / key release
send_buttons(session, XENORA_INPUT_NONE);
// Wait for the release to take effect in the guest
let s_released = wait_until(session, "release takes effect", |s| {
s.completed >= s1.completed + 2
});
let stopped_col = s_released.frame_id;
// Check next 15 frames: frame_id must remain fixed at stopped_col
let s2 = wait_until(session, "hold after release", |s| {
s.completed >= s_released.completed + 15
});
assert_eq!(s2.frame_id, stopped_col);
assert_eq!(s2.rgba.to_vec(), expected(stopped_col));
// Clean stop
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED);
assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn destroying_interactive_session_stops_cleanly() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 5000),
XENORA_OK
);
// Wait until it actually starts rendering
wait_until(session, "running", |s| s.completed >= 5);
let start = Instant::now();
assert_eq!(xenora_session_destroy(session), XENORA_OK);
assert!(
start.elapsed() < Duration::from_millis(500),
"destroy took too long: {:?}",
start.elapsed()
);
}
-40
View File
@@ -1,40 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Runs the trusted fixture through the C interface on a native Metal device.
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use xenora_ffi::*;
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
#[test]
fn guest_fixture_frame_reaches_the_caller_through_metal() {
for run in 0..3 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
let status = unsafe {
xenora_session_run_trusted_fixture(
session,
rgba.as_mut_ptr(),
64,
&mut width,
&mut height,
)
};
assert_eq!(status, XENORA_OK, "run {run}");
assert_eq!((width, height), (4, 3));
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
assert!(
rgba[48..].iter().all(|&b| b == 0),
"no write past the frame"
);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
}
-375
View File
@@ -1,375 +0,0 @@
// 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);
}
-13
View File
@@ -1,13 +0,0 @@
[package]
name = "xenora-import-gen"
description = "Deterministic Win32/CRT import binding generator for Xenora"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
# No external dependencies: pure-Rust code generation, no LLM, no network.
-125
View File
@@ -1,125 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! API-Set Redirection and Alias Resolution.
//!
//! Windows uses virtual DLL names (e.g. `api-ms-win-core-processthreads-l1-1-0.dll`)
//! that are redirected to canonical underlying modules (e.g. `kernel32.dll`, `KernelBase.dll`).
//!
//! This module resolves these virtual API-sets to canonical modules and vice-versa,
//! preventing duplicate stub generation and allowing unified handler lookup.
//! Source: Public Windows SDK `apisetcounters.h` and documented Microsoft API-set schema.
/// Resolve an API-set virtual DLL name to its canonical Windows module name.
///
/// API sets are matched exactly against [`get_api_sets_for_canonical`]. A name
/// that merely starts like a known family is not assumed to forward anywhere.
pub fn resolve_api_set_canonical(module: &str) -> &'static str {
let lower = module.to_ascii_lowercase();
for canonical in ["kernel32.dll", "ucrtbase.dll"] {
if get_api_sets_for_canonical(canonical).contains(&lower.as_str()) {
return canonical;
}
}
match lower.as_str() {
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
"ucrtbase.dll" => "ucrtbase.dll",
"ntdll.dll" => "ntdll.dll",
"ws2_32.dll" => "ws2_32.dll",
"advapi32.dll" => "advapi32.dll",
"vcruntime140.dll" | "vcruntime140_1.dll" => "vcruntime140.dll",
"msvcp140.dll" | "msvcp140_1.dll" | "msvcp140_2.dll" => "msvcp140.dll",
_ => "unknown.dll",
}
}
/// Known API sets that forward to the given canonical host module.
pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
match canonical {
"kernel32.dll" => &[
"api-ms-win-core-processthreads-l1-1-0.dll",
"api-ms-win-core-processthreads-l1-1-1.dll",
"api-ms-win-core-processthreads-l1-1-2.dll",
"api-ms-win-core-synch-l1-1-0.dll",
"api-ms-win-core-synch-l1-2-0.dll",
"api-ms-win-core-synch-l1-2-1.dll",
"api-ms-win-core-sysinfo-l1-1-0.dll",
"api-ms-win-core-sysinfo-l1-2-0.dll",
"api-ms-win-core-profile-l1-1-0.dll",
"api-ms-win-core-libraryloader-l1-2-0.dll",
"api-ms-win-core-libraryloader-l1-2-1.dll",
"api-ms-win-core-file-l1-1-0.dll",
"api-ms-win-core-file-l2-1-0.dll",
"api-ms-win-core-errorhandling-l1-1-0.dll",
"api-ms-win-core-debug-l1-1-0.dll",
"api-ms-win-core-handle-l1-1-0.dll",
"api-ms-win-core-interlocked-l1-1-0.dll",
"api-ms-win-core-fibers-l1-1-0.dll",
"api-ms-win-core-datetime-l1-1-1.dll",
"api-ms-win-core-timezone-l1-1-0.dll",
"api-ms-win-core-realtime-l1-1-0.dll",
"api-ms-win-core-memory-l1-1-0.dll",
],
"ucrtbase.dll" => &[
"api-ms-win-crt-math-l1-1-0.dll",
"api-ms-win-crt-string-l1-1-0.dll",
"api-ms-win-crt-stdio-l1-1-0.dll",
"api-ms-win-crt-runtime-l1-1-0.dll",
"api-ms-win-crt-heap-l1-1-0.dll",
"api-ms-win-crt-time-l1-1-0.dll",
"api-ms-win-crt-convert-l1-1-0.dll",
"api-ms-win-crt-utility-l1-1-0.dll",
"api-ms-win-crt-filesystem-l1-1-0.dll",
"api-ms-win-crt-locale-l1-1-0.dll",
"api-ms-win-crt-environment-l1-1-0.dll",
// The API set a program built with the mingw-w64 UCRT runtime
// imports `memcpy` and `__C_specific_handler` from. That it
// forwards to ucrtbase.dll is inferred from its name and from
// Microsoft's "Universal CRT deployment" page, which says the
// Universal CRT ships as ucrtbase.dll plus `api-ms-win-*.dll`
// forwarders. No document naming this set was found.
"api-ms-win-crt-private-l1-1-0.dll",
],
_ => &[],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_listed_api_sets_resolve() {
for unknown in [
"api-ms-win-core-file-l9-9-9.dll",
"api-ms-win-core-processthreads",
"api-ms-win-core-filesomething.dll",
"api-ms-win-crt-unknown-l1-1-0.dll",
] {
assert_eq!(
resolve_api_set_canonical(unknown),
"unknown.dll",
"{unknown}"
);
}
assert_eq!(
resolve_api_set_canonical("API-MS-Win-Core-Memory-L1-1-0.DLL"),
"kernel32.dll"
);
}
#[test]
fn test_api_set_resolution() {
assert_eq!(
resolve_api_set_canonical("api-ms-win-core-processthreads-l1-1-0.dll"),
"kernel32.dll"
);
assert_eq!(
resolve_api_set_canonical("api-ms-win-crt-math-l1-1-0.dll"),
"ucrtbase.dll"
);
assert_eq!(
resolve_api_set_canonical("api-ms-win-core-synch-l1-2-1.dll"),
"kernel32.dll"
);
}
}
@@ -1,49 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Generate the typed runtime adapters and report. Run from the repository root.
//! `--check` regenerates in memory and fails if a committed file differs.
use std::process::ExitCode;
use xenora_import_gen::typed::{generate_report, generate_rust, parse};
const REGISTRY: &str = "crates/loader/runtime/services.txt";
const TESTS: &str = "crates/loader/tests/runtime_services.rs";
const RUST: &str = "crates/loader/src/runtime_table.rs";
const REPORT: &str = "docs/runtime/services.md";
fn run() -> Result<String, String> {
let mode = std::env::args().nth(1).unwrap_or_default();
let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"));
let services =
parse(&read(REGISTRY)?, &read(TESTS)?).map_err(|e| format!("{REGISTRY}: {e}"))?;
let outputs = [
(RUST, generate_rust(&services)),
(REPORT, generate_report(&services)),
];
for (path, text) in &outputs {
match mode.as_str() {
"generate" => std::fs::write(path, text).map_err(|e| format!("{path}: {e}"))?,
"--check" if read(path)? != *text => {
return Err(format!(
"{path} is out of date; run xenora-runtime-gen generate"
));
}
"--check" | "validate" => {}
_ => return Err("usage: xenora-runtime-gen validate|generate|--check".into()),
}
}
Ok(format!("{} services", services.len()))
}
fn main() -> ExitCode {
match run() {
Ok(message) => {
println!("{message}");
ExitCode::SUCCESS
}
Err(message) => {
eprintln!("{message}");
ExitCode::FAILURE
}
}
}
File diff suppressed because it is too large. Load diff
-399
View File
@@ -1,399 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Rust source code generator.
//!
//! Produces three files:
//! - `generated_crt.rs` — `register_generated_crt_services(registry)`
//! - `generated_stubs.rs` — `register_generated_stubs(registry)`
//! - `generated_tests.rs` — `#[cfg(test)] mod generated_tests { ... }`
//!
//! All generated code uses only the existing `ImportRegistry` / `ServiceHandler` types.
//! No unsafe code is emitted in the registration layer; `extern "C"` libc calls are
//! wrapped in `unsafe` blocks with explicit guest-memory bounds checks.
use crate::classify::Classification;
use crate::classify::SymbolDb;
use crate::manifest::Manifest;
/// The three output files plus the Markdown manifest summary.
pub struct GeneratedFiles {
pub crt_rs: String,
pub stubs_rs: String,
pub tests_rs: String,
pub manifest_md: String,
}
impl GeneratedFiles {
/// Write all files into `out_dir`, creating it if needed.
pub fn write_all(&self, out_dir: &str) -> Result<(), String> {
std::fs::create_dir_all(out_dir).map_err(|e| format!("create dir {out_dir}: {e}"))?;
write_file(out_dir, "generated_crt.rs", &self.crt_rs)?;
write_file(out_dir, "generated_stubs.rs", &self.stubs_rs)?;
write_file(out_dir, "generated_tests.rs", &self.tests_rs)?;
write_file(out_dir, "generated_manifest.md", &self.manifest_md)?;
Ok(())
}
}
fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> {
let path = format!("{dir}/{name}");
std::fs::write(&path, content).map_err(|e| format!("write {path}: {e}"))
}
fn unique_entries(manifest: &Manifest) -> impl Iterator<Item = &crate::manifest::ManifestEntry> {
let mut seen = std::collections::BTreeSet::new();
manifest
.entries
.iter()
.filter(move |entry| seen.insert(entry.key()))
}
/// Generate all files from the manifest.
pub fn generate(manifest: &Manifest, _db: &SymbolDb) -> GeneratedFiles {
let crt_rs = gen_crt(manifest);
let stubs_rs = gen_stubs(manifest);
let tests_rs = gen_tests(manifest);
let manifest_md = manifest.render_markdown();
GeneratedFiles {
crt_rs,
stubs_rs,
tests_rs,
manifest_md,
}
}
// ---------------------------------------------------------------------------
// CRT native bindings
// ---------------------------------------------------------------------------
fn gen_crt(manifest: &Manifest) -> String {
let mut out = file_header("generated_crt.rs");
out.push_str(
r#"
//! Auto-generated CRT service registrations.
//! Maps Windows CRT API-set names to native macOS libc equivalents.
//! All mappings are derived from public ISO C / POSIX documentation.
//! Do not edit manually — regenerate with `xenora imports generate`.
use crate::cpu::{CpuState, ExitReason, Register};
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
use crate::memory::GuestMemory;
/// Register all automatically generated CRT bindings into `registry`.
///
/// These implementations are STUB-VERIFIED, not independently confirmed against
/// a live Xbox runtime. They must pass the conformance tests in
/// `generated_tests.rs` before being marked `ServiceStatus::Implemented`.
#[allow(unused_variables)]
pub fn register_generated_crt_services(registry: &mut ImportRegistry) {
"#,
);
for entry in unique_entries(manifest) {
match &entry.classification {
Classification::CrtNative { libc_sym, note } => {
out.push_str(&gen_crt_native_registration(
&entry.module,
&entry.symbol,
libc_sym,
note,
));
}
Classification::CrtWrapper {
libc_sym,
wrapper_note,
} => {
out.push_str(&gen_crt_wrapper_registration(
&entry.module,
&entry.symbol,
libc_sym,
wrapper_note,
));
}
Classification::RuntimeHelper { note } => {
out.push_str(&gen_runtime_helper_registration(
&entry.module,
&entry.symbol,
note,
));
}
_ => {} // Win32Stub and Manual go to stubs_rs
}
}
out.push_str("}\n");
out
}
/// Generate a registration block for a CrtNative symbol.
/// These use a simple `Win64Args` → libc dispatch pattern.
fn gen_crt_native_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String {
// Determine the calling pattern based on symbol name
let (status, dispatch) = match crt_dispatch_expr(symbol) {
Some(dispatch) => ("Partial", dispatch),
None => (
"Stub",
"Err(ExitReason::IllegalInstruction(0xFE))".to_owned(),
),
};
format!(
r#"
// {note}
// Source: ISO C / POSIX public specification.
registry.register_with_status(
"{module}", "{symbol}",
ServiceStatus::{status},
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
{dispatch}
}},
);
"#,
module = module,
symbol = symbol,
note = note,
dispatch = dispatch,
)
}
/// Generate a stub-wrapper registration for a CrtWrapper symbol (e.g. strcat_s → strcat).
fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String {
format!(
r#"
// {note}
registry.register_with_status(
"{module}", "{symbol}",
ServiceStatus::Stub,
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
Err(ExitReason::IllegalInstruction(0xFE))
}},
);
"#,
)
}
/// Generate a registration for a runtime helper (EH frame handlers, etc.).
fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String {
// Not implemented: fails explicitly instead of reporting success.
let body = "Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call";
format!(
r#"
// {note}
registry.register_with_status(
"{module}", "{symbol}",
ServiceStatus::Stub,
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
{body}
}},
);
"#,
)
}
// ---------------------------------------------------------------------------
// Win32 stubs
// ---------------------------------------------------------------------------
fn gen_stubs(manifest: &Manifest) -> String {
let mut out = file_header("generated_stubs.rs");
out.push_str(
r#"
//! Auto-generated Win32 service stubs.
//! Each stub stops the guest with an explicit unsupported-service exit.
//! Do not edit manually — regenerate with `xenora imports generate`.
use crate::cpu::{CpuState, ExitReason};
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
use crate::memory::GuestMemory;
/// Register all automatically generated Win32 stubs into `registry`.
#[allow(unused_variables)]
pub fn register_generated_stubs(registry: &mut ImportRegistry) {
"#,
);
for entry in unique_entries(manifest) {
if let Classification::Win32Stub { note, .. } = &entry.classification {
out.push_str(&format!(
r#"
// {note}
// STUB: Fails explicitly with unsupported status instead of fabricating success.
registry.register_with_status(
"{module}", "{symbol}",
ServiceStatus::Stub,
|_args: &Win64Args, _cpu: &mut CpuState, _mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call
}},
);
"#,
module = entry.module,
symbol = entry.symbol,
note = note,
));
}
}
out.push_str("}\n");
out
}
// ---------------------------------------------------------------------------
// Conformance tests
// ---------------------------------------------------------------------------
fn gen_tests(manifest: &Manifest) -> String {
let mut out = file_header("generated_tests.rs");
out.push_str(
r#"
//! Conformance tests for emitted service registrations.
//! Place this file and the two generated registration files together as
//! an integration test in a Cargo package that depends on xenora-loader.
pub use xenora_loader::{cpu, imports, memory};
#[path = "generated_crt.rs"]
mod generated_crt;
#[path = "generated_stubs.rs"]
mod generated_stubs;
use cpu::{CpuState, ExitReason};
use imports::{ImportRegistry, ServiceStatus, Win64Args};
use memory::GuestMemory;
fn check(module: &str, symbol: &str, input: u64, status: ServiceStatus, expected: Result<u64, ExitReason>) {
let mut registry = ImportRegistry::new();
generated_crt::register_generated_crt_services(&mut registry);
generated_stubs::register_generated_stubs(&mut registry);
let service = registry.binding(module, symbol).expect("generated binding");
assert_eq!(service.status, status);
let args = Win64Args { rcx: input, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
let mut cpu = CpuState::new(0x1000, 0x8000);
let mut memory = GuestMemory::new();
assert_eq!((service.handler)(&args, &mut cpu, &mut memory), expected);
}
"#,
);
for (index, entry) in unique_entries(manifest).enumerate() {
let (input, status, expected) = match &entry.classification {
Classification::CrtNative { .. } if crt_dispatch_expr(&entry.symbol).is_some() => {
let Some((input, expected)) = canonical_integer_case(&entry.symbol) else {
continue;
};
(input, "Partial", format!("Ok({expected})"))
}
Classification::CrtNative { .. }
| Classification::CrtWrapper { .. }
| Classification::RuntimeHelper { .. }
| Classification::Win32Stub { .. } => (
0,
"Stub",
"Err(ExitReason::IllegalInstruction(0xFE))".to_owned(),
),
_ => continue,
};
out.push_str(&format!(
r#"
#[test]
fn generated_test_{name}_{index}() {{
check({module:?}, {symbol:?}, {input}, ServiceStatus::{status}, {expected});
}}
"#,
name = symbol_to_ident_lower(&entry.symbol),
module = entry.module,
symbol = entry.symbol,
));
}
out
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn file_header(filename: &str) -> String {
format!(
"// SPDX-License-Identifier: GPL-3.0-or-later\n\
// AUTO-GENERATED by xenora-import-gen — DO NOT EDIT MANUALLY.\n\
// Source: public Win32/CRT documentation and ISO C standard.\n\
// Regenerate: `xenora imports generate --pe <executable>`\n\
// File: {filename}\n\n"
)
}
/// Convert a C symbol name to a valid Rust identifier (snake_case, no special chars).
fn symbol_to_ident(sym: &str) -> String {
sym.chars()
.map(|c| {
if c.is_alphanumeric() || c == '_' {
c
} else {
'_'
}
})
.collect()
}
fn symbol_to_ident_lower(sym: &str) -> String {
symbol_to_ident(sym).to_ascii_lowercase()
}
/// Returns a dispatch body for CRT calls with a compatible guest ABI adapter.
pub(crate) fn crt_dispatch_expr(symbol: &str) -> Option<String> {
Some(match symbol {
// abs(int) -> int
"abs" | "labs" => r#"let x = args.rcx as i32;
Ok(x.abs() as u64)"#
.to_string(),
"llabs" => r#"let x = args.rcx as i64;
Ok(x.unsigned_abs())"#
.to_string(),
// ISO C classification functions: char in RCX
"isalnum" | "isalpha" | "isdigit" | "islower" | "isupper" | "isspace" | "isprint"
| "iscntrl" | "ispunct" | "isxdigit" => {
let test = match symbol {
"isalnum" => "(c.is_ascii_alphanumeric())",
"isalpha" => "(c.is_ascii_alphabetic())",
"isdigit" => "(c.is_ascii_digit())",
"islower" => "(c.is_ascii_lowercase())",
"isupper" => "(c.is_ascii_uppercase())",
"isspace" => "(c.is_ascii_whitespace())",
"isprint" => "(!c.is_ascii_control())",
"iscntrl" => "(c.is_ascii_control())",
"ispunct" => "(c.is_ascii_punctuation())",
"isxdigit" => "(c.is_ascii_hexdigit())",
_ => "(false)",
};
format!(
r#"let c = (args.rcx & 0xFF) as u8 as char;
Ok(if {test} {{ 1 }} else {{ 0 }})"#,
test = test,
)
}
"tolower" => r#"let c = (args.rcx & 0xFF) as u8;
Ok(c.to_ascii_lowercase() as u64)"#
.to_string(),
"toupper" => r#"let c = (args.rcx & 0xFF) as u8;
Ok(c.to_ascii_uppercase() as u64)"#
.to_string(),
// Floating-point CRT calls also land here until XMM state is available.
_ => return None,
})
}
/// Independent canonical inputs and expected integer return bits.
fn canonical_integer_case(symbol: &str) -> Option<(u64, u64)> {
Some(match symbol {
"abs" | "labs" | "llabs" => ((-42i64) as u64, 42),
"tolower" => (65, 97),
"toupper" => (122, 90),
"isalnum" | "isalpha" | "isupper" | "isxdigit" => (65, 1),
"isdigit" => (53, 1),
"islower" => (122, 1),
"isspace" => (32, 1),
"isprint" => (65, 1),
"iscntrl" => (127, 1),
"ispunct" => (33, 1),
_ => return None,
})
}
-529
View File
@@ -1,529 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Decoding of Microsoft Visual C++ decorated names, for diagnostics.
//!
//! Written from the publicly described decoration scheme: a leading `?`,
//! `@`-terminated name fragments listed innermost first, single-digit name and
//! type back-references, an access and storage code, a calling convention,
//! the return type and the parameter list. Output follows the style of
//! Microsoft's `undname` tool. Anything outside the supported subset returns
//! `None` instead of a guess, so callers fall back to the decorated name.
const MAX_DEPTH: usize = 16;
/// The undecorated form of `symbol`, or `None` when it is not a decorated
/// C++ name or uses an unsupported construct.
pub fn demangle(symbol: &str) -> Option<String> {
let mut parser = Parser {
input: symbol.as_bytes(),
position: 0,
names: Vec::new(),
types: Vec::new(),
depth: 0,
};
let result = parser.symbol()?;
(parser.position == parser.input.len()).then_some(result)
}
/// A special name introduced by `?` and a code inside the qualified name.
enum Special {
Constructor,
Destructor,
Operator(&'static str),
Vftable,
}
struct Parser<'a> {
input: &'a [u8],
position: usize,
names: Vec<String>,
types: Vec<String>,
depth: usize,
}
impl Parser<'_> {
fn peek(&self) -> Option<u8> {
self.input.get(self.position).copied()
}
fn next(&mut self) -> Option<u8> {
let byte = self.peek()?;
self.position += 1;
Some(byte)
}
fn eat(&mut self, byte: u8) -> bool {
let found = self.peek() == Some(byte);
if found {
self.position += 1;
}
found
}
fn eat_str(&mut self, text: &str) -> bool {
let found = self.input[self.position..].starts_with(text.as_bytes());
if found {
self.position += text.len();
}
found
}
fn symbol(&mut self) -> Option<String> {
if !self.eat(b'?') {
return None;
}
let (name, special) = self.qualified_name(true)?;
match self.peek()? {
b'0'..=b'4' => self.variable(&name),
b'6' => {
self.next();
let qualifier = cv(self.next()?)?;
self.eat(b'@');
if !matches!(special, Some(Special::Vftable)) {
return None;
}
Some(format!("{} {name}", qualifier.trim()))
}
_ => self.function(&name, special.as_ref()),
}
}
fn variable(&mut self, name: &str) -> Option<String> {
let access = match self.next()? {
b'0' => "private: static ",
b'1' => "protected: static ",
b'2' => "public: static ",
_ => "",
};
let kind = self.data_type()?;
self.eat(b'E');
let qualifier = cv(self.next()?)?;
Some(format!("{access}{kind}{qualifier} {name}"))
}
fn function(&mut self, name: &str, special: Option<&Special>) -> Option<String> {
let (access, member) = match self.next()? {
b'A' | b'B' => ("private: ", true),
b'C' | b'D' => ("private: static ", false),
b'E' | b'F' => ("private: virtual ", true),
b'I' | b'J' => ("protected: ", true),
b'K' | b'L' => ("protected: static ", false),
b'M' | b'N' => ("protected: virtual ", true),
b'Q' | b'R' => ("public: ", true),
b'S' | b'T' => ("public: static ", false),
b'U' | b'V' => ("public: virtual ", true),
b'Y' | b'Z' => ("", false),
_ => return None,
};
let mut this = String::new();
if member {
let pointer64 = self.eat(b'E');
this.push_str(cv(self.next()?)?.trim_start());
if pointer64 {
this.push_str(" __ptr64");
}
}
let convention = match self.next()? {
b'A' | b'B' => "__cdecl",
b'C' | b'D' => "__pascal",
b'E' | b'F' => "__thiscall",
b'G' | b'H' => "__stdcall",
b'I' | b'J' => "__fastcall",
b'Q' => "__vectorcall",
_ => return None,
};
let returns = if self.eat(b'@') {
if !matches!(special, Some(Special::Constructor | Special::Destructor)) {
return None;
}
String::new()
} else {
if self.eat(b'?') {
cv(self.next()?)?;
}
format!("{} ", self.data_type()?)
};
let parameters = self.parameters()?;
if !self.eat(b'Z') {
return None;
}
Some(format!(
"{access}{returns}{convention} {name}({parameters}){this}"
))
}
fn parameters(&mut self) -> Option<String> {
if self.eat(b'X') {
return Some("void".to_owned());
}
let mut parameters = Vec::new();
loop {
match self.peek()? {
b'@' => {
self.next();
break;
}
b'Z' => {
self.next();
parameters.push("...".to_owned());
break;
}
_ => {
let start = self.position;
let kind = self.data_type()?;
if self.position - start > 1 && self.types.len() < 10 {
self.types.push(kind.clone());
}
parameters.push(kind);
}
}
}
Some(parameters.join(","))
}
/// Fragments up to `@`, joined outermost first.
fn qualified_name(&mut self, allow_special: bool) -> Option<(String, Option<Special>)> {
let mut special = None;
let mut fragments = Vec::new();
if allow_special
&& self.peek() == Some(b'?')
&& self.input.get(self.position + 1) != Some(&b'$')
{
self.next();
special = Some(self.special()?);
} else {
fragments.push(self.fragment()?);
}
while !self.eat(b'@') {
fragments.push(self.fragment()?);
}
fragments.reverse();
let scope = fragments.join("::");
let name = match &special {
None => scope,
Some(special) => {
let class = || Some(fragments.last()?.split('<').next()?.to_owned());
let leaf = match special {
Special::Constructor => class()?,
Special::Destructor => format!("~{}", class()?),
Special::Operator(name) => name.to_string(),
Special::Vftable => "`vftable'".to_owned(),
};
if scope.is_empty() {
leaf
} else {
format!("{scope}::{leaf}")
}
}
};
Some((name, special))
}
fn special(&mut self) -> Option<Special> {
Some(match self.next()? {
b'0' => Special::Constructor,
b'1' => Special::Destructor,
b'2' => Special::Operator("operator new"),
b'3' => Special::Operator("operator delete"),
b'4' => Special::Operator("operator="),
b'8' => Special::Operator("operator=="),
b'9' => Special::Operator("operator!="),
b'A' => Special::Operator("operator[]"),
b'R' => Special::Operator("operator()"),
b'_' => match self.next()? {
b'7' => Special::Vftable,
b'U' => Special::Operator("operator new[]"),
b'V' => Special::Operator("operator delete[]"),
_ => return None,
},
_ => return None,
})
}
fn fragment(&mut self) -> Option<String> {
if let Some(digit @ b'0'..=b'9') = self.peek() {
self.next();
return self.names.get(usize::from(digit - b'0')).cloned();
}
let fragment = if self.eat_str("?$") {
self.template()?
} else {
self.identifier()?
};
if self.names.len() < 10 && !self.names.contains(&fragment) {
self.names.push(fragment.clone());
}
Some(fragment)
}
fn identifier(&mut self) -> Option<String> {
let start = self.position;
while self.peek()? != b'@' {
let byte = self.next()?;
if !(byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$') {
return None;
}
}
let text = std::str::from_utf8(&self.input[start..self.position]).ok()?;
self.next();
(!text.is_empty()).then(|| text.to_owned())
}
/// `name@arguments@`, with back-references local to the argument list.
fn template(&mut self) -> Option<String> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return None;
}
let outer_names = std::mem::take(&mut self.names);
let outer_types = std::mem::take(&mut self.types);
let name = self.identifier();
if let Some(name) = &name {
self.names.push(name.clone());
}
let mut arguments = Vec::new();
let result = (|| {
let name = name?;
while !self.eat(b'@') {
let start = self.position;
let argument = if self.eat(b'$') {
if !self.eat(b'0') {
return None;
}
self.number()?.to_string()
} else {
self.data_type()?
};
if self.position - start > 1 && self.types.len() < 10 {
self.types.push(argument.clone());
}
arguments.push(argument);
}
let joined = arguments.join(",");
let close = if joined.ends_with('>') { " >" } else { ">" };
Some(format!("{name}<{joined}{close}"))
})();
self.names = outer_names;
self.types = outer_types;
self.depth -= 1;
result
}
/// `0`–`9` encode 1–10; otherwise hexadecimal digits `A`–`P` end with `@`.
fn number(&mut self) -> Option<i64> {
let negative = self.eat(b'?');
let value = match self.next()? {
digit @ b'0'..=b'9' => i64::from(digit - b'0') + 1,
b'@' => 0,
mut digit => {
let mut value: i64 = 0;
loop {
if !(b'A'..=b'P').contains(&digit) {
return None;
}
value = value
.checked_mul(16)?
.checked_add(i64::from(digit - b'A'))?;
digit = self.next()?;
if digit == b'@' {
break value;
}
}
}
};
Some(if negative { -value } else { value })
}
fn data_type(&mut self) -> Option<String> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return None;
}
let result = self.data_type_inner();
self.depth -= 1;
result
}
fn data_type_inner(&mut self) -> Option<String> {
let code = self.next()?;
let primitive = match code {
b'X' => "void",
b'C' => "signed char",
b'D' => "char",
b'E' => "unsigned char",
b'F' => "short",
b'G' => "unsigned short",
b'H' => "int",
b'I' => "unsigned int",
b'J' => "long",
b'K' => "unsigned long",
b'M' => "float",
b'N' => "double",
b'O' => "long double",
b'0'..=b'9' => return self.types.get(usize::from(code - b'0')).cloned(),
b'_' => match self.next()? {
b'J' => "__int64",
b'K' => "unsigned __int64",
b'N' => "bool",
b'W' => "wchar_t",
b'S' => "char16_t",
b'U' => "char32_t",
b'Q' => "char8_t",
_ => return None,
},
b'V' => return Some(format!("class {}", self.qualified_name(false)?.0)),
b'U' => return Some(format!("struct {}", self.qualified_name(false)?.0)),
b'T' => return Some(format!("union {}", self.qualified_name(false)?.0)),
b'W' => {
if !self.eat(b'4') {
return None;
}
return Some(format!("enum {}", self.qualified_name(false)?.0));
}
b'P' | b'Q' | b'R' | b'S' => return self.indirection("*", pointer_cv(code)),
b'A' => return self.indirection("&", ""),
b'B' => return self.indirection("&", " volatile"),
b'$' => {
if self.eat_str("$Q") {
return self.indirection("&&", "");
}
if self.eat_str("$T") {
return Some("std::nullptr_t".to_owned());
}
return None;
}
_ => return None,
};
Some(primitive.to_owned())
}
/// A pointer or reference: an optional `E` for `__ptr64`, the pointee's
/// qualifiers, then the pointee.
fn indirection(&mut self, symbol: &str, own: &str) -> Option<String> {
let pointer64 = self.eat(b'E');
let pointee_cv = cv(self.next()?)?;
let pointee = self.data_type()?;
let width = if pointer64 { " __ptr64" } else { "" };
Some(format!("{pointee}{pointee_cv} {symbol}{own}{width}"))
}
}
fn cv(code: u8) -> Option<&'static str> {
Some(match code {
b'A' => "",
b'B' => " const",
b'C' => " volatile",
b'D' => " const volatile",
_ => return None,
})
}
fn pointer_cv(code: u8) -> &'static str {
match code {
b'Q' => " const",
b'R' => " volatile",
b'S' => " const volatile",
_ => "",
}
}
#[cfg(test)]
mod tests {
use super::demangle;
#[test]
fn decodes_global_functions_and_operators() {
for (decorated, expected) in [
("?foo@@YAXXZ", "void __cdecl foo(void)"),
("?foo@@YAHH@Z", "int __cdecl foo(int)"),
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
("?f@@YAXHZZ", "void __cdecl f(int,...)"),
(
"??2@YAPEAX_K@Z",
"void * __ptr64 __cdecl operator new(unsigned __int64)",
),
(
"??3@YAXPEAX@Z",
"void __cdecl operator delete(void * __ptr64)",
),
(
"??_U@YAPEAX_K@Z",
"void * __ptr64 __cdecl operator new[](unsigned __int64)",
),
(
"?_Xlength_error@std@@YAXPEBD@Z",
"void __cdecl std::_Xlength_error(char const * __ptr64)",
),
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
] {
assert_eq!(
demangle(decorated).as_deref(),
Some(expected),
"{decorated}"
);
}
}
#[test]
fn decodes_members_constructors_and_data() {
for (decorated, expected) in [
(
"?bar@Foo@@QEAAXH@Z",
"public: void __cdecl Foo::bar(int) __ptr64",
),
(
"?get@Foo@@QEBAHXZ",
"public: int __cdecl Foo::get(void)const __ptr64",
),
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
(
"??1Foo@@UEAA@XZ",
"public: virtual __cdecl Foo::~Foo(void) __ptr64",
),
(
"?make@Foo@@SAPEAV1@XZ",
"public: static class Foo * __ptr64 __cdecl Foo::make(void)",
),
("?x@ns@@3HA", "int ns::x"),
("?count@Foo@@2HB", "public: static int const Foo::count"),
("??_7type_info@@6B@", "const type_info::`vftable'"),
] {
assert_eq!(
demangle(decorated).as_deref(),
Some(expected),
"{decorated}"
);
}
}
#[test]
fn decodes_templates_and_back_references() {
assert_eq!(
demangle("?g@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z")
.as_deref(),
Some(
"void __cdecl g(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)"
)
);
assert_eq!(
demangle("?h@@YAXV?$array@H$0BA@@std@@@Z").as_deref(),
Some("void __cdecl h(class std::array<int,16>)")
);
}
#[test]
fn rejects_undecorated_and_unsupported_names() {
for symbol in [
"malloc",
"",
"?",
"?foo@@",
"?foo@@YAXXZtrailing",
"??_R0?AVtype_info@@@8",
"?f@@YAXP6AXXZ@Z",
&format!("?f@@YAX{}@Z", "PEA".repeat(40) + "H"),
] {
assert_eq!(demangle(symbol), None, "{symbol}");
}
}
}
-217
View File
@@ -1,217 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Automated C / POSIX header parser for metadata ingestion.
//!
//! Ingests standard system headers (e.g. `/usr/include/math.h`, `_string.h`)
//! and extracts function signatures into typed `FunctionSignature` definitions.
//!
//! Preserves clean-room provenance and licensing attribution.
use crate::metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog, ParamDesc};
use std::path::Path;
/// Ingest C header files from disk into `catalog`.
pub fn ingest_header_file(
catalog: &mut MetadataCatalog,
module: &str,
header_path: &Path,
) -> Result<usize, String> {
let content = std::fs::read_to_string(header_path)
.map_err(|e| format!("cannot read {}: {e}", header_path.display()))?;
let filename = header_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("header.h");
let count = parse_c_declarations(catalog, module, filename, &content);
Ok(count)
}
/// Ingest standard macOS SDK math and string headers if available.
pub fn ingest_standard_system_headers(catalog: &mut MetadataCatalog) -> usize {
let candidates = [
(
"ucrtbase.dll",
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/math.h",
),
(
"ucrtbase.dll",
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_string.h",
),
];
let mut total = 0;
for (mod_name, path_str) in candidates {
let p = Path::new(path_str);
if p.exists()
&& let Ok(n) = ingest_header_file(catalog, mod_name, p)
{
total += n;
}
}
total
}
/// Parse C function prototypes from `content`.
fn parse_c_declarations(
catalog: &mut MetadataCatalog,
module: &str,
header_name: &str,
content: &str,
) -> usize {
let mut added = 0;
for line in content.lines() {
let line = line.trim();
// Look for lines containing function prototypes, e.g. "extern double acos(double);" or "int strcmp(...);"
if !line.contains('(')
|| !line.contains(')')
|| line.starts_with('#')
|| line.starts_with("/*")
|| line.starts_with('*')
{
continue;
}
// Clean up __attribute__, extern, etc.
let cleaned = line
.replace("extern ", "")
.replace("__DARWIN_ALIAS(", "/* alias */ ")
.replace("__DARWIN_ALIAS_C(", "/* alias */ ")
.replace("_LIBC_CSTR", "char *")
.replace("_LIBC_UNSAFE_INDEXABLE", "");
let Some(open_paren) = cleaned.find('(') else {
continue;
};
let Some(close_paren) = cleaned[open_paren..].find(')') else {
continue;
};
let close_paren = open_paren + close_paren;
let decl_left = cleaned[..open_paren].trim();
let args_str = cleaned[open_paren + 1..close_paren].trim();
// Split return type and function name
let parts: Vec<&str> = decl_left.split_whitespace().collect();
if parts.len() < 2 {
continue;
}
let ret_str = parts[..parts.len() - 1].join(" ");
let name_str = parts[parts.len() - 1].trim_start_matches('*');
if !is_valid_c_ident(name_str) {
continue;
}
let ret_type = match parse_c_type(&ret_str) {
Some(t) => t,
None => continue,
};
let mut params = Vec::new();
if !args_str.is_empty() && args_str != "void" {
for (idx, arg) in args_str.split(',').enumerate() {
let arg_clean = arg.trim();
let arg_parts: Vec<&str> = arg_clean.split_whitespace().collect();
let (param_name, type_str) = if arg_parts.is_empty() {
(format!("arg{idx}"), "void".to_string())
} else if arg_parts.len() == 1 {
(format!("arg{idx}"), arg_parts[0].to_string())
} else {
let last = arg_parts[arg_parts.len() - 1].trim_start_matches('*');
if is_valid_c_ident(last) {
(last.to_string(), arg_parts[..arg_parts.len() - 1].join(" "))
} else {
(format!("arg{idx}"), arg_clean.to_string())
}
};
let param_type = parse_c_type(&type_str).unwrap_or(AbiType::U64);
params.push(ParamDesc {
name: param_name,
abi_type: param_type,
});
}
}
let sig = FunctionSignature {
name: name_str.to_string(),
return_type: ret_type,
params,
convention: CallingConvention::Win64,
header_source: format!("<{header_name}>"),
doc: format!("Ingested from {header_name}"),
};
catalog
.entries
.insert((module.to_ascii_lowercase(), name_str.to_string()), sig);
added += 1;
}
added
}
fn is_valid_c_ident(s: &str) -> bool {
if s.is_empty() {
return false;
}
let bytes = s.as_bytes();
if !bytes[0].is_ascii_alphabetic() && bytes[0] != b'_' {
return false;
}
bytes
.iter()
.all(|&b| b.is_ascii_alphanumeric() || b == b'_')
}
fn parse_c_type(s: &str) -> Option<AbiType> {
let s = s.trim();
if s == "void" {
Some(AbiType::Void)
} else if s == "int" || s == "int32_t" {
Some(AbiType::I32)
} else if s == "unsigned int" || s == "uint32_t" || s == "unsigned" {
Some(AbiType::U32)
} else if s == "long long" || s == "int64_t" {
Some(AbiType::I64)
} else if s == "size_t" || s == "unsigned long" || s == "unsigned long long" || s == "uint64_t"
{
Some(AbiType::U64)
} else if s == "float" {
Some(AbiType::F32)
} else if s == "double" {
Some(AbiType::F64)
} else if s.contains("const char") || s.contains("char *") {
Some(AbiType::StringAnsi)
} else if s.contains('*') {
Some(AbiType::Pointer {
is_const: s.contains("const"),
pointee: "void".into(),
})
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_declarations_from_string() {
let mut cat = MetadataCatalog::new();
let c_code = r#"
extern double cos(double x);
extern double atan2(double y, double x);
int strcmp(const char *s1, const char *s2);
"#;
let count = parse_c_declarations(&mut cat, "ucrtbase.dll", "test.h", c_code);
assert_eq!(count, 3);
assert!(cat.lookup("ucrtbase.dll", "cos").is_some());
assert!(cat.lookup("ucrtbase.dll", "atan2").is_some());
assert!(cat.lookup("ucrtbase.dll", "strcmp").is_some());
}
}
-58
View File
@@ -1,58 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Deterministic Win32/CRT import binding generator for Xenora.
//!
//! Reads an import list (PE file or CSV produced by `xenora probe`), classifies each
//! symbol against a built-in public-API database derived from documented Win32/CRT
//! specifications and MinGW-w64 / POSIX equivalents, then generates:
//!
//! - `generated_crt.rs` — CRT functions mapped to native libc via `extern "C"` FFI
//! - `generated_stubs.rs` — Logged stubs for functions that cannot be automatically mapped
//! - `generated_tests.rs` — Conformance tests for every generated binding
//! - `generated_manifest.csv`— Machine-readable coverage report
//!
//! The generator is completely offline. It consumes no AI tokens and has no network
//! dependencies. Output is deterministic and idempotent given the same inputs.
//!
//! # Classification tiers
//!
//! | Tier | Meaning |
//! |------|---------|
//! | `CrtNative` | Directly maps to a libc symbol with identical semantics |
//! | `CrtWrapper` | Maps to libc with argument/return marshalling |
//! | `Win32Stub` | Windows-specific; generated as a logged stub |
//! | `Unsupported`| Proprietary/unavailable; noted in manifest, no code emitted |
//! | `Manual` | Requires hand-written implementation; flagged in report |
pub mod apiset;
pub mod classify;
pub mod codegen;
pub mod demangle;
pub mod ingest;
pub mod manifest;
pub mod metadata;
pub mod parse;
pub mod typed;
pub mod verify;
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
pub use classify::{Classification, SymbolDb};
pub use codegen::{GeneratedFiles, generate};
pub use demangle::demangle;
pub use ingest::{ingest_header_file, ingest_standard_system_headers};
pub use manifest::Manifest;
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
pub use parse::{ImportRecord, parse_csv};
pub use verify::{VerificationResult, run_verification};
/// Top-level entry point. Reads `csv_path`, classifies every symbol, generates
/// Rust source into `out_dir`, and writes `generated_manifest.csv`.
pub fn run(csv_path: &str, out_dir: &str) -> Result<Manifest, String> {
let records = parse_csv(csv_path)?;
let db = SymbolDb::builtin();
let manifest = Manifest::build(&records, &db);
let files = generate(&manifest, &db);
files.write_all(out_dir)?;
manifest.write_csv(&format!("{out_dir}/generated_manifest.csv"))?;
Ok(manifest)
}
-180
View File
@@ -1,180 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Coverage manifest: collects classified records and renders reports.
use crate::classify::{Classification, SymbolDb};
use crate::parse::ImportRecord;
use std::collections::{BTreeMap, BTreeSet};
/// One classified import entry.
#[derive(Clone, Debug)]
pub struct ManifestEntry {
pub module: String,
pub symbol: String,
pub ordinal: Option<u16>,
pub iat_rva: u64,
pub classification: Classification,
}
impl ManifestEntry {
pub(crate) fn key(&self) -> (String, Option<u16>, &str) {
(
self.module.to_ascii_lowercase(),
self.ordinal,
if self.ordinal.is_none() {
&self.symbol
} else {
""
},
)
}
pub fn tier(&self) -> &'static str {
self.classification.tier_name()
}
/// Runtime disposition of the generated output for this import.
pub fn emission(&self) -> &'static str {
match &self.classification {
Classification::StandardService => "runtime-service",
Classification::CrtNative { .. }
if crate::codegen::crt_dispatch_expr(&self.symbol).is_some() =>
{
"generated-adapter"
}
Classification::CrtNative { .. }
| Classification::CrtWrapper { .. }
| Classification::RuntimeHelper { .. }
| Classification::Win32Stub { .. } => "generated-stub",
Classification::Manual { .. } | Classification::Unsupported { .. } => "no-binding",
}
}
}
/// Full coverage manifest for a set of import records.
pub struct Manifest {
pub entries: Vec<ManifestEntry>,
}
impl Manifest {
/// Classify every record using the symbol database.
pub fn build(records: &[ImportRecord], db: &SymbolDb) -> Self {
let mut entries = Vec::with_capacity(records.len());
for rec in records {
// Check for exact symbol match, then wildcard module match
let classification = if rec.ordinal.is_some() {
Classification::Manual {
reason: "ordinal requires a documented export mapping in the typed runtime registry",
}
} else if let Some(c) = db.get(&rec.module, &rec.symbol) {
c.clone()
} else if let Some(c) = db.get(&rec.module, "__wildcard__") {
c.clone()
} else {
// Unknown — treat as Manual
Classification::Manual {
reason: "no entry in built-in database — engineer required",
}
};
entries.push(ManifestEntry {
module: rec.module.clone(),
symbol: rec.symbol.clone(),
ordinal: rec.ordinal,
iat_rva: rec.iat_rva,
classification,
});
}
Self { entries }
}
/// Count entries by tier.
pub fn summary(&self) -> BTreeMap<&'static str, usize> {
let mut m: BTreeMap<&'static str, usize> = BTreeMap::new();
for e in &self.entries {
*m.entry(e.tier()).or_default() += 1;
}
m
}
/// Count distinct module and symbol keys by emitted disposition.
pub fn emission_summary(&self) -> BTreeMap<&'static str, usize> {
let mut seen = BTreeSet::new();
let mut counts = BTreeMap::new();
for entry in &self.entries {
if seen.insert(entry.key()) {
*counts.entry(entry.emission()).or_default() += 1;
}
}
counts
}
/// Entries that the generator can produce code for.
pub fn generatable(&self) -> impl Iterator<Item = &ManifestEntry> {
self.entries
.iter()
.filter(|e| e.classification.is_generatable())
}
/// Write the manifest as CSV for `xenora imports sync` integration.
pub fn write_csv(&self, path: &str) -> Result<(), String> {
let mut out = String::from("module,symbol,iat_rva,tier,emission,import_kind\n");
for e in &self.entries {
let kind = if e.ordinal.is_some() {
"ordinal"
} else {
"name"
};
out.push_str(&format!(
"\"{}\",\"{}\",0x{:08x},{},{},{kind}\n",
e.module,
e.symbol,
e.iat_rva,
e.tier(),
e.emission()
));
}
std::fs::write(path, out).map_err(|e| format!("write manifest CSV {path}: {e}"))
}
/// Human-readable Markdown summary.
pub fn render_markdown(&self) -> String {
let summary = self.summary();
let total = self.entries.len();
let mut md = String::new();
md.push_str("# Xenora import generator manifest\n\n");
md.push_str("Generated by `xenora imports generate`. Do not edit manually.\n\n");
md.push_str("## Catalog classification by import slot\n\n");
md.push_str("| Tier | Count | % |\n| --- | ---: | ---: |\n");
let total_pct = if total == 0 { 0 } else { 100 };
md.push_str(&format!("| **Total** | {total} | {total_pct}% |\n"));
for (tier, count) in &summary {
let pct = (*count as f64 / total as f64 * 100.0) as u32;
md.push_str(&format!("| `{tier}` | {count} | {pct}% |\n"));
}
md.push_str("\n## Emitted disposition by distinct import\n\n");
md.push_str("| Disposition | Count |\n| --- | ---: |\n");
let emissions = self.emission_summary();
md.push_str(&format!(
"| **Total** | {} |\n",
emissions.values().sum::<usize>()
));
for (disposition, count) in emissions {
md.push_str(&format!("| `{disposition}` | {count} |\n"));
}
md.push_str("\nAdapters are emitted as partial handlers. Runtime services use existing registrations.\n");
md.push_str("\n## Functions requiring manual engineering\n\n");
for e in &self.entries {
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
&e.classification
{
match crate::demangle(&e.symbol) {
Some(name) => md.push_str(&format!(
"- `{}!{}` (`{name}`) — {reason}\n",
e.module, e.symbol
)),
None => md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol)),
}
}
}
md
}
}
-467
View File
@@ -1,467 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Versioned, offline API metadata definitions.
//!
//! Stores typed function signatures, parameter descriptions, calling conventions,
//! and header sources derived from public Win32 and MinGW-w64 metadata.
//!
//! Strictly clean-room: derived from public documentation, MIT/BSD-licensed headers,
//! or ISO C/POSIX standards.
use std::collections::BTreeMap;
/// Calling convention used by the foreign function.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CallingConvention {
/// Standard Microsoft x64 (RCX, RDX, R8, R9, Stack)
Win64,
/// Standard CDECL / System V AMD64
Cdecl,
}
/// Primitive argument and return types supported by the ABI translator.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AbiType {
Void,
Bool,
I32,
U32,
I64,
U64,
F32,
F64,
/// Opaque Win64 object handle.
Handle,
/// Raw guest pointer (virtual address).
Pointer {
is_const: bool,
pointee: String,
},
/// Null-terminated UTF-8 / ANSI string in guest memory.
StringAnsi,
/// Null-terminated UTF-16 wide string in guest memory.
StringWide,
/// Complex composite struct passed by pointer.
Struct(String),
}
/// Complete parameter specification.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParamDesc {
pub name: String,
pub abi_type: AbiType,
}
/// Complete function signature in the metadata database.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FunctionSignature {
pub name: String,
pub return_type: AbiType,
pub params: Vec<ParamDesc>,
pub convention: CallingConvention,
pub header_source: String,
pub doc: String,
}
/// Versioned metadata catalog for a subsystem or DLL.
pub struct MetadataCatalog {
pub version: u32,
pub entries: BTreeMap<(String, String), FunctionSignature>, // (canonical_module, symbol) -> sig
}
impl Default for MetadataCatalog {
fn default() -> Self {
Self::new()
}
}
impl MetadataCatalog {
pub fn new() -> Self {
Self {
version: 1,
entries: BTreeMap::new(),
}
}
/// Load the built-in clean-room metadata catalog and ingest system headers.
pub fn builtin() -> Self {
let mut cat = Self::new();
cat.populate_crt();
cat.populate_win32_core();
// Genuine automated ingestion of available public system C/POSIX headers
crate::ingest::ingest_standard_system_headers(&mut cat);
cat
}
pub fn lookup(&self, canonical_module: &str, symbol: &str) -> Option<&FunctionSignature> {
let key = (canonical_module.to_ascii_lowercase(), symbol.to_string());
self.entries.get(&key)
}
fn add(
&mut self,
module: &str,
name: &str,
ret: AbiType,
params: Vec<(&str, AbiType)>,
header: &str,
doc: &str,
) {
let sig = FunctionSignature {
name: name.to_string(),
return_type: ret,
params: params
.into_iter()
.map(|(pname, ptype)| ParamDesc {
name: pname.to_string(),
abi_type: ptype,
})
.collect(),
convention: CallingConvention::Win64,
header_source: header.to_string(),
doc: doc.to_string(),
};
self.entries
.insert((module.to_ascii_lowercase(), name.to_string()), sig);
}
fn populate_crt(&mut self) {
// math.h
for name in &[
"cos", "sin", "tan", "acos", "asin", "atan", "exp", "log", "sqrt", "fabs",
] {
self.add(
"ucrtbase.dll",
name,
AbiType::F64,
vec![("x", AbiType::F64)],
"<math.h>",
"ISO C standard math single-argument double",
);
}
for name in &[
"cosf", "sinf", "tanf", "acosf", "asinf", "atanf", "expf", "logf", "sqrtf", "fabsf",
] {
self.add(
"ucrtbase.dll",
name,
AbiType::F32,
vec![("x", AbiType::F32)],
"<math.h>",
"ISO C standard math single-argument float",
);
}
self.add(
"ucrtbase.dll",
"atan2",
AbiType::F64,
vec![("y", AbiType::F64), ("x", AbiType::F64)],
"<math.h>",
"ISO C arc tangent of two variables",
);
self.add(
"ucrtbase.dll",
"atan2f",
AbiType::F32,
vec![("y", AbiType::F32), ("x", AbiType::F32)],
"<math.h>",
"ISO C arc tangent of two variables (float)",
);
self.add(
"ucrtbase.dll",
"pow",
AbiType::F64,
vec![("base", AbiType::F64), ("exp", AbiType::F64)],
"<math.h>",
"ISO C power function",
);
self.add(
"ucrtbase.dll",
"powf",
AbiType::F32,
vec![("base", AbiType::F32), ("exp", AbiType::F32)],
"<math.h>",
"ISO C power function (float)",
);
// string.h
self.add(
"ucrtbase.dll",
"strlen",
AbiType::U64,
vec![("str", AbiType::StringAnsi)],
"<string.h>",
"Calculates the length of a string in guest memory",
);
self.add(
"ucrtbase.dll",
"strnlen",
AbiType::U64,
vec![("str", AbiType::StringAnsi), ("count", AbiType::U64)],
"<string.h>",
"Calculates a byte string length up to the supplied bound",
);
self.add(
"ucrtbase.dll",
"strcmp",
AbiType::I32,
vec![("str1", AbiType::StringAnsi), ("str2", AbiType::StringAnsi)],
"<string.h>",
"Compares two strings lexicographically",
);
self.add(
"ucrtbase.dll",
"strncmp",
AbiType::I32,
vec![
("str1", AbiType::StringAnsi),
("str2", AbiType::StringAnsi),
("count", AbiType::U64),
],
"<string.h>",
"Compares up to count characters of two strings",
);
self.add(
"ucrtbase.dll",
"wcslen",
AbiType::U64,
vec![("str", AbiType::StringWide)],
"<wchar.h>",
"Counts 16-bit Windows code units before the terminator",
);
self.add(
"ucrtbase.dll",
"wcsnlen",
AbiType::U64,
vec![("str", AbiType::StringWide), ("count", AbiType::U64)],
"<wchar.h>",
"Counts 16-bit Windows code units up to the supplied bound",
);
self.add(
"ucrtbase.dll",
"wcscmp",
AbiType::I32,
vec![("str1", AbiType::StringWide), ("str2", AbiType::StringWide)],
"<wchar.h>",
"Compares two strings of 16-bit Windows code units",
);
self.add(
"ucrtbase.dll",
"wcsncmp",
AbiType::I32,
vec![
("str1", AbiType::StringWide),
("str2", AbiType::StringWide),
("count", AbiType::U64),
],
"<wchar.h>",
"Compares up to count 16-bit Windows code units of two strings",
);
self.add(
"ucrtbase.dll",
"memset",
AbiType::Pointer {
is_const: false,
pointee: "void".into(),
},
vec![
(
"dest",
AbiType::Pointer {
is_const: false,
pointee: "void".into(),
},
),
("c", AbiType::I32),
("count", AbiType::U64),
],
"<string.h>",
"Fills memory with a constant byte",
);
self.add(
"ucrtbase.dll",
"memcpy",
AbiType::Pointer {
is_const: false,
pointee: "void".into(),
},
vec![
(
"dest",
AbiType::Pointer {
is_const: false,
pointee: "void".into(),
},
),
(
"src",
AbiType::Pointer {
is_const: true,
pointee: "void".into(),
},
),
("count", AbiType::U64),
],
"<string.h>",
"Copies memory between non-overlapping guest regions",
);
self.add(
"ucrtbase.dll",
"memmove",
AbiType::Pointer {
is_const: false,
pointee: "void".into(),
},
vec![
(
"dest",
AbiType::Pointer {
is_const: false,
pointee: "void".into(),
},
),
(
"src",
AbiType::Pointer {
is_const: true,
pointee: "void".into(),
},
),
("count", AbiType::U64),
],
"<string.h>",
"Copies memory between guest ranges that may overlap",
);
self.add(
"ucrtbase.dll",
"memcmp",
AbiType::I32,
vec![
(
"buf1",
AbiType::Pointer {
is_const: true,
pointee: "void".into(),
},
),
(
"buf2",
AbiType::Pointer {
is_const: true,
pointee: "void".into(),
},
),
("count", AbiType::U64),
],
"<string.h>",
"Compares bytes in two memory buffers",
);
}
fn populate_win32_core(&mut self) {
// kernel32 processthreads / synch
self.add(
"kernel32.dll",
"GetCurrentProcessId",
AbiType::U32,
vec![],
"<processthreadsapi.h>",
"Retrieves the process identifier of the calling process",
);
self.add(
"kernel32.dll",
"GetCurrentThreadId",
AbiType::U32,
vec![],
"<processthreadsapi.h>",
"Retrieves the thread identifier of the calling thread",
);
self.add(
"kernel32.dll",
"GetLastError",
AbiType::U32,
vec![],
"<errhandlingapi.h>",
"Retrieves the calling thread's last-error code value",
);
self.add(
"kernel32.dll",
"SetLastError",
AbiType::Void,
vec![("dwErrCode", AbiType::U32)],
"<errhandlingapi.h>",
"Sets the last-error code for the calling thread",
);
self.add(
"kernel32.dll",
"GetThreadId",
AbiType::U32,
vec![("Thread", AbiType::Handle)],
"<processthreadsapi.h>",
"Retrieves the identifier of the specified thread",
);
self.add(
"kernel32.dll",
"DuplicateHandle",
AbiType::Bool,
vec![
("hSourceProcessHandle", AbiType::Handle),
("hSourceHandle", AbiType::Handle),
("hTargetProcessHandle", AbiType::Handle),
(
"lpTargetHandle",
AbiType::Pointer {
is_const: false,
pointee: "HANDLE".into(),
},
),
("dwDesiredAccess", AbiType::U32),
("bInheritHandle", AbiType::Bool),
("dwOptions", AbiType::U32),
],
"<handleapi.h>",
"Creates another handle to the same object",
);
for (name, return_type) in [
("GetTickCount", AbiType::U32),
("GetTickCount64", AbiType::U64),
] {
self.add(
"kernel32.dll",
name,
return_type,
vec![],
"<sysinfoapi.h>",
"Returns elapsed system uptime in milliseconds",
);
}
self.add(
"kernel32.dll",
"QueryPerformanceCounter",
AbiType::Bool,
vec![(
"lpPerformanceCount",
AbiType::Pointer {
is_const: false,
pointee: "LARGE_INTEGER".into(),
},
)],
"<profileapi.h>",
"Retrieves the current value of the performance counter",
);
self.add(
"kernel32.dll",
"QueryPerformanceFrequency",
AbiType::Bool,
vec![(
"lpFrequency",
AbiType::Pointer {
is_const: false,
pointee: "LARGE_INTEGER".into(),
},
)],
"<profileapi.h>",
"Retrieves the frequency of the performance counter",
);
}
}
Loaded 100 of 696 files, more files were not shown because too many files have changed in this diff. Show more