Compare commits

..
Author SHA1 Message Date
atharvranjan 9923e59114 Merge pull request #296 from maridogolpeador/app/252-open-command
app: add Command-O and show file-picker errors (#252)
2026-11-25 12:08:20 -06:00
atharvranjan feba95fe39 Merge origin/main into app/252-open-command
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:52:31 -06:00
atharvranjan a275de6e2e Merge pull request #295 from maridogolpeador/app/251-inspection-request-order
app: keep inspection results tied to the latest selection (#251)
2026-11-25 11:51:15 -06:00
atharvranjan 25986845da Merge origin/main into app/251-inspection-request-order
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:46:03 -06:00
atharvranjan df9652740b Merge pull request #309 from soggyramennoodle/task/255-startup-diagnostics
Report trusted fixture startup progress
2026-11-25 11:42:21 -06:00
atharvranjan 1ca491d8d0 Merge pull request #297 from maridogolpeador/docs/260-texture-format-inventory
docs: inventory texture formats and layouts by stage (#260)
2026-11-25 11:42:08 -06:00
atharvranjan 964a8296f2 Merge pull request #294 from atesahmet0/task/154-cpu-coverage-map
Add the verified CPU/loader coverage map
2026-11-25 11:41:54 -06:00
atharvranjan d8a8c96408 Merge pull request #338 from Thxlx/perf/89-arm64-constant-load
perf: shorten ARM64 loads for zero-extended constants
2026-11-25 11:40:55 -06:00
atharvranjan 50321b3f14 Merge pull request #337 from Thxlx/docs/299-avx-contract 2026-11-25 10:56:04 -06:00
Thilo Schaeffer 1fe07f45ee test: clarify ARM64 assembler offset units
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:05 +01:00
Thilo Schaeffer d486d21813 docs: clarify AVX exception policy and Intel references
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:04 +01:00
Thilo Schaeffer 4c92c88b29 perf: shorten ARM64 loads for zero-extended constants
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:31:03 +01:00
Thilo Schaeffer 478e9218ac docs: specify the guest AVX and AVX2 contract
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:21:18 +01:00
Adeeb Rahman 8d2662dcd7 Preserve startup report delivery and worker errors
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:56:31 -05:00
Adeeb Rahman fe1bf568c8 Merge BetterXen main
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:51:45 -05:00
maridogolpeador 873652d685 app: run inspection reads on a Dispatch queue, not a concurrency worker (#251)
Review follow-up. The reader blocks on file I/O, and in the
--smoke-inspection-order check on its gate semaphore. Inside
Task.detached that blocked a Swift concurrency worker; with a
single-worker cooperative pool the released newer read could not start
while the older one waited, and the check timed out. The read now runs
on DispatchQueue.global(qos: .userInitiated) and is bridged back with
withCheckedContinuation. The request-number guard is unchanged.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:38:12 -03:00
ates 84f561b12b Fix the documented known-answer count command
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:14:50 +03:00
maridogolpeador 2b113a2e5e docs: separate host API coverage from guest reachability and link sources (#260)
Review follow-up. The Guest column credited the descriptor-table SRVs,
which tests call directly from Rust and the interface contract says
are not yet wired to guest imports. The table now has a Host graphics
API column for them and keeps Guest for paths an original PE fixture
reaches through imported services: today only RGBA8, through the
synthetic xenora.dll texture services of the Gate 5 fixture. Every
repository path is now a relative link, and each format row links the
exact Khronos DFS 1.3 section and Microsoft or Apple page it relies on.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:44 -03:00
maridogolpeador 9a26e1ee36 docs: inventory texture formats and layouts by stage (#260)
Add docs/research/texture-formats.md, built from BetterXen main. For
RGBA8, BC1-BC7 and Depth32Float it separates container recognition,
CPU decoding, layout conversion, native Metal upload and readback,
translated sampling and guest reachability, linking the implementing
files and tests for each cell, including the packed BC footprints from

It cross-references #208 and #209 rather than opening duplicate tasks,
records console layouts, console descriptors and asset or audio
containers as unknowns, and ranks three proposed follow-ups with an
original-fixture recipe, an independent source of expected values and
an owner each. Deferred formats with no demonstrated need are listed.

docs/README.md indexes the page. Research only; no code changed.

Ported from XenoraOSS/Xenora#427 and re-checked against BetterXen main.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:43 -03:00
maridogolpeador c84b80b24f app: route Command-O to the focused window's importer (#252)
Review follow-up. The command set a shared Boolean, so with every
window closed there was no importer to present it, and with several
windows each one bound the same flag. Each ContentView now owns its
importer state and publishes an open action with focusedSceneValue;
OpenExecutableCommand reads it with @FocusedValue, calls it for the
focused window and is disabled when no window provides it. The
inspector button uses the same per-window action. InspectionModel no
longer holds the importer flag; requestImport only clears the previous
selection error.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador ae804f0530 app: gate the inspection-order smoke check instead of sleeping (#251)
Review follow-up. The check used fixed 300/700 ms pauses, so on a
loaded host a late stale read could arrive after an assertion, or the
newer read could finish before the busy-state check. The injected
reader now blocks until the check releases that file, and the check
waits on InspectionModel.finishedReads, which counts every finished
read whether it was published or discarded. A five-second deadline
bounds the wait without deciding the order.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 64e7b16983 app: add Command-O and show file-picker errors (#252)
The inspector had an Open Executable… button but no app-level Open
command, and the file importer's completion ignored failures, so a
picker error was never shown.

- File > Open Executable… with Command-O, after New Window. It calls
  the same requestImport() as the button, so it opens the same
  read-only importer and the chosen file reaches inspect(), the path
  shared with drag and drop and Finder Open With.
- importFinished(_:) handles the importer result: success inspects,
  a user cancellation (CocoaError.userCancelled) shows nothing, and any
  other failure is shown in red with the error's description. The
  message clears on the next request or selection.
- --smoke-import-result checks cancellation, a shown failure and its
  clearing without opening files; scripts/build-app.sh runs it after
  --smoke. It fails with the previous importer handling and without the
  cancellation check.

Opening a file still never starts guest execution, the DBT or the JIT.

Ported from XenoraOSS/Xenora#424.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 1ea898b4bf app: keep inspection results tied to the latest selection (#251)
InspectionModel.inspect started a detached read per call and published
status, report and busy whenever any of them finished. A slow first
inspection that completed after a fast second one replaced the newer
report and status, and could clear busy while the newer read was still
running.

- Each inspect call takes a request number; a completion is applied
  only while it is still the latest, so stale success and stale failure
  are discarded. Picker, drag and drop and Finder Open With all go
  through inspect and share this.
- A new selection clears the previous report, and a failed inspection
  of the latest file is shown in red above its report.
- The read is unchanged: size checked before reading, balanced
  security-scoped access, nothing executed. The reader is injectable
  only for the smoke check.
- --smoke-inspection-order drives the model with an injected slow and
  fast reader: slow then fast with either outcome, and busy held for the
  newer request while an older read finishes. scripts/build-app.sh runs
  it after --smoke. All four checks fail without the change.

Ported from XenoraOSS/Xenora#423.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
ates 7946968cc4 Address coverage review and merge current main
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:03:49 +03:00
atharvranjan 67b8cff9df Merge pull request #326 from MacosPorters/claude/pr-294-review-nftzfu
Rewrite the README around the development phases and launch target
2026-11-25 05:59:17 -06:00
atharvranjan 51c23a2f38 Merge pull request #293 from maridogolpeador/ci/248-app-build
ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
2026-11-25 05:58:01 -06:00
Claude 7d97e67448 Rewrite the README around the development phases and launch target
Reorganize the README around the six development phases and the first
launchable application tracker, add colour-coded Mermaid diagrams and
registry-derived charts, a repository overview and a contributing
section, and correct the texture-sampling and recompiler wording.

Signed-off-by: Claude <noreply@anthropic.com>
2026-11-25 11:53:09 +00:00
atharvranjan d9261db887 Merge pull request #325 from MacosPorters/repo/add-codeowners
Add CODEOWNERS and replace
2026-11-25 04:39:37 -06:00
atharvranjan 5c0c82b3f9 Add a fast repository hygiene check
Add hygiene.yml and scripts/audit/docs_hygiene.py: fail on merge-conflict
markers, broken relative Markdown links and invalid workflow YAML, and
warn (advisory) when source changes lack a changelog entry.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:24:36 -06:00
atharvranjan b71db3c25a Remove the pull request template
Delete .github/PULL_REQUEST_TEMPLATE.md and update CONTRIBUTING.md and
the changelog to match.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:23:03 -06:00
atharvranjan 566f803111 Remove the PR template check
Delete the pr-template workflow, its checker script and tests, and the
CI step that ran those tests. Update CONTRIBUTING.md and the changelog.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:18:06 -06:00
atharvranjan 857c16fcf7 Merge origin/main into repo/add-codeowners
Resolve conflicts in favor of main's development phases and roadmap
text. Keep the game-title wording and PE-Vulkan project renames, the
PortWatch research notes and their docs index link.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:16:38 -06:00
atharvranjan 4f5c6913f5 Replace game-title and upstream-project names in our own docs
Use generic 'commercial title' wording for our own references to a
specific game, rename the ignored diagnostics folders to
title-candidate-* and title-check, and refer to the upstream PE/Vulkan
project as 'PE-Vulkan project' in prose. Third-party URLs and repository
paths are unchanged to keep provenance accurate. Also adds the native
macOS development phases and PortWatch research notes already in the
working tree.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:12:59 -06:00
Adeeb Rahman e4ddb05a1a Run startup draw check on native Metal hardware
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:27:42 -05:00
Adeeb Rahman d33a7c6941 Report trusted fixture startup progress
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:23:04 -05:00
maridogolpeador 4e838207fe ci: check the printed dependency listing and reject empty or failed listings (#248)
Review follow-up. build-app.sh now runs otool -L once in a checked
assignment, prints that output and parses the same text, so a failing
or empty listing fails the gate instead of skipping the loop. Every
Swift executable links libSystem, so an empty list is an error.
Bundle-relative entries (@rpath, @executable_path, @loader_path) get
their own message. The changelog entry now separates the designed CI
behaviour from what has been verified locally.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 02:09:22 -03:00
ates b40bbae1da Refresh the coverage map at merged main b2654e9
The branch now contains main b2654e9, which includes the merged DBT
cache-identity pull and the migration-benchmark checks, so the map pins
its single gate run to that revision: the former self-modifying-code
defect test executes and passes in both DBT engines (cpu_known_answers
50 passed, 0 ignored) and the workspace gate reports 116 result lines
with 1015 passed, 0 failed and 34 ignored. The ignore taxonomy in the
map names all three kinds from their own messages: Metal-gated,
LLVM-gated (gfx1030 AMDGPU target) and manual timing runs.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 08:07:53 +03:00
maridogolpeador b04b41f26a ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
The CI workflow built and inspected the CLI but never ran
scripts/build-app.sh, so a Swift compile, link or smoke failure in app/
passed CI.

- ci.yml: a second job, "Native app build and smoke", on the same
  macos-26 image, pinned Rust toolchain and CARGO_BUILD_JOBS as the Rust
  job. It verifies an arm64 host without Rosetta, prints the Xcode and
  Swift versions and runs scripts/build-app.sh. The Rust job is
  unchanged.
- build-app.sh: after the lipo check, print file and otool -L for the
  executable and fail if it links anything outside /System/Library/ and
  /usr/lib/.

No Metal fixture runs in the new job; --smoke probes the C interface
and the trusted fixture's headers only. The same change was proposed
upstream as XenoraOSS/Xenora#426.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 01:59:03 -03:00
ates 3dd3ef06e2 Merge main into CPU coverage map
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:58:15 +03:00
ates fee956293d Add the verified CPU/loader coverage map
Document what the CPU and loader tests verify, per operation family, in
docs/testing/cpu-coverage.md: the declared-form inventory (213 operations,
403 forms, 498 opcode slots from the validated registry), the per-operation
engine split (93 native-lowered, 120 shared-semantic, with the conditional
width and encoding gates), a per-artifact evidence table with exact pass
counts from one full workspace gate run on Apple M5, the reconciliation of
the eight operations covered by model tests instead of the assembly-fixture
corpus, and a recorded note that three advisory qa cpu-inventory
unsupported-catalog rows are stale against the implemented and tested forms.
Also updates the docs/README.md description line and adds the CHANGELOG
entry under [Unreleased].

Closes #154.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:52:19 +03:00
33 changed files with 2015 additions and 686 deletions

No files matched your search

-40
View File
@@ -1,40 +0,0 @@
## Summary
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
## Implementation and evidence
<!-- Describe affected subsystems, architecture assumptions, specification sections and upstream provenance where applicable. -->
## Verification
<!-- List actual commands and outcomes. Include hardware, validation-layer state and pass/fail/skip counts for GPU tests. Mark unrun checks explicitly. -->
| Check | Result / evidence |
| --- | --- |
| Formatting and lint | |
| Unit / integration tests | |
| GPU / differential tests | |
| Fuzzing / mutation / benchmarks, if relevant | |
## Compatibility and limitations
<!-- Note unsupported behavior, regressions, interface changes, performance effects and remaining uncertainty. -->
## Checklist
- [ ] I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
- [ ] I did not report skipped or unrun tests as passing.
- [ ] I updated applicable documentation, claims and status records.
- [ ] Third-party code and fixtures have verified licenses and provenance, or none were added.
- [ ] No restricted materials, credentials or private data are included.
- [ ] My commits are signed off under the DCO.
## AI assistance
<!-- Describe material assistance and the checks you personally performed, or state none. -->
+30 -2
View File
@@ -63,8 +63,6 @@ jobs:
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
@@ -90,3 +88,33 @@ jobs:
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
+43
View File
@@ -0,0 +1,43 @@
name: Repository hygiene
# Fast checks on tracked files that need no Rust toolchain and no network:
# merge-conflict markers, broken relative Markdown links and invalid workflow
# YAML (scripts/audit/docs_hygiene.py). A second, advisory step warns when
# source or script changes arrive without a CHANGELOG.md update; it never fails.
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: hygiene-${{ github.ref }}
cancel-in-progress: true
jobs:
hygiene:
name: Repository hygiene
runs-on: ubuntu-24.04-arm
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
- name: Install PyYAML
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
- name: Check documentation and workflow files
run: python3 scripts/audit/docs_hygiene.py --require-yaml
- name: Remind about the changelog (advisory)
if: github.event_name == 'pull_request'
env:
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)/' \
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
fi
-38
View File
@@ -1,38 +0,0 @@
name: PR template
# Fails when a pull request description does not follow
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
# is edited; comments never start it. Runs on the base branch: pull request
# code is never checked out or executed, and the description is read as data.
#
# To make it blocking, mark the "PR template / description" check as required
# in the branch protection rule for main.
on:
pull_request_target:
types: [opened, edited, reopened, synchronize]
permissions: {}
jobs:
description:
runs-on: ubuntu-24.04-arm
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the description against the template
run: |
set -u
status=0
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
cat "$RUNNER_TEMP/result.txt"
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -ne 0 ]; then
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
fi
exit "$status"
+2 -2
View File
@@ -36,8 +36,8 @@
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
/diagnostics/title-candidate-*/
/diagnostics/title-check/
# Native application build output
/app/.build/
+1 -1
View File
@@ -34,7 +34,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
- 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 Leonida, KyTx, AnyPS5 or similar projects.
- 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.
+17 -1
View File
@@ -9,8 +9,18 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
- 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.
- Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub.
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
### Removed
- 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 active phase plan and README X1–X25 roadmap with one native macOS workload sequence and added a pinned PortWatch ecosystem review linked to eight contributor follow-ups. The plan distinguishes existing synthetic execution from future Xbox compatibility; no new runtime behavior, execution result or independent acceptance is claimed.
- 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.
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
@@ -21,6 +31,7 @@ remains unsupported.
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
- The ARM64 assembler uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result.
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
@@ -34,6 +45,8 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
@@ -43,6 +56,9 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
- Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification.
- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run.
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+1 -1
View File
@@ -44,7 +44,7 @@ Before incorporating third-party code, verify per-file license compatibility wit
## Pull requests
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
- 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.
+181 -33
View File
@@ -1,51 +1,178 @@
<div align="center">
# BetterXen
BetterXen is a community-maintained continuation. Original Git history, licenses and contributor attribution are retained. See the [project history and migration notes](docs/migration.md) for source attribution and imported issue and pull-request records.
**Experimental Xbox Series X|S emulation research, built natively for Apple Silicon.**
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
BetterXen is an open-source project written primarily in Rust that 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.
[![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)
![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)
![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.**
BetterXen is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
</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).
> [!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.
[![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)
---
## How it fits together
One guest program travels through three native subsystems. Every stage is checked against an independently derived expectation.
```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
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
```
Legend: 🟦 guest loading · 🟩 guest CPU and services · 🟪 shader translation · 🟨 native Metal · 🟥 independent verification.
---
## What works today?
## Milestones
BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
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.
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
```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
```
### Development phases
<sub>🟨 work under way · ⬜ not started · 🟩 the next original-workload target. Nothing here is independently accepted.</sub>
The active plan follows demonstrable native macOS workloads. Every phase has
completion checks, dependencies and contributor issues in the
[full development plan](docs/development-phases.md).
| 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 |
| Phase | Result to demonstrate |
| --- | --- |
| 1 — Compiled guest boot | Reproduce and independently accept the existing original C execution path on native ARM64. |
| 2 — Modular guest runtime | Run an original executable with companion libraries, workers, checked waits and lifecycle cleanup. |
| 3 — Guest-controlled Metal scene | Reach translated textured rendering through compiled guest calls, with checked resource lifetime and pixels. |
| 4 — Interactive application | Combine guest execution, rendering, input, audio, saves and session controls in one original application. |
| 5 — Compatibility corpus | Expand CPU/runtime/shader behavior using varied original workloads and independently derived regressions. |
| 6 — Sustained native execution | Verify bounded long runs and measured performance on the Apple Silicon hosts actually tested. |
| 7 — Xbox compatibility experiments | Resolve public console contracts and demonstrate each separately admitted execution stage before claiming support. |
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).
These phases replace the previous roadmap. They are targets, not completed
acceptance claims or a game-release timeline. Console-contract research and
bounded subsystem work can proceed in parallel. Historical fixture identifiers
such as X9 remain labels for their original test/evidence records.
<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 |
| --- | --- | --- |
| 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 |
</details>
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
---
## 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.
@@ -166,9 +293,9 @@ Implemented and tested functionality includes:
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture-sampling instructions are not yet implemented.**
**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 existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
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.
@@ -219,13 +346,22 @@ flowchart TD
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 project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
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.
@@ -243,8 +379,8 @@ The following remain unsupported or incomplete:
| 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 | Translated texture sampling and broader resource binding |
| Textures | Authentic Xbox memory layouts and translated sampling |
| 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 |
@@ -340,9 +476,21 @@ Testing distinguishes between:
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 [development phases](docs/development-phases.md) for the current work order, 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).
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).
---
@@ -356,6 +504,6 @@ BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE
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, Rockstar Games or Apple.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, any game publisher or Apple.
---
+213 -6
View File
@@ -638,13 +638,65 @@ final class InspectionModel: ObservableObject {
@Published var report = ""
@Published var status: Int32 = Int32(XENORA_OK)
@Published var busy = false
@Published var importing = false
/// Why the last file selection could not be used, shown until the next selection.
@Published var selectionError: String?
/// Called when a window is about to show the read-only file importer, from its
/// button or File > Open Executable…. Each window presents its own importer.
func requestImport() {
selectionError = nil
}
/// Handles the importer's completion. A cancelled picker is not a failure.
func importFinished(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
inspect(url)
case .failure(let error):
if let cocoa = error as? CocoaError, cocoa.code == .userCancelled {
return
}
selectionError = "The selected file could not be opened: \(error.localizedDescription)"
}
}
/// Reads and reports one file off the main thread. Replaceable only for the
/// `--smoke-inspection-order` check.
private let reader: @Sendable (URL) -> (Int32, String)
/// Number of the latest `inspect` call. Only that call may publish a result.
private var latestRequest: UInt64 = 0
/// Reads that have finished, whether their result was published or discarded.
/// `--smoke-inspection-order` waits on it instead of on a fixed delay.
private(set) var finishedReads: UInt64 = 0
init(reader: @escaping @Sendable (URL) -> (Int32, String) = InspectionModel.run) {
self.reader = reader
}
var failed: Bool { !busy && fileName != nil && status != Int32(XENORA_OK) }
func inspect(_ url: URL) {
latestRequest &+= 1
let request = latestRequest
selectionError = nil
fileName = url.lastPathComponent
report = ""
status = Int32(XENORA_OK)
busy = true
let reader = reader
Task {
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
// The read blocks on file I/O (and, in `--smoke-inspection-order`, on
// its gate), so it runs on a Dispatch queue instead of occupying a
// Swift concurrency worker that other tasks may need.
let (newStatus, newReport) = await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
continuation.resume(returning: reader(url))
}
}
finishedReads &+= 1
// A newer selection owns the published state, including `busy`;
// an older read that finishes late is discarded.
guard request == latestRequest else { return }
status = newStatus
report = newReport
busy = false
@@ -685,17 +737,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
/// Opens the file importer of the focused window. Absent when no window can
/// present it, which disables File > Open Executable….
struct OpenExecutableKey: FocusedValueKey {
typealias Value = () -> Void
}
extension FocusedValues {
var openExecutable: OpenExecutableKey.Value? {
get { self[OpenExecutableKey.self] }
set { self[OpenExecutableKey.self] = newValue }
}
}
/// File > Open Executable… (Command-O), routed to the focused window's importer.
struct OpenExecutableCommand: Commands {
@FocusedValue(\.openExecutable) private var openExecutable
var body: some Commands {
CommandGroup(after: .newItem) {
Button("Open Executable…") { openExecutable?() }
.keyboardShortcut("o")
.disabled(openExecutable == nil)
}
}
}
struct InspectorView: View {
@ObservedObject var model: InspectionModel
let openImporter: () -> Void
var body: some View {
Section("Executable inspection (read-only)") {
HStack {
Button("Open Executable…") { model.importing = true }
Button("Open Executable…") { openImporter() }
Text("or drop a file on this window").foregroundStyle(.secondary)
}
if let error = model.selectionError {
Text(error).foregroundStyle(.red)
}
if let name = model.fileName {
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
if model.failed {
Text("Inspection of \(name) failed (status \(model.status)).")
.foregroundStyle(.red)
}
ScrollView {
Text(model.report)
.font(.system(.caption, design: .monospaced))
@@ -716,12 +802,19 @@ struct ContentView: View {
@ObservedObject var model: FrameModel
@ObservedObject var loop: FrameLoopModel
@ObservedObject var inspection = InspectionModel.shared
/// This window's importer. Kept per window so only the window that asked shows it.
@State private var importing = false
private var frame: GuestFrame? { model.frame }
private var running: Bool { model.running }
private func openImporter() {
inspection.requestImport()
importing = true
}
var body: some View {
Form {
InspectorView(model: inspection)
InspectorView(model: inspection, openImporter: openImporter)
Section("Guest display") {
if let image = frame?.image {
Image(decorative: image, scale: 1)
@@ -822,8 +915,8 @@ struct ContentView: View {
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
if case .success(let url) = result { inspection.inspect(url) }
.fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in
inspection.importFinished(result)
}
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first, url.isFileURL else { return false }
@@ -831,6 +924,7 @@ struct ContentView: View {
return true
}
.frame(minWidth: 520, minHeight: 680)
.focusedSceneValue(\.openExecutable, openImporter)
}
}
@@ -841,6 +935,7 @@ struct BetterXenApp: App {
var body: some Scene {
WindowGroup("BetterXen") { ContentView(model: model, loop: loop) }
.commands { OpenExecutableCommand() }
}
}
@@ -1009,6 +1104,118 @@ if CommandLine.arguments.contains("--smoke-frame") {
exit(frame.status == XENORA_OK ? 0 : 1)
}
// `--smoke-inspection-order` checks that only the latest selection publishes an
// inspection result. Files are never read: an injected reader blocks until the check
// releases that file, so the check, not timing, decides which read finishes first.
// It needs no GPU.
if CommandLine.arguments.contains("--smoke-inspection-order") {
final class ReadGates: @unchecked Sendable {
private let lock = NSLock()
private var gates: [String: DispatchSemaphore] = [:]
func gate(_ name: String) -> DispatchSemaphore {
lock.lock()
defer { lock.unlock() }
if let gate = gates[name] { return gate }
let gate = DispatchSemaphore(value: 0)
gates[name] = gate
return gate
}
func release(_ name: String) { gate(name).signal() }
}
let gates = ReadGates()
// "<scenario>-<a|b>-<ok|fail>"; a gate that is never released times out
// instead of hanging, and the check then fails on its own deadline.
let reader: @Sendable (URL) -> (Int32, String) = { url in
let name = url.lastPathComponent
_ = gates.gate(name).wait(timeout: .now() + 10)
let status = name.hasSuffix("-ok") ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT)
return (status, "report \(name)")
}
func file(_ name: String) -> URL { URL(fileURLWithPath: "/nonexistent/\(name)") }
Task { @MainActor in
var failures: [String] = []
// Waits for the model to finish `count` reads. The deadline only bounds the
// check; the order of completions is set by releasing gates.
@MainActor func settle(_ model: InspectionModel, _ count: UInt64, _ label: String) async -> Bool {
let deadline = Date().addingTimeInterval(5)
while model.finishedReads < count {
if Date() > deadline {
failures.append("\(label): read \(count) did not finish")
return false
}
try? await Task.sleep(nanoseconds: 2_000_000)
}
return true
}
@MainActor func expect(_ model: InspectionModel, _ name: String, busy: Bool, report: String, ok: Bool, _ label: String) {
let actual = "file=\(model.fileName ?? "-") busy=\(model.busy) status=\(model.status) report=\(model.report)"
if model.fileName != name || model.busy != busy || model.report != report
|| (model.status == Int32(XENORA_OK)) != ok {
failures.append("\(label): \(actual)")
}
}
// The newer read finishes first; the older one finishes afterwards and must
// change nothing, whatever its outcome.
for (scenario, first, second, ok) in [("s1", "a-ok", "b-ok", true), ("s2", "a-fail", "b-ok", true),
("s3", "a-ok", "b-fail", false)] {
let (older, newer) = ("\(scenario)-\(first)", "\(scenario)-\(second)")
let model = InspectionModel(reader: reader)
model.inspect(file(older))
model.inspect(file(newer))
gates.release(newer)
if await settle(model, 1, "\(older) then \(newer)") {
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "\(newer) finished")
}
gates.release(older)
if await settle(model, 2, "\(older) then \(newer)") {
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "stale \(older) finished")
}
}
// The older read finishes first and must not clear the newer request's busy state.
let model = InspectionModel(reader: reader)
model.inspect(file("s4-a-ok"))
model.inspect(file("s4-b-fail"))
gates.release("s4-a-ok")
if await settle(model, 1, "s4") {
expect(model, "s4-b-fail", busy: true, report: "", ok: true, "stale s4-a-ok finished first")
}
gates.release("s4-b-fail")
if await settle(model, 2, "s4") {
expect(model, "s4-b-fail", busy: false, report: "report s4-b-fail", ok: false, "s4-b-fail finished")
}
for failure in failures { print("smoke-inspection-order: FAILED \(failure)") }
print("smoke-inspection-order: \(failures.isEmpty ? "ok" : "\(failures.count) failed")")
exit(failures.isEmpty ? 0 : 1)
}
dispatchMain()
}
// `--smoke-import-result` checks how a file-importer result reaches the inspector:
// a cancelled picker shows nothing, a failure is shown, and a new selection clears it.
// No file is opened or read.
if CommandLine.arguments.contains("--smoke-import-result") {
let ok = MainActor.assumeIsolated { () -> Bool in
var failures: [String] = []
let model = InspectionModel()
model.importFinished(.failure(CocoaError(.userCancelled)))
if model.selectionError != nil || model.fileName != nil { failures.append("cancel shows a message") }
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
if model.selectionError == nil || model.fileName != nil { failures.append("failure is not shown") }
model.requestImport()
if model.selectionError != nil { failures.append("reopening keeps the old message") }
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
model.inspect(URL(fileURLWithPath: "/nonexistent/import-result-check"))
if model.selectionError != nil || model.fileName != "import-result-check" {
failures.append("a new selection keeps the old message")
}
for failure in failures { print("smoke-import-result: FAILED \(failure)") }
return failures.isEmpty
}
print("smoke-import-result: \(ok ? "ok" : "failed")")
exit(ok ? 0 : 1)
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
+120 -17
View File
@@ -2,10 +2,10 @@
use std::error::Error;
use std::ffi::OsString;
use std::fs::{self, File};
use std::fs::{self, File, OpenOptions};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::process::{Child, Command, ExitCode, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -16,6 +16,10 @@ use xenora_loader::{
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);
@@ -27,7 +31,7 @@ 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>]";
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report <path>]";
struct Options {
path: PathBuf,
@@ -35,6 +39,8 @@ struct Options {
worker: bool,
trace: bool,
hud: bool,
report: Option<PathBuf>,
journal: Option<PathBuf>,
}
impl Options {
@@ -42,6 +48,8 @@ impl Options {
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() {
@@ -56,6 +64,16 @@ impl Options {
.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,
@@ -66,12 +84,17 @@ impl Options {
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,
})
}
}
@@ -85,7 +108,7 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
}
};
let result = if options.worker {
run_worker(&options).map(|()| ExitCode::SUCCESS)
worker_command(&options)
} else {
launch_worker(&options)
};
@@ -99,8 +122,26 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
}
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 child = Command::new(std::env::current_exe()?)
let mut command = Command::new(executable);
command
.args([
"run",
"--experimental",
@@ -112,29 +153,73 @@ fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
.arg(options.max_steps.to_string())
.arg("--pe")
.arg(&options.path)
.stdin(Stdio::null())
.spawn()?;
.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 match status.code() {
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
None => Err(format!("worker terminated: {status}").into()),
};
}
Ok(None) if started.elapsed() < WALL_LIMIT => {
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 Err("experimental worker exceeded its 15 second wall deadline".into());
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;
@@ -158,14 +243,14 @@ fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
.ok_or_else(|| rejection.into())
}
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
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(124);
std::process::exit(i32::from(WATCHDOG_EXIT));
})?;
let fixture = verify_fixture(&options.path)?;
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
@@ -232,6 +317,16 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
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);
}
@@ -244,6 +339,11 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
.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}",
@@ -264,6 +364,9 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
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={}",
+399
View File
@@ -0,0 +1,399 @@
// 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}"
);
}
}
+109
View File
@@ -0,0 +1,109 @@
// 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}");
}
+33 -10
View File
@@ -633,15 +633,22 @@ impl Arm64Assembler {
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
}
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
/// MOVN plus MOVK instructions: one for each halfword that differs from
/// the background the first instruction leaves, and always at least one.
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
/// when more halfwords are 0xFFFF than zero.
/// Load a full 64-bit constant into Xd with the fewest wide moves.
/// A 32-bit MOVN leaves one low halfword set to 0xFFFF and zero-extends
/// the result into Xd. For other values, select a 64-bit MOVZ or MOVN
/// background and use MOVK for the remaining halfwords.
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
let zeros = halves.iter().filter(|&&h| h == 0).count();
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
// With only the top two halfwords zero, a 32-bit MOVN saves one
// instruction when either of the lower halfwords is all ones.
if zeros == 2 && ones != 0 && val >> 32 == 0 {
let index = usize::from(halves[1] != u16::MAX);
let imm16 = u32::from(!halves[index]);
self.emit(0x1280_0000 | ((index as u32) << 21) | (imm16 << 5) | u32::from(xd & 0x1f));
return;
}
let background = if ones > zeros { 0xffff } else { 0 };
// The first halfword that differs from the background, or halfword 0
// when none does (val is 0 or all ones).
@@ -883,12 +890,14 @@ mod tests {
}
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
const IMMEDIATE_EDGES: [u64; 16] = [
const IMMEDIATE_EDGES: [u64; 18] = [
0,
1,
0xffff,
0x1_0000,
0x8000_0000,
0xffff_1234,
0x1234_ffff,
0xffff_ffff,
0x1_0000_0000,
0x1234_0000_0000_0000,
@@ -904,10 +913,13 @@ mod tests {
#[test]
fn immediate_sequences_match_llvm_encodings() {
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
// A64 words from llvm-mc and Apple Clang's integrated assembler.
let cases: &[(u64, &[u32])] = &[
(0, &[0xd2800000]), // movz x0, #0
(u64::MAX, &[0x92800000]), // movn x0, #0
(0xffff_1234, &[0x129db960]), // movn w0, #0xedcb
(0x1234_ffff, &[0x12bdb960]), // movn w0, #0xedcb, lsl #16
(0xffff_ffff, &[0x12800000]), // movn w0, #0
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
@@ -930,9 +942,16 @@ mod tests {
);
}
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
/// A 32-bit MOVN can write a zero-extended value if its low word's
/// complement fits in a single halfword. Otherwise count the halfwords
/// that differ from either 64-bit initializer's background.
fn shortest_wide_move(value: u64) -> usize {
if let Ok(low) = u32::try_from(value) {
let complement = !low;
if complement <= u32::from(u16::MAX) || complement.trailing_zeros() >= 16 {
return 1;
}
}
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
let not_zero = halves.clone().filter(|&h| h != 0).count();
let not_ones = halves.filter(|&h| h != 0xffff).count();
@@ -964,9 +983,13 @@ mod tests {
for value in values {
for register in [X0, X9] {
let mut asm = Arm64Assembler::new();
// Seed the destination so a W-register load must clear the high bits.
asm.movn_64(register, 0, 0);
// Assembler offsets count 32-bit instruction words.
let start = asm.current_offset();
asm.load_imm_64(register, value);
assert_eq!(
asm.instructions().len(),
asm.current_offset() - start,
shortest_wide_move(value),
"{value:#x}"
);
+4 -4
View File
@@ -11,8 +11,6 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
Use the [BetterXen development phases](development-phases.md) for current work
order, existing issue/PR dependencies and measurable completion criteria.
Historical phase checkpoints retain their original evidence scope.
The active plan replaces the former roadmap with workload-based phases, from
compiled guest boot to separately admitted Xbox compatibility experiments.
## Architecture and technical design
@@ -40,6 +38,7 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
- [Proposed AVX and AVX2 guest contract](cpu/avx-contract.md) — VEX decoding, vector state, fault behavior and an original integer fixture specification.
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
- [Guest threads](runtime/threads.md) — Deterministic scheduler, thread services, limits and tests.
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
@@ -51,7 +50,7 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
- [CPU test runtime and shard selection](testing/cpu-coverage.md) — Measured CPU gate cost and deterministic test-target shards.
- [CPU test runtime, shards and coverage map](testing/cpu-coverage.md) — Measured CPU gate cost, deterministic test-target shards, and a verified per-operation CPU/loader coverage map with exact test evidence.
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
@@ -60,9 +59,10 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
## Research and engineering decisions
- [PortWatch projects and the native macOS plan](research/portwatch-native-macos.md) — Complete pinned tracker screen, native ARM64 gaps, contributor issues and revised phase dependencies; external claims remain unverified.
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
- [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups.
- [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only.
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
## Security, licensing, and contributions
+136
View File
@@ -0,0 +1,136 @@
# Proposed AVX and AVX2 guest contract
[Issue #299](https://github.com/MacosPorters/betterxen/issues/299) defines a
reviewable first step for Advanced Vector Extensions (AVX) in the x86-64 guest.
The current [instruction registry](instruction-registry.md) rejects VEX prefixes.
[`CpuState`](../../crates/loader/src/cpu.rs) holds 16 XMM registers and MXCSR,
the SIMD floating-point control and status register. The synthetic `CPUID`
advertises basic leaves through 1 and reports no AVX or extended-state support.
The architectural expectations come from the public Intel Software Developer's
Manual and apply to BetterXen's synthetic x86-64 guest profile. Which AVX and
AVX2 features Xbox Series X|S CPUs expose, and which extended register state
the console OS enables for applications, remain open research questions.
Resolving them requires public platform documentation or authorized hardware
evidence.
## Architectural state and encoding
In 64-bit mode, XMM0–XMM15 alias bits 127:0 of YMM0–YMM15. A legacy SSE
instruction that writes an XMM destination preserves bits 255:128. For the
packed VEX.128 forms in this proposal, writing an XMM destination clears that
register's upper 128 bits. A VEX.256 register destination replaces all 256 bits.
A store to memory leaves its source vector register intact. The proposed moves
and integer add leave RFLAGS and MXCSR unchanged. [Intel SDM Vol. 1, §14.8,
Accessing YMM Registers][sdm-ymm]. [Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
The shared [decoder](../../crates/loader/src/x86_decode.rs) should retain the
prefix family, opcode map, mandatory prefix, operand width and register
extensions until it selects the form. In 64-bit mode the VEX lead byte
identifies the prefix length. The table lists each payload byte's fields
from bit 7 to bit 0.
| Lead byte | Payload byte 1 | Payload byte 2 | Implied fields |
| --- | --- | --- | --- |
| `C5` | `~R ~vvvv L pp` | — | Map `0F`, `W=0`, logical `X=B=0` |
| `C4` | `~R ~X ~B mmmmm` | `W ~vvvv L pp` | Map selected by `mmmmm` |
The tilde indicates an inverted encoding. `R` extends ModRM.reg, while `X`
and `B` extend the applicable index and r/m or base fields. `vvvv` supplies
the first source of `VPADDD`. For `VMOVDQU` its encoded bits must be `1111b`.
`L=0` selects 128 bits and `L=1` selects 256 bits for these forms. The three
standard VEX maps are `00001b` (`0F`), `00010b` (`0F 38`) and `00011b`
(`0F 3A`). `pp` values 0 through 3 represent no mandatory prefix, `66`, `F3`
and `F2`. Both initial opcodes are in `0F`, with `W` ignored (`WIG`). Decode
both valid prefix lengths for them. Reject reserved maps and encodings,
including a physical `LOCK`, `66`, `F2`, `F3` or REX prefix before VEX, through
the existing illegal-instruction path. Legal forms outside the implemented
subset also stop explicitly. Keep the existing register and effective-address
rules and 15-byte fetch limit. [Intel SDM Vol. 2A, §2.3, VEX encoding][sdm-2a].
[Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
## First implementation increments
1. Append one upper 128-bit half per vector register to `CpuState`, retaining
the existing XMM storage as the low halves. Add layout assertions for the
offsets the dynamic binary translator (DBT) uses. Initialize both halves
in a fresh guest thread and carry them with the thread state when switching
or resuming. Add the shared VEX decoder and encoding controls before execution.
2. Implement `VMOVDQU` (128 and 256 bits, `F3.0F`, `6F /r` and `7F /r`,
register and checked memory forms) and `VPADDD` (128 and 256 bits,
`66.0F`, `FE /r`, register sources initially). The instruction entries
assign both move widths and 128-bit `VPADDD` to AVX, and 256-bit `VPADDD`
to AVX2. Read all sources before publishing the destination, including
when the destination aliases a source. Compare both engines with the
[original fixture specification](../../tests/compat_fixtures/avx/README.md).
3. After shared semantics pass, lower register moves and `VPADDD` to native
ARM64 vector operations on one or two 128-bit halves. Each `VPADDD` half
is four independent 32-bit additions modulo 2³². Use the checked-memory
helper for loads and stores. Check the DBT's fallback counter so a run
through that helper establishes only helper coverage for those forms.
Stage memory-source `VPADDD` and aligned moves separately. Reject masked
moves, gathers, cross-half permutations, floating-point forms, FMA, EVEX
and guest extended-state instructions in the initial slice. AMD64 bytes
remain guest data. All host execution uses native ARM64 code or checked
Rust helpers.
## Memory, faults and instruction budget
`VMOVDQU` permits unaligned operands. Check the complete 16- or 32-byte
guest span before publishing a load result or writing a store. A split
span across adjacent permitted mappings succeeds. A missing or protected
mapping produces the existing guest memory fault at the first inaccessible
byte. For a later `VMOVDQA` form, a memory operand must be aligned to its
width (16 or 32 bytes), with a misaligned operand raising
`GeneralProtection`. [Intel SDM Vol. 2B, MOVDQU and MOVDQA][sdm-2b].
Intel's Type 4 rules for `VMOVDQU` specify `#SS(0)` when a memory reference
through the stack segment (SS) has a noncanonical address and `#GP(0)`
for other noncanonical references. The initial BetterXen profile uses the
[existing 48-bit guest address check](../../crates/loader/src/x86_exec.rs)
and reports `GeneralProtection` for either segment case, including a span
whose first byte is canonical and whose last byte is noncanonical. Check
canonicality before guest memory lookup and before committing the move.
Distinct stack-segment exception reporting remains outside this profile.
[Intel SDM Vol. 2A, Table 2-21, Type 4 exceptions][sdm-2a].
Before adding masked moves, use a separate per-lane access contract. For
`VPMASKMOVD`, only lanes with the high mask bit set may access memory or
report a memory fault. A clear bit zeroes a load lane and leaves a store
lane untouched. A test with lane 4 on an unmapped page must pass with that
lane disabled and fault with it enabled. A full-width span check would
incorrectly reject the disabled case. Specify store commit behavior before
admitting that form. [Intel SDM Vol. 2C, VPMASKMOV][sdm-2c].
Require interpreter and DBT parity for the exit reason, fault address when
reported, RIP, instruction count and complete guest register and memory
state. A rejected move or add has no partial destination update and does
not retire. A successful 256-bit instruction consumes one guest step even
when the DBT emits two halves. With an exhausted budget, stop at the next
guest RIP before decoding or executing that instruction. Check cold and warm
DBT paths and resume in the middle of the same sequence.
## Feature exposure
Run the initial forms only in explicitly enabled synthetic test cases.
Keep normal guest `CPUID` and extended-state behavior at the current baseline.
Before guest-visible AVX support, the guest OS model needs coherent reporting
for `CPUID.1:ECX` bits 26 (XSAVE), 27 (OSXSAVE) and 28 (AVX), and `XGETBV`
with `ECX=0` must report both XMM and YMM state enabled in `XCR0[2:1]`. The
extended-state layout reported by `CPUID.0Dh`, save and restore behavior,
and per-thread ownership must agree. Verify the exception behavior for
disabled state and invalid `XGETBV` selectors before exposing the facility.
AVX2 separately requires `CPUID.(7,0):EBX[5]` and the same OS state. Gate
each advertised feature on its full instruction and state contract,
with probes for enabled and disabled combinations. [Intel SDM Vol. 1,
§14.3, AVX detection][sdm-avx]. [Intel SDM Vol. 1, §14.7.1, AVX2 detection][sdm-avx2].
[Intel SDM Vol. 2A, CPUID][sdm-2a]. [Intel SDM Vol. 2D, XGETBV, XSAVE and XRSTOR][sdm-2d].
[sdm-ymm]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=376
[sdm-avx]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=359
[sdm-avx2]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=375
[sdm-2a]: https://cdrdv2-public.intel.com/929353/253666-093-sdm-vol-2a.pdf
[sdm-2b]: https://cdrdv2-public.intel.com/929354/253667-093-sdm-vol-2b.pdf
[sdm-2c]: https://cdrdv2-public.intel.com/929355/326018-093-sdm-vol-2c.pdf
[sdm-2d]: https://cdrdv2-public.intel.com/929356/334569-093-sdm-vol-2d.pdf
+187 -296
View File
@@ -1,347 +1,238 @@
# BetterXen development phases
BetterXen's objective is to execute supported Xbox Series software through an
original native ARM64 runtime and direct Metal on macOS. Commercial game
execution, including GTA VI, is currently unsupported. The demonstrated results
are bounded, independently authored programs and shaders.
This is BetterXen's working development plan. Each phase ends with a reproducible
application or engineering result. The plan is based on the current repository,
not on completing an inherited prompt or reaching a compatibility percentage.
No phase authorizes a release, publication, or commercial-game compatibility claim.
This is the sole active phase sequence. It replaces the previous phase plan and
the README's X1–X25 roadmap. Historical fixture names and acceptance records
retain their meaning as evidence for their original candidates; they are not a
second development schedule.
## Starting point
## Starting position
The source review used `19a905c30ea85166c05084da4fba67e356920912` on destination
`main`, with the local documentation work starting after the separate CODEOWNERS
commit `f02eb2678e76e91876be5706ce91dca25dcc3017`. The latter changes governance,
not runtime behavior. Open issues and PRs were inspected on November 24, 2026
(America/Chicago). Recheck their current heads and claims before taking work.
The reviewed main revision is
[`b2654e93a42e74e29570183da1f31bb8cdc6f721`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721),
checked on November 24, 2026 (America/Chicago). Research began from a working
tree at `f02eb2678e76e91876be5706ce91dca25dcc3017` and inspected newer main in a
separate snapshot. This documentation change is based on the reviewed main
revision; it changes no runtime implementation.
This task performed source inspection and read-only inventories. It did not
rerun the Rust, native GPU, application, fuzz, mutation, or performance suites.
Historical results below remain evidence for their recorded candidates only.
On inspected main, the source contains an x86-64 interpreter, an ARM64 dynamic
binary translator (DBT), PE32+ loading, a partial runtime, a deterministic guest
scheduler, translated graphics, texture/sampler bindings and a native Swift app.
The hosted C fixtures A1 and A2 are implemented and reported locally passing;
both still await independent acceptance. These pieces have not established a
complete commercial game or one integrated threaded 3D application.
The [public-project review](research/portwatch-native-macos.md) explains the
external comparisons and current-source limits. Windows projects often execute
x86-64 instructions directly and use Windows/D3D12 services. The inspected Mac
guest-execution projects use Rosetta; native asset renderers demonstrate a
different workload. Their progress is a research lead, not BetterXen evidence.
No competitor emulator implementation may be copied or adapted.
No phase is declared complete by this planning task. It ran documentation and
inventory checks, not new CPU/GPU execution, fuzzing, mutation or benchmarks.
## Delivery sequence
| Phase | Demonstrable result | Principal dependency |
| Area | Present in the inspected source | Boundary for this plan |
| --- | --- | --- |
| 1 | A reproducible compiled guest boots and exits on native ARM64 | Existing A1/A2 and native tool evidence |
| 2 | One modular guest program runs workers and cleans up correctly | Module startup, scheduling and lifecycle contracts |
| 3 | Guest code controls a translated textured Metal scene | Validated guest graphics calls, bindings and completion |
| 4 | An original interactive application combines execution, graphics, input, audio and saves | The supported paths from phases 2 and 3 |
| 5 | A varied original workload corpus exposes and closes specific compatibility gaps | A repeatable integrated application and diagnostics |
| 6 | Sustained execution is measured and verified across native Apple Silicon hosts | Checked workloads, resource bounds and actual host reports |
| 7 | A separately admitted Xbox compatibility experiment has documented contracts and reproducible results | Public console evidence and all behavior required by that input |
| Guest CPU | Generated x86-64 decoder, interpreter, ARM64 dynamic binary translator (DBT), integer and vector tests; inventory reports 491 declared forms and 206 operations | Declarations and lowering classifications do not establish independent acceptance or broad application compatibility. |
| Runtime | PE loading, import resolution, service handlers, process-exit tests and the compiled-C A1 fixture | The typed registry inventories only 20 services: 7 marked implemented and 13 partial. Many handwritten handlers are outside that inventory; 20 is not the total runtime service count. |
| Threads | Deterministic scheduler, guest thread contexts and guarded stacks, thread services and compiled-C thread tests | Guest threads execute serially on one host thread. Blocking synchronization, sleep behavior and thread lifecycle callbacks still have documented gaps. |
| Graphics | gfx1030 shader decoder/compiler/reference, native Metal execution paths, texture and draw tests | Synthetic desktop instruction fixtures do not establish Xbox behavior. Acceptance is tracked separately from local readback. |
| Native app | Swift app, Rust C interface, controller input and audio/virtual-filesystem fixtures | Existing fixtures do not establish one integrated threaded C++ 3D application. |
| Quality tools | CPU/runtime inventories, shader coverage reconciliation, task queue, PR checks and acceptance records | Some inventories and ledgers contain stale limitation text. A successful tool invocation does not prove every catalog entry is current. |
Each result has its own admission profile. A simple scene need not wait for all
AVX2 instructions, mesh shaders or ray tracing. A workload needing an unsupported
feature stops explicitly. Research, diagnostics, CPU expansion and performance
measurement can proceed alongside these phases on independently claimed paths.
A phase's number does not grant exclusive ownership of a subsystem.
Sources: [CPU registry](cpu/instruction-registry.md),
[runtime registry](runtime/registry.md), [guest threads](runtime/threads.md),
[interfaces](interfaces.md), [shader coverage](shaders/semantic-coverage.md),
[Gate A](testing/gate-a.md), and [QA tooling](testing/infrastructure/README.md).
The read-only shader reconciliation reported zero mismatches during this task;
that result is inventory consistency, not new GPU verification.
## Phase 1 — Boot a reproducible compiled guest
## How previous phase names fit
**Deliverable:** a contributor can build an original guest from source, start it
through BetterXen's supported test entry point and reproduce its output and exit
without an Intel host executable or Windows compatibility runtime.
Keep historical evidence and attribution intact. These records remain useful,
but their phase numbers are not the sequence for new BetterXen work.
Use the existing [Gate A fixtures](testing/gate-a.md). On inspected main,
[PR #283](https://github.com/MacosPorters/betterxen/pull/283) already supplies the
hosted C program. Reproduce and review that implementation; do not create a
competing CRT startup or mark it unimplemented because this checkout is older.
| Existing record or name | Meaning | How to use it now |
| --- | --- | --- |
| [Phase 01 checkpoints and assurance](testing/phase01-assurance.md), [risk register](risk-register.md), [review log](testing/review-log.md) and [mutation record](testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. |
| [Phase 02 GPU/guest baseline](testing/phase-02-baseline.md) and [CPU feasibility](research/phase02-cpu-feasibility.md), [ecosystem](research/phase02-ecosystem.md), [collaboration](research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. |
| [CPU/runtime campaign ledger](coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. |
| [Infrastructure Phase II/III tooling](testing/infrastructure/README.md) and [compatibility ledger](testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. |
| [Gate A](testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. |
| Native app numbered gates in `crates/ffi` and `app` | Bounded session, graphics, audio and filesystem fixtures | Inspect their tests before proposing integration. Gate numbers are separate from shader acceptance gates. |
| README X1–X25 milestones | Broad capability map | Retain as a capability reference; use the phases below for the next work order. |
| Supplied Discord III, III-B, IV, V and VI excerpts | Broad runtime, graphics, application and performance objectives | Only excerpts were supplied. Their omitted requirements and completion status are unknown; they are not execution instructions. |
The candidate record identifies the exact source revision, local modifications,
native compiler/linker, linked support-code licenses, execution path and limits.
Check host executables/dependencies with `file`, `lipo -archs` and `otool -L`.
Guest x86-64 bytes are permitted data; native host tools must support ARM64.
Use `aarch64-apple-darwin` for BetterXen.
Bare issue numbers in historical documents may refer to the source repository.
All issue and PR links in the work sections below refer to **MacosPorters/betterxen**.
Use [migration records](migration.md) to resolve historical references.
**Completion checks:**
## Phase 1 — Establish a trustworthy working baseline
- A1/A2 reproduce the specified stdout/stderr, files, callback order, exit status
and cleanup on the named candidate. Missing compilers fail visibly.
- Existing wrong-input, unresolved-import and instruction-budget controls still
fail for their specified reasons. A trapped stub is not implemented behavior.
- The admission profile states which CPU forms, imports and startup features it
supports. The test entry point is distinguished from CLI/app execution.
- Independent reviewers accept the semantic expectations and the scope of the
native evidence. A local pass alone does not close this phase.
**Outcome:** contributors can tell what exists on main, what is pending review,
and which checks actually ran on the candidate they are using.
**Contributor work:** [CPU coverage #154](https://github.com/MacosPorters/betterxen/issues/154),
[native reports #303](https://github.com/MacosPorters/betterxen/issues/303), and
[existing compatibility report #254](https://github.com/MacosPorters/betterxen/issues/254).
Use existing audit/test tooling and coordinate schema changes with its owners.
1. Reconcile the current source with the CPU campaign ledger, Gate A document,
runtime inventory scope, and QA compatibility ledger. In particular, the QA
CPU inventory's intentional-rejection catalog still lists strings and
atomics/fences despite source and tests for supported subsets. Correct the
catalog through its existing owner; do not remove explicit unsupported forms.
2. Preserve all imported attribution. Repair destination links in migrated PRs
without recreating sign-offs or treating archived reviews as current approval.
3. Reproduce the applicable existing CPU, generator and repository checks for a
pinned candidate. Run GPU and app checks separately on an eligible native host.
Record errors, unavailable tools and skipped tests separately.
4. Review conflicting PR branches with their authors. Changing descriptions
cannot resolve source conflicts or provide missing ARM64 build checks.
5. Finish BetterXen's active branding where needed. Preserve copyright notices,
licenses and accurate historical records. Package names, C symbols, guest ABI
names and environment variables require a compatibility migration, not a
blanket search-and-replace. Do not rewrite authorship to imply new ownership.
## Phase 2 — Run a modular program with guest workers
Existing work: [migration checks #286](https://github.com/MacosPorters/betterxen/issues/286),
[QA scope #219](https://github.com/MacosPorters/betterxen/issues/219),
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248).
**Deliverable:** an original executable and companion libraries initialize,
start workers, exchange results, block/resume and exit with checked teardown.
**Exit criteria:** a candidate SHA, a current capability/blocker inventory,
links to retained logs for each executed gate, explicit pending reviews, and
usable PR descriptions. Independent acceptance remains a separate decision.
No release is required.
Begin with [the EXE/two-DLL startup contract #301](https://github.com/MacosPorters/betterxen/issues/301)
and [worker lifecycle design #305](https://github.com/MacosPorters/betterxen/issues/305).
The fixture records dependency initialization, per-module static thread-local
storage (TLS), worker-visible values and supported detach/destructor calls.
Expected order must be derived before implementing the loader or callbacks.
Built-in service-module lookup is not general guest DLL loading.
## Phase 2 — Finish a reproducible hosted C application
Extend the existing serial scheduler under
[#228](https://github.com/MacosPorters/betterxen/issues/228). Its documented
`Sleep` behavior can stall every worker; [#304](https://github.com/MacosPorters/betterxen/issues/304)
owns the narrow yielding fix after parent/runtime ownership coordination.
Handle critical sections, condition variables and other waits as separately
specified gaps, not incidental additions to that fix.
**Outcome:** an original hosted C program starts, uses the runtime, reports
results and exits through the guest path with checked cleanup.
Broader CPU behavior is driven by the admitted fixture. Start
[AVX/YMM design #299](https://github.com/MacosPorters/betterxen/issues/299) and
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300) in
parallel, but do not require their entire future scope for a simpler program.
A workload using those features must wait for real support. CPU feature bits
must not advertise unsupported behavior. Stack walking, structured exception
handling (SEH) and C++ exceptions are separate capabilities.
Review and integrate existing work rather than creating a competing runtime:
**Completion checks:**
| Prerequisite | Existing destination work |
| --- | --- |
| CRT startup calls | [issue #237](https://github.com/MacosPorters/betterxen/issues/237), [PR #273](https://github.com/MacosPorters/betterxen/pull/273) |
| Arguments and environment | [issue #242](https://github.com/MacosPorters/betterxen/issues/242), [PR #277](https://github.com/MacosPorters/betterxen/pull/277) |
| Normal termination and exit handlers | [issue #243](https://github.com/MacosPorters/betterxen/issues/243), [PR #280](https://github.com/MacosPorters/betterxen/pull/280) |
| Formatted standard output | [issue #245](https://github.com/MacosPorters/betterxen/issues/245), [PR #281](https://github.com/MacosPorters/betterxen/pull/281) |
| File streams | [issue #246](https://github.com/MacosPorters/betterxen/issues/246), [PR #282](https://github.com/MacosPorters/betterxen/pull/282) |
| Integrated hosted-C fixture | [issue #262](https://github.com/MacosPorters/betterxen/issues/262), [PR #283](https://github.com/MacosPorters/betterxen/pull/283) |
- The source-built module graph has independently derived results and
initialization/teardown records, with explicit forwarder/cycle/search policy.
- One worker progresses while another waits. Results hold across specified
scheduling quanta; the injected clock and timeout units remain consistent.
- Static TLS, dynamic TLS, fiber-local storage (FLS), errors, errno and CPU state
retain their specified per-thread isolation. Dropping a value does not count
as executing its registered guest callback.
- Missing exports, failed attach, invalid callback targets, stack faults,
timeouts, deadlock and exhausted budgets have precise, bounded outcomes.
- Repeated runs reclaim owned modules, handles, stacks and callback state.
Unsupported delayed imports or lifecycle paths are rejected explicitly.
Check dependency order and stacked branches against their actual heads. Audit
the compiler and linked CRT's per-file licensing and native ARM64 build tools.
An x86-64 guest fixture is permitted; its compiler must run natively on ARM64.
**Contributor work:** reuse [package census #211](https://github.com/MacosPorters/betterxen/issues/211)
and the existing scheduler. Runtime PRs #263/#290 overlap; their authors and
maintainers must resolve ownership before shared production edits. Parallel
host-thread execution remains outside the serial scheduler's ordering claim.
**Exit criteria:** reproducible original fixture build; checked stdout/stderr,
arguments, file contents, exit status, callback order and cleanup; unresolved
imports and exhausted budgets fail explicitly. Existing A1 behavior still passes.
Independent reviewers derive expected results from public specifications and the
fixture contract. No general C++ or Xbox startup claim follows from this result.
## Phase 3 — Render a scene controlled by guest code
## Phase 3 — Make threaded application behavior coherent
**Deliverable:** a compiled original guest creates resources, uploads a texture
and geometry, submits translated rendering, waits for completion and checks the
resulting frame through its guest-visible interface.
**Outcome:** an original worker-based application can block and resume without
stalling unrelated guest work or leaking per-thread state.
Use [startup-to-frame integration #256](https://github.com/MacosPorters/betterxen/issues/256)
as the integration task. A Rust test calling a host graphics method does not
alone prove the compiled guest can call it. Specify the supported service/call
boundary and check its Win64 argument/return and nonvolatile-state behavior.
Guest addresses must resolve to checked ranges and opaque handles, never host
pointers.
Extend the existing scheduler under [issue #228](https://github.com/MacosPorters/betterxen/issues/228).
Prioritize a small fixture that exposes a documented gap: guest sleep currently
delays all guest threads, and critical-section/SRW/condition-variable waits are
not fully connected to scheduling. Claim one gap and its paths before editing.
Existing translated `image_sample_lz`, guest descriptor-table bindings, texture
upload paths, blend/index/depth tests and packed compressed-texture footprints
are starting components. [Binding/entry design #302](https://github.com/MacosPorters/betterxen/issues/302)
specifies expansion beyond the bounded texture/sampler contract. Use an original
scene with distinguishable textures and resource updates so wrong bindings or
stale data change checked pixels.
Then add the thread lifecycle behavior required by that workload, including
static thread-local storage (TLS), library attach/detach and fiber-local storage
(FLS) cleanup where supported. Keep unsupported callbacks explicit until their
semantics and safety are implemented. Preserve Win64 nonvolatile register checks
and coordinate with [issue #193 / PR #268](https://github.com/MacosPorters/betterxen/pull/268).
**Completion checks:**
**Exit criteria:** deterministic results at several scheduling quanta; another
worker progresses while one waits; timeouts, cancellation, abandoned objects,
thread-local errors, stack bounds and cleanup have negative controls. Repeat
runs reclaim thread resources. Serial guest scheduling remains the execution
model unless a separately reviewed memory-ordering design replaces it.
- Actual native Metal execution produces frame readback matching expectations
derived independently of the decoder, compiler and production renderer.
- Changing one guest texture, transform or binding changes the expected frame;
a skipped draw or substituted shader cannot pass as correct rendering.
- Update, submit, completion, readback and retirement order are checked.
Resources remain valid for in-flight work and stale handles are rejected.
- Bad descriptors, overflowing ranges, unsupported shader forms and invalid
resource states fail before unsupported work reaches Metal.
- The report records device capability queries, validation settings, candidate,
commands and hardware. Synthetic gfx1030 success is not Xbox GPU verification.
## Phase 4 — Connect resource updates to translated rendering
**Contributor work:** [resource-update workload #147](https://github.com/MacosPorters/betterxen/issues/147),
[shared lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
[fences #224](https://github.com/MacosPorters/betterxen/issues/224), and
[format inventory #260](https://github.com/MacosPorters/betterxen/issues/260).
Respect the active format claim; do not duplicate its inventory.
**Outcome:** one original guest workload updates a texture and geometry, submits
translated rendering, waits for completion and produces an independently checked
frame through the existing native Metal backend.
## Phase 4 — Run an original interactive application
Start with a bounded scene and its concrete missing features. Do not make all
RDNA2 instructions, mesh shaders or ray tracing prerequisites for a first scene.
Reuse the semantic registry and distinguish declared, decoded, lowered,
reference-tested, locally GPU-tested and independently accepted forms.
**Deliverable:** one small original game-like application runs through the guest
CPU/runtime and native app with translated graphics, scripted input, bounded
audio and a save/load cycle in a persistent session.
Coordinate [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205),
[mip footprints #241 / PR #278](https://github.com/MacosPorters/betterxen/pull/278),
[graphics fences #224](https://github.com/MacosPorters/betterxen/issues/224),
[shared resource lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
and [texture-update workload #147](https://github.com/MacosPorters/betterxen/issues/147).
Wave divergence, cross-lane operations and additional formats get separate
fixture contracts and claims when this workload needs them.
Compose the admitted paths from phases 2 and 3. Define the application source,
input replay, frame checkpoints, sample-data checks and save format before
implementation. Start with the CPU/shader subset already justified by the scene.
Add C++ or additional runtime functionality only when an original failing
fixture demonstrates the requirement and linked runtime terms are reviewed.
**Exit criteria:** actual Metal execution and frame readback against an
independently derived expectation; update/submission/retirement order is checked;
invalid descriptors, stale handles and unsupported shader forms fail explicitly.
Record host capability detection, hardware, validation settings and evidence
class. Test counts and tolerances retain their existing definitions. Results
remain synthetic desktop-gfx1030 evidence, never Xbox hardware verification.
Wire the application through the existing Swift/Rust interface and worker
lifecycle. Existing native audio, controller and filesystem demonstrations are
components, not proof that guest code reaches each service. This phase must
exercise those guest connections in one session.
## Phase 5 — Run one integrated interactive application reliably
**Completion checks:**
**Outcome:** a small, original application joins guest execution, rendering,
input, bounded audio, filesystem access and lifecycle behavior in one session.
- A deterministic replay reaches independently specified state/frame checkpoints.
- Input reaches guest logic; expected audio samples are checked before device
playback; save/load preserves specified state and reports I/O failures.
- Start, pause, resume, stop, restart and worker failure have defined outcomes.
Commands do not report success after a worker has failed.
- Resource/handle counts and cleanup remain bounded across repeated sessions;
invalid guest paths and resource requests fail according to the interface.
- The native app/CLI provide a reproducible quick start and useful stage-specific
failure reports. This fixture still establishes no commercial compatibility.
Start from [multi-module startup #256](https://github.com/MacosPorters/betterxen/issues/256)
and the existing app/FFI fixtures. First prove a compiled workload can reach a
checked frame. Add C++ language/runtime features only when an independently
authored failing fixture demonstrates the need. Audit any linked runtime first.
Do not treat the Swift audio/input demonstrations as guest integration evidence.
**Contributor work:** [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
Coordinate [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
[session errors #250](https://github.com/MacosPorters/betterxen/issues/250),
[report schema #254](https://github.com/MacosPorters/betterxen/issues/254),
[worker diagnostics #255](https://github.com/MacosPorters/betterxen/issues/255),
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248), and
[quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
Execution-admission policy remains with
[#212](https://github.com/MacosPorters/betterxen/issues/212).
and [application quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
Execution-admission changes remain owned by [issue #212](https://github.com/MacosPorters/betterxen/issues/212).
## Phase 5 — Expand compatibility through a varied workload corpus
**Exit criteria:** scripted input and deterministic checkpoints; start, pause,
resume, stop and restart behavior; checked audio sample data before device
playback; bounded memory and handle use; sandbox escape attempts rejected;
useful failure reports and a repeatable soak protocol. Specify soak duration,
resource limits and acceptance conditions before measuring. A fixture worker
passing does not certify arbitrary files safe or commercial titles playable.
**Deliverable:** a versioned set of original source-built workloads exercises
meaningfully different CPU, runtime and graphics behavior through the integrated
path, with precise accepted/rejected profiles and reproducible regressions.
## Phase 6 — Improve measured bottlenecks
Choose additions from actual failures. Examples include another compiler or
runtime profile, vector-heavy arithmetic, runtime-dependent shader branches,
bounded loops, multiple resource views and streaming texture updates. Each
addition must demonstrate a gap not already owned by an existing task.
**Outcome:** faster or lower-resource execution of workloads whose correctness
is already checked, with measurements that another contributor can reproduce.
Use [CPU design #299](https://github.com/MacosPorters/betterxen/issues/299),
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300),
[runtime uniform branches #179](https://github.com/MacosPorters/betterxen/issues/179),
[bounded shader loops #180](https://github.com/MacosPorters/betterxen/issues/180),
and [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205).
Wave divergence, cross-lane operations, local data share (LDS), barriers, mesh
stages and ray tracing require their own public contracts, fixtures and native
capability checks when a selected workload needs them.
Performance analysis can begin earlier; changes must preserve the relevant
phase's correctness. Select bottlenecks from actual measurements rather than
assuming every shared-semantics call, allocation or cache miss needs replacement.
Potential work includes CPU helper lowering, bounded translation-cache policy,
Metal startup, texture transfers and frame-loop overhead.
**Completion checks:**
Reuse [startup measurements #171 / PR #266](https://github.com/MacosPorters/betterxen/pull/266),
[TLS optimization #107 / PR #284](https://github.com/MacosPorters/betterxen/pull/284),
[DBT comparison #110 / PR #272](https://github.com/MacosPorters/betterxen/pull/272),
and [conditional cache prewarming #258](https://github.com/MacosPorters/betterxen/issues/258).
- Each workload identifies its source/build recipe, required forms/services,
original expected outputs, limits and exact independently accepted candidate.
- Coverage separates declared, decoded, lowered, CPU-tested, locally GPU-tested
and independently accepted behavior. Compilation counts are not compatibility.
- Unsupported behavior retains explicit diagnostic controls; expected values do
not come from the same implementation being tested.
- Targeted mutation/fuzz/regression checks demonstrate sensitivity to the changed
behavior without altering tolerances, gate definitions or mutation counting.
- Earlier integrated workloads still pass. Failures become bounded tasks with
proposed files and dependencies, not a generic rewrite of a subsystem.
**Exit criteria:** correctness gates pass on the changed candidate; baseline and
candidate use equivalent inputs, toolchains, settings and hardware; idle-machine
samples include variance and separate cold/warm startup. Report regressions as
well as gains. Run validation-off benchmarks separately from validation-on GPU
correctness. Capability differences across Apple Silicon generations remain
unknown until measured; runtime detection controls optional paths.
**Contributor work:** [original corpus #150](https://github.com/MacosPorters/betterxen/issues/150),
[shader acceptance #225](https://github.com/MacosPorters/betterxen/issues/225),
CPU coverage #154 and the existing QA owner #219. Reuse their tools and acceptance
rules; do not create another competing status or test framework.
## Taking the next task
## Phase 6 — Sustain execution across Apple Silicon
Begin with Phase 1's evidence reconciliation and review Phase 2's existing PRs.
The phase-plan issue does not claim their implementation files. Read every
comment on a target issue and inspect linked PRs; never take a live claim.
Issue #219's QA paths and subsystem owners remain independent of this plan.
**Deliverable:** admitted workloads run for a specified duration under bounded
memory/resource use, and performance/correctness reports are reproducible on
the actual native hosts contributors test.
Each implementation task needs a bounded outcome, permitted files, dependencies,
public semantic sources, a failing fixture or other meaningful acceptance check,
and the required independent reviewers. Use original code and expectations;
never copy another emulator to satisfy a phase. Do not require a fixed number
of agents: use available resources only within the repository's LOW-reasoning
and independent-review rules.
Specify soak duration, replay, resource limits and failure conditions before the
run. Measure guest execution, translation, service calls, transfers, Metal
startup, submission and readback to identify the actual bottleneck. Record
cold/warm behavior, variance and regressions as well as improvements.
Useful existing commands for the candidate record:
Use the existing native audit, GPU tests and benchmarks. Reuse merged startup
measurements and DBT comparison tooling; evaluate prewarming/persistence only
under [#258](https://github.com/MacosPorters/betterxen/issues/258) when measurements
justify it. Guest code-cache lifetime and same-block executable writes remain
explicit CPU correctness risks under #95 and #291.
```sh
PYTHONPATH=scripts python3 -m qa cpu-inventory --compact
PYTHONPATH=scripts python3 -m qa runtime-inventory --compact
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
python3 scripts/audit/status.py --check
scripts/audit/claims.sh
scripts/audit/dependencies.sh
```
**Completion checks:**
- The agreed soak/restart protocol passes on the pinned candidate with recorded
resource accounting and no hidden fallback or silent loss of work.
- Baseline/candidate measurements use equivalent inputs, toolchains, settings
and hardware. Validation-on correctness and validation-off performance are
separate runs; benchmarks use an idle host as required by the protocol.
- [Native reports #303](https://github.com/MacosPorters/betterxen/issues/303)
distinguish host binary architecture, documented capabilities, actual execution,
failure, unavailable tools and skipped tests. Skips are never GPU passes.
- Runtime capability detection selects optional paths. M1–M5/future-device cells
stay unknown until actual reports exist; one machine cannot verify them all.
- Contributor preview preparation follows app/native gates. Signing, notarization,
redistribution review and publication require their own evidence and explicit
release authorization; this phase does not authorize uploads.
**Contributor work:** [soak #149](https://github.com/MacosPorters/betterxen/issues/149),
[memory pressure #204](https://github.com/MacosPorters/betterxen/issues/204),
[dependency evidence #158](https://github.com/MacosPorters/betterxen/issues/158),
and [preview preparation #259](https://github.com/MacosPorters/betterxen/issues/259).
## Phase 7 — Attempt documented Xbox compatibility
**Deliverable:** a separately reviewed compatibility experiment with admissible
inputs demonstrates exactly the supported startup/execution/rendering stages,
or records a specific unresolved contract that prevents the attempt.
Begin [public console-contract research #306](https://github.com/MacosPorters/betterxen/issues/306)
now, alongside the earlier engineering phases. Maintain evidence for launch and
CPU entry state, executable admission, service ABI, shader entry/bindings,
resource and command layouts, synchronization and memory aliases. Public PE,
AMD desktop ISA and D3D12 documents establish their documented contracts; they
do not automatically establish Xbox behavior. Unknown console details remain
unknown rather than becoming guessed implementations.
An actual execution attempt depends on demonstrated technical support for its
input, project-permitted authorized/unprotected material, explicit admission
and independent review. Do not obtain or use leaked executables, restricted
SDKs, confidential headers, proprietary shader collections, firmware or keys;
do not implement protection bypasses. A torrent filename or container does not
establish a supported executable, launch environment or compatibility result.
User files stay outside the repository. File validation concerns technical
compatibility and safety; it must not demand receipts, accounts or ownership
provenance uploads.
**Completion checks:**
- Required contracts have precise public sources and repository evidence classes,
or are visible blockers. Restricted/unavailable evidence is not bypassed.
- The admitted input profile, candidate, runtime capabilities and expected
outcomes are reviewed before execution and precisely bounded.
- Actual results separately identify inspection, loading, entry, menu/frame,
world simulation, interaction and sustained play. Reaching one does not
certify the next; crashes and missing behavior remain in the report.
- R1 audits evidence/provenance and R2 independently derives semantic expectations.
BetterXen has no Xbox hardware access and must never claim such verification.
- No game title is called supported or playable without a demonstrated repeatable
result. No date, compatibility percentage or release follows from this plan.
This phase can remain blocked while earlier original workloads continue to
improve. There is currently no demonstrated GTA VI execution in BetterXen.
## How contributors start
The [research tracker #298](https://github.com/MacosPorters/betterxen/issues/298)
links the eight new bounded tasks #299–#306 and the existing work they depend on.
The phase plan claims no implementation files. Research/design tasks can begin
on their documented paths; production changes must coordinate subsystem owners
and active claims. Read all comments, including imported archived claims, and
inspect linked open PRs before claiming one issue in a plain reply.
Every task needs an outcome, proposed files, dependencies, public semantic
sources, meaningful positive/negative checks and independent reviewers. Update
the changelog for meaningful changes. Record candidate-specific results and raw
logs under ignored `artifacts/`; distinguish implementation, local verification
and independent acceptance. Preserve historical evidence and attribution.
Run the applicable commands from `AGENTS.md`. Across simultaneous work use at
most four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or
mutation campaign. Never count unrun or skipped checks as passes. No commit,
push, merge or release is authorized by a phase or an issue claim.
For implementation, run the applicable checkout commands in `AGENTS.md` and the
subsystem acceptance protocol. Keep logs under ignored `artifacts/`. Use at most
four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or mutation
campaign at a time. New verification must name the exact candidate; skipped
tests never count as GPU evidence. Passing a phase does not authorize a release.
+25
View File
@@ -141,6 +141,31 @@ pages count toward the 256 MiB mapping budget of one image, which is checked
before anything is mapped. `ParsedPe::parse` does not make these checks, so
static inspection of a file is unchanged.
`betterxen run --experimental --pe <trusted-fixture> --startup-report <path>`
writes a versioned JSON summary after the worker stops. The supervisor creates the new report path before launching the worker.
The report is optional and uses the same exact-byte fixture admission, startup
observer and wall deadline as an ordinary run.
Schema version 1 lists the observed stages in order in `stages` and copies
the last valid stage to `last_completed_stage` (null if none). The order is
`parsed`, `mapped`, `relocated`, `imports_bound`, `tls_completed`, `entry`,
`exit`, and `framebuffer`. `entry` records the handoff to guest entry.
`exit` records the fixture halt, and `framebuffer` records verification of its
offscreen readback. The supervisor reports an `outcome` of `verified`,
`stage_failure`, `early_exit`, `timeout`, or `unknown`. It includes the
worker exit code when available, termination detail when applicable, and the
original reported error when available. Errors are capped at 2 KiB of UTF-8
and carry an `error_truncated` flag.
The supervisor reads at most 8 KiB plus one byte from the worker journal.
`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized`,
`unreadable`, or `unwritable`. Worker exit codes 124 and 125 are reserved for
its watchdog and journal I/O errors, respectively. `--startup-journal` is an
internal worker option. Only the valid ordered prefix counts toward progress. A
complete journal may still contain only a partial startup if the worker
stopped between records. These records describe runtime observations from
the trusted fixtures.
`betterxen probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. Without `--report` it writes to `diagnostics/probe`,
where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
+4 -4
View File
@@ -19,16 +19,16 @@ Request original gfx1030 Wave64 assembly, a mask/lane design note and per-lane e
KyTx declares GPL-2.0. Tx's conditional GPL-2.0-or-later offer covers only material they own and can license. Require file-level authorship, explicit compatible terms (GPL-3.0-or-later preferred for new Xenora fixtures), preserved notices and DCO. Inherited GPL-2.0-only code cannot enter the GPL-3.0-or-later combined work under those terms. The separate Kyty MIT notice does not settle a derived file's full provenance. No KyTx submodule is justified for the fixture. [KyTx license and notices](https://github.com/TxCsOffc/KyTx/tree/10f50d3eff0c0df36ee5d7007848a7b0b15072eb/LICENSES), [KyTx license](https://github.com/TxCsOffc/KyTx/blob/10f50d3eff0c0df36ee5d7007848a7b0b15072eb/LICENSE)
## Leonida
## PE-Vulkan project
Public revision `2d3369a4c82e6f36c5190c4c534d3df600e135ec`. Candidate study surfaces and limits:
| Surface | Evidence and disposition |
| --- | --- |
| Decode and translation | `decode_bytes` decodes RDNA words with an explicit wave-mode argument. The SPIR-V generator exposes `Gen` and `assemble`. Compare supported operand forms on independent synthetic inputs. Keep Xenora's typed decoder and MSL backend. [Decoder](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/rdna2_decode.py#L1397), [Generator](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/rdna2spirv.py#L219) |
| Containers and GPU API | `wave_size` and `binding_table` expose Leonida's FSSM interpretation. The D3D12 Vulkan shim and its device test are concrete source paths. Their existence does not establish a public authoritative Xbox ABI or PM4 contract. Keep metadata and guest handles outside Xenora's decoder, with explicit wave size, checked byte ranges and validated resource bindings. [FSSM reader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/fssm_header.py#L155), [Device shim](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/shims/d3d12_vulkan_device.cpp), [Device test](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/test/d3d12_vulkan_device_test.cpp) |
| Containers and GPU API | `wave_size` and `binding_table` expose PE-Vulkan project's FSSM interpretation. The D3D12 Vulkan shim and its device test are concrete source paths. Their existence does not establish a public authoritative Xbox ABI or PM4 contract. Keep metadata and guest handles outside Xenora's decoder, with explicit wave size, checked byte ranges and validated resource bindings. [FSSM reader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/fssm_header.py#L155), [Device shim](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/shims/d3d12_vulkan_device.cpp), [Device test](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/test/d3d12_vulkan_device_test.cpp) |
| Executable and services | `Loader::load` and `Loader::load_runtime_module` establish an implemented Windows PE loading and shim boundary. CMake registers loader, bounds and TLS tests. The upstream stand-in run is reported. For Xenora, study the boundary using original PE fixtures, with checked image metadata, guest address translation and explicit service dispatch. Native Windows execution and the Vulkan runtime conflict with Xenora's host contract. [PE loader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/src/pe_loader.cpp#L608), [Test registration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/CMakeLists.txt#L516) |
The README reports 26,503 translations and SPIR-V validation at specific earlier revisions. It contains conflicting Wave64 counts, so leave that count unresolved. The linked GPU reports cover synthetic cases and include a MoltenVK path. Validation and pipeline creation do not check game shader output. The pinned status explicitly says the game does not boot. Xenora's GTA VI intro remains unverified, and no authorized test input was established in this review. [Pinned status](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/README.md#project-status), [Reported validator run](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586), [Upstream GPU reports](https://github.com/ItsNotRexed/Leonida/issues/166)
The README reports 26,503 translations and SPIR-V validation at specific earlier revisions. It contains conflicting Wave64 counts, so leave that count unresolved. The linked GPU reports cover synthetic cases and include a MoltenVK path. Validation and pipeline creation do not check game shader output. The pinned status explicitly says the game does not boot. Xenora's commercial-title intro remains unverified, and no authorized test input was established in this review. [Pinned status](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/README.md#project-status), [Reported validator run](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586), [Upstream GPU reports](https://github.com/ItsNotRexed/Leonida/issues/166)
Leonida carries GPL v3 text at the inspected pin. Any adoption still requires R1 to establish exact file terms and ownership, check generated tables and SDK-derived material, and review the separate `third_party/rpf9-explorer` gitlink at `e2939175c36a02d6ed25fa2c217b9d6ddcb8b516`. Game-derived metadata, shaders and asset outputs are outside this collaboration. Use public design references and original synthetic inputs. No Leonida submodule is justified. [Leonida license](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/LICENSE), [Submodule declaration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/.gitmodules)
PE-Vulkan project carries GPL v3 text at the inspected pin. Any adoption still requires R1 to establish exact file terms and ownership, check generated tables and SDK-derived material, and review the separate `third_party/rpf9-explorer` gitlink at `e2939175c36a02d6ed25fa2c217b9d6ddcb8b516`. Game-derived metadata, shaders and asset outputs are outside this collaboration. Use public design references and original synthetic inputs. No PE-Vulkan project submodule is justified. [PE-Vulkan project license](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/LICENSE), [Submodule declaration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/.gitmodules)
+1 -1
View File
@@ -5,7 +5,7 @@ Historical reuse discussion records the earlier survey. Xenora uses
public specifications and original fixtures, with other emulator
projects serving only as references for test selection.
Screened the eight A3 leads on 2026-11-23 against section 6 of the dual-track brief. The pins below identify the default-branch snapshots and their latest observed commits in UTC. The OpenScarlett tip changes documentation. A recent tip establishes activity, and its commit message records the subject of that activity. See the companion notes for [KyTx and Leonida](phase02-collaboration.md) and [CPU engine selection and original interpreter fixture](phase02-cpu-feasibility.md).
Screened the eight A3 leads on 2026-11-23 against section 6 of the dual-track brief. The pins below identify the default-branch snapshots and their latest observed commits in UTC. The OpenScarlett tip changes documentation. A recent tip establishes activity, and its commit message records the subject of that activity. See the companion notes for [KyTx and PE-Vulkan project](phase02-collaboration.md) and [CPU engine selection and original interpreter fixture](phase02-cpu-feasibility.md).
GitHub metadata and tree entries establish availability and paths. Pinned text inspection establishes what a selected function does in source. Upstream test counts, captures and README statements remain upstream reports. No upstream code, builds, fixtures or GPU workloads were executed here. Repository-level license labels are provisional for reuse. File-specific grants, origin and transitive terms remain unverified for every code surface below.
+8 -11
View File
@@ -50,8 +50,7 @@ with existing local documentation edits. Read-only `git fetch` found newer main
[`b2654e93`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721).
A separate ignored source snapshot was inspected without switching, resetting
or merging the working tree. This distinction changes the hosted-C status.
The documentation PR is based on the reviewed newer main revision and changes
no runtime implementation.
Local documentation edits from this review do not install that newer runtime.
## Why the PC results do not transfer directly
@@ -114,7 +113,7 @@ project's title-specific API totals or implementation.
| Hosted C | A1 and A2 are present; PR #283 merged as d26af53c. Gate A records local passes awaiting independent review | Do not open another “implement hosted C” issue. Reproduce/accept the candidate and expand from a failing original workload. |
| Modules | startup.rs accepts one image; modules.rs exposes built-in service modules | Built-in LoadLibrary/GetProcAddress is not general EXE plus guest-DLL startup and teardown. |
| Threads | Deterministic serial guest scheduler with worker stacks/TEBs, waits and handles | Sleep can stall all workers; static worker TLS and thread/FLS callbacks remain documented gaps. Serial scheduling does not prove parallel x86 memory ordering. |
| Graphics | Translated image_sample_lz pixel stage, native texture tests and guest descriptor-table bindings already exist | The inspected README's former X10 description understated this bounded path; the replacement roadmap removes that stale planning row. Broader bindings, control flow and sampling still need contracts. |
| Graphics | Translated image_sample_lz pixel stage, native texture tests and guest descriptor-table bindings already exist | README X10 and generic “no sampling” descriptions are stale for this bounded path. Broader bindings, control flow and sampling still need contracts. |
| Shader inventory | Table records 1,465 identified forms, 189 decoded, 185 IR/MSL, 18 accepted Metal forms; reconciliation finds zero mismatches | Different domains and acceptance stages must stay separate. The compute inventory does not fully describe graphics-only sampling. #225 owns pending acceptance. |
| Texture/resource work | Packed BC footprints and bounded private texture staging merged; original resource/draw tests exist | Reuse them. Do not duplicate #260's active format inventory or assume guest/console integration from host upload success. |
| Native app | Existing Swift/FFI fixtures; app/CI and usability PRs remain separate | UI/audio/input fixtures are not one integrated compiled guest application. #256 is the existing integration task. |
@@ -232,7 +231,7 @@ reuse permission. Descriptions below classify documentation, not executed code.
| ScarlettX (`Freminet/ScarlettX`) | [`01c642cf`](https://github.com/Freminet/ScarlettX/blob/01c642cf62a6d9978f535e2c438c488ebcb4cd39/README.md); license metadata: `unresolved` | Windows x64 HLE/D3D12; separates console precompiled-shader gaps from desktop paths. Console-binary-derived findings need independent public evidence. |
| TuxBox (`brcly/TuxBox`) | [`97b8ad31`](https://github.com/brcly/TuxBox/blob/97b8ad3192def18d491fe72ea3a55e204bc77a5d/README.md); license metadata: `Apache-2.0` | x86-64 Windows and Linux/Proton; owned guest fixtures and provider-specific failures are useful testing patterns, not an ARM64 solution. |
| americas-recomp (`realdody/americas-recomp`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| Leonida (`ItsNotRexed/Leonida`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| PE-Vulkan project (`ItsNotRexed/Leonida`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| OpenScarlett (`californiaAlmonds/OpenScarlett`) | [`022a8b25`](https://github.com/californiaAlmonds/OpenScarlett/blob/022a8b25148cc08412df8ac7e752b9efed4cd819/README.md); license metadata: `MIT` | Windows x64, D3D12/Vulkan; broad completeness claims are upstream reports. Public-spec-backed original fixtures are the only proposed transfer. |
| scarlett-layer (`jadeowaowa/scarlett-layer`) | [`0e436b3e`](https://github.com/jadeowaowa/scarlett-layer/blob/0e436b3e1c654765b193c1cb705918fbf101b10b/README.md); license metadata: `Apache-2.0` | Windows import interception/shims, D3D12 and synthetic test tiers; useful distinction between desktop samples and console compatibility. |
| Xbox2Windows (`R0Y00/Xbox2Windows`) | [`ab9a020c`](https://github.com/R0Y00/Xbox2Windows/blob/ab9a020c0783f9ce1dd10876cbeb119707b9ada9/README.md); license metadata: `MIT` | x64-to-C++ AOT/loader and DXIL research; distinguishes modified diagnostic startup from original executable compatibility. Host ABI still differs. |
@@ -291,9 +290,9 @@ reuse permission. Descriptions below classify documentation, not executed code.
| `edsuuu/VI-BR-PORT` | [`7a30f506`](https://github.com/edsuuu/VI-BR-PORT/blob/7a30f5063dafeda1ceab84d251c22dc581d4dfc6/README.md); license metadata: `GPL-3.0` | VIctory-family Windows/NVIDIA memory tuning; wave32 assumptions must not be transferred to Apple GPU capability claims. |
| `xcl-dev/xcl` | [`f5c5bdf0`](https://github.com/xcl-dev/xcl/blob/f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f/README.md); license metadata: `GPL-2.0` | Windows x64 direct execution plus D3D12/DXIL; host services and pipeline behavior matter. GPL-2.0-only README; no reuse clearance. |
| `ZigZagBoi1/ScarlettPort` | [`48ba23a9`](https://github.com/ZigZagBoi1/ScarlettPort/blob/48ba23a91a83121f8d0625a633e88fa463d5a0ca/README.md); license metadata: `NOASSERTION` | Windows x64/D3D12 compatibility route; no native Darwin CPU/runtime established. |
| `Steinkoloss/port-of-the-americas` | [`0f3be36a`](https://github.com/Steinkoloss/port-of-the-americas/blob/0f3be36aaefe69c25f06e05222b88453f3557acd/README.md); license metadata: `unresolved` | Linux x64/Proton/vkd3d-proton shims; README names Leonida shader conversion. No implementation reuse. |
| `Steinkoloss/port-of-the-americas` | [`0f3be36a`](https://github.com/Steinkoloss/port-of-the-americas/blob/0f3be36aaefe69c25f06e05222b88453f3557acd/README.md); license metadata: `unresolved` | Linux x64/Proton/vkd3d-proton shims; README names PE-Vulkan project shader conversion. No implementation reuse. |
| `Leucodermique/VIce` | [`8c7b24fd`](https://github.com/Leucodermique/VIce/blob/8c7b24fda90eb08fe64044726b7c880065a86ee0/README.md); license metadata: `GPL-3.0` | VIctory-based Windows distribution/frontend; consolidation does not independently validate combined changes. |
| `flipflapov/DSTN` | [`7066ae66`](https://github.com/flipflapov/DSTN/blob/7066ae669c7b0e20d0b05675826169cdc7442883/README.md); license metadata: `GPL-3.0` | Leonida fork; tool portability on macOS does not establish native guest execution. No implementation reuse. |
| `flipflapov/DSTN` | [`7066ae66`](https://github.com/flipflapov/DSTN/blob/7066ae669c7b0e20d0b05675826169cdc7442883/README.md); license metadata: `GPL-3.0` | PE-Vulkan project fork; tool portability on macOS does not establish native guest execution. No implementation reuse. |
| `daeken/XSXEmu` | [`2d937f83`](https://github.com/daeken/XSXEmu/blob/2d937f8360fbcdac368a0e363c24df322fa24db2/README.md); license metadata: `MIT` | macOS Rust host with Rosetta guest execution and separate native Metal shader fixtures; not a fully ARM64 guest CPU path. No game frame claimed. |
| `SixLauncher/VILauncher` | [`bf2f6ca9`](https://github.com/SixLauncher/VILauncher/blob/bf2f6ca9a6445aee6ebdff2b1cef87266f9cf1f4/README.md); license metadata: `GPL-3.0` | Linux launcher selecting VIctory/XCL under Wine/Proton. Not a new guest execution or Metal implementation. |
| `4Sakens/Project-Kalaga` | [`56b41fb4`](https://github.com/4Sakens/Project-Kalaga/blob/56b41fb4a68b89e5e356c1445699ba4ac6b8cc83/README.md); license metadata: `unresolved` | Windows consolidation of existing efforts; aggregated subsystems and local paths are not independent compatibility evidence. |
@@ -306,7 +305,7 @@ reuse permission. Descriptions below classify documentation, not executed code.
| `Joaco9020/mangrove` | [`d16326c6`](https://github.com/Joaco9020/mangrove/blob/d16326c652b6f82e7b59b390f63e37cab816acd3/README.md); license metadata: `GPL-3.0` | VIctory-family Windows fork tuned for lower-VRAM NVIDIA GPUs. Settings are not portable Metal correctness work. |
| `chvabalo-interactive/sludgemu` | [`29cf795e`](https://github.com/chvabalo-interactive/sludgemu/blob/29cf795e23bb4917b9a8acd6be95d38a0f3b99b1/README.md); license metadata: `unresolved` | Windows direct guest execution and D3D12/DXIL, early startup with logging stubs. Stubs are not behavior support. |
| `larpingvibecoder/sonoma` | [`835f386a`](https://github.com/larpingvibecoder/sonoma/blob/835f386a144eca0b903b8bec63c0a003d7e07071/README.md); license metadata: `Apache-2.0` | Windows Rust runtime/direct DXIL, early proof of concept; name does not indicate macOS support. |
| `7jycwjmbfn-eng/scenegate-vi` | [`d5908947`](https://github.com/7jycwjmbfn-eng/scenegate-vi/blob/d590894710631a3c6adc6cca526c44d3c0c2bd41/README.md); license metadata: `MIT` | Windows/Vulkan startup and scene work based on Leonida; retain only documented failure categories, not code or title-derived inputs. |
| `7jycwjmbfn-eng/scenegate-vi` | [`d5908947`](https://github.com/7jycwjmbfn-eng/scenegate-vi/blob/d590894710631a3c6adc6cca526c44d3c0c2bd41/README.md); license metadata: `MIT` | Windows/Vulkan startup and scene work based on PE-Vulkan project; retain only documented failure categories, not code or title-derived inputs. |
| `TaynanGT/victory-windows-anterior-20261125` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| `TaynanGT/victory-windows` | [`cdcff8fe`](https://github.com/TaynanGT/victory-windows/blob/cdcff8fe96182bade41343a10b985c028e9e8968/README.md); license metadata: `GPL-3.0` | VIctory-family Windows work on a non-main default branch; pin the actual branch, not its name. |
| `Archivist-Atlas/gta-vi-astral` | [`ff21332e`](https://github.com/Archivist-Atlas/gta-vi-astral/blob/ff21332e5ea2ea1c254a97c0b3036d36ff8e79ce/README.md); license metadata: `unresolved` | Go Windows runtime research citing VIctory/Leonida designs; no independent ARM64/Metal execution established. |
@@ -351,7 +350,5 @@ No Rust build, CPU execution suite, native GPU test, demo, fuzz, mutation or
benchmark ran for this documentation task. New acceptance must use the exact
candidate, actual native tool architecture and actual eligible hardware.
Independent reviewers have not certified this report's proposed implementations.
The research stage installed or executed no upstream project or game content.
Documentation publication and the GitHub research/follow-up issues were requested
by the user; their delivery status is recorded in the linked PR/tracker. No
runtime merge, release or compatibility acceptance is implied.
Nothing was committed, pushed, merged, released or installed by this review.
The GitHub research/follow-up issues were created at the user's request.
+3 -3
View File
@@ -11,8 +11,8 @@ in this checkout uses original fixtures and public specifications.
| Project and audited snapshot | Type and observed evidence | Claimed-only behavior or provenance risk | Xenora work and original acceptance fixture | Priority and owner |
| --- | --- | --- | --- | --- |
| [Xenora `3133d8e`](https://github.com/ranveersoni98/Xenora/tree/3133d8e) | Native Rust guest and shader research. X1–X4 fixtures and gfx1030 compiler in tree. | GPL-3.0-or-later. Console execution unsupported. | Re-run the guest and translated compute fixtures on ARM64. | Immediate, integration |
| [Leonida `3faac55`](https://github.com/ItsNotRexed/Leonida/tree/3faac55) | Windows PE mapping, service shims and Vulkan proxy tests. | GPL-3 family and Xenora no-port rule. Commercial boot absent in audit. | Original PE startup and GPU resource contracts. | Later, CPU and Metal |
| [Project ReCity `cb4840b`](https://github.com/pixl27/ProjectReCity/tree/cb4840b) | Windows/Vulkan implementation and PE tests. | GPL-3, Leonida-derived. Separate retail proof absent. | Same synthetic startup coverage as Leonida, no parallel benchmark. | Later, CPU |
| [PE-Vulkan project `3faac55`](https://github.com/ItsNotRexed/Leonida/tree/3faac55) | Windows PE mapping, service shims and Vulkan proxy tests. | GPL-3 family and Xenora no-port rule. Commercial boot absent in audit. | Original PE startup and GPU resource contracts. | Later, CPU and Metal |
| [Project ReCity `cb4840b`](https://github.com/pixl27/ProjectReCity/tree/cb4840b) | Windows/Vulkan implementation and PE tests. | GPL-3, PE-Vulkan project-derived. Separate retail proof absent. | Same synthetic startup coverage as PE-Vulkan project, no parallel benchmark. | Later, CPU |
| [Xbox2Windows `6de5738`](https://github.com/R0Y00/Xbox2Windows/tree/6de5738) | Static recompilation tests for imports, CPU startup, TLS and GPU output. See `tests/cpu/startup_exe.cpp`. | MIT at repository level. Full title startup unverified. | Build a source-authored PE guest and test exact service results. | Immediate, CPU |
| [americas-recomp `9bf220e`](https://github.com/realdody/americas-recomp/tree/9bf220e) | Audited main root had a license file. | GPL-2.0. Other branches uninspected. | No fixture justified by audited tree. | Deferred, research |
| [6stars `480d9a4`](https://github.com/meetox80/6stars/tree/480d9a4) | Swift/Metal renderer and sampler mapping in `Sources/SixStars`. | No verified root license. Guest CPU execution unverified. | Original translated shader, validated resource range and known readback. | Immediate, Metal |
@@ -63,7 +63,7 @@ in this checkout uses original fixtures and public specifications.
services, hardware queues, formats and memory initialization need their
own sources and tests. [Xbox GPU evidence](../research/xbox-gpu.md) ·
[PE format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format)
- GTA VI startup and execution remain unsupported. No authorized retail
- Commercial-title startup and execution remain unsupported. No authorized retail
executable was loaded. Actual title imports, startup ordering, resource
bindings and pipeline behavior remain unverified. Relocation, thread-local
storage, process and thread services, dynamic shader execution and
+96
View File
@@ -0,0 +1,96 @@
# Texture format and layout inventory
This page records which texture formats and memory layouts BetterXen handles today, and at which stage. It also records which gaps are worth closing and which are deferred. It is an inventory of the repository at the time of writing, built from the code and tests it links. It is not a support claim: a format listed here works only for the original synthetic fixtures named, on desktop specifications, and nothing here says anything about Xbox hardware or commercial titles.
## Stages
A format can be handled at one stage and missing at the next. The columns below keep them apart:
- **Container**: recognising a file or package format that holds textures (DDS, KTX and similar).
- **CPU decode**: turning one compressed block into texels on the CPU, used as an independent reference.
- **Layout**: converting between a stored memory layout and the row-major layout Metal expects.
- **Native**: uploading to a Metal texture of that pixel format and reading it back on the GPU.
- **Sampling**: a translated RDNA 2 image instruction reading the texture inside a shader.
- **Host graphics API**: the D3D12-shaped `GraphicsContext` entry points, exercised by tests that call them directly from Rust. [The interface contract](../interfaces.md#guest-texture-binding-descriptor-tables) states they are not yet wired to guest imports, so this column is not guest evidence.
- **Guest**: an original guest program (PE fixture) reaching the path through imported services, with a test that runs it.
- **Specification**: the public sections the implementation and its expected values cite.
"—" means not implemented. "Rejected" means the input is refused with an error rather than handled.
## Formats
| Format | Container | CPU decode | Layout | Native | Sampling | Host graphics API | Guest | Specification |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| RGBA8 unorm | — | not needed | row-major mips, direct or budgeted staged upload ([`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs)) | upload and render target (`render_rgba8*`, [`crates/metal/tests/native/texture_sampling.rs`](../../crates/metal/tests/native/texture_sampling.rs)) | `image_sample_lz`, 2D, level 0 ([`crates/isa/src/lib.rs`](../../crates/isa/src/lib.rs), [`crates/metal/tests/native/translated_render.rs`](../../crates/metal/tests/native/translated_render.rs)) | one-level 2D SRV, `DXGI_FORMAT_R8G8B8A8_UNORM`, called from Rust ([`crates/loader/src/graphics.rs`](../../crates/loader/src/graphics.rs), [`crates/loader/tests/graphics_textures.rs`](../../crates/loader/tests/graphics_textures.rs)) | synthetic `xenora.dll` texture services (`texture_create`, `texture_update`, `frame_submit_textured`, `texture_destroy`) driven by the Gate 5 original PE fixture ([`crates/ffi/src/lib.rs`](../../crates/ffi/src/lib.rs), test `textured_pe_fixture_executes_dynamic_updates_and_retirement` in [`crates/ffi/tests/resources.rs`](../../crates/ffi/tests/resources.rs)); not through the descriptor-table API | [`MTLPixelFormat.rgba8Unorm`](https://developer.apple.com/documentation/metal/mtlpixelformat/rgba8unorm) |
| BC1 | — | `decode_bc1` ([`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs)) | synthetic tiled layout, pitched uploads (`TiledBc1`, `Bc1Upload`) and per-subresource packed footprints (`BcTextureLayout`, `PackedBcUpload`) | `read_tiled_bc1`, `read_bc1_upload`, including packed footprints ([`crates/metal/tests/native/texture.rs`](../../crates/metal/tests/native/texture.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | sampled by the translated `image_sample_lz` pixel stage (`render_rgba8_sampled_bc1`, [`crates/metal/tests/native/translated_bc1.rs`](../../crates/metal/tests/native/translated_bc1.rs)) | one-level 2D SRV, `DXGI_FORMAT_BC1_UNORM`, called from Rust (same files as RGBA8) | — | [Khronos DFS 1.3, S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) (BC1 with and without alpha); [Microsoft, BC1](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
| BC2, BC3 | — | `decode_bc2`, `decode_bc3` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcAlphaUpload`) and packed footprints | `read_bc_alpha_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_alpha.rs`](../../crates/metal/tests/native/texture_bc_alpha.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, S3TC BC2](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc2) and [BC3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc3); [Microsoft, BC2 and BC3](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
| BC4, BC5 (unorm, snorm) | — | `decode_bc4_*`, `decode_bc5_*` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcChannelUpload`) and packed footprints | `read_bc_channel_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_channel.rs`](../../crates/metal/tests/native/texture_bc_channel.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, RGTC BC4](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc4) and [BC5](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc5); [Microsoft, BC4 and BC5](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
| BC6H (ufloat, sfloat) | — | single-subset modes only; two-subset modes rejected ([`crates/texture/src/bc6h.rs`](../../crates/texture/src/bc6h.rs), [`crates/texture/tests/bc6h.rs`](../../crates/texture/tests/bc6h.rs), vectors [`crates/texture/tests/fixtures/bc6h_vectors.txt`](../../crates/texture/tests/fixtures/bc6h_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC6H](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h) (section 20.2, Tables 121 and 122); [Microsoft, BC6H Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) |
| BC7 unorm | — | all eight modes ([`crates/texture/src/bc7.rs`](../../crates/texture/src/bc7.rs), [`crates/texture/tests/bc7.rs`](../../crates/texture/tests/bc7.rs), vectors [`crates/texture/tests/fixtures/bc7_vectors.txt`](../../crates/texture/tests/fixtures/bc7_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC7](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) (section 20.1, Tables 109–120); [Microsoft, BC7 Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format) |
| BC7 sRGB | — | same bytes as BC7; the sRGB transfer function is outside the decoder | — | — | — | — | — | as BC7 |
| Depth32Float | — | not needed | render attachment | `render_depth` with depth readback ([`crates/metal/tests/native/depth.rs`](../../crates/metal/tests/native/depth.rs)) | — | — | — | [`MTLPixelFormat.depth32Float`](https://developer.apple.com/documentation/metal/mtlpixelformat/depth32float) |
Sampler state is limited to nearest filtering and clamp-to-edge addressing ([`crates/texture/src/sampler.rs`](../../crates/texture/src/sampler.rs)). Other filter or address modes are rejected.
Native BC paths require `supportsBCTextureCompression`. A device without it fails as a capability error ([`crates/metal/src/compute.rs`](../../crates/metal/src/compute.rs)), separately from implementation failures.
Known source differences, recorded where they are implemented:
- **BC6H:** the Khronos text and Microsoft's sample code disagree on whether a negative value that rounds to zero keeps its sign (`-0.0` against `0.0`). `bc6h.rs` follows Khronos.
- **BC1:** Apple's hardware rounds BC1's interpolated palette entries differently from the spec-exact decoder (171/84 against 170/85, see `CHANGELOG.md`). The sampled BC1 fixtures therefore use only endpoint colours.
## Layouts
| Layout | State | Where |
| --- | --- | --- |
| Row-major RGBA8 mips | implemented | [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) |
| Budgeted staged RGBA8 upload | implemented | `MetalRgba8Texture::upload_staged`, [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) |
| Pitched, layer-major BC uploads (one pitch for every mip, padded slices) | implemented for BC1–BC5 | [`crates/texture/src/upload.rs`](../../crates/texture/src/upload.rs) |
| Per-subresource packed footprints for block-compressed mip chains (tight or aligned rows) | layout implemented for BC1–BC7; native readback covers BC1–BC5 (#241, PR #278) | [`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs), [`crates/texture/tests/bc_footprint.rs`](../../crates/texture/tests/bc_footprint.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs) |
| The synthetic 2×2-tile BC1 layout | implemented; defined by the project's fixtures, not by any console | [`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs) |
| Desktop RDNA 2 surface tiling (swizzle modes) | unknown; not researched in this repository | — |
| Console texture memory layouts | unknown; no public source reviewed | — |
## Public specifications
These are the primary sources the implementations above cite. The format rows already name them in their source files.
- [Khronos Data Format Specification 1.3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html): the [S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) section (BC1–BC3), the [RGTC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#RGTC) section (BC4, BC5), section 20.1 ["BC7"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) and section 20.2 ["BC6H"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h).
- Microsoft Direct3D documentation: ["Texture Block Compression in Direct3D 11"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11), ["Block Compression (Direct3D 10)"](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression), ["BC6H Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) and ["BC7 Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format). These are used for the format definitions and DXGI format codes, not for console behaviour.
- Apple Metal documentation: [`MTLPixelFormat`](https://developer.apple.com/documentation/metal/mtlpixelformat) and [`MTLDevice.supportsBCTextureCompression`](https://developer.apple.com/documentation/metal/mtldevice/supportsbctexturecompression), for the native pixel formats and the capability check.
- AMD "RDNA 2" Instruction Set Architecture reference guide ([GPUOpen architecture documentation](https://gpuopen.com/amd-gpu-architecture-programming-documentation/)): MIMG instructions such as `image_sample_lz`, and the image resource and sampler descriptor formats. These cover desktop gfx1030 only. [Xbox GPU evidence](xbox-gpu.md) records why desktop statements do not transfer to the console without separate evidence.
## Unknowns
These are research questions, not missing features:
- **Console texture memory layouts and tiling.** No public specification has been reviewed. Desktop RDNA 2 tiling would be a separate research note and would still not establish console behaviour.
- **Console resource descriptor formats.** Unknown. See [Xbox GPU evidence](xbox-gpu.md), which lists descriptor layout among the unresolved items.
- **Asset and audio containers.** BetterXen parses none. The runtime's audio path accepts only raw PCM (`XENORA_AUDIO_FORMAT_PCM_S16LE` and `PCM_F32LE` in [`crates/ffi/include/xenora.h`](../../crates/ffi/include/xenora.h)). No original workload has shown a need for a container or a compressed audio format.
## Follow-ups
Ranked by how close each is to existing tested paths. The first item is already tracked; the others are proposals, so do not start them without an issue and a claim.
1. **BC6H two-subset modes and native BC6H/BC7.** Tracked in #208 (CPU decode, with an archived request to take it) and #209 (native upload and readback, whose imported proposal waits for maintainer approval). BC6H and BC7 already have packed footprints, so #209 can build on `PackedBcUpload`. Do not duplicate them.
2. **Translated sampling of BC2–BC5.**
- Fixture: original blocks with hand-chosen endpoints and indices, sampled by the existing `image_sample_lz` pixel stage.
- Expected values: derived by hand from the Khronos tables. The `bc.rs` decoders must not produce them, so that the decoder and the reference stay independent.
- Owners: Metal and Compiler.
3. **Additional sampler state** (linear filtering, wrap and mirror addressing).
- Fixture: a small original RGBA8 texture with distinct texels.
- Expected values: from the public Direct3D and Metal sampling equations, computed in exact fractions.
- Owners: Metal and Compiler.
4. **Desktop RDNA 2 image resource descriptor decoding.** Needed before guest-supplied descriptors can select formats.
- Fixture: original descriptor words for each supported format.
- Expected values: from the AMD RDNA 2 ISA guide's descriptor tables.
- Owner: ISA.
- This does not cover console descriptors.
Deferred, with no demonstrated need:
- BC7 sRGB
- DDS and KTX containers
- ASTC and ETC (not part of the desktop Direct3D 12 BC set this target uses)
- any compressed audio format
- console tiling, until a public source exists
+171 -5
View File
@@ -1,9 +1,10 @@
# CPU test runtime and shard selection
# CPU test runtime, shards and coverage map
This page records what the CPU test gate costs and describes
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards. The
shards are a convenience for local iteration and parallel runners. They do not
replace any gate: `cargo test --locked --workspace` stays the full CPU gate, and
This page records what the CPU test gate costs, describes
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards, and
maps which x86-64 and loader behavior the tests verify. The shards are a
convenience for local iteration and parallel runners. They do not replace any
gate: `cargo test --locked --workspace` stays the full CPU gate, and
`scripts/test-gpu.sh` stays the GPU gate.
## What counts as a CPU test
@@ -96,3 +97,168 @@ than the full gate, because each target pays Cargo start-up.
different commits are not comparable.
- The experiment workspace `experiments/x1` is outside the selection. CI runs
it separately.
## CPU and loader coverage map
This map inventories what the CPU and loader tests verify, per operation
family, with the exact evidence commands and counts behind every number. It is
documentation of verified state, not a compatibility claim, and it contains no
percentages: every figure below is a count that a recorded command produced on
one machine. The behavioral rules behind the map (how forms are declared, what
"implemented" means, which forms are rejected on purpose) are documented in
[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and are not
repeated here except where the map adds evidence.
### Method and revision
All commands ran on Apple M5, macOS 26.6.2, native arm64, Rust
`1.100.0-aarch64-apple-darwin` (the revision CI pins), `CARGO_BUILD_JOBS=2`,
on the branch holding this change, based on upstream `main` at
`67b8cff` (2026-11-25).
Recorded evidence commands:
```sh
python3 crates/loader/generate_x86.py validate # 213 operations, 403 forms, 498 opcode slots
python3 crates/loader/generate_x86.py --check # x86_table.rs is fresh
PYTHONPATH=scripts python3 -m qa cpu-inventory # advisory partitions, cross-checked below
cargo test --locked --workspace # 116 result lines: 1015 passed, 0 failed, 34 ignored
```
The registry numbers are the generator's own count, not a hand count. The
advisory `qa cpu-inventory` output was cross-checked against the code before
use, and one stale row is called out under "Intentionally rejected forms".
The default run recorded 34 ignored tests.
| Count | Category | Files |
| --- | --- | --- |
| 26 | Native Metal correctness | Five in `crates/loader/tests/` (`dbt_render.rs`, `graphics_d3d12.rs`, `graphics_textures.rs`, `runtime_x15.rs`), seven in `tests/validation/known_answers.rs`, and fourteen across `tests/validation/tests/` (`operand_domains.rs`, `sop1_unary.rs`, `sop2_arith.rs`, `sop2_stage_c.rs`, `sopc_stage_d.rs`, `sopk.rs`, `vop1_integer.rs`, `vop2_integer.rs`, `vop2_vcc.rs`, `vop3_compare.rs`, `vop3_integer.rs`, `vopc_f_t.rs`, `vopc_wide.rs`). |
| 5 | LLVM AMDGPU oracle | Two in `crates/decoder/tests/gfx1030.rs` and one each in `crates/isa/tests/extension_word_negative.rs`, `meta_corpus.rs` and `meta_llvm.rs`. |
| 3 | Manual CPU timing | Warm guest memory in `crates/loader/src/memory.rs`, relocation in `crates/loader/src/reloc.rs` and TLS templates in `crates/loader/src/tls.rs`. |
The two manual GPU timing tests in `crates/metal/tests/native_compute.rs`
are outside these totals. Cargo requires the `gpu-tests` feature to build
that target.
### Declared instruction inventory
`crates/loader/x86/instructions.toml` declares the decodable x86-64 surface.
`generate_x86.py validate` reports **213 operations, 403 forms, 498 opcode
slots** at this revision. By opcode map the slots split 235 one-byte and 263
`0F`; by mandatory prefix 352 none, 107 `66`, 16 `F2`, 23 `F3`; by operand size
96 byte (`b`), 139 variable 16/32/64 (`v`), 160 XMM 16-byte (`x`), 58 no
operand (`n`), 22 32/64-only (`y`), 23 64-bit (`q`).
A declared form is decodable, not implemented. A form counts as supported only
when it has semantics and fixture evidence. The fixture half is enforced:
`every_declared_form_is_executed_by_a_fixture` in
`crates/loader/tests/x86_integer.rs` decodes every line of the three assembly
corpora (`tests/x86/integer.txt`, `vector.txt`, `float.txt`) and fails if any
declared form is never executed. It lists the operations that are covered
elsewhere instead (control flow and exits, `LDMXCSR`, and the
`MOVS`/`STOS`/`CLD`/`STD` string family, which need their own memory layout and
are covered form by form in `tests/cpu_rep.rs` and the loop tests).
### Engine path per operation
Of the 213 declared operations, **93 have at least one ARM64-lowered form**.
Some other forms of those operations still use the shared interpreter helper.
**119 operations use the helper for every translated form**, and **one**,
`SYSCALL`, is decoded but refused by `is_translatable` in the DBT. Helper
calls count toward `DbtMetrics::interpreter_fallbacks`. The conditional gates
in `is_native` in `crates/loader/src/dbt.rs` apply at form level.
- `ADD`, `SUB`, `CMP`, `AND`, `OR`, `XOR`, `TEST`, `INC`, `DEC`, `NEG`, `NOT`
and `CMOV` are native only at 32- and 64-bit width; 8- and 16-bit forms use
the shared semantics.
- `ADC` and `SBB` are native only for register and immediate operands; a memory
destination stays on the helper path.
- `BT` is native only in the `0F A3` register-index form; the `0F BA /4`
immediate-index form can read a memory operand and uses the helper.
- `BSF` and `BSR` are native at 16/32/64-bit width.
- `POP` is native only in the opcode-register form.
`tests/x86_integer.rs` asserts the split both ways for every fixture: native
forms must never call the helper, and helper forms always must. The interpreter
runs all 213 operations through the shared semantics.
### Test evidence by artifact
Counts are from the full gate run recorded above (target name, tests run,
passed/ignored). Expectation sources are named so independence can be judged.
| Artifact (under `crates/loader/tests/`) | Expectations derived from | Run result |
| --- | --- | --- |
| `x86_integer.rs` + `x86/integer.txt` (1230 fixture lines) | LLVM-assembled encodings; byte-level references written from the SDM/APM operation text, independent of the production semantics | 16 passed, 0 failed |
| `x86_vector.rs` + `x86/vector.txt` (374 lines) | same method, SSE2 packed forms | 9 passed |
| `x86_float.rs` + `x86/float.txt` (172), `x86/float_vectors.txt` (6824), `x86/float_reference.py` | exact-fraction reference computed by script, following SDM Vol. 1 floating-point rules | 9 passed |
| `cpu_known_answers.rs` (50 tests, 838 named case lines) | Intel SDM and AMD APM sections cited per case; both engines run each case | 50 passed, 0 ignored |
| `movsxd.rs` | SDM operation text; modular arithmetic in the test; LLVM-assembled encodings | 9 passed |
| `x86_atomic.rs` | SDM LOCK/XADD/CMPXCHG rules; both compare outcomes, unaligned operands, faults | 5 passed |
| `x86_carry_chain.rs` | widening `u128`/`i128` reference arithmetic on 256-bit chains | 8 passed |
| `x86_prefix_length.rs` | SDM prefix and length rules | 8 passed |
| `cpu_loop.rs` | a loop-model reference over every count, match point and budget | 3 passed |
| `cpu_rep.rs` | a byte-array model over every MOVS/STOS form, direction and count, plus step accounting and faults | 7 passed |
| `cpu_features.rs` | CPUID feature-bit pairing per the SDM; each reported bit requires the feature's fixtures, each commonly-tested unreported bit requires a refused witness | 4 passed |
| `cpu_differential.rs` | interpreter and DBT must agree on shared fixtures | 5 passed |
| `arm64_encodings.rs` | LLVM encodings for the assembler's emitted ARM64 | 3 passed |
| `memory_page_boundaries.rs`, `memory_validation.rs` | mapping/permission/boundary contracts | 8 + 9 passed |
| `generated_conformance.rs`, `bootstrap.rs`, `gate_a1.rs`, `gate_a2.rs`, `indirect_control.rs`, `bswap.rs`, `dbt_render.rs`, `process_exit.rs` | per-file documented contracts (generated conformance vectors, startup gates, control flow) | all passed except one Metal-gated ignore in `dbt_render.rs` |
Count named known-answer rows, including both byte-encoded and decoded cases,
with the following command. This excludes section directives, format comments
and Rust match arms.
```sh
rg -c '^[A-Za-z0-9_]+:.*=>' crates/loader/tests/cpu_known_answers.rs
```
The cache revalidation change in [PR #269](https://github.com/MacosPorters/betterxen/pull/269)
restored `dbt_executes_modified_code_after_a_jump`. It passed in this run,
and `cpu_known_answers.rs` reported 50 passes and zero ignores.
### Operations covered by model tests instead of the fixture corpus
The mnemonic-level fixture scan behind the advisory
`PYTHONPATH=scripts python3 -m qa cpu-inventory` reports no assembly-text
fixture for eight operations: `cld`, `std`, `jrcxz`, `loop`, `loope`,
`loopne`, `movs`, `stos`. That is by design, not a gap: those operations need
their own memory layout or counter model and are covered form by form in
`tests/cpu_rep.rs` (MOVS/STOS/REP, the direction flag set by `STD` and cleared
by `CLD`) and `tests/cpu_loop.rs` (LOOP/LOOPE/LOOPNE, JRCXZ on zero RCX). The
declared-form enforcement test also exempts `LDMXCSR`, `Jcc`, `JMP`,
`CALL`, `RET`, `HLT` and `SYSCALL`. It checks the remaining forms against the
corpora.
### Intentionally rejected forms
The rejection list with its scope rules (LOCK limited to the memory forms of
XADD and CMPXCHG, every x87 instruction except FNINIT,
LODS/CMPS/SCAS/REPE/REPNE, MMX, RCP/RSQRT approximations, SSE3 and later,
VEX, address-size overrides, 16-bit stack/branch forms, 16-bit BSWAP and
MOVSXD, bit tests of memory by register index, CMPXCHG8B/16B, and the DBT
refusing raw SYSCALL) is maintained in
[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and is
tested by refusal cases inside the files above; this map does not duplicate it.
One advisory-tool discrepancy is recorded for its owner: the hand-written
`unsupported_catalog` in `scripts/qa/cpu_inventory.py` lists "RCL/RCR/SHLD/
SHRD", "string instructions" and "atomics/fences", which is stale against the
code and tests at this revision — RCL/RCR/SHLD/SHRD are declared registry
forms with implemented semantics (`x86_exec.rs`), 9 named `rcl*` cases and 8 named `shld*` or `shrd*` cases using the rule above,
and 72 SHLD/SHRD assembly fixture lines; MOVS/STOS and the
LOCK forms of XADD/CMPXCHG and the fences are supported within the documented
scope. The catalog is advisory only and does not feed any gate.
### Map limitations
- Every count is pinned to the revision, host and single run named above.
- The fixture evidence is mnemonic-level where it comes from the assembly
corpora: it proves every declared form executes somewhere, not that every
encoding variant of a form has its own expected-value case. The known-answer
files carry the per-case expectations; their case lines are counted, not
audited one by one here.
- The native/shared partition is read from `is_native` at this revision and
asserted by the fixtures; it is not a promise for other revisions.
- Nothing here was compared with x86 hardware, no compatibility percentage is
implied, and this is local documentation evidence, not independent
acceptance.
+1 -1
View File
@@ -48,7 +48,7 @@ separate backend evidence. The [host evidence](../research/host-lab.md) records
| Gate | Baseline disposition |
| --- | --- |
| P2-01 | Baseline captured. Phase 01 evidence and blockers are linked above. |
| P2-02 | KyTx, Leonida and eight additional projects screened. Original fixtures and public specifications are the implementation source. No emulator code, tables or metadata are in scope for adoption. |
| P2-02 | KyTx, PE-Vulkan project and eight additional projects screened. Original fixtures and public specifications are the implementation source. No emulator code, tables or metadata are in scope for adoption. |
| P2-03 | VGPR-only OR verified on Apple M5. |
| P2-04 | Workspace, LLVM and native GPU regression runs passed after OR integration. |
| P2-05 | Independent OR expected values matched CPU execution and Metal readback. |
+5 -5
View File
@@ -8,7 +8,7 @@ limit. A CPU rejection pass does not certify GPU execution.
| Upstream reference | Tested behavior | Xenora equivalent | Current result | Blocker |
| --- | --- | --- | --- | --- |
| [Leonida compute](https://github.com/ItsNotRexed/Leonida/blob/3faac557b1584d39004357918e60325b4d4ff0fe/runtime/test/d3d12_compute_test.cpp) | Vulkan replay submits three distinct bindings and compares every readback word. Null, denied, malformed and out-of-bounds views decode to zero descriptors in separate controls. | Guest buffer view and original XOR readback. Persistent lifetime and snapshot tests extend this gate. | PASS for X8 view and readback | Xenora uses explicit faults for bad views. |
| [PE-Vulkan project compute](https://github.com/ItsNotRexed/Leonida/blob/3faac557b1584d39004357918e60325b4d4ff0fe/runtime/test/d3d12_compute_test.cpp) | Vulkan replay submits three distinct bindings and compares every readback word. Null, denied, malformed and out-of-bounds views decode to zero descriptors in separate controls. | Guest buffer view and original XOR readback. Persistent lifetime and snapshot tests extend this gate. | PASS for X8 view and readback | Xenora uses explicit faults for bad views. |
| [Xbox2Windows startup](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/cpu/startup_exe.cpp) | CPU startup exercises loading two DLLs, thread notifications and wait failures. | Original named-import PE32+ startup and missing import control. DLL and thread-local storage ordering are separate gates. | UNIMPLEMENTED for DLL and thread ordering | Bounded fixed-base guest profile. |
| [Xbox2Windows wave shuffle](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/wave_shuffle.cpp) | D3D12 dispatch maps output by reported wave and lane, checks affine and rotation shuffles plus mirror and uniform controls, and rejects duplicate lanes or wrong widths. Forced variants require device capability. | ARM64 CPU compiler rejects an original gfx1030 cross-lane permute with a supported compile control. Native Wave64 shuffle needs a two-wave exact oracle. | PASS for rejection. UNIMPLEMENTED for Wave64 Metal dispatch. | No cross-lane lowering or Wave64 execution contract. |
| [Xbox2Windows compute services](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/cpu/shim_compute_check.py) | Checks allocation, dispatch and free observations. Independently calculates four readback words. Provider rejection must produce zero output bytes. Native hardware is selected for the explicit hardware case. | Exact guest XOR readback, invalid import commands and observable destroy/reuse. | PASS for X8 XOR and malformed commands | Persistent resources have a separate X9 gate. |
@@ -57,9 +57,9 @@ data sections, and no native host pointer crosses that boundary.
| Upstream reference | Tested behavior | Xenora equivalent | Current result | Blocker |
| --- | --- | --- | --- | --- |
| Leonida compute and Xbox2Windows compute services | Repeat dispatch, update and release a resource with observable results | Original X9 PE repeats XOR with a nonzero view, updates words and destroys and reuses a slot. | PASS on Apple M5 | Device buffers are uploaded per completion. |
| Leonida compute | Submission bindings and lifetime are independent of later changes | X9 queues a view, changes or destroys its owner and still gets the captured output. A second queued submission is rejected. | PASS on Apple M5 for queued snapshots | Actual GPU work already in flight during release is UNIMPLEMENTED. |
| Leonida compute | Isolate guest runs and release resources at exit | X9 drops the table and any queued view at guest return. A queued-work exit returns guest status 73 and produces no GPU commands for that submission. | PASS for queued-work exit | Native Metal object residency across guest calls is UNIMPLEMENTED. |
| Leonida compute | Reject malformed resource ranges | X9 rejects invalid or stale handles, out-of-range views, offset overflow, writeback into read-only memory and invalid resource types. | PASS for guest fault controls | The guest profile exposes one bounded submission at a time. |
| PE-Vulkan project compute and Xbox2Windows compute services | Repeat dispatch, update and release a resource with observable results | Original X9 PE repeats XOR with a nonzero view, updates words and destroys and reuses a slot. | PASS on Apple M5 | Device buffers are uploaded per completion. |
| PE-Vulkan project compute | Submission bindings and lifetime are independent of later changes | X9 queues a view, changes or destroys its owner and still gets the captured output. A second queued submission is rejected. | PASS on Apple M5 for queued snapshots | Actual GPU work already in flight during release is UNIMPLEMENTED. |
| PE-Vulkan project compute | Isolate guest runs and release resources at exit | X9 drops the table and any queued view at guest return. A queued-work exit returns guest status 73 and produces no GPU commands for that submission. | PASS for queued-work exit | Native Metal object residency across guest calls is UNIMPLEMENTED. |
| PE-Vulkan project compute | Reject malformed resource ranges | X9 rejects invalid or stale handles, out-of-range views, offset overflow, writeback into read-only memory and invalid resource types. | PASS for guest fault controls | The guest profile exposes one bounded submission at a time. |
| Xbox2Windows pixel attributes | GPU pixels agree with a CPU expectation | X9 renders a constant or perspective-interpolated triangle through both translated stages. The PE checks every returned pixel. A separate host oracle checks exact values and the guest report. Changing the expected red byte of one interior pixel makes the PE return 93 after the same GPU readback. | PASS on Apple M5 | Shader selection uses original fixed fixture IDs. |
| bcpack-rs round trips and Xbox2Windows texture LOD | Edge data and malformed input distinguish valid subresources | X9 validates a pitched descriptor, rejects wrong usage, layer, size and update requests, and reads selected BC1 mips and layers back through Metal. | PASS on Apple M5 for selected subresource readback | Translated texture sampling and GPU texture lifetime across guest calls are UNIMPLEMENTED. |
+1 -1
View File
@@ -6,7 +6,7 @@ identified the arithmetic shift as a candidate. Xenora uses the public
and its existing pinned AMD XML generator for the VOP2 encoding. The lowering
uses signed integer shift from the
[Metal Shading Language Specification](https://developer.apple.com/metal/Metal-Shading-Language-Specification).
The implementation and fixture were authored in Xenora. No Leonida code, tables,
The implementation and fixture were authored in Xenora. No PE-Vulkan project code, tables,
dependencies or game material were imported.
The decoder accepts the VOP2 VGPR/VGPR form. The shader lifter retains the synthetic
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Fast, deterministic documentation and repository hygiene checks.
Checks only tracked files:
1. no merge-conflict markers in tracked text files;
2. every relative Markdown link points at a tracked file or directory;
3. every workflow file under .github/workflows parses as YAML.
External URLs and in-page anchors are not fetched or validated, so the result
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
when PyYAML is missing.
"""
import re
import subprocess
import sys
from pathlib import Path, PurePosixPath
from urllib.parse import unquote
ROOT = Path(__file__).resolve().parents[2]
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
FENCE = re.compile(r"^\s*(```|~~~)")
def tracked():
out = subprocess.run(["git", "ls-files", "-z"], cwd=ROOT, check=True,
capture_output=True).stdout.decode("utf-8", "replace")
return [p for p in out.split("\0") if p and (ROOT / p).is_file()]
def text(path):
data = (ROOT / path).read_bytes()
if b"\0" in data:
return None
return data.decode("utf-8", "replace")
def check_markers(files, problems):
for path in files:
if path.endswith((".patch", ".diff")):
continue
body = text(path)
if body is None:
continue
for number, line in enumerate(body.splitlines(), 1):
if MARKER.match(line):
problems.append(f"{path}:{number}: merge conflict marker")
def check_links(files, problems):
known = set(files)
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
for path in files:
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
continue
in_fence = False
for number, line in enumerate((text(path) or "").splitlines(), 1):
if FENCE.match(line):
in_fence = not in_fence
continue
if in_fence:
continue
line = re.sub(r"`[^`]*`", "", line)
for target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
continue
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
if not target:
continue
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
norm = "/".join(parts)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
def check_workflows(files, problems, require_yaml):
try:
import yaml
except ImportError:
if require_yaml:
problems.append("PyYAML is not installed but --require-yaml was given")
else:
print("note: PyYAML not installed; workflow YAML parse check skipped", file=sys.stderr)
return
for path in files:
if path.startswith(".github/workflows/") and path.endswith((".yml", ".yaml")):
try:
yaml.safe_load((ROOT / path).read_text(encoding="utf-8"))
except yaml.YAMLError as err:
problems.append(f"{path}: invalid YAML: {str(err).splitlines()[0]}")
def main():
files = tracked()
problems = []
check_markers(files, problems)
check_links(files, problems)
check_workflows(files, problems, "--require-yaml" in sys.argv[1:])
for problem in problems:
print(problem)
print(f"docs hygiene: {len(files)} tracked files checked, {len(problems)} problem(s)")
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
+19
View File
@@ -54,5 +54,24 @@ codesign --force --sign - "$bundle"
binary="$bundle/Contents/MacOS/BetterXen"
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
file "$binary"
# Only system libraries may be linked: anything else would be a host dependency
# shipped or expected outside macOS, which this bundle does not carry. List the
# dependencies once, print that listing and check the same output.
dependencies=$(otool -L "$binary") || fail "otool -L failed for $binary"
printf '%s\n' "$dependencies"
dependencies=$(printf '%s\n' "$dependencies" | tail -n +2 | awk '{print $1}')
# Every Swift executable links at least libSystem, so an empty list is an error.
[ -n "$dependencies" ] || fail "otool -L listed no dependencies for $binary"
for dependency in $dependencies; do
case "$dependency" in
/System/Library/*|/usr/lib/*) ;;
@rpath/*|@executable_path/*|@loader_path/*)
fail "executable links a bundle-relative library, but this bundle ships none: $dependency" ;;
*) fail "executable links a non-system library: $dependency" ;;
esac
done
"$binary" --smoke
"$binary" --smoke-inspection-order
"$binary" --smoke-import-result
echo "build-app: built $bundle"
-105
View File
@@ -1,105 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Check that a pull request description follows .github/PULL_REQUEST_TEMPLATE.md.
Standard library only. The description is read as data from the GitHub event
file (or a plain text file with --body-file); it is never executed.
Exit status 0 when the description passes, 1 when something is missing.
"""
import argparse
import json
import re
import sys
SECTIONS = (
"Summary",
"Implementation and evidence",
"Verification",
"Compatibility and limitations",
"Checklist",
"AI assistance",
)
# Checklist items that must be ticked, found by the start of their text.
REQUIRED_TICKS = (
("I claimed the linked issue", "the claimed-first checkbox"),
("My commits are signed off under the DCO", "the DCO sign-off checkbox"),
)
ISSUE_LINK = re.compile(r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#\d+", re.I)
NO_ISSUE = re.compile(r"^\s*No linked issue:\s*\S", re.I | re.M)
COMMENT = re.compile(r"<!--.*?-->", re.S)
EMPTY_LINK = re.compile(r"^\s*(?:close|fix|resolve)\w*\s*#\s*$", re.I)
HEADING = re.compile(r"^##\s+(.+?)\s*$", re.M)
def sections(body):
"""Map each level-2 heading to its text, with HTML comments removed."""
text = COMMENT.sub("", body.replace("\r\n", "\n"))
found = {}
marks = list(HEADING.finditer(text))
for i, m in enumerate(marks):
end = marks[i + 1].start() if i + 1 < len(marks) else len(text)
found[m.group(1).strip().lower()] = text[m.end():end].strip()
return text, found
def has_content(name, value):
if name == "Verification":
# The empty table from the template does not count: some cell must be filled.
rows = [r for r in value.splitlines() if r.strip().startswith("|")]
filled = [r for r in rows[2:] if [c for c in r.strip().strip("|").split("|")[1:] if c.strip()]]
prose = [r for r in value.splitlines() if r.strip() and not r.strip().startswith("|")]
return bool(filled or prose)
if name == "Checklist":
return "- [" in value
# A bare "Closes #" left over from the template is not content.
rest = [l for l in value.splitlines() if l.strip() and not EMPTY_LINK.match(l)]
return bool(rest)
def check(body):
"""Return a list of human-readable problems; empty means the body passes."""
if not body or not body.strip():
return ["The description is empty. Copy .github/PULL_REQUEST_TEMPLATE.md into it and fill it in."]
text, found = sections(body)
problems = []
for name in SECTIONS:
if name.lower() not in found:
problems.append('Missing section "## %s".' % name)
elif not has_content(name, found[name.lower()]):
problems.append('Section "## %s" is empty.' % name)
if not ISSUE_LINK.search(text) and not NO_ISSUE.search(text):
problems.append('No linked issue: add "Closes #<number>", or a line "No linked issue: <reason>".')
checklist = found.get("checklist", "")
for prefix, label in REQUIRED_TICKS:
item = re.search(r"^\s*[-*]\s*\[( |x|X)\]\s*" + re.escape(prefix), checklist, re.M)
if not item:
problems.append("Checklist is missing %s." % label)
elif item.group(1) == " ":
problems.append("Tick %s." % label)
return problems
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__)
src = ap.add_mutually_exclusive_group(required=True)
src.add_argument("--event", help="GitHub event JSON file (pull_request or pull_request_target)")
src.add_argument("--body-file", help="file holding the description text")
args = ap.parse_args(argv)
if args.event:
with open(args.event, encoding="utf-8") as fh:
body = (json.load(fh).get("pull_request") or {}).get("body") or ""
else:
with open(args.body_file, encoding="utf-8") as fh:
body = fh.read()
problems = check(body)
if problems:
print("The pull request description does not follow .github/PULL_REQUEST_TEMPLATE.md:")
for p in problems:
print("- " + p)
print("Edit the description to fix this; the check runs again on every edit.")
return 1
print("The pull request description follows the template.")
return 0
if __name__ == "__main__":
sys.exit(main())
+90
View File
@@ -0,0 +1,90 @@
# Original AVX integer fixture specification
This fixture is a proposed known-answer test for the
[guest AVX contract](../../../docs/cpu/avx-contract.md). It uses only the
source below, fixed register values and synthetic guest memory. Run the
eventual fixture in both guest engines on fresh copies of the same initial
state. Use the independent expected values below for each engine.
## Guest sequence
Set `r8` and `r9` to separate readable ranges containing arrays A and B.
Set `r10` to a writable 96-byte output region initialized to `0xA5` with
mapped sentinel bytes before and after it. Map the code separately as guest
executable memory. Initialize flags, MXCSR and untouched vector registers to
known nonzero values, then record their initial values. The sequence uses no
stack, imports or host calls.
```asm
.intel_syntax noprefix
.text
vmovdqu ymm1, ymmword ptr [r8]
vmovdqu ymm2, ymmword ptr [r9]
vpaddd ymm3, ymm1, ymm2
vmovdqu ymmword ptr [r10], ymm3
movdqu xmm3, xmm1
vmovdqu ymmword ptr [r10 + 32], ymm3
vmovdqu xmm3, xmm2
vmovdqu ymmword ptr [r10 + 64], ymm3
hlt
```
The high base registers require three-byte VEX for the memory moves, while
the low-register `VPADDD` and register `VMOVDQU` can use two-byte VEX.
Store each table row as eight little-endian 32-bit words, with lane 0 at
the lowest address. All entries are hexadecimal.
| Words | Lane 0 | Lane 1 | Lane 2 | Lane 3 | Lane 4 | Lane 5 | Lane 6 | Lane 7 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| A | `ffffffff` | `7fffffff` | `80000000` | `00000000` | `00000010` | `fffffffe` | `12345678` | `aaaaaaaa` |
| B | `00000001` | `00000001` | `80000000` | `ffffffff` | `00000020` | `00000003` | `11111111` | `55555556` |
| Output +0 | `00000000` | `80000000` | `00000000` | `ffffffff` | `00000030` | `00000001` | `23456789` | `00000000` |
| Output +32 | `ffffffff` | `7fffffff` | `80000000` | `00000000` | `00000030` | `00000001` | `23456789` | `00000000` |
| Output +64 | `00000001` | `00000001` | `80000000` | `ffffffff` | `00000000` | `00000000` | `00000000` | `00000000` |
For output +0, add corresponding words as unsigned integers and discard
bits above bit 31 in each sum. For example, lane 0 wraps `0x100000000` to
zero, so lane 1 has no incoming carry. At +32, the legacy move replaces the
low four words with A and retains the high four words of the sum. At +64,
the VEX.128 move replaces the low four words with B and clears the high
four. Final YMM1 and YMM2 equal A and B. Final YMM3 equals output +64.
All other vector registers, the input bytes, sentinels, general-purpose
registers, flags and MXCSR retain their initial values. Expect `Halt` with
nine steps, including the terminal `HLT`.
## Controls
| Case | Expected result |
| --- | --- |
| `VPADDD` writes to one of its input registers | Same eight-word sum using both inputs as they stood before the instruction. The other source survives. |
| 128-bit `VPADDD` with seeded destination upper half | Output +0's low four words and four zero words. Both sources survive when distinct from the destination. |
| 128-bit `VMOVDQU` store with sentinels | Exactly the low 16 bytes are stored. The entire source YMM and memory outside the operand survive. |
| 256-bit `VMOVDQU` at a 32-byte-aligned address, at an address offset by one byte, and at `P-16` across adjacent accessible mappings | Same 32 bytes at each address. `P` is the start of the second mapping. |
| Split load at `P-16`, with the second mapping unreadable or unmapped | Memory fault at `P`. Every destination bit retains its pre-instruction value. |
| Split store at `P-16`, with the second mapping read-only or unmapped | Memory fault at `P`. The 16 writable bytes before `P` retain their sentinels. |
| 256-bit `VMOVDQU` load and store at `0x0000_7fff_ffff_fff0` | Map the first 16 bytes read/write and leave the noncanonical half starting at `0x0000_8000_0000_0000` unmapped. Both operations report `GeneralProtection` under the BetterXen profile. The destination register and the mapped bytes retain their original values. |
| 256-bit `VMOVDQU` load from `[rsp]` with `rsp = 0x0000_8000_0000_0000` | The BetterXen profile reports `GeneralProtection` and preserves the destination. Intel's Type 4 rules specify `#SS(0)` for this SS-based operand. |
| Future `VMOVDQA` at aligned and misaligned addresses | An aligned, permitted span transfers the same bytes. A span misaligned by one byte produces `GeneralProtection` and has no data effects. Run at both widths. |
| Future masked dword load from `P-16` | With only lanes 0–3 enabled, load four words and zero lanes 4–7 even if the mapping at `P` is absent. Enabling lane 4 faults at `P`. An all-zero mask reads no lanes and returns an all-zero destination. |
| Future masked dword store to the same split span | With only lanes 0–3 enabled, write those four words; disabled lanes neither access the second mapping nor alter any bytes there when it is mapped. Enabling lane 4 with its mapping absent faults at `P`. |
| Reserved move `vvvv`, reserved VEX map, prohibited prefix before VEX | Illegal instruction at the offending instruction's RIP. No destination or memory update. |
| Equivalent legal `C5` and `C4` register forms, including both `W` values for `WIG` | Equal results and state, with RIP advancement matching each encoding length. Include a high ModRM.reg destination and high `vvvv` source. |
| Budget of two steps | Stop at `VPADDD` (`entry + 0xA` with the encoding shown below) with both inputs loaded, YMM3 and output untouched. Resume with seven steps and reach the same final state as a nine-step run. Repeat with a warm DBT cache. |
For faults, place a completed instruction before the failing instruction.
Assert that only the earlier instruction retires and its effects persist.
Check snapshots of the full destination or nearby memory as appropriate.
## Build provenance
Use native Apple Silicon LLVM tools to assemble the sequence as an x86-64
object, for example with `xcrun clang -arch x86_64 -c avx-fixture.s`.
Verify the resolved Clang and `llvm-objdump` executables support ARM64 before
running them. Record their versions and the output of disassembling the
object. Apple Clang 21.0.0 emits `C4 C1 7E 6F 08` for the first load and
`C5 F5 FE DA` for `VPADDD` at offset `0xA`. Keep generated sources and
objects under ignored `artifacts/`.
The test harness consumes only the object's verified instruction bytes
as guest data. Reserved encodings can be authored separately from Intel's
bit-field tables, since an assembler may reject them. Use source-derived
lane values and checked-memory expectations for the test oracle.
-99
View File
@@ -1,99 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import subprocess
import sys
import tempfile
import unittest
import pr_template_check as c
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
TEMPLATE = open(os.path.join(ROOT, ".github", "PULL_REQUEST_TEMPLATE.md"), encoding="utf-8").read()
GOOD = """## Summary
Adds X.
Closes #12
## Implementation and evidence
Touches crates/texture only.
## Verification
| Check | Result / evidence |
| --- | --- |
| Formatting and lint | cargo fmt --check: clean |
| Unit / integration tests | cargo test -p xenora-texture: 40 passed |
## Compatibility and limitations
None known.
## Checklist
- [x] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
- [x] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [x] My commits are signed off under the DCO.
## AI assistance
None.
"""
class Check(unittest.TestCase):
def test_good_body_passes(self):
self.assertEqual(c.check(GOOD), [])
def test_unfilled_template_fails_on_every_rule(self):
problems = c.check(TEMPLATE)
text = "\n".join(problems)
for want in ('"## Summary" is empty', '"## Implementation and evidence" is empty',
'"## Verification" is empty', '"## Compatibility and limitations" is empty',
'"## AI assistance" is empty', "No linked issue", "claimed-first", "DCO"):
self.assertIn(want, text)
def test_empty_and_freeform_bodies_fail(self):
self.assertTrue(c.check(""))
self.assertTrue(c.check("Fixes a bug. Closes #3"))
def test_missing_section_is_named(self):
body = GOOD.replace("## Compatibility and limitations\n\nNone known.\n", "")
self.assertEqual(c.check(body), ['Missing section "## Compatibility and limitations".'])
def test_unticked_boxes_fail(self):
body = GOOD.replace("- [x] I claimed", "- [ ] I claimed").replace("- [x] My commits", "- [ ] My commits")
problems = c.check(body)
self.assertEqual(len(problems), 2)
self.assertIn("claimed-first", problems[0])
self.assertIn("DCO", problems[1])
def test_issue_link_forms(self):
for link in ("Fixes #4", "resolves #4", "Closed #4", "No linked issue: requested by the maintainer"):
self.assertEqual(c.check(GOOD.replace("Closes #12", link)), [], link)
self.assertIn("No linked issue", "\n".join(c.check(GOOD.replace("Closes #12", "See issue 12"))))
def test_link_inside_comment_does_not_count(self):
self.assertTrue(c.check(GOOD.replace("Closes #12", "<!-- Closes #12 -->")))
def test_new_claim_checkbox_wording_passes(self):
body = GOOD.replace("I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.",
"I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.")
self.assertEqual(c.check(body), [])
def test_cli_exit_codes_from_event_file(self):
script = os.path.join(ROOT, "scripts", "pr_template_check.py")
with tempfile.TemporaryDirectory() as d:
for body, want in ((GOOD, 0), (TEMPLATE, 1), (None, 1)):
path = os.path.join(d, "event.json")
with open(path, "w", encoding="utf-8") as fh:
json.dump({"pull_request": {"body": body}}, fh)
run = subprocess.run([sys.executable, script, "--event", path], capture_output=True, text=True)
self.assertEqual(run.returncode, want, run.stdout)
if __name__ == "__main__":
unittest.main()