Compare commits

..
Author SHA1 Message Date
atharvranjan ded1371b99 Correct the GPU-executed test counts in the victory-shader record using libtest JSON output 2026-11-25 15:36:33 -06:00
atharvranjan 6cebcc559e Add the shader GPU test runner script and the victory-shader integration record 2026-11-25 15:22:19 -06:00
atharvranjan 790061e7c0 Vendor victory-shader (GFX10 to DXIL recompiler) from skakwy/victory-mac and add translate_native with BetterXen fixture tests 2026-11-25 15:22:19 -06:00
atharvranjan 8e5856bbcf Detect stalled runs, wait for memory to settle after a stop, and stop bottles through WINEPREFIX (#385) 2026-11-25 15:08:42 -06:00
atharvranjan 566272082a Record the first CrossOver 26.3 execution baseline, backend comparison and licence entry 2026-11-25 14:55:51 -06:00
atharvranjan 64ba56079f Add the D3D11 frame-loop workload, negative controls and reproducible workload builds 2026-11-25 14:55:51 -06:00
atharvranjan e266670e87 Add betterxen-hybrid run and bench: supervised CrossOver launches with structured records and backend comparison 2026-11-25 14:55:50 -06:00
atharvranjan 54b06fea3e Record the victory-mac component review, registry, reuse matrix and notices 2026-11-25 14:41:24 -06:00
atharvranjan 8eb25fb9fe Add original Windows workloads and a checksum-pinned llvm-mingw build script 2026-11-25 14:41:24 -06:00
atharvranjan 40ffea2789 Add betterxen-hybrid guard: memory-pressure supervisor adapted from skakwy's victory-mac memory guard 2026-11-25 14:41:24 -06:00
atharvranjan 80eacf9ac2 Add the betterxen-hybrid crate: host receipt, CrossOver discovery, toolchain probe and frame statistics 2026-11-25 14:33:22 -06:00
atharvranjan d9816e4cb5 Record the upstream integration audit and extend the registry and reuse matrix 2026-11-25 14:33:22 -06:00
112 changed files with 2852 additions and 1131 deletions

No files matched your search

+1 -2
View File
@@ -1,7 +1,6 @@
## Related issue
Closes #<number>, or state the direct maintainer assignment if no issue applies.
For stacked work, name the base PR and any dependencies absent from its base.
Closes #
## Summary
+102
View File
@@ -0,0 +1,102 @@
name: Agent PR checks
# Checks pull requests against the task queue: linked claimed task, file
# ownership, overlap with other open pull requests, and independent
# verification. Runs on the base branch only: pull request code is never checked
# out or executed; changed files come from the API. Not yet run on GitHub.
#
# Advisory: problems are reported as a warning and in the run summary, but the
# check does not fail until a live smoke test and the migration of existing
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
# with /verified starts the verify job; ordinary comments start nothing.
on:
pull_request_target:
types: [opened, synchronize, reopened, edited]
issue_comment:
types: [created]
permissions: {}
jobs:
check:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: read
pull-requests: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check pull request
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
verify:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
runs-on: ubuntu-24.04-arm
# issues: write posts the reply.
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and check again
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
# Check again only after an accepted verification of the current head: refused, stale,
# malformed or unauthorized /verified comments get a reply and nothing else.
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
# pull_request_target runs are recorded against the base branch, not the pull request
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check after verification'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
+3 -7
View File
@@ -1,6 +1,6 @@
# BetterXen engineering rules
These rules apply to every contributor and coding agent. They reflect the accepted CrossOver-based hybrid direction; earlier native-first instructions are historical. `CLAUDE.md` is a symlink to this file. The decision is recorded in `docs/adr/0005-crossover-hybrid-direction.md`; the plan is `docs/roadmap.md`.
These rules apply to every contributor and coding agent. They were rewritten on the `planning/hybrid-first-transition` branch when BetterXen moved from native-first to CrossOver-based hybrid development. `CLAUDE.md` is a symlink to this file. The decision is recorded in `docs/adr/0005-crossover-hybrid-direction.md`; the plan is `docs/roadmap.md`.
### Direction
@@ -63,11 +63,11 @@ These rules apply to every contributor and coding agent. They reflect the accept
No AI slop (section 29).
Read docs/roadmap.md, docs/architecture.md, docs/interfaces.md and docs/progress.md before implementation. Read crates/README.md and docs/testing/README.md for component scope and validation. Native contracts, generated coverage tables and historical gate checklists do not authorize native expansion or establish hybrid acceptance.
Read docs/roadmap.md, docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
Several people and coding agents work on this repository at the same time. For issue-based work, claim the issue before editing and never take work someone else has claimed. A direct maintainer task with no issue (including a documentation-only stacked PR) does not require creating an issue; record that assignment and scope in the PR and check overlapping open work.
Several people and coding agents work on this repository at the same time. Claim an issue before you edit anything, and never take work someone else has claimed.
1. **Check.** Read every comment on the issue and look for open pull requests that link it. A claim is any comment in which someone says they are taking the issue, in any words (for example "I'll take this" or `/claim`). If a claim exists and is not stale (step 4), pick another issue.
2. **Claim.** Reply on the issue in plain words, for example: "I'm taking this. Plan: …". No command, label or bot step is needed. The earliest claim wins. Claim one issue per comment.
@@ -100,10 +100,6 @@ A coding agent claims in the name of the person it works for and follows the sam
## Checkout commands
These maintain workspace regressions, including the paused native implementation.
They do not certify CrossOver execution. Hybrid checks and prerequisites are in
`docs/testing/README.md`; documentation-only changes use its documentation checks.
- Format: `cargo fmt --all -- --check`
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
- Test: `cargo test --workspace`
+12 -7
View File
@@ -10,10 +10,17 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Fixed the two wave-operation failures the vendored victory-shader tests showed under D3DMetal (`docs/research/shader-wave-semantics.md`). Device capabilities were measured with a new original D3D12 host (`workloads/d3d12-wave-probe`): shader model 6.6, wave operations, waves exactly 32 lanes, no double-precision shader operations. One failure was a wrong test precondition (a 64-lane lowering run on the 32-lane device); the test now checks the device width and asserts the recompiler's refusal. The other was unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` ran without writing anything, while float wave operations worked. The recompiler's one native-double site (`active_f64_sum`) now builds the console's balanced sum tree with its existing integer fp64 add and no longer declares doubles. Local results on one Apple M4 under CrossOver 26.3, not independently reproduced: the whole suite passes (229 passed, 3 ignored; the vendored original had 2 failures); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both regression tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer.
- Added `scripts/hybrid/run-shader-gpu-tests.sh`, which cross-builds the vendored `victory-shader` test executable for Windows and runs it under CrossOver through `betterxen-hybrid run` (supervision, memory guard, stall detection, JSON record), either BetterXen's four fixture tests or the whole upstream suite. It takes the test executable's path from cargo's own build message instead of guessing the target layout (the first version looked in `debug/build/.../out/`; the usual location is `debug/deps/`, which is the fallback). It needs the runner from #384 and #388. Verified on the Apple M4 with CrossOver 26.3: fixtures pass; the whole suite shows the known failures; the `debug/deps` fallback is untested on this machine, whose cargo layout puts the executable elsewhere. Not independently reviewed.
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and, on Windows targets, run them on the GPU through D3D12. Local results on one Apple M4 with CrossOver 26.3 (D3DMetal), not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed, 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. At that initial review, VIctory-family projects were excluded from reuse on provenance grounds; the subsequent shader-only snapshot has a separate component record above. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and run them on the Apple GPU through D3D12 under CrossOver 26.3 (D3DMetal), plus `scripts/hybrid/run-shader-gpu-tests.sh`, which runs them through `betterxen-hybrid run`. Local results on the M4, not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words (add, float-exact, bitwise-branch, or, shifts, ashr) matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed (wave-wide reductions), 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
- Added `--stall-timeout` and a memory-settle wait to `betterxen-hybrid run`/`bench` (#385): a run that prints nothing for the given time is stopped and classified `stalled`, and after any stop the supervisor waits (up to `--settle-bound`, default 60 s) until free memory is back above the start threshold and records whether it recovered. Based on supervision lessons from skakwy's victory-mac (reimplemented, not copied). Also fixes a defect found by the first real stall run: stopping a bottle used `CX_BOTTLE`, which does not select the bottle, so a stopped Windows process kept running; it now sets `WINEPREFIX`. Verified with 4 new unit tests (stub launcher) and a real CrossOver 26.3 run on the M4: a silent workload was stopped as `stalled` after 4.7 s of a 120 s timeout, nothing was left running, and the next run passed. The low-memory recovery path is only tested with an injected memory reader. Not independently reviewed.
- Added `betterxen-hybrid run` and `bench`: launch a Windows program through an installed CrossOver (`bin/wine --bottle`, an interface CodeWeavers does not document for macOS), with timeout, the memory guard, failure classification (passed, failed exit, timed out, stopped on low memory, cannot execute, no graphics device), sampled CrossOver process memory and CPU, thermal notes, recognised host-noise diagnostics and frame statistics, and write a JSON record; `bench` repeats a workload across graphics backends. Locally verified with 24 unit tests (stub launcher) and with real runs on CrossOver 26.3 on the Apple M4.
- Executed the original Windows workloads under CrossOver 26.3 for the first time (`docs/research/crossover-baseline-2026-11-25.md`). x86-64 C, Rust, Direct3D 11 clear and triangle/frame-loop programs passed; all four ARM64 builds were rejected by CrossOver (`cannot execute`). Five-repeat, 2000-frame comparison of default, D3DMetal, DXMT, DXVK and wined3d on a trivial offscreen workload: D3DMetal's median submit-and-wait was about 1.8 times the others; this is not rendering performance. Observed on one machine, not independently reproduced, using an undocumented backend variable.
- Added `workloads/d3d11-frameloop` (indexed triangle, shaders, event-query frame loop) and negative controls for both Direct3D programs; made workload builds byte-reproducible on one machine with `--no-insert-timestamp`.
- Added `betterxen-hybrid guard`, a memory-pressure supervisor: it refuses to start a command when system-wide free memory is below a threshold and stops it (SIGTERM, then SIGKILL) when memory drops below a limit, reporting why. It is adapted from the memory guard in contributor skakwy's `victory-mac` `mac/run-victory.sh` (GPL-3.0, used with his permission) and reimplemented in Rust. Locally verified with 6 unit tests and three end-to-end runs (refuse, pass-through, stop) on macOS 27.0; the `memory_pressure -Q` output format is not a documented interface; not independently reviewed.
- Added original Windows workloads and a build script (#364, #365): a C and a Rust self-checking console program and a Direct3D 11 clear-and-readback program (`workloads/`), built for x86-64 and ARM64 with a checksum-verified llvm-mingw 20261117 by `scripts/hybrid/build-windows-workloads.sh` (`docs/research/hybrid-toolchain.md`). All six outputs were confirmed as the right PE architecture with `file`. **The x86-64 outputs were later run under CrossOver (see below).**
- Extended `docs/research/upstream-integration-audit.md` with a component-level review of skakwy's `victory-mac`: the reported ~1 FPS is, in his own notes, 1 to 1.9 s per frame of a leaked console-game dump measured by his runtime, so it is not reproducible or adoptable here. His Windows cross-link wrapper failed with Homebrew `llvm@17` and was not integrated; his Metal swizzle and D3DMetal-internals fixes are rejected; game-specific loader patches are rejected.
- Added the `betterxen-hybrid` crate (`crates/hybrid`, no third-party dependencies, native arm64) with `host`, `crossover`, `toolchain`, `frames` and `receipt` commands that print JSON: a host receipt (macOS, chip, memory, core split, whether an x86_64 binary runs under Rosetta, GPU and Metal family), CrossOver discovery limited to `Info.plist` metadata, `lipo -archs` and the documented `BottleDir` and `ManagedBottleDirs` preferences, a Windows cross-compiler probe, and frame-time statistics (nearest-rank percentiles, 1 % and 0.1 % lows, stutter count). Locally verified: 13 unit tests, clippy with warnings denied, and a run on the Apple M4 reference machine, where CrossOver is **not installed** (the report says so) and only Homebrew mingw-w64 x86_64 and i686 compilers were found. CrossOver discovery has been tested on a synthetic bundle only and has never inspected a real CrossOver; nothing launches a program or measures a game. Not independently reviewed (#353, #350, #364, #145).
- Added `docs/research/upstream-integration-audit.md` and registry and reuse-matrix rows for skakwy/victory-mac, MacBox, ScarlettMac, ossover, Whisky and rum (source read through the GitHub API, nothing executed, no code copied). Findings: MacBox and ScarlettMac are GPL-2.0 and game-specific, so they are rejected; the Game Porting Toolkit licence text (a third-party copy of version 4.0) limits use to developing, testing or evaluating games and distribution to non-commercial; contributor-reported frame results (about 1 FPS, then two rendered frames) are recorded as unverified.
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
- Added 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.
@@ -22,12 +29,10 @@ remains unsupported.
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
### Removed
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Aligned contributor and agent guidance, architecture boundaries, crate documentation and testing instructions with active CrossOver hybrid integration. Marked native plans, contracts and campaigns as preserved or historical, documented split-stack runner dependencies and retained the original evidence limits. Documentation only; no new runtime validation or phase acceptance.
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. At that transition checkpoint no hybrid component existed; later shader integration is recorded above. No Xbox title is shown to run, and no phase is verified complete.
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
+13 -16
View File
@@ -8,16 +8,15 @@ The only active development track is the CrossOver-based hybrid architecture in
## Getting started
- Read `README.md`, `AGENTS.md`, `CHANGELOG.md`, `docs/roadmap.md`, `docs/architecture.md`, `docs/interfaces.md`, `docs/progress.md` and the relevant architecture decisions. Generated native status tables describe fixtures, not active priorities.
- Discuss substantial changes in an issue before implementing them, unless directly assigned by a maintainer. Small fixes do not require prior approval; direct assignments without an issue do not require a new issue.
- For issue-based work, claim the issue before working on it by replying on it in plain words, after checking its comments for an existing claim. Never claim over someone else. A claim with no pull request after about one week may be taken over with a reply saying so. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Claim an issue before working on it by replying on it in plain words, after checking its comments for an existing claim. Never claim over someone else. A claim with no pull request after about one week may be taken over with a reply saying so. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
## Development and verification
Use the [testing guide](docs/testing/README.md) to select hybrid, documentation or
preserved-native checks. The workspace regression commands are:
When the Cargo workspace exists, run from its root:
```sh
cargo fmt --all -- --check
@@ -27,7 +26,7 @@ cargo test --workspace
Follow repository documentation for actual GPU tests, fuzzing, mutation testing and benchmarks. Report commands, versions, pass/fail/skip counts and hardware used. A successful shader compile is not successful GPU execution. Do not report unavailable tools or skipped tests as passes.
For an explicitly authorized native instruction or compiler change, cite the applicable ISA section, state the exact architecture, document operand and execution-mask semantics, and add tests for encodings, edge cases, unsupported cases and independent expected results. Where applicable, verify the resulting MSL through actual Metal execution. Do not convert unsupported instructions into silent no-ops.
For an instruction or compiler change, cite the applicable ISA section, state the exact architecture, document operand and execution-mask semantics, and add tests for encodings, edge cases, unsupported cases and independent expected results. Where applicable, verify the resulting MSL through actual Metal execution. Do not convert unsupported instructions into silent no-ops.
For a performance change, provide reproducible before-and-after results using equivalent inputs, hardware and settings. For a new dependency, explain why it is needed, verify its license and native ARM64 compatibility, and record its provenance.
@@ -37,21 +36,19 @@ Use publicly accessible specifications and authorized materials only. Do not sub
Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware.
The preserved native runtime, decoder, typed intermediate representation, shader
compiler and Metal backend use original implementations and independent tests.
Active hybrid work reuses established upstream infrastructure after per-file
license and provenance review. The vendored `victory-shader` snapshot has a
separate [provenance record](crates/victory-shader/UPSTREAM.md); its inclusion
does not authorize adopting other VIctory-family components or game material.
Do not copy from projects built around leaked or unauthorized inputs without the
recorded review required by `AGENTS.md`. Game-specific and decryption code stay excluded.
BetterXen implements its own Rust guest runtime, decoder, typed IR, shader
compiler and native Metal backend from public technical specifications
and independently derived tests. Contributions must not copy, port or
adapt code, decoder tables, internal metadata or implementation
architecture from other emulators. External results can inform test
selection. Author the resulting code and fixtures independently.
Before incorporating third-party code, verify per-file license compatibility with GPL-3.0-or-later, record the exact upstream revision and original paths, preserve copyright notices and document changes. Update applicable attribution records. Public visibility alone is not proof of authorization or license compatibility.
## Pull requests
- Branch from current `main`, or the explicitly requested top of a PR stack. For stacked work, name the base PR and dependencies. Keep commits focused and link relevant issues; a direct maintainer assignment without an issue needs no new issue.
- Describe what changes and why, link the issue you claimed with `Closes #<number>` when applicable, state which checks you actually ran, and disclose material AI assistance. Separate unverified work from supported behavior.
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Describe what changes and why, link the issue you claimed with `Closes #<number>`, state which checks you actually ran, and disclose material AI assistance. Separate unverified work from supported behavior.
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
- Never include secrets, personal paths, credentials or private data in patches or logs.
Generated
+4
View File
@@ -15,6 +15,10 @@ dependencies = [
"xenora-shader",
]
[[package]]
name = "betterxen-hybrid"
version = "0.1.0"
[[package]]
name = "bitflags"
version = "2.13.2"
+7 -40
View File
@@ -11,10 +11,10 @@
![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)
**Active work integrates an externally installed CrossOver. The independent native runtime and Metal compiler are preserved and paused.**
**The paused native implementation described below uses no Wine, CrossOver, Rosetta or Vulkan runtime. The active hybrid direction intends to use CrossOver and Rosetta 2, subject to research and licensing review.**
> [!IMPORTANT]
> **Current direction.** BetterXen's only active development track is a CrossOver-based hybrid architecture: CrossOver (installed externally) as the compatibility foundation, with BetterXen providing whatever integration, configuration, diagnostics, benchmarking and optimization research shows is missing. This is the *intended* architecture, **not a verified Xbox compatibility stack**: no Xbox title has been shown to run through it, and CrossOver is not assumed to provide Xbox runtime compatibility. Phase 1 remains active; integration work and local fixture results do not establish phase completion. Planning is progressive: only the current phase has open issues. The independent native implementation described below is **preserved but paused indefinitely**. See the [roadmap](docs/roadmap.md), [ADR 0005](docs/adr/0005-crossover-hybrid-direction.md), the [upstream research registry](docs/research/upstream-registry.md) and the [deferred native roadmap](docs/research/native-roadmap.md). The rewritten engineering rules are in [AGENTS.md](AGENTS.md).
> **Current direction.** BetterXen's only active development track is a CrossOver-based hybrid architecture: CrossOver (installed externally) as the compatibility foundation, with BetterXen providing whatever integration, configuration, diagnostics, benchmarking and optimization research shows is missing. This is the *intended* architecture, **not a verified Xbox compatibility stack**: no Xbox title has been shown to run through it, and CrossOver is not assumed to provide Xbox runtime compatibility. Work is at the research stage (Phase 1). Planning is progressive: only the current phase has open issues. The independent native implementation described below is **preserved but paused indefinitely**. See the [roadmap](docs/roadmap.md), [ADR 0005](docs/adr/0005-crossover-hybrid-direction.md), the [upstream research registry](docs/research/upstream-registry.md) and the [deferred native roadmap](docs/research/native-roadmap.md). The rewritten engineering rules are in [AGENTS.md](AGENTS.md).
</div>
@@ -28,35 +28,6 @@ BetterXen is a community-maintained, open-source project written primarily in Ru
---
## Active hybrid architecture
BetterXen develops integration, environment configuration, diagnostics, reproducible
workloads, run records and measured optimization around CrossOver. Wine-based
runtime services and the installed CPU/graphics translation components belong to
the external compatibility stack; BetterXen does not replace them by default.
Backend capabilities and integration interfaces must be verified per version.
| Component | Scope at this stack revision |
| --- | --- |
| CrossOver, Rosetta 2, D3DMetal and other selected backends | External dependencies, subject to their own licenses and host support. No proprietary binaries are bundled. |
| `victory-shader` | Vendored GFX10-to-DXIL recompiler and bridge for original compute fixtures. Local GPU observations and failures are recorded in the [integration report](docs/research/victory-shader-integration.md); no console shader corpus was validated. |
| `scripts/hybrid/run-shader-gpu-tests.sh` | Cross-builds a Windows test executable and invokes `betterxen-hybrid run`. It requires the runner from [PR #384](https://github.com/MacosPorters/betterxen/pull/384) and [PR #388](https://github.com/MacosPorters/betterxen/pull/388), absent from this split stack's base. |
| Native `xenora-*` crates and Swift app | Preserved synthetic research and regression tests, paused as an independent development track. Not the CrossOver runtime. |
See the [architecture and integration boundaries](docs/architecture.md),
[crate guide](crates/README.md), [testing guide](docs/testing/README.md) and
[roadmap](docs/roadmap.md). The six original compute fixtures have recorded
single-host results, with independent reproduction outstanding. No Xbox title
execution, general console runtime compatibility or performance improvement is claimed.
## Preserved native implementation
The detailed diagrams, capability counts, results and build instructions below
refer to the **paused native research path**, unless explicitly labelled hybrid.
They remain useful for regression testing, not as instructions to expand native
CPU, runtime or Metal coverage. Native work needs a demonstrated hybrid dependency
or an explicit maintainer decision. Earlier phase and X-number milestones are historical.
## How it fits together
One guest program travels through three native subsystems. Every stage is checked against an independently derived expectation.
@@ -269,7 +240,7 @@ The texture upload and readback paths use authored Metal kernels. They should no
Xbox-specific texture layouts and additional compression formats require further research and validation.
## Preserved native architecture
## Architecture
BetterXen is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
@@ -331,7 +302,7 @@ BetterXen's host execution environment is native ARM64. The guest architecture b
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
The native ARM64 dynamic recompiler covers a bounded subset of x86-64 instructions; the rest run through the shared interpreter semantics (see the [CPU coverage map](docs/testing/cpu-coverage.md)). The project does not provide 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.
@@ -339,10 +310,6 @@ See [Interface Contracts](docs/interfaces.md) for the documented execution and r
## Current limitations
Hybrid limitations include version-specific external interfaces, incomplete independent
reproduction and the absence of demonstrated Xbox execution. The table below
describes the preserved native implementation; it is not an active backlog.
BetterXen is an engineering research project, not a working commercial-game emulator.
The following remain unsupported or incomplete:
@@ -452,12 +419,12 @@ 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. For issue-based work, follow these steps. Direct maintainer assignments without an issue need no new issue; record their scope and stack base in the PR.
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); use public documentation, original code and reviewed, compatibly licensed upstream code. Anyone who has seen leaked or confidential Xbox material must not contribute.
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.
@@ -468,7 +435,7 @@ See the [roadmap](docs/roadmap.md) for the current phase and the [changelog](CHA
---
**Active work builds reproducible CrossOver integration on Apple Silicon, with evidence before compatibility or performance claims.**
**The goal is to build a trustworthy native Apple Silicon compatibility framework, one verifiable subsystem at a time.**
---
+2 -2
View File
@@ -16,6 +16,6 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission. The stall detection and memory-settle logic in `crates/hybrid/src/run.rs` follows supervision lessons from the same repository (`mac/PROGRESS.md`, `crates/victory-core/src/notes.rs`) and is reimplemented, not copied.
Microsoft's DirectX Shader Compiler (release v1.9.2609, `dxc_2026_09_29.zip`; University of Illinois/NCSA licence with MIT components per its `LICENSE-LLVM.txt`, `LICENCE-MIT.txt` and `LICENSE-MS.txt`) is used as an external tool to compile the HLSL probes in `workloads/d3d12-wave-probe/hlsl/`; it is not vendored or distributed.
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
-30
View File
@@ -1,30 +0,0 @@
# Crate guide
The active direction is [CrossOver-based hybrid integration](../docs/architecture.md).
A crate's presence in the workspace or its API documentation does not make it an
active development priority. Legacy `xenora-*` package names and guest ABI symbols
remain for compatibility; they do not name a second active architecture.
| Directory | Role | Development scope |
| --- | --- | --- |
| `victory-shader` | Vendored GFX10-to-DXIL compiler with an original compute-fixture bridge | Active hybrid integration; see [its guide](victory-shader/README.md) and [provenance](victory-shader/UPSTREAM.md). |
| `cli` | `betterxen` CLI for the bounded native experiments and inspection | Preserved native tooling; distinct from the separate `betterxen-hybrid` runner. |
| `loader` | PE32+ parsing, checked guest memory, x86-64 interpreter, ARM64 translator and synthetic services | Preserved, paused; not Wine or the CrossOver loader. |
| `import-gen` | Deterministic import classification and binding generation | Preserved native tooling; not proof of Xbox service compatibility. |
| `isa` | Typed gfx1030 instruction forms and generated ISA data | Preserved native shader path. |
| `decoder` | Bounded gfx1030 decoder | Preserved native shader path; separate from the vendored compiler's decoder. |
| `shader` | Synthetic gfx1030 compute/graphics to Metal Shading Language | Preserved, paused; not the DXIL bridge. |
| `ref` | Independent CPU expectations for native synthetic shader and rendering tests | Preserve independence from production implementations. |
| `metal` | Bounded trusted MSL execution, rendering and readback | Preserved native backend; not D3DMetal. |
| `texture` | Original synthetic texture layout and block-format helpers | Preserved native fixture support; not a verified Xbox layout. |
| `ffi` | Versioned C interface used by the Swift app | Preserved native application boundary; not CrossOver integration. |
`tests/validation` and `benchmarks` are additional workspace members for
independent native validation and correctness-gated measurements. The Swift app
is under `app/`. Keep their regressions passing; extending them requires an
explicit hybrid need or a maintainer decision.
`betterxen-hybrid` is not in this split stack's base. Its separate integration
PRs and the GPU script prerequisites are documented in the
[testing guide](../docs/testing/README.md). Use `cargo +1.100.0 doc --locked --workspace --no-deps` for crate API documentation; compiling documentation does not validate
GPU behavior or upstream provenance.
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "betterxen-hybrid"
description = "Host receipt, CrossOver discovery, frame-time statistics and Windows cross-toolchain probes for the hybrid direction"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[[bin]]
name = "betterxen-hybrid"
path = "src/main.rs"
+13
View File
@@ -0,0 +1,13 @@
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
//! never a guessed value.
use std::process::Command;
pub fn run(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
if !out.status.success() {
return None;
}
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
Some(s)
}
+162
View File
@@ -0,0 +1,162 @@
//! Discover installed CrossOver bundles and read standard bundle metadata.
//!
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
//! interface (#350). The graphics backend of a bottle is deliberately not read.
use crate::cmdutil::run;
use crate::json::Json;
use std::path::{Path, PathBuf};
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
#[derive(Debug, Clone, PartialEq)]
pub struct Install {
pub path: PathBuf,
pub bundle_id: Option<String>,
pub short_version: Option<String>,
pub build_version: Option<String>,
pub executable_archs: Option<Vec<String>>,
pub minimum_macos: Option<String>,
}
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
let mut v = vec![
PathBuf::from("/Applications/CrossOver.app"),
home.join("Applications/CrossOver.app"),
];
if let Some(found) = run(
"/usr/bin/mdfind",
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
) {
for line in found.lines().filter(|l| !l.is_empty()) {
let p = PathBuf::from(line);
if !v.contains(&p) {
v.push(p);
}
}
}
v
}
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
candidates.iter().filter_map(|p| inspect(p)).collect()
}
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
pub fn inspect(app: &Path) -> Option<Install> {
let plist = app.join("Contents/Info.plist");
if !plist.is_file() {
return None;
}
let json = run(
"/usr/bin/plutil",
&["-convert", "json", "-o", "-", plist.to_str()?],
)?;
let exe = crate::host_string(&json, "CFBundleExecutable");
let archs = exe.and_then(|e| {
let p = app.join("Contents/MacOS").join(e);
run("/usr/bin/lipo", &["-archs", p.to_str()?])
.map(|s| s.split_whitespace().map(String::from).collect())
});
Some(Install {
path: app.to_path_buf(),
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
build_version: crate::host_string(&json, "CFBundleVersion"),
executable_archs: archs,
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
})
}
/// A documented CrossOver preference, or None when unset or unreadable.
pub fn preference(key: &str) -> Option<String> {
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
}
impl Install {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("path", Json::str(self.path.display().to_string())),
("bundle_id", Json::opt_str(self.bundle_id.clone())),
("short_version", Json::opt_str(self.short_version.clone())),
("build_version", Json::opt_str(self.build_version.clone())),
(
"executable_archs",
self.executable_archs.as_ref().map_or(Json::Null, |a| {
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
}),
),
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
(
"bundle_id_is_codeweavers_crossover",
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
// A synthetic bundle written by the test: it proves the metadata path, not that
// any real CrossOver build has this layout.
fn fake_bundle(dir: &Path) -> PathBuf {
let app = dir.join("CrossOver.app");
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
fs::write(
app.join("Contents/Info.plist"),
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>CrossOver</string>
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
<key>CFBundleShortVersionString</key><string>99.1.2</string>
<key>CFBundleVersion</key><string>12345</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
</dict></plist>"#,
)
.unwrap();
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
app
}
#[test]
fn reads_bundle_metadata() {
if !cfg!(target_os = "macos") {
return;
}
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp).unwrap();
let app = fake_bundle(&tmp);
let i = inspect(&app).expect("inspect");
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
assert_eq!(i.build_version.as_deref(), Some("12345"));
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
assert!(
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
"{:?}",
i.executable_archs
);
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
fs::remove_dir_all(&tmp).unwrap();
}
#[test]
fn missing_or_plistless_bundle_is_none() {
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
assert!(inspect(&tmp.join("X.app")).is_none());
assert!(inspect(&tmp.join("Nope.app")).is_none());
fs::remove_dir_all(&tmp).unwrap();
}
}
+192
View File
@@ -0,0 +1,192 @@
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
//!
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
//! percentile interval. These definitions are fixed here so reports are comparable; other
//! tools define lows differently (for example as the mean of the worst 1 %).
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct FrameStats {
pub frames: usize,
pub total_ms: f64,
pub mean_ms: f64,
pub avg_fps: f64,
pub min_ms: f64,
pub max_ms: f64,
pub p50_ms: f64,
pub p95_ms: f64,
pub p99_ms: f64,
pub p999_ms: f64,
pub low_1pct_fps: f64,
pub low_01pct_fps: f64,
/// Frames longer than twice the median interval.
pub stutters: usize,
}
#[derive(Debug, PartialEq)]
pub enum FrameError {
Empty,
Invalid { index: usize, value: f64 },
Parse { line: usize, text: String },
}
impl std::fmt::Display for FrameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FrameError::Empty => write!(f, "no frame intervals"),
FrameError::Invalid { index, value } => {
write!(
f,
"frame {index}: interval {value} is not a positive finite number of milliseconds"
)
}
FrameError::Parse { line, text } => {
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
}
}
}
}
impl std::error::Error for FrameError {}
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
let n = sorted.len();
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
sorted[rank.min(n) - 1]
}
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
if intervals_ms.is_empty() {
return Err(FrameError::Empty);
}
for (index, &value) in intervals_ms.iter().enumerate() {
if !value.is_finite() || value <= 0.0 {
return Err(FrameError::Invalid { index, value });
}
}
let mut sorted = intervals_ms.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
let total: f64 = intervals_ms.iter().sum();
let n = sorted.len();
let p50 = nearest_rank(&sorted, 50.0);
let p99 = nearest_rank(&sorted, 99.0);
let p999 = nearest_rank(&sorted, 99.9);
Ok(FrameStats {
frames: n,
total_ms: total,
mean_ms: total / n as f64,
avg_fps: n as f64 / (total / 1000.0),
min_ms: sorted[0],
max_ms: sorted[n - 1],
p50_ms: p50,
p95_ms: nearest_rank(&sorted, 95.0),
p99_ms: p99,
p999_ms: p999,
low_1pct_fps: 1000.0 / p99,
low_01pct_fps: 1000.0 / p999,
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
})
}
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
let mut out = Vec::new();
for (i, line) in text.lines().enumerate() {
let t = line.trim();
if t.is_empty() || t.starts_with('#') {
continue;
}
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
line: i + 1,
text: t.to_string(),
})?;
out.push(v);
}
Ok(out)
}
impl FrameStats {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("frames", Json::Num(self.frames as f64)),
("total_ms", Json::Num(self.total_ms)),
("mean_ms", Json::Num(self.mean_ms)),
("avg_fps", Json::Num(self.avg_fps)),
("min_ms", Json::Num(self.min_ms)),
("max_ms", Json::Num(self.max_ms)),
("p50_ms", Json::Num(self.p50_ms)),
("p95_ms", Json::Num(self.p95_ms)),
("p99_ms", Json::Num(self.p99_ms)),
("p999_ms", Json::Num(self.p999_ms)),
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
("percentile_method", Json::str("nearest-rank")),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
// Expected values below are worked out by hand, not produced by analyze().
#[test]
fn known_answer_ten_frames() {
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
let s = analyze(&v).unwrap();
assert_eq!(s.frames, 10);
assert_eq!(s.total_ms, 200.0);
assert_eq!(s.mean_ms, 20.0);
assert_eq!(s.avg_fps, 50.0);
assert_eq!(s.p50_ms, 10.0); // rank 5
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
assert_eq!(s.p99_ms, 100.0);
assert_eq!(s.low_1pct_fps, 10.0);
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
}
#[test]
fn stutter_threshold_is_strict() {
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
assert_eq!(s.stutters, 1);
}
#[test]
fn one_frame_per_second() {
let s = analyze(&[1000.0, 1000.0]).unwrap();
assert_eq!(s.avg_fps, 1.0);
}
#[test]
fn rejects_bad_input() {
assert_eq!(analyze(&[]), Err(FrameError::Empty));
assert!(matches!(
analyze(&[1.0, 0.0]),
Err(FrameError::Invalid { index: 1, .. })
));
assert!(matches!(
analyze(&[f64::NAN]),
Err(FrameError::Invalid { .. })
));
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
}
#[test]
fn parses_text() {
assert_eq!(
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
vec![16.5, 8.0]
);
assert_eq!(
parse_intervals("1\nabc\n"),
Err(FrameError::Parse {
line: 2,
text: "abc".into()
})
);
}
}
+140
View File
@@ -0,0 +1,140 @@
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
//!
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
use crate::cmdutil::run;
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct HostReceipt {
pub macos_version: Option<String>,
pub macos_build: Option<String>,
pub chip: Option<String>,
pub apple_silicon: Option<bool>,
pub memory_bytes: Option<u64>,
pub logical_cpus: Option<u32>,
pub performance_cores: Option<u32>,
pub efficiency_cores: Option<u32>,
/// True only if an x86_64 slice of a system binary actually executed.
pub rosetta_executes_x86_64: Option<bool>,
pub gpu_name: Option<String>,
pub gpu_cores: Option<String>,
pub metal_support: Option<String>,
pub host_arch_of_this_binary: &'static str,
}
fn sysctl(name: &str) -> Option<String> {
run("/usr/sbin/sysctl", &["-n", name])
}
pub fn collect() -> HostReceipt {
let gpu = run(
"/usr/sbin/system_profiler",
&["SPDisplaysDataType", "-json"],
)
.and_then(|j| parse_gpu(&j));
HostReceipt {
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
macos_build: sysctl("kern.osversion"),
chip: sysctl("machdep.cpu.brand_string"),
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
// now; it does not distinguish "not installed" from "disabled".
rosetta_executes_x86_64: Some(
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
),
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
host_arch_of_this_binary: std::env::consts::ARCH,
}
}
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
let model = string_value(json, "sppci_model")?;
Some((
model,
string_value(json, "sppci_cores"),
string_value(json, "spdisplays_mtlgpufamilysupport"),
))
}
fn string_value(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('"')?;
let end = rest.find('"')?;
Some(rest[..end].to_string())
}
impl HostReceipt {
pub fn to_json(&self) -> Json {
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
Json::obj(vec![
("macos_version", Json::opt_str(self.macos_version.clone())),
("macos_build", Json::opt_str(self.macos_build.clone())),
("chip", Json::opt_str(self.chip.clone())),
(
"apple_silicon",
self.apple_silicon.map_or(Json::Null, Json::Bool),
),
(
"memory_bytes",
self.memory_bytes
.map_or(Json::Null, |x| Json::Num(x as f64)),
),
("logical_cpus", n(self.logical_cpus)),
("performance_cores", n(self.performance_cores)),
("efficiency_cores", n(self.efficiency_cores)),
(
"rosetta_executes_x86_64",
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
),
("gpu_name", Json::opt_str(self.gpu_name.clone())),
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
("metal_support", Json::opt_str(self.metal_support.clone())),
(
"receipt_binary_arch",
Json::str(self.host_arch_of_this_binary),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_gpu_fixture() {
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
let g = parse_gpu(j).unwrap();
assert_eq!(g.0, "Apple M4");
assert_eq!(g.1.as_deref(), Some("10"));
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
}
#[test]
fn missing_gpu_is_none() {
assert!(parse_gpu("{}").is_none());
}
#[test]
fn collect_runs_on_this_host() {
let r = collect();
if cfg!(target_os = "macos") {
assert!(r.macos_version.is_some());
assert!(r.memory_bytes.unwrap() > 0);
}
assert!(r.to_json().render().contains("receipt_binary_arch"));
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
pub fn str(s: impl Into<String>) -> Json {
Json::Str(s.into())
}
pub fn opt_str(s: Option<String>) -> Json {
s.map_or(Json::Null, Json::Str)
}
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
pub fn render(&self) -> String {
let mut out = String::new();
self.write(&mut out, 0);
out.push('\n');
out
}
fn write(&self, out: &mut String, depth: usize) {
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) if n.is_finite() => {
if n.fract() == 0.0 && n.abs() < 1e15 {
out.push_str(&format!("{}", *n as i64));
} else {
out.push_str(&format!("{n}"));
}
}
// JSON has no NaN or infinity; refuse to invent a number.
Json::Num(_) => out.push_str("null"),
Json::Str(s) => escape(s, out),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
pad(out, depth + 1);
item.write(out, depth + 1);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push(']');
}
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (k, v)) in fields.iter().enumerate() {
pad(out, depth + 1);
escape(k, out);
out.push_str(": ");
v.write(out, depth + 1);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push('}');
}
}
}
}
fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_and_nests() {
let j = Json::obj(vec![
("a", Json::str("q\"\\\n\u{1}")),
(
"b",
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
),
("c", Json::Num(f64::NAN)),
]);
let r = j.render();
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
assert!(r.contains("0.5"));
assert!(r.contains(r#""c": null"#));
}
}
+32
View File
@@ -0,0 +1,32 @@
//! BetterXen hybrid tooling: read-only inspection and measurement helpers around an
//! externally installed CrossOver. Nothing here launches a game or claims compatibility.
pub mod cmdutil;
pub mod crossover;
pub mod frames;
pub mod host;
pub mod json;
pub mod memory;
pub mod run;
pub mod toolchain;
/// Value of a top-level string key in flat JSON produced by `plutil -convert json`.
pub fn host_string(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..]
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
+325
View File
@@ -0,0 +1,325 @@
use betterxen_hybrid::{crossover, frames, host, json::Json, memory, run, toolchain};
use std::path::PathBuf;
use std::process::ExitCode;
const USAGE: &str = "usage: betterxen-hybrid <command>
host host receipt (JSON)
crossover [--app P] CrossOver installs and documented preferences (JSON)
toolchain Windows cross-compilers found on PATH (JSON)
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
run CMD; refuse to start / stop it when free memory is low
run --bottle B [--backend X] [--timeout S] [--stall-timeout S] [--settle-bound S] [--expect TEXT] [--out DIR]
[--min-start-free N] [--min-free N] -- EXE [ARGS...]
run a Windows program through CrossOver; write a JSON record
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
run the program per backend N times; summarise frame times
receipt host + crossover + toolchain in one JSON document";
fn crossover_json(app: Option<PathBuf>) -> Json {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let cands = match app {
Some(p) => vec![p],
None => crossover::candidate_paths(&home),
};
let installs = crossover::discover(&cands);
Json::obj(vec![
("installed", Json::Bool(!installs.is_empty())),
(
"installs",
Json::Arr(installs.iter().map(|i| i.to_json()).collect()),
),
(
"bottle_dir_preference",
Json::opt_str(crossover::preference("BottleDir")),
),
(
"managed_bottle_dirs_preference",
Json::opt_str(crossover::preference("ManagedBottleDirs")),
),
(
"searched",
Json::Arr(
cands
.iter()
.map(|p| Json::str(p.display().to_string()))
.collect(),
),
),
(
"note",
Json::str(
"Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).",
),
),
])
}
fn toolchain_json() -> Json {
let path = std::env::var("PATH").unwrap_or_default();
Json::Arr(
toolchain::probe(&path)
.iter()
.map(|c| c.to_json())
.collect(),
)
}
fn guard(args: &[String]) -> ExitCode {
let mut limits = memory::Limits {
min_start_free: 70,
min_free: 20,
poll: std::time::Duration::from_secs(1),
grace: std::time::Duration::from_secs(10),
};
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args.get(i + 1).and_then(|v| v.parse::<u8>().ok());
match (args[i].as_str(), v) {
("--min-start-free", Some(v)) => limits.min_start_free = v,
("--min-free", Some(v)) => limits.min_free = v,
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
}
i += 2;
}
let Some(cmd) = args.get(i + 1) else {
eprintln!("{USAGE}");
return ExitCode::from(2);
};
match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) {
memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS,
memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8),
other => {
eprintln!("guard: {other:?}");
ExitCode::from(3)
}
}
}
struct RunArgs {
cfg: run::RunConfig,
backends: Vec<String>,
repeat: u32,
out: Option<PathBuf>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut bottle = None;
let mut backend = None;
let mut backends = Vec::new();
let mut repeat = 1u32;
let mut timeout = 300u64;
let mut stall = None;
let mut settle = 60u64;
let mut expect = None;
let mut out = None;
let (mut min_start, mut min_free) = (50u8, 15u8);
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args
.get(i + 1)
.ok_or_else(|| format!("{} needs a value", args[i]))?
.clone();
match args[i].as_str() {
"--bottle" => bottle = Some(v),
"--backend" => backend = Some(v),
"--backends" => backends = v.split(',').map(String::from).collect(),
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
"--expect" => expect = Some(v),
"--out" => out = Some(PathBuf::from(v)),
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
"--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?,
o => return Err(format!("unknown option {o}")),
}
i += 2;
}
let program = args.get(i + 1).ok_or("missing program after --")?.clone();
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let installs = crossover::discover(&crossover::candidate_paths(&home));
let install = installs.first().ok_or("no CrossOver installation found")?;
let wine = run::wine_path(&install.path);
if !wine.is_file() {
return Err(format!(
"{} not found in this CrossOver build",
wine.display()
));
}
let work = out
.clone()
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs"));
Ok(RunArgs {
cfg: run::RunConfig {
wine,
bottle: bottle.ok_or("--bottle is required")?,
backend,
program,
args: args[i + 2..].to_vec(),
timeout: std::time::Duration::from_secs(timeout),
limits: memory::Limits {
min_start_free: min_start,
min_free,
poll: std::time::Duration::from_millis(250),
grace: std::time::Duration::from_secs(10),
},
expect,
work_dir: work,
stall_timeout: stall.map(std::time::Duration::from_secs),
settle_bound: std::time::Duration::from_secs(settle),
read_free: memory::free_percentage,
},
backends,
repeat,
out,
})
}
fn crossover_build() -> Option<String> {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
crossover::discover(&crossover::candidate_paths(&home))
.first()
.and_then(|i| {
Some(format!(
"{} ({})",
i.short_version.clone()?,
i.build_version.clone()?
))
})
}
fn save(dir: &std::path::Path, name: &str, j: &Json) {
let _ = std::fs::create_dir_all(dir);
let _ = std::fs::write(dir.join(name), j.render());
}
fn run_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) => a,
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let r = run::execute(&a.cfg, crossover_build());
print!("{}", r.json.render());
if let Some(dir) = &a.out {
save(
dir,
&format!(
"run-{}.json",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
),
&r.json,
);
}
if r.class == run::Class::Passed {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn bench_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) if !a.backends.is_empty() => a,
Ok(_) => {
eprintln!("bench needs --backends\n{USAGE}");
return ExitCode::from(2);
}
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let build = crossover_build();
let mut per_backend = Vec::new();
let mut all_ok = true;
for b in &a.backends {
let mut runs = Vec::new();
for _ in 0..a.repeat {
let mut cfg = a.cfg.clone();
cfg.backend = if b == "default" {
None
} else {
Some(b.clone())
};
let r = run::execute(&cfg, build.clone());
all_ok &= r.class == run::Class::Passed;
runs.push(r.json);
}
per_backend.push(Json::obj(vec![
("backend", Json::str(b.clone())),
("runs", Json::Arr(runs)),
]));
}
let doc = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-bench/0")),
("repeat", Json::Num(a.repeat as f64)),
("host", host::collect().to_json()),
("results", Json::Arr(per_backend)),
]);
print!("{}", doc.render());
if let Some(dir) = &a.out {
save(dir, "bench.json", &doc);
}
if all_ok {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("run") => return run_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("bench") => return bench_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
_ => {}
}
if std::env::args().nth(1).as_deref() == Some("guard") {
return guard(&std::env::args().skip(2).collect::<Vec<_>>());
}
let args: Vec<String> = std::env::args().skip(1).collect();
let result: Result<Json, String> = match args.first().map(String::as_str) {
Some("host") => Ok(host::collect().to_json()),
Some("crossover") => {
let app = match args.get(1).map(String::as_str) {
Some("--app") => args.get(2).map(PathBuf::from),
_ => None,
};
Ok(crossover_json(app))
}
Some("toolchain") => Ok(toolchain_json()),
Some("frames") => match args.get(1) {
None => Err("frames needs a file".into()),
Some(f) => std::fs::read_to_string(f)
.map_err(|e| format!("{f}: {e}"))
.and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string()))
.and_then(|v| frames::analyze(&v).map_err(|e| e.to_string()))
.map(|s| s.to_json()),
},
Some("receipt") => Ok(Json::obj(vec![
("schema", Json::str("betterxen-hybrid-receipt/0")),
("host", host::collect().to_json()),
("crossover", crossover_json(None)),
("windows_cross_compilers", toolchain_json()),
])),
_ => Err(USAGE.into()),
};
match result {
Ok(j) => {
print!("{}", j.render());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("{e}");
ExitCode::from(2)
}
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Memory-pressure supervision of a child process.
//!
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
//! the author's permission): do not start a workload when little memory is free, and stop it
//! when system-wide free memory falls below a limit, because GPU memory is wired under
//! unified memory and a runaway workload can take the whole Mac down. This version is
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
//! stopped. It supervises any command; it contains nothing game-specific.
//!
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
//! stable interface, so an unreadable value is an error, never "assume enough memory".
use crate::cmdutil::run;
use std::process::{Child, Command};
use std::time::{Duration, Instant};
pub fn parse_free_percentage(output: &str) -> Option<u8> {
let line = output
.lines()
.find(|l| l.contains("System-wide memory free percentage"))?;
let digits: String = line
.split(':')
.nth(1)?
.trim()
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let v: u8 = digits.parse().ok()?;
(v <= 100).then_some(v)
}
pub fn free_percentage() -> Option<u8> {
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Limits {
/// Refuse to start below this percent free.
pub min_start_free: u8,
/// Stop the child when free memory drops below this percent.
pub min_free: u8,
pub poll: Duration,
/// Time between SIGTERM and SIGKILL.
pub grace: Duration,
}
#[derive(Debug, PartialEq)]
pub enum Outcome {
/// The child ran to completion; `None` means it ended by a signal.
Exited(Option<i32>),
RefusedToStart {
free: u8,
need: u8,
},
StoppedLowMemory {
free: u8,
limit: u8,
},
/// Memory could not be read, so no guarantee can be given.
MemoryUnreadable,
SpawnFailed(String),
}
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
let _ = Command::new("/bin/kill")
.args(["-TERM", &child.id().to_string()])
.status();
let t0 = Instant::now();
while t0.elapsed() < grace {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
}
/// Run `program` under `limits`, reading memory through `read_free`.
pub fn supervise(
program: &str,
args: &[String],
limits: Limits,
read_free: &mut dyn FnMut() -> Option<u8>,
) -> Outcome {
match read_free() {
None => return Outcome::MemoryUnreadable,
Some(free) if free < limits.min_start_free => {
return Outcome::RefusedToStart {
free,
need: limits.min_start_free,
};
}
Some(_) => {}
}
let mut child = match Command::new(program).args(args).spawn() {
Ok(c) => c,
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
};
loop {
match child.try_wait() {
Ok(Some(status)) => return Outcome::Exited(status.code()),
Ok(None) => {}
Err(e) => return Outcome::SpawnFailed(e.to_string()),
}
match read_free() {
None => {
terminate(&mut child, limits.grace);
return Outcome::MemoryUnreadable;
}
Some(free) if free < limits.min_free => {
terminate(&mut child, limits.grace);
return Outcome::StoppedLowMemory {
free,
limit: limits.min_free,
};
}
Some(_) => {}
}
std::thread::sleep(limits.poll);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> Limits {
Limits {
min_start_free: 50,
min_free: 20,
poll: Duration::from_millis(20),
grace: Duration::from_millis(500),
}
}
#[test]
fn parses_memory_pressure_output() {
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
assert_eq!(parse_free_percentage(real), Some(71));
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 100%"),
Some(100)
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 101%"),
None
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: x"),
None
);
assert_eq!(parse_free_percentage("nothing"), None);
}
#[test]
fn refuses_to_start_when_low() {
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
}
#[test]
fn unreadable_memory_is_an_error() {
assert_eq!(
supervise("/usr/bin/true", &[], limits(), &mut || None),
Outcome::MemoryUnreadable
);
}
#[test]
fn child_exit_code_is_reported() {
let out = supervise(
"/bin/sh",
&["-c".into(), "exit 7".into()],
limits(),
&mut || Some(90),
);
assert_eq!(out, Outcome::Exited(Some(7)));
}
#[test]
fn stops_child_when_memory_drops() {
let mut calls = 0;
let t0 = Instant::now();
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
calls += 1;
Some(if calls < 4 { 90 } else { 10 })
});
assert_eq!(
out,
Outcome::StoppedLowMemory {
free: 10,
limit: 20
}
);
assert!(
t0.elapsed() < Duration::from_secs(10),
"child was not stopped promptly"
);
}
#[test]
fn real_reading_is_available_on_macos() {
if cfg!(target_os = "macos") {
assert!(free_percentage().is_some());
}
}
}
+685
View File
@@ -0,0 +1,685 @@
//! Launch a Windows program through an installed CrossOver, supervise it, and write a
//! structured record of what happened.
//!
//! Interface used: `<CrossOver.app>/Contents/SharedSupport/CrossOver/bin/wine --bottle B EXE`
//! and `.../bin/wineserver -k`. These are **not documented by CodeWeavers** for macOS; they
//! exist in the installed build and answer `--help` (cxbottle, cxstart) as observed on build
//! 26.3.0.39832. Every record therefore carries the CrossOver build and a flag saying the
//! launcher interface is vendor-help-only. The graphics backend is selected through the
//! `CX_GRAPHICS_BACKEND` environment variable, which appears in third-party launch scripts and
//! is likewise undocumented; an unrecognised value was observed to be ignored silently, so a
//!
//! Stall detection and the wait for memory to settle after a stop follow the supervision
//! lessons in skakwy's <https://github.com/skakwy/victory-mac> (`mac/PROGRESS.md`,
//! `mac/run-victory.sh`, `crates/victory-core/src/notes.rs` at commit 22b3f8e45a59; his own
//! work, GPL-3.0, used with his permission): detect a hung run by absence of progress, stop a
//! bottle with `wineserver -k` and its prefix, and do not start the next run until memory has
//! been returned. Reimplemented here; none of his code is copied.
//!
//! A record names the backend *requested* and relies on the workload's own diagnostics
//! (adapter name, backend log lines) to show what actually ran.
use crate::frames;
use crate::json::Json;
use crate::memory;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone)]
pub struct RunConfig {
pub wine: PathBuf,
pub bottle: String,
pub backend: Option<String>,
pub program: String,
pub args: Vec<String>,
pub timeout: Duration,
pub limits: memory::Limits,
/// Text that must appear in stdout for a zero exit to count as a pass.
pub expect: Option<String>,
pub work_dir: PathBuf,
/// Stop the run when neither stdout nor stderr has grown for this long.
pub stall_timeout: Option<Duration>,
/// After a stop, wait at most this long for free memory to return to `min_start_free`.
pub settle_bound: Duration,
/// Free-memory reader; `memory::free_percentage` outside tests.
pub read_free: fn() -> Option<u8>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Class {
Passed,
FailedExit(i32),
MissingExpectedMarker,
TimedOut,
/// No output on stdout or stderr for the stall timeout.
Stalled,
StoppedLowMemory,
RefusedToStart,
/// The Windows loader did not accept the file (for example an ARM64 PE this build cannot run).
CannotExecute,
/// The workload reported that no graphics device could be created.
NoDevice,
MemoryUnreadable,
LaunchFailed,
}
impl Class {
pub fn name(&self) -> String {
match self {
Class::Passed => "passed".into(),
Class::FailedExit(c) => format!("failed_exit_{c}"),
Class::MissingExpectedMarker => "missing_expected_marker".into(),
Class::TimedOut => "timed_out".into(),
Class::Stalled => "stalled".into(),
Class::StoppedLowMemory => "stopped_low_memory".into(),
Class::RefusedToStart => "refused_to_start_low_memory".into(),
Class::CannotExecute => "cannot_execute".into(),
Class::NoDevice => "no_graphics_device".into(),
Class::MemoryUnreadable => "memory_unreadable".into(),
Class::LaunchFailed => "launch_failed".into(),
}
}
}
/// Classify a finished (or stopped) run from observable facts only.
pub fn classify(exit: Option<i32>, stdout: &str, stderr: &str, expect: Option<&str>) -> Class {
if stderr.contains("cannot execute") {
return Class::CannotExecute;
}
if stdout.contains("NO DEVICE") && exit == Some(2) {
return Class::NoDevice;
}
match exit {
Some(0) => match expect {
Some(m) if !stdout.contains(m) => Class::MissingExpectedMarker,
_ => Class::Passed,
},
Some(c) => Class::FailedExit(c),
None => Class::FailedExit(-1),
}
}
/// Known host-environment noise in CrossOver output, reported as diagnostics instead of
/// silently dropped. Returns (kind, line) for each recognised line.
pub fn diagnostics(text: &str) -> Vec<(&'static str, String)> {
let mut out = Vec::new();
for line in text.lines() {
if line.contains("LibClamAV Error") || line.contains("Can't open file or directory") {
out.push(("clamav-database-missing", line.to_string()));
} else if line.starts_with("warn:") && line.contains("DXVK") {
out.push(("dxvk-warning", line.to_string()));
}
}
out
}
/// Which graphics layer announced itself, judged from the workload's stdout and stderr.
pub fn detected_backend(output: &str) -> &'static str {
if output.contains("DXVK:") {
"dxvk"
} else if output.contains("DXMT") || output.contains("D3D_FEATURE_LEVEL_11_1\ninfo: Using") {
"dxmt"
} else if output.contains("adapter=AMD Compatibility Mode") {
"d3dmetal (inferred: Apple-reported adapter identity)"
} else if output.contains("adapter=Apple M") {
"wined3d (inferred: native adapter name, no layer banner)"
} else {
"unknown"
}
}
#[derive(Debug, Default, Clone)]
pub struct Samples {
pub peak_rss_kb: u64,
pub mean_cpu_percent_of_core: f64,
pub min_free_percent: Option<u8>,
pub samples: u32,
}
/// Sum RSS (KB) and CPU % of processes whose command line mentions the CrossOver bundle or the
/// bottle directory. Heuristic: processes not started from those paths are not counted.
fn sample_processes(needles: &[String]) -> (u64, f64) {
let Some(out) = crate::cmdutil::run("/bin/ps", &["-axo", "rss=,pcpu=,command="]) else {
return (0, 0.0);
};
let (mut rss, mut cpu) = (0u64, 0f64);
for l in out.lines() {
if !needles.iter().any(|n| l.contains(n.as_str())) {
continue;
}
let mut it = l.split_whitespace();
rss += it.next().and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
cpu += it.next().and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
}
(rss, cpu)
}
fn thermal() -> Json {
match crate::cmdutil::run("/usr/bin/pmset", &["-g", "therm"]) {
Some(t) => Json::Arr(
t.lines()
.map(|l| Json::str(l.trim()))
.filter(|j| *j != Json::str(""))
.collect(),
),
None => Json::Null,
}
}
pub struct RunRecord {
pub class: Class,
pub duration: Duration,
pub exit: Option<i32>,
pub stdout: String,
pub stderr: String,
pub samples: Samples,
pub json: Json,
}
pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
let t_wall = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let _ = std::fs::create_dir_all(&cfg.work_dir);
let out_path = cfg
.work_dir
.join(format!("stdout-{t_wall}-{}.txt", std::process::id()));
let err_path = cfg
.work_dir
.join(format!("stderr-{t_wall}-{}.txt", std::process::id()));
let mut settle: Option<(Duration, bool)> = None;
let thermal_before = thermal();
let free_start = (cfg.read_free)();
let mut result = RunRecord {
class: Class::LaunchFailed,
duration: Duration::ZERO,
exit: None,
stdout: String::new(),
stderr: String::new(),
samples: Samples::default(),
json: Json::Null,
};
match free_start {
None => result.class = Class::MemoryUnreadable,
Some(f) if f < cfg.limits.min_start_free => result.class = Class::RefusedToStart,
Some(_) => {
let files = std::fs::File::create(&out_path)
.and_then(|o| std::fs::File::create(&err_path).map(|e| (o, e)));
if let Ok((o, e)) = files {
let mut cmd = Command::new(&cfg.wine);
cmd.arg("--bottle")
.arg(&cfg.bottle)
.arg(&cfg.program)
.args(&cfg.args);
cmd.stdout(Stdio::from(o)).stderr(Stdio::from(e));
if let Some(b) = &cfg.backend {
cmd.env("CX_GRAPHICS_BACKEND", b);
}
let started = Instant::now();
if let Ok(mut child) = cmd.spawn() {
let bundle = cfg
.wine
.to_string_lossy()
.split("/Contents/")
.next()
.unwrap_or("")
.to_string();
let needles = vec![bundle, format!("Bottles/{}", cfg.bottle)];
let (mut cpu_sum, mut n) = (0f64, 0u32);
let mut stop: Option<Class> = None;
let mut last_len = 0u64;
let mut last_growth = Instant::now();
loop {
match child.try_wait() {
Ok(Some(st)) => {
result.exit = st.code();
break;
}
Ok(None) => {}
Err(_) => break,
}
let (rss, cpu) = sample_processes(&needles);
result.samples.peak_rss_kb = result.samples.peak_rss_kb.max(rss);
cpu_sum += cpu;
n += 1;
match (cfg.read_free)() {
Some(f) => {
let m = result.samples.min_free_percent.map_or(f, |x| x.min(f));
result.samples.min_free_percent = Some(m);
if f < cfg.limits.min_free {
stop = Some(Class::StoppedLowMemory);
}
}
None => stop = Some(Class::MemoryUnreadable),
}
let len = [&out_path, &err_path]
.iter()
.map(|p| std::fs::metadata(p).map_or(0, |m| m.len()))
.sum::<u64>();
if len != last_len {
last_len = len;
last_growth = Instant::now();
}
if stop.is_none() && started.elapsed() > cfg.timeout {
stop = Some(Class::TimedOut);
}
if stop.is_none()
&& cfg.stall_timeout.is_some_and(|d| last_growth.elapsed() > d)
{
stop = Some(Class::Stalled);
}
if stop.is_some() {
memory::terminate(&mut child, cfg.limits.grace);
stop_bottle(&cfg.wine, &cfg.bottle);
break;
}
std::thread::sleep(cfg.limits.poll);
}
result.duration = started.elapsed();
if stop.is_some() {
let t = Instant::now();
let need = cfg.limits.min_start_free;
let mut recovered = false;
loop {
if (cfg.read_free)().is_some_and(|f| f >= need) {
recovered = true;
break;
}
if t.elapsed() >= cfg.settle_bound {
break;
}
std::thread::sleep(cfg.limits.poll);
}
settle = Some((t.elapsed(), recovered));
}
result.samples.samples = n;
result.samples.mean_cpu_percent_of_core =
if n > 0 { cpu_sum / n as f64 } else { 0.0 };
result.stdout = std::fs::read_to_string(&out_path).unwrap_or_default();
result.stderr = std::fs::read_to_string(&err_path).unwrap_or_default();
result.class = stop.unwrap_or_else(|| {
classify(
result.exit,
&result.stdout,
&result.stderr,
cfg.expect.as_deref(),
)
});
}
}
}
}
let intervals: Vec<f64> = result
.stdout
.lines()
.filter_map(|l| l.strip_prefix("frame_ms "))
.filter_map(|v| v.trim().parse().ok())
.collect();
let frame_stats = frames::analyze(&intervals).ok().map(|s| s.to_json());
let combined = format!("{}\n{}", result.stdout, result.stderr);
let diags: Vec<Json> = diagnostics(&combined)
.into_iter()
.map(|(k, l)| Json::obj(vec![("kind", Json::str(k)), ("line", Json::str(l))]))
.collect();
let tail = |s: &str| -> Json {
let lines: Vec<&str> = s.lines().filter(|l| !l.starts_with("frame_ms ")).collect();
let keep = if lines.len() > 40 {
&lines[lines.len() - 40..]
} else {
&lines[..]
};
Json::Arr(keep.iter().map(|l| Json::str(*l)).collect())
};
result.json = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-run/0")),
("unix_time", Json::Num(t_wall as f64)),
("crossover_build", Json::opt_str(crossover_build)),
(
"launcher_interface",
Json::str(
"CrossOver bin/wine --bottle (vendor --help only; not documented by CodeWeavers for macOS)",
),
),
("bottle", Json::str(cfg.bottle.clone())),
("backend_requested", Json::opt_str(cfg.backend.clone())),
("backend_variable_documented", Json::Bool(false)),
("backend_detected", Json::str(detected_backend(&combined))),
("program", Json::str(cfg.program.clone())),
(
"args",
Json::Arr(cfg.args.iter().map(|a| Json::str(a.clone())).collect()),
),
("classification", Json::str(result.class.name())),
(
"exit_code",
result.exit.map_or(Json::Null, |c| Json::Num(c as f64)),
),
(
"duration_ms",
Json::Num(result.duration.as_secs_f64() * 1000.0),
),
("timeout_s", Json::Num(cfg.timeout.as_secs_f64())),
(
"stall_timeout_s",
cfg.stall_timeout
.map_or(Json::Null, |d| Json::Num(d.as_secs_f64())),
),
(
"memory_settle_after_stop",
settle.map_or(Json::Null, |(d, ok)| {
Json::obj(vec![
("waited_ms", Json::Num(d.as_secs_f64() * 1000.0)),
("recovered_to_start_threshold", Json::Bool(ok)),
("bound_s", Json::Num(cfg.settle_bound.as_secs_f64())),
])
}),
),
(
"free_memory_percent_at_start",
free_start.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"min_free_memory_percent_during_run",
result
.samples
.min_free_percent
.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"peak_crossover_rss_kb_sampled",
Json::Num(result.samples.peak_rss_kb as f64),
),
(
"mean_crossover_cpu_percent_of_one_core_sampled",
Json::Num(result.samples.mean_cpu_percent_of_core),
),
("process_samples", Json::Num(result.samples.samples as f64)),
(
"gpu_utilization",
Json::str("not collected: no unprivileged documented source on this host"),
),
("thermal_before", thermal_before),
("thermal_after", thermal()),
("diagnostics", Json::Arr(diags)),
("frame_stats", frame_stats.unwrap_or(Json::Null)),
("stdout_tail", tail(&result.stdout)),
("stderr_tail", tail(&result.stderr)),
]);
let _ = std::fs::remove_file(&out_path);
let _ = std::fs::remove_file(&err_path);
result
}
/// Prefix directory of a bottle. CrossOver documents `BottleDir` in its preferences; otherwise
/// the default location under Application Support is used.
pub fn bottle_prefix(bottle: &str) -> PathBuf {
let base = crate::crossover::preference("BottleDir")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(std::env::var("HOME").unwrap_or_default())
.join("Library/Application Support/CrossOver/Bottles")
});
base.join(bottle)
}
/// Stop every process of one bottle with `wineserver -k`, selecting the bottle through
/// `WINEPREFIX`. Setting `CX_BOTTLE` instead was tried first and observed NOT to select the
/// bottle: the Windows process kept running after the supervisor reported it stopped.
pub fn stop_bottle(wine: &Path, bottle: &str) {
if let Some(dir) = wine.parent() {
let _ = Command::new(dir.join("wineserver"))
.arg("-k")
.env("WINEPREFIX", bottle_prefix(bottle))
.status();
}
}
pub fn wine_path(app: &Path) -> PathBuf {
app.join("Contents/SharedSupport/CrossOver/bin/wine")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_from_observed_facts() {
assert_eq!(classify(Some(0), "PASS", "", Some("PASS")), Class::Passed);
assert_eq!(
classify(Some(0), "ok", "", Some("PASS")),
Class::MissingExpectedMarker
);
assert_eq!(classify(Some(0), "", "", None), Class::Passed);
assert_eq!(classify(Some(1), "FAIL", "", None), Class::FailedExit(1));
assert_eq!(
classify(Some(2), "NO DEVICE hr=0x1", "", None),
Class::NoDevice
);
assert_eq!(classify(Some(2), "other", "", None), Class::FailedExit(2));
assert_eq!(
classify(
Some(1),
"",
"winewrapper.exe:error: cannot execute L\"a.exe\"",
None
),
Class::CannotExecute
);
}
#[test]
fn recognises_noise_and_backends() {
let d = diagnostics(
"LibClamAV Error: x\nERROR: Can't open file or directory\nwarn: DXVK: No state cache\nfine",
);
assert_eq!(d.len(), 3);
assert_eq!(d[0].0, "clamav-database-missing");
assert!(detected_backend("info: DXVK: cxaddon\nadapter=Apple M4").starts_with("dxvk"));
assert!(detected_backend("adapter=AMD Compatibility Mode").starts_with("d3dmetal"));
assert_eq!(detected_backend("nothing"), "unknown");
}
fn stub(dir: &Path, body: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir).unwrap();
let p = dir.join("wine");
std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
p
}
fn cfg(wine: PathBuf, timeout_ms: u64, tag: &str) -> RunConfig {
RunConfig {
wine,
bottle: "t".into(),
backend: None,
program: "x.exe".into(),
args: vec![],
timeout: Duration::from_millis(timeout_ms),
limits: memory::Limits {
min_start_free: 0,
min_free: 0,
poll: Duration::from_millis(30),
grace: Duration::from_millis(500),
},
expect: Some("PASS".into()),
work_dir: std::env::temp_dir().join(format!("bxrun-{tag}-{}", std::process::id())),
stall_timeout: None,
settle_bound: Duration::from_millis(200),
read_free: memory::free_percentage,
}
}
// These use a stub standing in for the launcher: they prove the supervision and record
// logic, not anything about CrossOver.
#[test]
fn stub_run_records_pass_frames_and_env() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub1-{}", std::process::id()));
let w = stub(
&dir,
"echo \"backend=$CX_GRAPHICS_BACKEND\"; echo 'frame_ms 10'; echo 'frame_ms 20'; echo PASS",
);
let mut c = cfg(w, 10_000, "a");
c.backend = Some("dxmt".into());
let r = execute(&c, Some("test".into()));
assert_eq!(r.class, Class::Passed);
let j = r.json.render();
assert!(j.contains("\"frames\": 2"), "{j}");
assert!(j.contains("backend=dxmt"), "{j}");
assert!(j.contains("\"backend_requested\": \"dxmt\""));
assert!(
!j.contains("frame_ms 10"),
"frame lines belong in frame_stats, not the tail"
);
}
#[test]
fn stub_run_times_out_and_is_stopped() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub2-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let t0 = Instant::now();
let r = execute(&cfg(w, 300, "b"), None);
assert_eq!(r.class, Class::TimedOut);
assert!(t0.elapsed() < Duration::from_secs(10));
}
#[test]
fn stub_failure_is_classified_with_exit_code() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub3-{}", std::process::id()));
let w = stub(&dir, "echo FAIL; exit 3");
assert_eq!(
execute(&cfg(w, 10_000, "c"), None).class,
Class::FailedExit(3)
);
}
#[test]
fn silent_workload_is_stopped_as_stalled_before_the_timeout() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall1-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 20_000, "d");
c.stall_timeout = Some(Duration::from_millis(300));
let t0 = Instant::now();
let r = execute(&c, None);
assert_eq!(r.class, Class::Stalled);
assert!(
t0.elapsed() < Duration::from_secs(5),
"stall must fire long before the 20 s timeout"
);
assert!(r.json.render().contains("\"classification\": \"stalled\""));
}
#[test]
fn workload_that_keeps_printing_is_not_stalled() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall2-{}", std::process::id()));
// Prints every 0.1 s for about 1.2 s: longer than the 0.5 s stall timeout in total.
let w = stub(
&dir,
"i=0; while [ $i -lt 12 ]; do echo tick; i=$((i+1)); sleep 0.1; done; echo PASS",
);
let mut c = cfg(w, 20_000, "e");
c.stall_timeout = Some(Duration::from_millis(500));
assert_eq!(execute(&c, None).class, Class::Passed);
}
static FREE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(90);
fn fake_free() -> Option<u8> {
Some(FREE.load(std::sync::atomic::Ordering::SeqCst))
}
// One test owns the shared `FREE` value, so it does not race with the others.
#[test]
fn after_a_stop_the_run_waits_for_memory_to_return() {
use std::sync::atomic::Ordering::SeqCst;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-settle-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 300, "f");
c.read_free = fake_free;
c.limits.min_start_free = 50;
c.limits.min_free = 0; // only the timeout stops the run
c.settle_bound = Duration::from_secs(5);
// Memory drops 100 ms in and returns 900 ms in; the timeout stop happens at about 300 ms.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
std::thread::sleep(Duration::from_millis(800));
FREE.store(90, SeqCst);
});
let r = execute(&c, None);
h.join().unwrap();
assert_eq!(r.class, Class::TimedOut);
let j = r.json.render();
assert!(j.contains("\"recovered_to_start_threshold\": true"), "{j}");
assert!(r.duration >= Duration::from_millis(300));
// Memory never returns: the wait gives up at the bound and says so.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
});
c.settle_bound = Duration::from_millis(400);
let t0 = Instant::now();
let r = execute(&c, None);
h.join().unwrap();
assert!(t0.elapsed() < Duration::from_secs(5));
assert!(
r.json
.render()
.contains("\"recovered_to_start_threshold\": false")
);
FREE.store(90, SeqCst);
}
#[test]
fn stopping_a_bottle_selects_it_through_wineprefix() {
use std::os::unix::fs::PermissionsExt;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stop-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let log = dir.join("wineserver.log");
let ws = dir.join("wineserver");
std::fs::write(
&ws,
format!(
"#!/bin/sh\necho \"args=$* WINEPREFIX=$WINEPREFIX\" > '{}'\n",
log.display()
),
)
.unwrap();
std::fs::set_permissions(&ws, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_bottle(&dir.join("wine"), "my-bottle");
let got = std::fs::read_to_string(&log).unwrap();
assert!(got.contains("args=-k"), "{got}");
assert!(
got.contains("Bottles/my-bottle") || got.contains("/my-bottle"),
"{got}"
);
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Probe Windows cross-compilers for original test programs (issue #364).
//!
//! Reports what is installed and what each compiler targets; it does not install anything.
use crate::cmdutil::run;
use crate::json::Json;
/// (name, kind). Order is the discovery order only, not a preference.
pub const CANDIDATES: &[&str] = &[
"aarch64-w64-mingw32-clang",
"x86_64-w64-mingw32-clang",
"x86_64-w64-mingw32-gcc",
"i686-w64-mingw32-gcc",
];
#[derive(Debug, Clone, PartialEq)]
pub struct Compiler {
pub name: String,
pub path: String,
pub version_line: Option<String>,
pub target_machine: Option<String>,
}
pub fn probe(search_path: &str) -> Vec<Compiler> {
CANDIDATES
.iter()
.filter_map(|name| {
let path = search_path
.split(':')
.map(|d| std::path::Path::new(d).join(name))
.find(|p| p.is_file())?;
let p = path.to_str()?.to_string();
Some(Compiler {
name: name.to_string(),
version_line: run(&p, &["--version"])
.and_then(|s| s.lines().next().map(String::from)),
target_machine: run(&p, &["-dumpmachine"]),
path: p,
})
})
.collect()
}
impl Compiler {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("name", Json::str(self.name.clone())),
("path", Json::str(self.path.clone())),
("version", Json::opt_str(self.version_line.clone())),
("target_machine", Json::opt_str(self.target_machine.clone())),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_path_finds_nothing() {
assert!(probe("").is_empty());
assert!(probe("/nonexistent-dir").is_empty());
}
#[test]
fn finds_a_stub_compiler_and_reports_its_output() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let f = dir.join("x86_64-w64-mingw32-gcc");
std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap();
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
let found = probe(dir.to_str().unwrap());
assert_eq!(found.len(), 1);
assert_eq!(
found[0].target_machine.as_deref(),
Some("x86_64-w64-mingw32")
);
assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
-22
View File
@@ -1,22 +0,0 @@
# victory-shader in BetterXen
This is the active hybrid shader integration, distinct from the paused native
`xenora-shader` MSL compiler. The pinned upstream snapshot translates GFX10
machine code to PC DXIL. BetterXen's `emit::translate_native` entry point and
fixture tests exercise original compute shaders with explicit root layouts.
Read [UPSTREAM.md](UPSTREAM.md) for attribution, exact source, modifications and
scope, and the [integration report](../../docs/research/victory-shader-integration.md)
for initial failures and the local results after the included wave fixes. Upstream container-parsing APIs are
present, but no authorized console shader container was validated. Their API
documentation describes formats, not BetterXen compatibility guarantees.
```sh
CARGO_BUILD_JOBS=2 cargo +1.100.0 test --locked -p victory-shader
```
On macOS this runs CPU-side tests; Windows-only GPU modules are not compiled.
The [hybrid testing guide](../../docs/testing/README.md) explains cross-building,
external CrossOver requirements and the separate runner dependencies needed for
GPU readback. Preserve skipped-test distinctions and do not generalize original
fixture results to arbitrary console shaders or games.
-7
View File
@@ -21,13 +21,6 @@ Changes to upstream files (19 lines, nothing functional) and files BetterXen add
- `src/lib.rs`: `#[rustfmt::skip]` on each `mod` so the vendored files stay byte-comparable with upstream.
- `src/emit/mod.rs`, `src/emit/f64.rs`, `src/emit/lower.rs`: `#[allow(...)]` attributes only, so the crate passes `clippy -D warnings` here. They silence imports and variables used only by Windows-only tests, an unused trait method, a test constant that looks like pi, and two dead duplicate match arms in `lower.rs` that exist upstream (an earlier arm already handles `v_cvt_f32_f64` and `v_permlanex16_b32`).
### Functional edits to upstream files (research/shader-wave-semantics, PR #392)
- `src/emit/lower.rs` (`active_f64_sum`, about 90 lines): the whole-wave f64 sum no longer emits a native `double` wave operation (`makeDouble`, `waveActiveOp.f64`, `splitDouble`); it builds the console's balanced tree over the lanes with the crate's own integer `add_f64`, reading partner runs through `waveReadLaneAt` and a ballot for lanes that are not present, and no longer sets the doubles feature flag. Why: D3DMetal reports no double-precision shader operations and a shader that uses a `double` ran without writing anything (docs/research/shader-wave-semantics.md).
- `src/emit/bitcode.rs`: two `#[allow(dead_code)]` for the double type, now never constructed.
- `src/emit/host.rs`: `Host::wave_lane_count_max()` (test host only).
- `src/emit/wave64_tests.rs`: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` checks the device's wave width and, on a device narrower than 64 lanes, asserts the recompiler's refusal instead of running a 64-lane lowering.
## Not carried
The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. The shader inputs the upstream project was built for are not included; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record).
@@ -220,177 +220,3 @@ mod on_the_gpu {
}
}
}
// ---- f64 whole-wave sum (research/shader-wave-semantics) --------------------------------------
//
// The console's whole-wave f64 sum, as `valu_tests::whole_wave_f64_sum_and_cvt_f32_f64` builds it,
// but storing both words of the f64 result instead of converting to f32, so all 64 bits are
// compared. Upstream lowered it to a native `double` wave operation, which D3DMetal does not run
// (docs/research/shader-wave-semantics.md); it is now done with the integer fp64 add.
// Expected results come from a CPU model of the balanced tree over the lanes in their order
// (lanes 2k and 2k+1, then pairs, ...) with the CPU's own f64 additions, `+0.0` for lanes that
// are not launched; nothing is taken from the recompiler.
const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 {
0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF)
}
const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
[
0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32,
(src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18,
]
}
const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] {
[
0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF),
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8,
]
}
/// A one-group compute program over `threads` threads: each lane's f64 is root constants
/// `(s0, s1)`; the program sums the wave and stores the sum's low then high word to the UAV.
fn f64_wave_sum_program(threads: u32) -> NativeProgram {
let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)];
let v_mov_row_mirror = |vdst: u8, vsrc: u8| {
[
vop1(0x001, vdst, 0xFA),
vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28),
]
};
let mut w: Vec<u32> = Vec::new();
w.push(0xBE80_0000 | 5 << 16 | 0x03 << 8 | 0x80); // s_mov_b32 s5, 0 (table address high)
w.extend_from_slice(&[0x3D << 26 | 0x02 << 18 | 8 << 6 | (4 >> 1), 125 << 25]); // s_load_dwordx4 s[8:11], s[4:5], 0
w.push(vop1(0x001, 6, 0)); // v_mov_b32 v6, s0
w.push(vop1(0x001, 7, 1)); // v_mov_b32 v7, s1
w.push(0xBE80_0000 | 12 << 16 | 0x3D << 8 | 0xC1); // s_or_saveexec_b32 s12, -1
w.extend_from_slice(&vop3(0x101, 2, 0x80, 256 + 6, 12));
w.extend_from_slice(&vop3(0x101, 3, 0x80, 256 + 7, 12));
for sel in [14570689u32, 9658386, 2340] {
w.extend_from_slice(&v_mov_dpp8(4, 2, sel));
w.extend_from_slice(&v_mov_dpp8(5, 3, sel));
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0)); // v_add_f64
}
w.extend_from_slice(&v_mov_row_mirror(4, 2));
w.extend_from_slice(&v_mov_row_mirror(5, 3));
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
w.extend_from_slice(&vop3(0x378, 4, 256 + 2, 0x80, 0x80)); // v_permlanex16_b32
w.extend_from_slice(&vop3(0x378, 5, 256 + 3, 0x80, 0x80));
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
w.extend_from_slice(&vop3(0x360, 14, 256 + 2, 0x80, 0)); // v_readlane_b32 s14, v2, 0
w.extend_from_slice(&vop3(0x360, 15, 256 + 3, 0x80, 0)); // v_readlane_b32 s15, v3, 0
w.push(0xBE80_0000 | 16 << 16 | 0x03 << 8 | 14); // s_mov_b32 s16, s14
w.push(0xBE80_0000 | 17 << 16 | 0x03 << 8 | 15); // s_mov_b32 s17, s15
w.push(0xBE80_0000 | 126 << 16 | 0x03 << 8 | 12); // s_mov_b32 exec_lo, s12
w.push(vop1(0x001, 0, 16)); // v_mov_b32 v0, s16 (low word)
w.extend_from_slice(&buffer_store_dword(0, 8, 0));
w.push(vop1(0x001, 0, 17)); // v_mov_b32 v0, s17 (high word)
w.extend_from_slice(&buffer_store_dword(0, 8, 4));
w.push(0xBF81_0000); // s_endpgm
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
let param = |root, sgprs, user_data, slot| RootParam {
root,
table_offset_dwords: 0,
sgprs,
base_register: 0,
user_data,
slot,
};
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 12,
layout: vec![param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1)],
used: vec![UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 4,
user_data: 4,
slot: 1,
}],
io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [threads, 1, 1] }),
code,
}
}
/// The CPU model: the balanced tree over 32 lanes, the first `launched` holding `x`, the rest `+0.0`.
fn tree_sum(x: f64, launched: usize) -> f64 {
let mut v: Vec<f64> = (0..32).map(|l| if l < launched { x } else { 0.0 }).collect();
while v.len() > 1 {
v = v.chunks(2).map(|p| p[0] + p[1]).collect();
}
v[0]
}
#[test]
fn the_f64_wave_sum_is_lowered_without_native_doubles() {
let shader = translate_native(&f64_wave_sum_program(4)).expect("translate");
let c = crate::dxbc::Container::parse(&shader.dxil).expect("container");
let sfi0 = c.part(crate::dxbc::FourCC::SFI0).expect("SFI0 part").data;
let features = u64::from_le_bytes(sfi0[..8].try_into().unwrap());
assert_ne!(features & 0x4000, 0, "the sum uses wave operations (sanity check of this parse)");
assert_eq!(features & 0x1, 0, "no native double may be declared: D3DMetal does not run them");
}
#[test]
fn the_cpu_model_is_the_balanced_tree() {
// 4 lanes of 1.25: (1.25 + 1.25) twice, then 2.5 + 2.5, then the rest +0
assert_eq!(tree_sum(1.25, 4), 5.0);
assert_eq!(tree_sum(1.25, 32), 40.0);
// the order matters for values that round: this is not the sequential sum
let x = 0.1;
let sequential: f64 = (0..32).fold(0.0, |a, _| a + x);
assert_ne!(tree_sum(x, 32).to_bits(), sequential.to_bits());
}
#[cfg(windows)]
mod f64_on_the_gpu {
use super::*;
use crate::emit::host::{Dispatch, Host, Root, View};
/// Whole-wave f64 sums on the default D3D12 device, all 64 bits compared with the CPU model,
/// for full and partial waves and for values that round. Fails when there is no device.
#[test]
fn f64_wave_sums_match_the_cpu_tree_bit_for_bit() {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified");
let mut ran = 0;
for threads in [1u32, 4, 20, 32] {
let shader = translate_native(&f64_wave_sum_program(threads)).expect("translate");
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
for x in [1.25f64, 0.1, -3.75e10, 1.0e-300, 123456.789, f64::from_bits(0x3FF0_0000_0000_0001)] {
let b = x.to_bits();
let inputs = [b as u32, (b >> 32) as u32, 0, 0];
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Constants, 0) => inputs[u.dword as usize],
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(2)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
let got = u64::from(out[0][0]) | u64::from(out[0][1]) << 32;
let want = tree_sum(x, threads as usize).to_bits();
assert_eq!(got, want, "{threads} threads of {x:e}: got {got:#018x}, want {want:#018x}");
ran += 1;
}
}
eprintln!("betterxen: {ran} f64 wave sums ran on the GPU and matched the CPU tree bit for bit");
}
}
@@ -30,7 +30,6 @@ enum TypeDef {
Void,
Int(u32),
Float,
#[allow(dead_code)] // BetterXen: no native double is emitted any more (see lower.rs active_f64_sum)
Double,
/// Pointee and address space.
Ptr(Ty, u32),
@@ -249,7 +248,6 @@ impl Module {
pub fn float(&mut self) -> Ty {
self.ty(TypeDef::Float)
}
#[allow(dead_code)] // BetterXen: see TypeDef::Double
pub fn double(&mut self) -> Ty {
self.ty(TypeDef::Double)
}
-18
View File
@@ -82,24 +82,6 @@ fn err(e: windows::core::Error) -> String {
}
impl Host {
/// The widest wave the device reports (`D3D12_OPTIONS1.WaveLaneCountMax`), or `None` when the
/// device does not report wave operations. BetterXen addition: tests that lower for a given
/// host wave width must not run on a narrower device (see wave64_tests.rs).
pub fn wave_lane_count_max(&self) -> Option<u32> {
let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
// SAFETY: `o` is a correctly sized, writable feature-data struct for this feature.
unsafe {
self.device
.CheckFeatureSupport(
D3D12_FEATURE_D3D12_OPTIONS1,
(&mut o as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS1).cast(),
std::mem::size_of::<D3D12_FEATURE_DATA_D3D12_OPTIONS1>() as u32,
)
.ok()?;
}
(o.WaveOps.as_bool() && o.WaveLaneCountMax > 0).then_some(o.WaveLaneCountMax)
}
/// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`).
pub fn new(warp: bool) -> Result<Self, String> {
let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
+31 -58
View File
@@ -2052,19 +2052,6 @@ impl<'a> Lower<'a> {
/// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
/// returning the low (`!high`) or high (`high`) 32-bit word.
///
/// BetterXen change (research/shader-wave-semantics): upstream emitted a native `double`
/// wave operation here (`makeDouble`, `waveActiveOp.f64`, `splitDouble`). The host this is
/// run on (D3DMetal over Metal) has no fp64: it reports no double-precision shader operations
/// and, observed with shaders from Microsoft's DXC, a shader that uses a `double` runs without
/// writing anything. Every other fp64 instruction here is done with 64-bit integer
/// operations ([`super::f64::add_f64`], checked against the CPU's doubles); this does the
/// same. The console's sum is the balanced tree over the lanes in their order (lanes 2k and
/// 2k+1, then pairs, ...; [`super::wave::buddies`]), which is how it is built here: each
/// lane adds its partner run's partial sum, read from the first lane of that run that is
/// present, and `+0.0` where none is (a lane outside EXEC adds `+0` on the console, and a
/// lane the host never launched is the same). The addition is commutative, so every lane
/// holds the same sum.
fn active_f64_sum(
&mut self,
lo: Value,
@@ -2088,48 +2075,25 @@ impl<'a> Lower<'a> {
let z = self.s.m.i32(0);
let lo = self.s.m.select(c, on, lo, z);
let hi = self.s.m.select(c, on, hi, z);
self.s.flags |= flags::WAVE_OPS;
self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
let f64t = self.s.m.double();
let i32t = self.s.t.i32;
let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
let here = self.s.m.bool(true);
let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]);
let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1));
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k));
// Steps within one host wave: the console wave's lanes, or 32 of them when two host
// waves of 32 exchange their halves for the last addition.
let steps = if self.exchange.is_some() || !self.x.native.wave64 { 5 } else { 6 };
let mut sum = self.join64(lo, hi);
for step in 0..steps {
let size = 1u32 << step;
let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1)));
let other = self.s.m.bin(c, Bin::Xor, lane, bit);
let base = self.s.m.bin(c, Bin::And, other, run);
// The lanes of the partner run that are here, from bit 0.
let upper = self.s.m.cmp(c, pred::IUGE, base, k32);
let word = self.s.m.select(c, upper, bhi, blo);
let at = self.s.m.bin(c, Bin::And, base, k31);
let shifted = self.s.m.bin(c, Bin::LShr, word, at);
let bits = if size >= 32 {
shifted
} else {
let mk = self.s.m.i32((1u32 << size) - 1);
self.s.m.bin(c, Bin::And, shifted, mk)
};
// FirstbitLo (dx.op 32): the run's first lane that is here
let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]);
let any = self.s.m.cmp(c, pred::NE, bits, zero);
let first = self.s.m.select(c, any, first, zero);
let from = self.s.m.bin(c, Bin::Add, base, first);
let (slo, shi) = self.split64(sum);
let tlo = self.read_lane(slo, from);
let thi = self.read_lane(shi, from);
let tlo = self.s.m.select(c, any, tlo, zero);
let thi = self.s.m.select(c, any, thi, zero);
let theirs = self.join64(tlo, thi);
sum = super::f64::add_f64(&mut Gen { l: self }, sum, theirs);
}
let (mut r_lo, mut r_hi) = self.split64(sum);
let split_ty = self
.s
.m
.named_struct("dx.types.splitdouble", vec![i32t, i32t]);
let arg = self
.s
.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
let sum = self
.s
.op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
let split = self
.s
.op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
let mut r_lo = self.s.m.extract(c, split, 0);
let mut r_hi = self.s.m.extract(c, split, 1);
if self.exchange.is_some() {
if !self.all_lanes(self.cur_ir) {
need(self.cur_ir);
@@ -2137,10 +2101,19 @@ impl<'a> Lower<'a> {
}
let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
let d0 = self.join64(lo0, hi0);
let d1 = self.join64(lo1, hi1);
let total = super::f64::add_f64(&mut Gen { l: self }, d0, d1);
(r_lo, r_hi) = self.split64(total);
let c = self.cur;
let d0 = self
.s
.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
let d1 = self
.s
.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
let total = self.s.m.bin(c, Bin::Add, d0, d1);
let split = self
.s
.op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
r_lo = self.s.m.extract(c, split, 0);
r_hi = self.s.m.extract(c, split, 1);
}
Ok(if high { r_hi } else { r_lo })
}
@@ -235,23 +235,6 @@ fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() {
words[1] = 0xBF88_0000 | (words.len() as u32 - 2);
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
// BetterXen correction (research/shader-wave-semantics): this program is lowered for a host
// of 64-lane waves. A device whose waves are narrower cannot run that lowering: its lanes 32
// and up do not exist, and the observed result was 0 instead of the tree. Such a device
// must be offered the lowering for its own width instead, which the recompiler refuses for
// this program ("a wave sum of 16-bit floats where not every lane runs"): the test then
// asserts that refusal, which is the correct behaviour, rather than reporting a failure
// or silently skipping.
if let Some(w) = Host::new(false).ok().and_then(|h| h.wave_lane_count_max()).filter(|&w| w < 64) {
let refused = lowered_on(&native, &p, &HashSet::new(), w);
assert!(
matches!(&refused, Err(ShaderError::Unsupported { what, .. }) if what.contains("16-bit floats where not every lane runs")),
"a {w}-lane device must be refused this program, got {:?}",
refused.as_ref().map(|_| "a shader")
);
eprintln!("device waves are {w} lanes; refused for that width as expected; not run on the device");
return;
}
let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
+12 -21
View File
@@ -3,11 +3,10 @@
## Getting started
Start with the [project README](../README.md) for scope and build commands,
then read the [hybrid architecture](architecture.md), [crate guide](../crates/README.md)
and [testing guide](testing/README.md). The [interface contracts](interfaces.md),
[original guest experiments](../experiments/x1/README.md) and
[independent native validation](../tests/validation/README.md) describe preserved
research, not the active runtime. The [changelog](../CHANGELOG.md) records notable changes.
then read the [interface contracts](interfaces.md). Reproduce an
[original guest test program](../experiments/x1/README.md) or run the
[independent validation suite](../tests/validation/README.md) before changing
either path. The [changelog](../CHANGELOG.md) records notable changes.
Use the [roadmap](roadmap.md) for the active CrossOver-based hybrid plan, phases,
critical path and completion criteria; see [ADR 0005](adr/0005-crossover-hybrid-direction.md)
@@ -20,27 +19,18 @@ paused: [deferred native roadmap](research/native-roadmap.md) and the archived
[component reuse matrix](research/component-reuse-matrix.md). Historical phase
checkpoints retain their original evidence scope.
## Active hybrid architecture
- [Architecture and integration boundaries](architecture.md) — Responsibilities, split-stack dependencies, implemented fixture bridge and unverified capabilities.
- [Crate guide](../crates/README.md) — Active vendored compiler versus preserved native components.
- [Shader integration report](research/victory-shader-integration.md) — Recorded local CrossOver results, known failures and reproduction limits.
## Preserved native architecture and technical design
The native sections below document regression contracts and historical evidence.
Their extension recipes and next tasks are not an active roadmap.
## Architecture and technical design
- [Interface contracts](interfaces.md) — Translated shader stages, guest services, native command submission, and synthetic textures.
- [Fixture memory model](adr/0003-demo-memory-model.md) and [CPU boundary](adr/0004-cpu-boundary.md) — Buffer bindings, guest address translation, and dependency direction.
## Preserved native Metal graphics
## Native Metal graphics
- [Translated offscreen stages](interfaces.md#translated-offscreen-stages) — Translated vertex and pixel stages for the bounded gfx1030 subset.
- [Blend and depth passes](interfaces.md) — Native blend and depth graphics passes with per-draw state.
- [Apple GPU evidence](research/apple-gpu.md) and [host lab record](research/host-lab.md) — Observed behavior and historical floating-point results.
## Preserved native RDNA 2 decoding and shader translation
## RDNA 2 decoding and shader translation
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
@@ -51,7 +41,7 @@ Their extension recipes and next tasks are not an active roadmap.
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
## Preserved native guest CPU and runtime experiments
## Guest CPU and runtime 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.
@@ -78,8 +68,10 @@ Their extension recipes and next tasks are not an active roadmap.
- [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.
- [Upstream integration audit](research/upstream-integration-audit.md) — Source-level review of external macOS compatibility projects, licence and provenance decisions, and what was implemented in `crates/hybrid`.
- [victory-shader integration](research/victory-shader-integration.md) — The vendored GFX10-to-DXIL recompiler, how BetterXen's fixtures run through it on the GPU under CrossOver, and what is not verified.
- [Shader wave-semantics investigation](research/shader-wave-semantics.md) — Why two upstream wave tests failed under D3DMetal: device capabilities, independent probes, the fix and its limits.
- [CrossOver baseline](research/crossover-baseline-2026-11-25.md) — First executions of original workloads under CrossOver 26.3 on the M4, backend comparison and its limits.
- [Windows cross-toolchain](research/hybrid-toolchain.md) — Pinned llvm-mingw release, how original Windows workloads are built, and what was and was not executed.
- [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.
@@ -92,10 +84,9 @@ Their extension recipes and next tasks are not an active roadmap.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Historical native campaign checkpoints, batches and evidence; its next target is paused.
- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the BetterXen native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target.
- [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling.
- [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository.
- [Infrastructure QA tooling](testing/infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
- [Documentation alignment audit](testing/documentation-alignment.md) — Audit coverage, retained history and documentation checks for the hybrid transition.
- [Migration to BetterXen](migration.md): source attribution, imported history and compatibility names.
-2
View File
@@ -1,7 +1,5 @@
# 0003. Use disjoint lane-indexed buffers for the first fixture
Status: **Retained for the paused native implementation.** [ADR 0005](0005-crossover-hybrid-direction.md) supersedes native-first project direction. This contract still governs its existing synthetic fixtures and dependency boundaries; it does not define CrossOver integration or authorize new native work.
For the synthetic compute fixture, the resource beginning at SGPR 0 denotes the read-only input words and the one beginning at SGPR 4 denotes the output words. VGPR 0 starts at the lane index and must remain unchanged when used as a resource index. Each allocation has the same word count, and each dispatched invocation accesses only its own lane's word. The fixture ABI provides no raw resource descriptor bits or guest virtual addresses.
The compiler must reject descriptor forms, offsets, index changes and control flow outside this contract. Both engines must honor the load dependency and completion order. The host reads output after command completion. Supporting shared writable buffers will require a new ordering and aliasing contract.
-2
View File
@@ -1,7 +1,5 @@
# 0004. Keep CPU recompilation outside the graphics dependency graph
Status: **Retained for the paused native implementation.** [ADR 0005](0005-crossover-hybrid-direction.md) supersedes native-first project direction. This contract still governs its existing synthetic fixtures and dependency boundaries; it does not define CrossOver integration or authorize new native work.
Phase 01 accepts synthetic shader code and explicit buffer bindings. A later guest CPU runtime will submit graphics commands using opaque resource handles, addresses, lengths and access modes. The graphics side will resolve addresses through checked mappings, retain resources through command completion and return fence completions or interrupt events via the command interface. CPU code may consume that interface. Graphics crates may depend on shared boundary types and graphics crates only, with no dependency on guest CPU or host x86-specific code.
Keep guest address arithmetic separate from host virtual addresses. Validate ranges before constructing a Metal view and retain the backing allocation for all queued users. Define aliasing and synchronization before supporting shared writable mappings. The first fixture uses independent input and output buffers and has no guest virtual address space.
+2 -10
View File
@@ -19,22 +19,14 @@ BetterXen provides integration, configuration, environment management, diagnosti
## Unverified integration assumptions
- General workload coverage and a reproducible baseline (#355). Later local compute-fixture observations are bounded evidence, not general compatibility.
- That CrossOver, Rosetta 2, D3DMetal or DXMT run any authorized workload BetterXen needs. Assumed not until measured (#355).
- That CrossOver offers supported interfaces for bottle management, configuration, launching and diagnostics (#350).
- Rosetta 2's support lifetime and D3DMetal's license terms (#349, #354).
- That any of this provides Xbox runtime compatibility. It is assumed not to.
## Verified implementation capabilities
At the decision date, no hybrid capability had been verified. Subsequent split
integration work adds a vendored GFX10-to-DXIL compiler and an original compute
fixture bridge; single-host CrossOver results and known failures are recorded in
the [integration report](../research/victory-shader-integration.md). The test
script also requires the separate hybrid runner PRs. See the
[current architecture](../architecture.md) for checkout boundaries. These
observations do not accept the full proposed architecture, complete Phase 1 or
establish Xbox compatibility. Preserved native evidence remains in
[progress](../progress.md).
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
## Planning consequence
-88
View File
@@ -1,88 +0,0 @@
# CrossOver hybrid architecture and integration boundaries
[ADR 0005](adr/0005-crossover-hybrid-direction.md) establishes CrossOver as the
primary compatibility foundation and hybrid as the only active development
track. The [roadmap](roadmap.md) defines phase acceptance. This guide describes
component boundaries without treating the proposed complete stack as verified.
## Responsibilities
BetterXen owns integration, configuration, environment inspection, diagnostics,
reproducible workloads, run records, benchmarking and measured optimization.
CrossOver is installed externally. Its Wine-based runtime and selected CPU and
graphics translation components are upstream responsibilities. Record installed
versions and supported interfaces; an observed environment variable or bottle
setting is not automatically a supported vendor API.
BetterXen's own host tools must run natively as ARM64. Windows x86-64 test
executables are guest workloads, not BetterXen host binaries. Rosetta 2 may be
used by the selected external stack where supported. Metal is the host graphics
API; a backend using Vulkan through MoltenVK must be assessed as that backend's
path rather than an independent BetterXen graphics architecture.
CrossOver, D3DMetal, Rosetta 2 and Apple tools are not bundled. Their exact terms,
versions and support status must be checked. See the [upstream registry](research/upstream-registry.md),
[reuse matrix](research/component-reuse-matrix.md) and [license review](licenses.md).
## What is present in the split integration stack
This documentation branch is stacked on [PR #395](https://github.com/MacosPorters/betterxen/pull/395),
which is based on the shader-crate [PR #394](https://github.com/MacosPorters/betterxen/pull/394).
That base contains:
- `victory-shader`: a pinned upstream GFX10-to-DXIL compiler, with a BetterXen
entry point for original compute machine code and root-layout inputs.
- Original compute-fixture tests that compare output with the fixture manifest.
- `scripts/hybrid/run-shader-gpu-tests.sh`: a Windows cross-build and test-launch
script. It delegates execution and run records to `betterxen-hybrid`.
The `betterxen-hybrid` crate is supplied separately by
[PR #384](https://github.com/MacosPorters/betterxen/pull/384), with stall supervision
in [PR #388](https://github.com/MacosPorters/betterxen/pull/388). Neither is in
#395's base. The script cannot run from this stack alone: its first build of
`betterxen-hybrid` fails if that package is absent. Use a checkout containing
those dependencies before following the [hybrid test procedure](testing/README.md).
No merge, rebase or combined implementation is performed by this documentation PR.
With those dependencies available, the tested fixture path is:
```text
Original gfx1030 compute fixtures + explicit root layout
-> victory-shader -> PC DXIL -> Windows D3D12 test executable
-> external CrossOver / selected D3D12 backend -> GPU readback
-> comparison with independently derived manifest words
```
The [integration report](research/victory-shader-integration.md) records local
Apple M4/CrossOver observations, six compute fixtures with matching output and
the [wave-operation investigation and fixes](research/shader-wave-semantics.md)
now included in this stack. The original two suite failures and the later
229-passed/3-ignored run remain separate records. Independent reproduction is outstanding. Windows
GPU tests are not compiled by the macOS test run, and upstream tests can report
success after skipping GPU work. These results do not demonstrate console
shader-container compatibility, Xbox startup, game execution or a performance gain.
The wave investigation began in [PR #392](https://github.com/MacosPorters/betterxen/pull/392)
and is now included through #394/#395. Its 64-lane-only test checks rejection on
the recorded 32-lane device; that passing test is not a GPU sum verification.
The corrected fp64 sum has recorded local GPU comparisons, with console tree
recognition and performance limits still documented in the investigation.
## Preserved native research
The independent decoder, x86-64 interpreter and ARM64 translator, synthetic
runtime services, gfx1030-to-MSL compiler, Metal backend and Swift app remain in
the workspace. Their contracts and tests remain valid for their documented
synthetic scope. They are not the CrossOver runtime and their coverage counts
are not hybrid compatibility metrics.
[ADRs 0003](adr/0003-demo-memory-model.md) and
[0004](adr/0004-cpu-boundary.md) retain native fixture and dependency contracts.
[Interfaces](interfaces.md), [native progress](progress.md) and historical
acceptance records retain their original evidence scope. Earlier native phases,
G-number gates, X-number experiments and CPU campaigns do not define active
hybrid milestones. See the [deferred native roadmap](research/native-roadmap.md).
Keep native regression tests passing. Expand native components only for a
specific demonstrated hybrid need or an explicit maintainer decision to resume.
Do not open a parallel native roadmap or adopt other upstream components merely
because a shader snapshot was included.
+3 -2
View File
@@ -36,9 +36,10 @@ pending-run replay and exact head-SHA verification against a real repository.
## Production follow-ups
1. Coordinate adding `pull-requests: read` to the production audit job permissions
1. Keep `agent-pr-checks` advisory until this evidence is reviewed.
2. Coordinate adding `pull-requests: read` to the production audit job permissions
(same defect as the smoke audit failure).
2. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
3. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
## Local unit suite
+21 -7
View File
@@ -1,9 +1,7 @@
# Agent task queue
Only current hybrid work is active; legacy queue areas do not authorize native expansion. Follow [AGENTS.md](../../AGENTS.md) for claim precedence, direct maintainer assignments and current scope. The optional bot lease is not permission to override a plain-reply claim or a claim with an open PR.
Work items are GitHub issues. Contributors and coding agents claim them with a comment, work in
their own branch, and open a pull request linked to the issue. Claims must be read manually; the former Agent PR checks workflow has been removed. The claim rules for
their own branch, and open a pull request that is checked against the claim. The claim rules for
everyone are in `AGENTS.md` ("Claiming work before you start"): a plain reply is a valid claim, and
a claim goes stale after about one week without a pull request. The commands below are an optional
layer for contributors listed in `.github/agent-queue.json`; the bot only sees `/claim` comments, so
@@ -11,10 +9,10 @@ read the issue's comments before using it and never `/claim` over a plain-reply
deterministic: the rules live in `scripts/agent_queue/` (standard-library Python, no network, no
model or external service), and GitHub Actions and the shell helpers only call it.
The original queue implementation was unit-tested locally; the subsequent
[smoke record](agent-queue-smoke.md) preserves the disposable-repository results.
Those records do not establish current production configuration. The former
Agent PR checks workflow is removed; manual claiming and review rules still apply.
Status: implemented and unit-tested locally. **Not yet run on GitHub**: the workflows are untested
against the real API until the first live run. Until a live smoke test has passed and existing issues
have been migrated into the queue, the pull request check is **advisory**: it reports problems but
never blocks a merge, and it must not be made a required check.
## Areas
@@ -92,6 +90,22 @@ cycles `agent:invalid` (and restores them when fixed), flags overlapping claims
writes a JSON summary to the run summary. `scripts/agent-queue.sh status --json` prints the same
machine-readable summary (counts and lists per area, priority and state).
## Pull request checks
`agent-pr-checks` fails a pull request when: it has no `Closes #N` for a claimed task; the task is held
by someone else; it changes files outside the task's patterns; it changes a file that another open
pull request also changes; the claim has lapsed without a push; or no eligible `/verified <current
head sha>` exists. The SHA must be the full 40 characters and the only argument: a commit with the
same short prefix is cheap to make. After an accepted `/verified` (an eligible verifier, the current
head) the verify job evaluates the same check again and writes it to its run summary; the earlier
check run is not re-run, since `pull_request_target` runs are recorded against the base branch and
cannot be found by the pull request head. Refused, stale, malformed or unauthorized `/verified`
comments get a reply and nothing else, and other pull request comments start no job.
The check is advisory for now: a failure is shown as a warning and in the run summary, and the job
still succeeds. It becomes blocking (fail on problems, then a required check) only after a live smoke
test on GitHub and the migration of existing issues into the queue.
## Forks and upstream sync
Work from a fork, but synchronise against the real upstream (`ranveersoni98/Xenora` in the
-2
View File
@@ -1,7 +1,5 @@
# Xenora CPU/Runtime Expansion Campaign — Progress Ledger
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
Evidence below is local to the named host unless stated. Nothing here is independently reviewed yet.
## Continuation checkpoint
@@ -1,7 +1,5 @@
# Infrastructure QA campaign ledger
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
Running record for the infrastructure and engineering-quality campaign.
Update after each meaningful commit batch. Do not invent passing tests.
@@ -1,7 +1,5 @@
# Infrastructure and QA ownership manifest
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
Non-overlapping file ownership for the infrastructure and engineering-quality
campaign. Active CPU/runtime, RDNA2 and native-application Gates 4–9 work stays
outside this manifest.
-2
View File
@@ -1,7 +1,5 @@
# Proposed AVX and AVX2 guest contract
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
[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.
-2
View File
@@ -1,7 +1,5 @@
# x86-64 instruction registry
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
The static PE probe, the interpreter and the native ARM64 dynamic binary translator (DBT) decode guest code through one function, `x86_decode::decode`. Its tables are generated from `crates/loader/x86/instructions.toml`.
| Part | File | Role |
-4
View File
@@ -1,9 +1,5 @@
# Interfaces
## Scope and active integration boundary
Active CrossOver integration is described in [architecture.md](architecture.md). The contracts below govern the preserved native fixture runtime and Metal path. They are not Wine APIs, a CrossOver plugin interface or an Xbox runtime ABI. Native expansion is paused; retain these contracts for regression testing and any explicitly justified hybrid reuse.
## gfx1030 compute fixtures
The first input is little-endian gfx1030 machine code for a compute fixture with optional statically resolved forward scalar branches. The synthetic ABI starts with full Wave32 EXEC and reserves vector general-purpose register (VGPR) 0 for the grid index used by buffer accesses. Resource operands select documented synthetic bindings. The parser must require explicit target identification and validate all lengths before allocating. Console containers and AMDHSA initialization require separate contracts.
-5
View File
@@ -4,11 +4,6 @@ BetterXen does not circumvent console security or DRM, does not load encrypted o
## User-provided game files
This is the input policy, not a claim of implemented game loading or execution.
The preserved native inspection path and active hybrid workloads have different
limits; see the [architecture guide](architecture.md). No Xbox title execution
is demonstrated.
Users obtain and supply their own files. BetterXen evaluates file structure,
supported features, compatibility and safe execution. Game import does
not check ownership, request receipts or account verification, investigate
+1 -9
View File
@@ -12,21 +12,13 @@ The workspace is GPL-3.0-or-later. The following is the lead's preliminary compa
| bitflags | 2.13.2, `80ce9b545acb0bd42150695fc351889cac1d8eb4` | MIT from MIT OR Apache-2.0 | Runtime transitive dependency |
| AMD RDNA 2 ISA XML | 2026-02-20, schema 1.1.1 | MIT | Source for generated decoder constants |
| LLVM AMDGPU tools | 23.1.6 | Apache-2.0 WITH LLVM-exception | External fixture tool, not linked |
| llvm-mingw | 20261117 (sha256 `98d340bb…446aa`) | Apache-2.0 WITH LLVM-exception, plus component licences in its LICENSE.TXT (mingw-w64 runtime and headers have their own terms; not audited line by line) | External build tool for original Windows test programs, not linked, not distributed |
| victory-shader (vendored) | victory-mac `22b3f8e45a59`, directory snapshot | GPL-3.0 (same as BetterXen's GPL-3.0-or-later); Mesa-derived opcode table MIT | GFX10-to-DXIL shader recompiler; see its UPSTREAM.md |
| thiserror, zlib-rs, windows, windows-sys | 2.0.21, 0.6.8, 0.62.2, 0.61.2 | MIT OR Apache-2.0; Zlib; MIT OR Apache-2.0 | Dependencies of victory-shader; licences from each crate's metadata, not independently audited |
| DirectX Shader Compiler | v1.9.2609, `dxc_2026_09_29.zip` (sha256 `ad31b1fc…a7e7f1`) | University of Illinois/NCSA plus MIT components (per its licence files) | External tool for compiling HLSL probes under CrossOver; not vendored, not distributed |
| Xcode and Metal tools | Xcode 27.2 | Apple proprietary terms | External host tools, not distributed |
## Runtime redistribution review
**Historical native artifact review.** The six-package graph and G11 findings below
apply to the named native candidate, not the current whole-workspace graph or
external CrossOver stack. The vendored shader compiler adds the dependencies
listed above; its independent license/provenance audit is not established by
this older review. CrossOver, Rosetta 2 and D3DMetal remain externally supplied
and unbundled; use the [reuse records](research/component-reuse-matrix.md) for
selected component scope. No redistribution permission is inferred here.
Reviewed 2026-11-22 against the locked Apple Silicon graph. Run `cargo tree --locked --target aarch64-apple-darwin --edges normal,build` and `cargo metadata --locked --format-version 1` to reproduce the graph and declared licenses. The external runtime graph comprises the six Cargo packages listed above. The reviewed registry packages identify their source revisions in `.cargo_vcs_info.json`. The five objc2 registry packages declare the listed licenses but contain no standalone license text. Each of the three pinned upstream `LICENSE.md` files matches the preserved copy byte for byte.
The declared MIT terms are compatible with GPL-3.0-or-later for code the upstream authors have rights to license. MIT remains the selected option for objc2-core-foundation, objc2-metal and bitflags. Distribution of copies or substantial portions subject to MIT requires retaining the applicable copyright and permission notice. Preserve the project GPL text, AMD's MIT notice, the bitflags MIT notice, and the objc2 notices. For a linked Xenora binary, also satisfy the GPLv3 section 6 Corresponding Source requirements for the shipped build, including applicable linked dependency source and build scripts, subject to the license's System Libraries exception. See the [project GPL text](../LICENSE).
+3 -12
View File
@@ -1,7 +1,5 @@
# Engineering progress
**Scope:** generated counts and historical host results below describe preserved native research. For active hybrid components, dependencies and bounded local results, see the [architecture guide](architecture.md) and [shader integration report](research/victory-shader-integration.md). No hybrid phase is certified complete by these tables.
BetterXen is an experimental research project. Verified work is restricted to
independently authored synthetic programs and shaders; commercial game
execution and authentic Xbox startup are unsupported. Progress is measured by
@@ -22,7 +20,7 @@ reproducible tests, not by estimated game compatibility percentages.
| xbox-execution | Xbox Series X\|S | unsupported | untested | unverified | U | Game execution, proprietary guest containers and full guest execution-mask divergence are unsupported. The console launch ABI is unknown. |
<!-- status:features:end -->
## Reproduce preserved native checks
## Reproduce
Run on native Apple Silicon with Rust 1.100.0, Xcode 27.2, Python 3.11 or later and LLVM 23.1.6. The verified host was Apple M5 with macOS 27.3. Metal's safe and precise compile options must be available. Use up to four Cargo jobs total across at most two builds, one GPU workload and one fuzz or mutation campaign at a time. The final checkpoint used two Cargo jobs.
@@ -43,13 +41,6 @@ scripts/audit/dependencies.sh
The independent CPU validation tests are part of the workspace. The native suite and optional LLVM oracle run separately so CPU-only CI can report them accurately. Final local logs are under ignored `artifacts/`. Keep the historical lab and candidate logs separate.
## Active priorities and retained findings
## Remaining work
Follow the [hybrid roadmap](roadmap.md): establish supported integration
interfaces, exact dependency versions, reproducible authorized workloads,
independent baseline reproduction and the responsibility boundary with CrossOver.
Native wave execution, mesh stages, texture sampling and resource expansion are
paused research findings, not the active work queue. Historical G-number gates
remain attached to their original candidates; they neither certify hybrid
acceptance nor authorize redistribution. Keep existing regression tests passing.
See the [current limitations](../README.md#current-limitations) for the outstanding items. The active research steps are: finish the remaining RDNA2 wave execution and mesh stages, translated texture sampling, broader resource binding and synchronization. Close independent claims, status, history and review findings against the current candidates, and verify the [runtime redistribution blockers](licenses.md#runtime-redistribution-review) before closing the redistribution gate (G11).
+10 -11
View File
@@ -1,15 +1,5 @@
# Component reuse matrix
## Split integration update
The original discovery assessment below is retained as a dated research snapshot. The split shader integration subsequently included only `crates/victory-shader` from `skakwy/victory-mac` at `22b3f8e45a59f7d11fef7718988c58d0b3f1d0f9`, plus BetterXen fixture additions. Its [provenance record](../../crates/victory-shader/UPSTREAM.md), [license record](../licenses.md) and [local integration results](victory-shader-integration.md) are the component-specific records, not an approval of the wider VIctory family. This documentation audit does not independently certify that review. Other upstream runtime, loader, game-specific and decryption components remain excluded.
| Component | Selected scope | Recorded license and limits |
| --- | --- | --- |
| `victory-shader` | Vendored GFX10-to-DXIL snapshot and original compute-fixture bridge | Upstream GPL record and retained MIT opcode-table notice; exact files, modifications and attribution in `UPSTREAM.md`. Independent provenance/acceptance review is not claimed here. |
## Original discovery assessment (2026-11-25)
Companion to the [upstream registry](upstream-registry.md); same evidence limits (class D, nothing run, not legal advice). "External" means installed or supplied by the user and invoked, never bundled or copied. GPL-3.0-or-later is BetterXen's license.
| Need | Candidate | Decision | Reason and condition |
@@ -23,10 +13,19 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| Direct3D to Vulkan | DXVK | **Evaluate** only together with MoltenVK | zlib/libpng is permissive and GPL-compatible. Value on macOS unknown. |
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
| Vulkan on Metal | MoltenVK | **Evaluate** | Apache-2.0 (compatible with GPLv3). Subset of Vulkan; coverage vs consumers unknown. |
| Shader compiler / runtime | VIctory, VIctory-macOS | **Initial rejection; later shader-only record above** | Built for a specific commercial game's Xbox Series build whose provenance is not established as authorized. Ideas only. |
| Shader compiler / runtime | VIctory, VIctory-macOS | **Rejected for reuse** | Built for a specific commercial game's Xbox Series build whose provenance is not established as authorized. Ideas only. |
| Project discovery | PortWatch VI | Reference only | Editorial tracker; not engineering evidence; nothing imported. |
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
| Host receipt, frame statistics, cross-toolchain probe | `crates/hybrid` | **Build** (original Rust, public system interfaces) | ossover and Whisky are Swift references; no code adapted. See [audit](upstream-integration-audit.md). |
| Metal HUD log parsing | ossover `MetalHUDLog` | **Reference only** | Log format is documented only by third-party observation; implement after a real trace is captured (#145). |
| Bottle and bundle internals (`cxbottle.conf`, SharedSupport layout) | ossover and others | **Do not depend** | Undocumented, derived from reverse engineering; #350 decides. |
| Game-specific XCL layers | MacBox, ScarlettMac | **Rejected** | GPL-2.0-only and game-specific. |
| Memory-pressure guard for workloads | skakwy/victory-mac `mac/run-victory.sh` | **Adapted** into `crates/hybrid/src/memory.rs` | Contributor-authored, GPL-3.0, permission granted; reimplemented in Rust. |
| Windows cross-linker wrapper | skakwy/victory-mac `tools/macos/gnullvm-cc.sh` | **Not used** | Failed with Homebrew `llvm@17`; llvm-mingw covers the need. |
| Windows cross toolchain | llvm-mingw 20261117 | **External dependency**, not vendored | Apache-2.0 with LLVM exceptions; checksum recorded in [hybrid-toolchain.md](hybrid-toolchain.md). |
| Zero-copy Metal swizzle, D3DMetal state fixes | skakwy/victory-mac `mac/unixlib`, `PROGRESS.md` | **Rejected** | Act on D3DMetal internals; Apple licence forbids reverse engineering. |
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
+1 -3
View File
@@ -1,10 +1,8 @@
# CPU boundary research
**Historical native feasibility notes.** These unknowns and proposed evaluations predate the bounded ARM64 translator now preserved in `crates/loader`. They do not describe CrossOver CPU translation or an active native work queue. See the [active architecture](../architecture.md).
Microsoft's March 2020 Xbox Series X hardware disclosure identifies the shipped CPU family as custom AMD Zen 2. The vendor hardware disclosure carries class D (CLAIM-XBOX-SERIES-X-CPU). Using x86-64 as the future guest ISA is based on that family identification. Platform-specific calling conventions and guest virtual-memory rules remain unknown. [Xbox Series X hardware disclosure](https://news.xbox.com/en-us/2020/03/16/xbox-series-x-tech/)
Apple documents the JIT mapping and write-protection APIs for Apple Silicon, including instructions for making newly written machine code visible to instruction fetch. Class B applies to the documented host APIs. At the time of this study, Xenora had not chosen ahead-of-time translation or JIT compilation. The preserved implementation now includes a bounded ARM64 dynamic binary translator; see the [instruction registry](../cpu/instruction-registry.md). [Apple JIT porting guide](https://developer.apple.com/documentation/apple-silicon/porting-just-in-time-compilers-to-apple-silicon)
Apple documents the JIT mapping and write-protection APIs for Apple Silicon, including instructions for making newly written machine code visible to instruction fetch. Class B applies to the documented host APIs. Xenora has yet to choose ahead-of-time translation or JIT compilation. [Apple JIT porting guide](https://developer.apple.com/documentation/apple-silicon/porting-just-in-time-compilers-to-apple-silicon)
No guest page-size contract has been established. Host mapping operations use host page granularity. Any finer guest protection granularity will require an explicit software policy. Class B applies to documented host mapping semantics. [Apple mmap manual](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/mmap.2.html)
@@ -0,0 +1,59 @@
# CrossOver baseline on the M4 reference machine (2026-11-25)
Evidence class: observed runs on one machine by one person (class B in the sense of [claims.toml](../claims.toml)); **not independently reproduced**, so #355 and #353 stay open. Every result is for original BetterXen workloads, never for a game. Nothing here shows Xbox compatibility.
## Environment
| Item | Value (source) |
| --- | --- |
| Machine | Apple M4, 10 cores (4 performance, 6 efficiency), 24 GiB, macOS 27.0 build 26A428 (`betterxen-hybrid host`) |
| CrossOver | `/Applications/CrossOver.app`, 26.3, build 26.3.0.39832, bundle id `com.codeweavers.CrossOver`, main executable universal (x86_64, arm64) (`betterxen-hybrid crossover`). Licence or trial state not inspected; runs worked |
| Wine host binaries | `wineloader` and `wineserver` are **x86_64 only** (`lipo -archs`), so CrossOver's Wine runs under Rosetta 2 on this Mac. `arch -x86_64 /usr/bin/true` executes |
| Bottle | `betterxen-test`, template `win11_64`, created in 18.7 s with `cxbottle --bottle betterxen-test --create --template win11_64` |
| Launch interface | `bin/wine --bottle B program` and `bin/wineserver -k`. `cxbottle --help` and `cxstart --help` exist in the bundle. **None of these command-line interfaces is documented by CodeWeavers for macOS**: the [Mac user guide](https://support.codeweavers.com/en_US/crossover-mac-user-guide) and [advanced configuration page](https://support.codeweavers.com/advanced-crossover-mac-configuration) cover the GUI and hook variables only. They are used here as observed vendor behaviour of this build |
| Backend selection | `CX_GRAPHICS_BACKEND=<name>` in the environment. Undocumented (see #350). An unknown value (`bogus`) was **accepted silently** and gave the same result as the default |
| Toolchain | llvm-mingw 20261117, Rust 1.100.0; see [hybrid-toolchain.md](hybrid-toolchain.md) |
| Host noise | CrossOver's antivirus helper prints `LibClamAV Error` and `Can't open file or directory` because Homebrew's ClamAV has no database in `/opt/homebrew/var/lib/clamav`. Harmless to results; the run record reports it as a diagnostic |
## Workloads executed
Run with `betterxen-hybrid run --bottle betterxen-test --expect PASS -- <exe>`, default backend.
| Workload | x86-64 result | ARM64 result |
| --- | --- | --- |
| C self-check (CRC-32, four threads) | passed, exit 0, 1.4 s | `cannot_execute` |
| Rust self-check (threads, TLS) | passed, exit 0, 0.6 s | `cannot_execute` |
| D3D11 clear and readback | passed, exit 0, 1.1 s | `cannot_execute` |
| D3D11 indexed triangle, shaders, frame loop | passed, exit 0, 0.8 s | `cannot_execute` |
CrossOver 26.3 here **rejects Windows ARM64 executables** with `winewrapper.exe:error: cannot execute`. The ARM64 builds exist and have the correct PE type, but cannot be run in this environment. Process memory sampled while running was about 325 MB (CrossOver's persistent processes, identical across workloads, so it says nothing about the workloads themselves); minimum system free memory stayed at 64 to 68 %.
Negative controls (#365): `d3d11-clear --negative-control` and `d3d11-frameloop --negative-control` expect a deliberately wrong colour and exit 1; the normal runs exit 0.
### Defects found in BetterXen's own workloads, not in CrossOver
1. **Clear test required exact bytes.** The first run read green as 127 where the program expected 128 (0.5 × 255 = 127.5, an exact tie). Re-derived from the primary source ([Direct3D data conversion rules](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-data-conversion)): the ideal conversion adds 0.5 and drops the fraction (128), but implementations are permitted a tolerance of 0.6 unit-last-place on the integer side (`D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP (0.6f)` in the mingw-w64 header; the D3D11 constant is described by the same page). 127 is 0.5 from 127.5 and is within tolerance. The workload now checks that tolerance and prints how many pixels differ from the ideal. This was a correction to match the specification, not a loosening to get a pass: the negative control still fails.
2. **Triangle was culled.** The first frame-loop run left the centre black. The index order was counter-clockwise, which Direct3D 11 culls by default. Fixed to clockwise; the centre then read (51, 102, 204, 255) exactly.
## Graphics backend comparison
`betterxen-hybrid bench --backends default,d3dmetal,dxmt,dxvk,wined3d --repeat 5`, 2000 frames per run, workload `d3d11-frameloop`: a 640x360 offscreen RGBA8 target, one indexed triangle with a vertex and a pixel shader, an event query waited on every frame. **No window and no presentation.** All 25 runs passed. Medians across five runs:
| Backend (detected from workload output) | Adapter reported | Median frame | p95 | p99 | Frame rate | Startup + run, median |
| --- | --- | --- | --- | --- | --- | --- |
| default | AMD Compatibility Mode | 0.281 ms | 0.448 ms | 0.929 ms | 3153 | 1.42 s |
| d3dmetal | AMD Compatibility Mode | 0.282 ms | 0.558 ms | 1.805 ms | 2898 | 1.44 s |
| dxmt | Apple M4 | 0.158 ms | 0.239 ms | 0.382 ms | 5896 | 1.13 s |
| dxvk (via MoltenVK, "cxaddon-1.10.3") | Apple M4 | 0.150 ms | 0.263 ms | 0.478 ms | 5835 | 1.13 s |
| wined3d | Apple M4 | 0.150 ms | 0.256 ms | 0.419 ms | 5788 | 1.13 s |
Observations, with their limits:
- **The default behaved like D3DMetal** (same adapter identity, same timings) for a bottle made from `win11_64` and an unknown executable. CodeWeavers' Advanced Settings page, as recorded in [primary-source-verification](primary-source-verification-2026-11-25.md), says Auto falls back to wined3d without a per-game database entry. The observation disagrees with that reading; why was not investigated.
- D3DMetal's median per-frame submit-and-wait time was about 1.8 times that of the other three, with a larger tail. This is the cost of a trivial draw plus synchronisation, **not rendering throughput**, and shows nothing about real scenes. It identifies a candidate for investigation, not a bottleneck.
- Sustained run, 200,000 frames: D3DMetal 64.1 s, median 0.283 ms, p99 0.987 ms, p99.9 2.07 ms, maximum 20.3 ms; DXMT 29.6 s, median 0.135 ms, p99 0.339 ms, p99.9 0.48 ms, maximum 7.4 ms. No failure, no hang, and free memory did not trend downward (minimum 64 % and 66 %).
- Not measured: GPU utilization (no unprivileged documented source on this host), memory use of the workload itself, thermal behaviour under load (pmset reported no thermal, performance or CPU-power warning before and after; the workload loads the GPU too lightly for that to mean anything), presentation and frame pacing, texture sampling, depth testing, and Direct3D 12.
## What this does and does not establish
Established on this machine and build: CrossOver 26.3 runs original x86-64 console, threaded, Direct3D 11 clear and triangle programs under four graphics backends with correct pixels; it does not run ARM64 Windows programs; BetterXen can detect, supervise, classify and record such runs. Not established: anything about Direct3D 12, real-scene performance, other macOS or CrossOver versions, other machines, or any game. A second contributor still has to reproduce this.
@@ -1,6 +1,6 @@
# Hybrid backlog research record (2026-11-25)
Evidence class D: public documentation and repository metadata, plus search summaries; see [primary-source-verification-2026-11-25.md](primary-source-verification-2026-11-25.md) for the re-check. Nothing was installed, built or run. Not legal advice. The candidate rows are retained as the original research record; consult the [upstream registry](upstream-registry.md) for their recorded disposition rather than treating this page as a pending merge instruction.
Evidence class D: public documentation and repository metadata, plus search summaries; see [primary-source-verification-2026-11-25.md](primary-source-verification-2026-11-25.md) for the re-check. Nothing was installed, built or run. Not legal advice. Candidate registry rows are listed here; merge them into [upstream-registry.md](upstream-registry.md) once that file's pending commit has landed.
## Findings that created issues
+36
View File
@@ -0,0 +1,36 @@
# Windows cross-toolchain for original workloads (issue #364)
Evidence class B for the build results (commands run on the reference machine, 2026-11-25), class D for licences. The x86-64 programs were later run under CrossOver 26.3; results are in [crossover-baseline-2026-11-25.md](crossover-baseline-2026-11-25.md).
## Pinned toolchain
| Item | Value |
| --- | --- |
| Toolchain | [llvm-mingw](https://github.com/mstorsjo/llvm-mingw) release `20261117`, asset `llvm-mingw-20261117-ucrt-macos-universal.tar.xz` |
| SHA-256 | `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`, equal to the digest GitHub shows for the asset; computed locally with `shasum -a 256` after download |
| Host binaries | Mach-O universal (x86_64, arm64); `codesign -dv` shows the clang driver is signed. Runs natively on Apple Silicon |
| Targets used | `x86_64-w64-mingw32` and `aarch64-w64-mingw32` (clang), Rust `x86_64-pc-windows-gnullvm` and `aarch64-pc-windows-gnullvm` |
| Licence | `LICENSE.TXT` in the release opens with "The LLVM Project is under the Apache License v2.0 with LLVM Exceptions" and then lists further component licences (the mingw-w64 runtime has its own terms). The full file was **not** audited line by line. It is an external build tool: nothing from it is shipped or copied into this repository |
| Install | Download, check the digest, unpack outside the repository (for example `~/toolchains/`), pass the directory to the build script. It is not vendored |
Rust 1.100.0 with `rustup target add x86_64-pc-windows-gnullvm aarch64-pc-windows-gnullvm`.
## Build and result
`scripts/hybrid/build-windows-workloads.sh <llvm-mingw-dir>` builds three original programs for both architectures with `-Wall -Wextra -Werror` and then checks each output with `file`; it exits non-zero if a PE has the wrong machine type.
| Program | Source | x86-64 | ARM64 | Executed under CrossOver 26.3 |
| --- | --- | --- | --- | --- |
| C self-check: CRC-32 check value, four threads, interlocked counter | `workloads/win-selfcheck-c` | built; passed | built; rejected (`cannot execute`) | x86-64 yes, ARM64 no |
| Rust self-check: thread-local storage across four threads | `workloads/win-selfcheck-rust` | built; passed | built; rejected | x86-64 yes, ARM64 no |
| Direct3D 11 clear and readback of a 64x64 RGBA8 target (first step of #365) | `workloads/d3d11-clear` | built; passed within the specified tolerance | built; rejected | x86-64 yes, ARM64 no |
A fourth program, `workloads/d3d11-frameloop` (indexed triangle, shaders, sustained frame loop; needs `-ldxguid -ld3dcompiler`), builds the same way. The D3D11 programs exit 2 ("no device") rather than passing when no hardware device exists, so a missing GPU path cannot be mistaken for success.
## Alternative evaluated: skakwy's `gnullvm-cc.sh`
The contributor's `tools/macos/gnullvm-cc.sh` (victory-mac commit `22b3f8e45a59`) links `x86_64-pc-windows-gnullvm` with Homebrew clang and rustup's lld. On the reference machine, with Homebrew `llvm@17` as `LLVM_PREFIX`, it failed at link time: `clang-17` aborted with `dyld: Symbol not found: _LLVMInitializeLanaiAsmParser`, because the script sets `DYLD_LIBRARY_PATH` to the Rust toolchain's `libLLVM`. It probably expects a newer Homebrew LLVM; which version was not asked. llvm-mingw covers the same need without that dependency, so the script was **not integrated**. His note that the plain `x86_64-pc-windows-gnu` target aborts on thread start is unverified here, since no program was run.
## Reproducibility
Rebuilding twice on one machine and path gives byte-identical SHA-256 for all eight outputs, after adding `-Wl,--no-insert-timestamp` (the C programs differed before because of the PE timestamp). The Rust outputs were identical without it. A build in a different directory was not tested and may embed paths; the second-contributor reproduction that #364 requires has not happened. The `file` check shows the llvm-mingw host binaries are universal (x86_64 and arm64), so the issue's "arm64 only" criterion is not met by this release asset.
-2
View File
@@ -1,7 +1,5 @@
# Native issue archive
Issue/PR states and “active work” labels below are a snapshot of the transition, not a live assignment list. An open historical native PR does not reopen the native roadmap; check its current discussion and the hybrid priorities before taking work.
**Preserved history, not a backlog.** BetterXen's active direction is the CrossOver-based hybrid architecture ([roadmap](../roadmap.md)). The independent native implementation is paused indefinitely; this page replaces its GitHub issue backlog so the work can be found without occupying the active Issues tab. Native source code, tests, benchmarks, Git history and attribution are untouched. Resuming native work needs an explicit maintainer decision ([native roadmap](native-roadmap.md)).
Every issue below keeps its full text, comments and attribution on GitHub and can be reopened; closing used the reason "not planned". Issues imported from the earlier Xenora repository say so in their first lines, and their original author is recorded below. Excerpts are the first sentence of the issue's objective, not a summary of acceptance criteria.
+1 -1
View File
@@ -4,7 +4,7 @@
## Existing implementation (preserved in the workspace)
The native `xenora-*` crates and `betterxen` CLI, Swift code under `app/`, native tests, fixtures, fuzz targets and benchmarks. The separately vendored `victory-shader` is active hybrid integration; not every crate under `crates/` belongs to this paused track. See the [crate guide](../../crates/README.md). The last `main` commit before the hybrid transition is tagged `native-first-final`. Contributor history is untouched.
Rust crates under `crates/` and `app/`, tests under `tests/`, fixtures, fuzz targets and benchmarks. The last `main` commit before the hybrid transition is tagged `native-first-final`. Contributor history is untouched.
## Verified achievements (synthetic evidence only)
-2
View File
@@ -1,7 +1,5 @@
# Phase 02 collaboration research
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
The implementation policy is [independent authorship](../../CONTRIBUTING.md).
Historical reuse discussion records the earlier survey. Xenora uses
public specifications and original fixtures, with other emulator
-2
View File
@@ -1,7 +1,5 @@
# Phase 02 Track B CPU feasibility
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
This historical feasibility study predates the [implemented guest experiments](../../experiments/x1/README.md). This review used the local dual-track brief and public sources. Local inspection reported `Darwin arm64` and macOS 27.3 (26C5047e). No CPU engine, loader, JIT or GPU workload was built or run for this report. [Existing CPU research](cpu-boundary.md) · [CPU boundary decision](../adr/0004-cpu-boundary.md)
## Engine comparison
-2
View File
@@ -1,7 +1,5 @@
# Phase 02 Xbox ecosystem research
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
The implementation policy is [independent authorship](../../CONTRIBUTING.md).
Historical reuse discussion records the earlier survey. Xenora uses
public specifications and original fixtures, with other emulator
+2 -4
View File
@@ -1,7 +1,5 @@
> **Superseded in part (2026-11-25).** This review recommended against Rosetta, Wine and CrossOver under the native-first plan. BetterXen's direction is now the CrossOver-based hybrid architecture ([roadmap](../roadmap.md), [ADR 0005](../adr/0005-crossover-hybrid-direction.md)); the screening facts below remain useful, the native-first recommendations do not. See the [upstream registry](upstream-registry.md) for the current provenance decision on VIctory-family projects.
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
# PortWatch review and a native macOS execution plan
Reviewed November 24, 2026 (America/Chicago). This is a public-documentation and
@@ -203,8 +201,8 @@ texture inventory respectively. Runtime PRs #263/#290 overlap substantially;
their author/maintainer must resolve them before new runtime edits. These
references are destination-repository numbers, not imported source numbers.
At this historical review, the [native development phases](../archive/development-phases-native-first.md) defined the
then-active work order, from compiled guest boot through modular workers, a
The replacement [development phases](../archive/development-phases-native-first.md) define the sole
active work order, from compiled guest boot through modular workers, a
guest-controlled Metal scene, an interactive application, a compatibility
corpus, sustained native execution and conditional Xbox experiments.
Hosted C is implemented on inspected main, awaiting independent acceptance;
@@ -1,9 +1,5 @@
# Primary-source verification (2026-11-25)
This is a dated desk-research and toolchain checkpoint. Later local shader
fixture observations are in the [integration report](victory-shader-integration.md);
its results do not resolve every unknown listed here.
Re-checks claims first taken from search summaries in [hybrid-backlog-research-2026-11-25.md](hybrid-backlog-research-2026-11-25.md). Evidence class D (public documentation read; nothing installed or run). Not legal advice. #363 still has to re-derive these independently.
| Claim | Result | Primary source read |
-2
View File
@@ -1,7 +1,5 @@
# Shader inputs and provenance
**Scope:** the original native fixture input contract below remains preserved. The active hybrid bridge supplies original compute machine code and explicit root layouts to `victory-shader`; no console-container corpus was validated. See the [integration report](victory-shader-integration.md). Parser presence is not compatibility evidence.
Use original assembly assembled by `llvm-mc` for `gfx1030`. Preserve its exact tool version and target options, byte range and endianness, object and extracted code digests, and independently derived outputs. Pass the validated code range and explicit stage and architecture through the Xenora fixture interface. Use a symbol or a declared code range when extracting from an object so alignment bytes and padding do not enter execution. An AMDHSA object also has a separate documented code object ABI (CLAIM-LLVM-GFX1030). [LLVM AMDGPU usage and code object layout](https://llvm.org/docs/AMDGPUUsage.html)
The documented DirectX container can carry either DXBC or DXIL shader parts. Its outer `DXBC` magic identifies the container structure. A DXIL program part contains versioned LLVM bitcode (CLAIM-DXCONTAINER-PAYLOAD). A self-authored HLSL shader compiled with public DXC remains a possible separate input path for later work. Apple's shader converter documents DXIL input to a Metal library (CLAIM-MSC-DXIL). [LLVM DXContainer](https://llvm.org/docs/DirectX/DXContainer.html), [Microsoft DXIL format](https://github.com/microsoft/DirectXShaderCompiler/blob/915bf4f93a254d920b4bcab75b6b1c622eacd816/docs/DXIL.rst#dxil-container-format), [Apple shader converter](https://developer.apple.com/metal/shader-converter/#your-first-conversion)
-61
View File
@@ -1,61 +0,0 @@
# Shader wave-operation failures under D3DMetal: investigation
Part of the shader integration PR (#394). It began as the separate investigation PR #392, whose content is carried here. Evidence class B (runs on one machine: Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, default backend), not independently reproduced. The two failures are the ones recorded in `victory-shader-integration.md`. This note separates what is **established** from what is **a hypothesis**.
## Device capabilities (measured with BetterXen's own host, `workloads/d3d12-wave-probe/d3d12_run.c caps`)
| Field | Value |
| --- | --- |
| Adapter reported | "AMD Compatibility Mode", vendor 0x1002, 18,186 MB (D3DMetal's reported identity; the hardware is the M4) |
| Device created at feature level | 12_1 |
| Highest shader model | 6.6 |
| `WaveOps` | supported |
| `WaveLaneCountMin` / `Max` | 32 / 32 (waves are exactly 32 lanes; `TotalLaneCount` 1024) |
| `DoublePrecisionFloatShaderOps` | **0** (no double-precision shader operations) |
| `Int64ShaderOps` | supported |
| Min-precision support | 0x2 (16-bit) |
## Failure 2: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (established)
**Cause: a wrong test precondition (a subgroup-size assumption), not a translation error.**
1. The test lowers the program with `lowered_on(.., 64)`, "for a host of 64-lane waves (AMD)" per its own comment, then dispatches it on the default device without asking that device's wave width.
2. The device's waves are exactly 32 lanes (table above). A program written for 64-lane waves reads lanes 32 to 63, which do not exist; the observed result was `0x0` against the expected tree `0x5914`.
3. It is the only test in that file that lowers for 64 lanes (line 238); the sibling `a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit` lowers for 32 (line 160) and passes on the same device.
4. Lowering this same program for a 32-lane host does not produce a wrong shader: the recompiler refuses it with `Unsupported: a wave sum of 16-bit floats where not every lane runs`. So the recompiler already behaves correctly; it states a limit instead of emitting something wrong.
5. The expected value `0x5914` is derived on the host by integer 16-bit float arithmetic in the test itself, independent of the recompiler.
**Correction made (test, not recompiler):** `Host::wave_lane_count_max()` (new, from `D3D12_OPTIONS1`), and the test now checks the device first. On a device narrower than 64 lanes it asserts the refusal above and returns, printing why; on a 64-lane device it runs the original hardware comparison unchanged. After the change the test passes on this device, and what it verifies there is "the recompiler refuses a 64-lane-only program for a 32-lane host", not "the sum is correct on the GPU". The correct-sum claim stays **unverified on 32-lane hardware** and has not been run on a 64-lane device.
## Failure 1: `whole_wave_f64_sum_and_cvt_f32_f64` (established: unsupported double-precision operations in D3DMetal; fixed in the recompiler)
Observed: a Wave32 program with 4 launched threads, each contributing 1.25, should store 5.0; it stored `0x00000000`. It is a Wave32 program on a 32-lane device, so wave width was never the cause.
**Independent evidence** (Microsoft's DXC compiled original HLSL, BetterXen's own host dispatched it; expected values derived by hand before running; DXC v1.9.2609 digest-verified and run under CrossOver 26.3):
| Probe (`workloads/d3d12-wave-probe/hlsl/`) | Expected | Observed |
| --- | --- | --- |
| `lanes4`: wave size and lane index, 4 threads | `0x2000`..`0x2003` (wave of 32) | exactly that |
| `sum_f32_4`: `WaveActiveSum(1.25f)`, 4 threads | `0x40a00000` in every lane | exactly that |
| `add_f64_4`: a plain `double` add (no wave operation) | low `0x00000000`, high `0x40000000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
| `sum_f64_4`: `WaveActiveSum` over a `double` | low `0x00000000`, high `0x40140000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
So wave operations, wave width and partial waves are fine on this device. Any shader that uses a `double` runs without effect: pipeline creation succeeds, the dispatch completes, and nothing is stored. That matches the capability record (`DoublePrecisionFloatShaderOps = 0`; Metal has no fp64). Upstream's test harness zero-fills its output buffer, which is why it saw `0` instead of the sentinel. **Conclusion:** the failure comes from unsupported double-precision operations in the backend, combined with the recompiler emitting a native `double` in one place (`active_f64_sum`) while using integer emulation everywhere else. It is not a mistranslation of the wave operation and not a wave-semantics problem.
**Fix (recompiler, `active_f64_sum`):** the existing integer fp64 add (`add_f64`, checked upstream against the CPU's doubles) is reused to build the console's sum, which is the balanced tree over the lanes in their order. Each lane adds its partner run's partial sum, read through `waveReadLaneAt` from the first lane of that run that is present (found with a ballot, as `half_sum_present` already does for 16-bit sums), `+0.0` where none is, which is what a lane outside EXEC adds on the console. No `double` type is emitted and the doubles feature flag is no longer set. The same code covers the console wave64 on two host waves of 32 (an integer add for the last step).
**Validation** (M4, CrossOver 26.3, default backend; one machine, not independently reproduced):
- Whole suite under CrossOver: **229 passed, 0 failed, 3 ignored** (was 224 passed, 2 failed). macOS: 179 + new tests pass (`cargo test -p victory-shader`).
- New test `f64_wave_sums_match_the_cpu_tree_bit_for_bit`: 24 cases (1, 4, 20 and 32 launched threads; six values including ones that round: 0.1, 123456.789, a value one ulp above 1.0, -3.75e10, 1e-300), comparing all 64 bits with a CPU model of the balanced tree using the CPU's own f64 additions and `+0.0` for lanes that are not launched. All 24 match. The model is independent of the recompiler.
- Negative controls: against the **original** lowering this GPU test fails (`got 0x0000000000000000, want 0x3ff4000000000000`) and the new `the_f64_wave_sum_is_lowered_without_native_doubles` test (the container's feature word must declare wave operations but not doubles) fails too; both pass with the fix.
**Limits:** (1) the tree order is what the recompiler's recognizer claims the console program computes (`wave::buddies`); this was not independently simulated from the DPP instructions, so bit-for-bit fidelity to the console for rounding values is only as good as that recognition. (2) The cost of the integer version was not measured and no performance claim is made. (3) Other fp64 wave operations (products, min/max) were not examined; only this one site emitted native doubles. (4) On a device with real fp64 the old native operation would work and is no longer used. (5) DXC is an external tool (University of Illinois/NCSA licence plus MIT components per its licence files), used only to compile probes; nothing from it is in the repository.
## Reproduce
```sh
scripts/hybrid/run-shader-gpu-tests.sh <llvm-mingw-dir> betterxen-test all # the runner script is in PR #395; or run the cross-built test executable with wine directly # expect: 0 failures with the fix in this branch (the vendored original has 2)
# probes: compile hlsl/*.hlsl with DXC under CrossOver, then d3d12_run.exe run <file>.dxil 1 <dwords>
# capabilities (needs the d3d12_run.exe built from workloads/d3d12-wave-probe/d3d12_run.c with llvm-mingw):
# x86_64-w64-mingw32-clang -O2 -o d3d12_run.exe d3d12_run.c -ld3d12 -ldxgi -ldxguid
# CrossOver bin/wine --bottle <bottle> ./d3d12_run.exe caps
```
+1 -1
View File
@@ -1,6 +1,6 @@
# Public graphics sources
Reviewed 2026-11-22. Evidence classes apply to the specific claims in [claims.toml](../claims.toml). The sources below were consulted for original research notes. No upstream files or binary artifacts were imported by that source review. Later component reuse, including the vendored shader compiler, is recorded separately in the [upstream registry](upstream-registry.md).
Reviewed 2026-11-22. Evidence classes apply to the specific claims in [claims.toml](../claims.toml). The sources below were consulted for original research notes. No upstream files or binary artifacts were imported.
| Publisher and version | Consulted sections | License and access |
|---|---|---|
-2
View File
@@ -1,7 +1,5 @@
# Synthetic guest integration and upstream evidence
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
## Source snapshots
The repository audit supplied for this session inspected these public
-2
View File
@@ -1,7 +1,5 @@
# Texture format and layout inventory
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
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
+114
View File
@@ -0,0 +1,114 @@
# Upstream integration audit (2026-11-25)
Companion to the [upstream registry](upstream-registry.md) and [component reuse matrix](component-reuse-matrix.md); those two hold the canonical rows, this file holds the audit evidence behind the new ones. Evidence class D unless stated: public repository metadata, file trees and files read through the GitHub API, plus one Apple license read as text. **No upstream script, installer, binary or build hook was executed and no upstream code was copied.** Not legal advice. CrossOver is **not installed** on the reference machine (Apple M4, 24 GB, macOS 27.0 build 26A428), so nothing below was validated against CrossOver.
## Contributor-reported progress (unverified)
skakwy (a BetterXen contributor) maintains [skakwy/victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0 per GitHub; head `main` pushed 2026-11-25). Reports received: about 1 frame per second with a commercial game, and later "two rendered frames". Both are contributor statements. No hardware, macOS or CrossOver version, workload, instrumentation or raw data has been shared, and the repository's own README gives only build and run commands. Treat both as **unverified**; neither is a compatibility claim. The repository describes itself as a fork of VIctory, a project whose purpose is a leaked Xbox Series build of a commercial game (see the registry), so it is a discovery reference at documentation level only. Information worth requesting from skakwy is listed under "Contributor request" below.
## Projects reviewed
Pins are the default-branch head or the commit read on 2026-11-25. "Equivalent" is what BetterXen has or lacks. Status values: **implemented** (code and tests on this branch), **reference** (read, nothing taken), **rejected**.
| Project | URL | Pin | Licence (file read where stated) | Verified facts | BetterXen equivalent | Provenance | Classification | Status |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| victory-mac | github.com/skakwy/victory-mac | not pinned (not reviewed past README and tree) | GPL-3.0 (GitHub) | Rust workspace with `mac/` build and run scripts for CrossOver, D3DMetal, Rosetta 2; README says "VIctory fork with a Mac build" | none needed | Built on a game-specific upstream whose inputs are unauthorized; file-level review not done | Technical reference only | reference |
| VIctory-macOS | github.com/pragyaangaur/VIctory-macOS | see registry | GPL-3.0 (GitHub) | Described as an attempt to run one commercial game | none needed | Same concern | Rejected for reuse | rejected |
| MacBox | github.com/aykhanium/MacBox | not pinned | **GPL-2.0** (GitHub) | README is candid: "not playable", "retail gameplay is unverified", test suite "known failures"; layers on XCL, an Xbox Series runtime for unpacked console executables | none | Game-specific; also **GPL-2.0-only is not combinable with GPL-3.0-or-later** (see decisions) | Rejected for reuse | rejected |
| ScarlettMac | github.com/paveledits/ScarlettMac | not pinned | GPL-2.0 (GitHub); also `LICENSE-silicon-rans`, `SOURCE-NOTICES.md` | Patch set and shell scripts for XCL on CrossOver; README states game screenshots and a game-specific status | none | Game-specific; mixed licences | Rejected for reuse | rejected |
| PortWatch VI | portwatch-vi.xyz | see registry | NOASSERTION | Editorial tracker | none | Not engineering evidence | Reference only | reference |
| ossover | github.com/hemkum/ossover | `5c11bd7be8da` | GPL-3.0-or-later (README, `ATTRIBUTION.md` lists per-file adaptations from Whisky and highball) | Swift package: `SysInfo` (macOS, chip, memory, Rosetta probe), `Bench/MetalHUDLog` (parser for `metal-HUD:` log lines), `Bench/Harness`, `Store/EngineProbe`, `Renderer/CrossOverBottleConfig`, `doctor` command. README: alpha, one game verified on one machine, "no benchmark numbers have been published". Its design was derived from reverse engineering a CrossOver 26.3.0 bundle | Host receipt, frame statistics (this branch) | Clean, attribution explicit. Reverse-engineered CrossOver internals are **not** a supported interface | Technical reference; ideas re-implemented independently | reference |
| Whisky | github.com/Whisky-App/Whisky | `fd5480a76b3e` | GPL-3.0-or-later (file header read: "version 3 ... or (at your option) any later version") | Archived 2025-05-11. `WhiskyKit`: bottle settings, Wine process control, PE parser, Rosetta 2 check | Rust host receipt covers the Rosetta check | Clear | Technical reference only (Swift; no reuse path) | reference |
| rum | github.com/lunguini/rum | `657461b194e1` | GPL-3.0 (GitHub) | Active Whisky fork: DXMT/DXVK setup, run history, graphics settings views | none needed | Fork of Whisky | Technical reference only | reference |
| Sikarugir | github.com/Sikarugir-App/Sikarugir | `5446b7d18072` | none reported | 23 files; hosts copies of Apple's Game Porting Toolkit documents (`D3DMetal/<ver>/License.pdf`) | none | Redistributes Apple documents; no licence of its own | Reference only; no reuse | reference |
| Sikarugir-foss-sources | github.com/Sikarugir-App/Sikarugir-foss-sources | not reviewed | LGPL-2.1 (GitHub) | Fork of Wineskin sources | none | Unreviewed | Reference only | reference |
| Mythic | github.com/MythicApp/Mythic | see registry | GPL-3.0 | Launcher using a custom GPTK implementation | none | Not reviewed | Reference only | reference |
| DXMT | github.com/3Shain/dxmt | see registry | LGPL-2.1-or-later (LICENSE read by prior pass); GitHub shows NOASSERTION | D3D11/10 on Metal under Wine | Selected by CrossOver as a backend | Clear | External dependency (via CrossOver) | reference |
| DXVK, VKD3D-Proton, MoltenVK | see registry | see registry | zlib, LGPL-2.1, Apache-2.0 | No change from registry | none | Clear | External (via CrossOver) | reference |
| Gcenx macOS Wine builds | github.com/Gcenx/macOS_Wine_builds | `72f8915f2d01` | none reported | Community Wine packages | none | Binary provenance unreviewed | Reference only | reference |
| llvm-mingw | github.com/mstorsjo/llvm-mingw | `903f4cf7faa2` | NOASSERTION per GitHub; LICENSE not yet read | ARM64-capable mingw toolchain | `toolchain` probe (this branch) finds it if installed | Clear | External dependency (candidate for #364) | reference |
| Wine | github.com/wine-mirror/wine | see registry | LGPL-2.1 | Upstream of CrossOver's runtime | none | Clear | Reference | reference |
| Apple Game Porting Toolkit licence | text of `D3DMetal/4.0/License.pdf`, copy hosted by Sikarugir | document read, 6 pages | Apple proprietary agreement | See next section | none | Third-party copy of an Apple document; the original download was not read | Proprietary; user-supplied only | reference |
## Apple Game Porting Toolkit licence (for #354)
Read from the 4.0 `License.pdf` copy in the Sikarugir repository (not from Apple's site; confirm against Apple's download before relying on it). Section 2A grants a limited, personal licence to install, internally use and test the software "for the sole purpose of developing, testing, or evaluating video games for use on Apple-branded products", and to distribute it "solely for non-commercial purposes". Section 2C forbids use on non-Apple hardware, says components may not be separated from the bundle except that the Framework and Redistributables may be distributed separately (still non-commercial only), and section 2D forbids reverse engineering. Consequence for BetterXen: D3DMetal stays a user-supplied external component and is never bundled or redistributed by this repository. Whether running unrelated Windows software through it fits "evaluating video games for use on Apple-branded products" is a question for a lawyer, not answered here.
## Decisions
1. **No external code was incorporated.** The useful general-purpose ideas (host receipt, frame statistics, toolchain probe) are small, and the closest implementations are Swift, so they were written independently in Rust from public system interfaces. ossover and Whisky are credited as technical references in this file; nothing is adapted.
2. **GPL-2.0-only projects (MacBox, ScarlettMac) cannot be combined into this GPL-3.0-or-later workspace** regardless of provenance. Both are also game-specific.
3. **Undocumented CrossOver internals are not a stable interface.** ossover reads `cxbottle.conf` and bundle internals derived from reverse engineering. The new CrossOver module reads only `Info.plist`, `lipo -archs` and the `defaults` keys CodeWeavers documents, and states so in its output.
4. **The Metal HUD log parser in ossover was not ported.** Its line format (`metal-HUD: …`) is documented only by that project's observation; it was not verified against Apple documentation or a real trace here. Frame statistics therefore take plain intervals. A HUD parser can be added when a real trace is captured (#145).
## Implemented on this branch
New crate `crates/hybrid` (`betterxen-hybrid`, no third-party dependencies, native arm64 verified with `lipo -archs`: `arm64`).
| Command | Purpose | Issue | Validated |
| --- | --- | --- | --- |
| `host` | macOS version and build, chip, memory, core split, whether an x86_64 binary executes (Rosetta), GPU and Metal family from `system_profiler` | #353 | Run on the M4 reference machine; unit tests parse a GPU fixture |
| `crossover` | Finds `CrossOver.app` in standard locations and by Spotlight bundle identifier; reads version, build, executable architectures, minimum macOS, and the documented `BottleDir` and `ManagedBottleDirs` preferences | #350, #355 | Unit test on a **synthetic** bundle only. On the reference machine it reports `installed: false`. It has never inspected a real CrossOver |
| `toolchain` | Lists mingw-w64 and llvm-mingw cross-compilers on `PATH` with version and target | #364 | Stub-compiler unit test; on the reference machine it found Homebrew `x86_64-w64-mingw32-gcc` 16.2.0 and `i686-w64-mingw32-gcc`. No ARM64 Windows target is installed. No program was compiled or run |
| `frames <file>` | Frame-time statistics: mean, FPS, nearest-rank p50/p95/p99/p99.9, 1 % and 0.1 % lows, stutter count | #145 | Hand-derived known-answer tests, rejection of non-positive or non-finite intervals |
| `receipt` | The above as one JSON document, `betterxen-hybrid-receipt/0` | #353 | Run once; no second contributor has reproduced it |
Not implemented: launching programs, bottle management, graphics-backend selection or detection, GPU or thermal sampling, a HUD parser, any rendering workload. None is justified yet by Phase 1 evidence.
## Contributor request (to send, not sent)
Ask skakwy only for shareable, general information: Mac model, macOS and CrossOver versions, how frame rate was measured and over what duration, whether the two frames were presented or merely rendered, and any general-purpose tooling and authorized test workloads he wrote himself. Do not ask for game files, traces or instructions for running the leaked build.
## Remaining blockers
CrossOver is not installed here, so criteria 2 and 6 of Phase 1 cannot progress on this machine; `docs/research/primary-source-verification-2026-11-25.md` lists documents still to read. The Rust toolchain default (`stable`, 1.94.1) is older than the workspace's 1.100; use `rustup run 1.100.0 cargo`.
## skakwy/victory-mac: component-level review (second pass)
skakwy, the repository's maintainer and a BetterXen contributor, authorized integrating his independently developed work. His permission cannot cover third-party material, and the repository's purpose fixes what most of it is. Reviewed: full history (302 commits, 65 by skakwy, 194 tracked files at `22b3f8e45a59`, `main` on 2026-11-25), every file he authored under `mac/` and `tools/macos/`, and the headers and authorship of the game-facing crates. Nothing was executed; the checkout stayed outside this repository with git hooks disabled.
### What the reported result is
From his own `mac/PROGRESS.md` and `mac/run-victory.sh` (his statements, unverified): the workload is an unpacked Xbox Series X dump of a commercial game, about 209 GB, run through VIctory under a CrossOver Preview bottle with Rosetta 2 and D3DMetal 4.0b2 on an Apple M3 Max with 36 GB and macOS 27.2.1. "About 1 fps" is 1 to 1.9 seconds per frame in the game world over a 17-minute run ("run 31, ~1.1 fps"), with 5,000 to 7,000 draws per frame and a GPU share of 0.15 to 0.5 s of each frame, taken from VIctory's own per-frame log line. So it is real presented frames from a program VIctory drives, measured by that program, on an input that BetterXen's rules forbid. It is **not** reproducible here, was not measured with independent instrumentation, and says nothing about authorized workloads. It does indicate, as an unverified observation, that a Rust-built Windows x86-64 program using D3D12 can reach D3DMetal under CrossOver on macOS 27. BetterXen has no evidence of that yet; the original D3D11 workload built on this branch is the authorized way to test it once CrossOver is installed.
### Component record
Original repository for every row: https://github.com/skakwy/victory-mac (GPL-3.0, file `LICENSE`). Author: skakwy unless stated. Permission: granted by skakwy through the maintainer, not recorded in the repository itself.
| Component | Source path (commit) | Provenance | Classification | BetterXen destination and method | Validation | Limits |
| --- | --- | --- | --- | --- | --- | --- |
| Memory guard: do not start below N % free, stop a workload below M % | `mac/run-victory.sh` (`22b3f8e45a59`) | skakwy only; logic is general | **Integrated, adapted** | `crates/hybrid/src/memory.rs` and the `guard` command, reimplemented in Rust, SIGTERM then SIGKILL, unreadable memory is an error | 6 unit tests including a child stopped on a simulated drop; end-to-end runs of refuse, pass-through and stop; real `memory_pressure -Q` parsed on macOS 27.0 | Output format of `memory_pressure -Q` is not a documented stable interface; one machine |
| Windows cross-link wrapper for the gnullvm target | `tools/macos/gnullvm-cc.sh` (`22b3f8e45a59`) | skakwy only | **Unnecessary here** | Evaluated; not functional with Homebrew `llvm@17`; superseded by llvm-mingw (see hybrid-toolchain.md). Awaiting clarification of the LLVM version he uses | Link failure reproduced | Not integrated |
| Build wrapper for the victory exe | `mac/build.sh` | skakwy only | Unnecessary | Three lines around `cargo build`; `scripts/hybrid/build-windows-workloads.sh` replaces the idea | n/a | n/a |
| CrossOver launch conventions: `bin/wine --bottle B --cx-app EXE run`, `wineserver -k`, prefix at `~/Library/Application Support/CrossOver/Bottles/B`, `CX_GRAPHICS_BACKEND` and `_VERSION` | `mac/run-victory.sh` | skakwy only; observations of "CrossOver Preview" | **Awaiting clarification** / reference | Recorded for #350 as undocumented third-party observations. Not coded: they are not documented interfaces. His note that backend version 3 gave a black screen and 4 worked is game-specific evidence | none | Undocumented; version unknown beyond "Preview" |
| Rosetta observations: AVX masked stores and `vcvtps2ph` stores to write-watched memory hung on macOS 26, handled on 27; `ROSETTA_ADVERTISE_AVX` | `mac/PROGRESS.md`, `mac/run-victory.sh` | skakwy only | Reference | Hypotheses to test with an original workload; no code adopted | none | Unverified; tied to his loader |
| Native helpers: `mach_vm_remap` aliases as a Wine unixlib (`valias`), Metal zero-copy swizzle | `mac/unixlib/*` | skakwy only; the swizzle credits UTM's d3dmetal-native | **Rejected** | The swizzle acts on D3DMetal internals; Apple's licence section 2D forbids reverse engineering and his notes give D3DMetal struct offsets (`+0x58`, `+0x28c`) found that way. The alias code serves game-memory copy-back | none | Awaiting clarification only for `valias` as a generic Wine unixlib example |
| Instruction and shader scanner | `mac/scan/*` | skakwy only | **Rejected** | Parses the game's shader pack format and a Rosetta-unsafe instruction census of its image | none | Game-specific |
| Game-specific loader patches: watchdog stepping, masked-store and MWAIT patching, BCPack placeholder fills | `crates/victory-loader/*`, `mac/PROGRESS.md` | skakwy and others | **Rejected** | Defeats a title's own self-protection and patches a leaked image; never adopted | none | n/a |
| GPU layer, shader emitters, HLE (`victory-gpu`, `victory-shader`, `victory-hle`, `victory-loader`, `victory-core`) | skakwy commits `ea9da87` to `22b3f8e45a59` on top of Marvis, fxceless, Duff and others (about 260 inherited commits) | Mixed: inherited files carry other authors, and the content is console-game recompilation | **Rejected / requires provenance** | His share is real but inseparable from a runtime whose input is unauthorized; the console-shader work is also native-paused scope | none | File-level provenance would be needed for any future reuse |
| Run notes (`mac/PROGRESS.md`, `mac/new_agent.md`) | same | skakwy only | Reference | Source of the context above; not copied | none | Contains game-specific detail, not republished |
Counts for this pass: 11 component groups reviewed; 1 integrated (adapted); 0 integrated verbatim; 3 reference or awaiting clarification; 2 unnecessary; 5 rejected (some groups overlap categories above).
### Other repositories, completed
- **VIctory-macOS** (`pragyaangaur/VIctory-macOS`, 215 files): a fork whose README describes running "the Xbox Series build" of one game; PortWatch calls the efforts it tracks builds of a "leaked Xbox Series build". Workflow files `fleet-*.yml` orchestrate an agent fleet, not build or test infrastructure of value here. Its README says it was built "with Claude on a free Claude Pro plan" and asks for sponsorship; irrelevant to reuse. Rejected, unchanged.
- **PortWatch VI** (portwatch-vi.xyz): its own description says "leaked Xbox Series build of GTA VI". Reference for discovery only, unchanged.
- **MacBox, ScarlettMac:** see above; unchanged.
- **ossover CI** (`.github/workflows/ci.yml`): a macOS arm64 runner running `bash -n` over shell scripts, a standard-library Python manifest check with `python3 -I`, and `swift build`/`test`. The two cheap ideas (shell syntax check, isolated-interpreter script) match what `docs_hygiene.py` already does; a `bash -n` step for `scripts/hybrid/*.sh` is a candidate follow-up, not added.
### Per-file authorship of victory-mac (measured with `git blame` at `22b3f8e45a59`)
"Owned" means every line is attributed to skakwy. His permission covers these; it cannot cover lines written by others, and some owned files still carry other restrictions.
| File (lines, all his) | What it is | Decision |
| --- | --- | --- |
| `crates/victory-shader/src/emit/f64.rs` (409) | fp64 by 64-bit integer operations, with tests against the CPU's `f64` | General-purpose. Candidate for the native shader compiler; native work is paused, so it waits for a maintainer decision (#387) |
| `mac/run-victory.sh` (139), `crates/victory-core/src/notes.rs` (135) | Run script with memory guard; stall bookkeeping | Memory guard adapted (`guard`); stall detection and settle adapted in #385; the rest is game-specific launch configuration |
| `mac/unixlib/*`, `crates/victory-gpu/src/alias.rs` (369), `zerocopy.rs` (365), `crates/victory-hle/src/modules/vmem.rs` (208) | Alias mappings and a Metal swizzle over game memory | Not integrated: they act on D3DMetal internals and game memory (Apple's licence section 2D forbids reverse engineering; his notes give D3DMetal struct offsets) |
| `crates/victory-loader/src/maskmov.rs` (830), `masked_stores.rs` (243) | Rewrites masked AVX stores in a console title's image for Rosetta | Not integrated: the header says it follows XCL's `maskmov.rs`, which is GPL-2.0-only (incompatible with GPL-3.0-or-later), and it patches a title image |
| `crates/victory-gpu/src/ambient.rs` (193), `mac/scan/*` | Replaces one game's lighting output; scans its shader pack | Not integrated: game-specific |
| `crates/victory-gpu/src/dxc.rs` (110) | Loads Microsoft's `dxcompiler.dll` to compile HLSL under Wine | General-purpose. Not needed yet: D3D12 minimal tests can use SM 5.1 through `d3dcompiler_47`. Revisit when a workload needs SM 6 |
| `tools/macos/gnullvm-cc.sh`, `mac/build.sh` | Windows cross-link wrapper, build wrapper | Evaluated; failed with Homebrew `llvm@17`; superseded by llvm-mingw |
Everything else in the repository is mostly or entirely other authors' work (for example `victory-gpu/src/host.rs` is 8 % his, `victory-shader/src/emit/lower.rs` 1 %).
+16 -11
View File
@@ -1,15 +1,5 @@
# Upstream research registry
## Split integration update
The original discovery assessment below is retained as a dated research snapshot. The split shader integration subsequently included only `crates/victory-shader` from `skakwy/victory-mac` at `22b3f8e45a59f7d11fef7718988c58d0b3f1d0f9`, plus BetterXen fixture additions. Its [provenance record](../../crates/victory-shader/UPSTREAM.md), [license record](../licenses.md) and [local integration results](victory-shader-integration.md) are the component-specific records, not an approval of the wider VIctory family. This documentation audit does not independently certify that review. Other upstream runtime, loader, game-specific and decryption components remain excluded.
| Component | Selected scope | Recorded license and limits |
| --- | --- | --- |
| `victory-shader` | Vendored GFX10-to-DXIL snapshot and original compute-fixture bridge | Upstream GPL record and retained MIT opcode-table notice; exact files, modifications and attribution in `UPSTREAM.md`. Independent provenance/acceptance review is not claimed here. |
## Original discovery assessment (2026-11-25)
Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official or project material) in the sense used by the issue templates and [claims.toml](../claims.toml): a review of public documentation and repository metadata. Nothing here was installed, built or run, so none of it is a statement that a project works for BetterXen's goals. Licenses are what the repository's own license file or GitHub's license detection reported; they still need the per-file check in the [reuse matrix](component-reuse-matrix.md) and are not legal advice. Pins are the default-branch head observed with `git ls-remote` on the review date. Independent re-derivation of this table is tracked in issue #363.
| Project | Source | Pin (head) | License as reported | Role for BetterXen | Findings |
@@ -37,10 +27,25 @@ Found by GitHub search on 2026-11-25. Only repository metadata was read; none wa
| Mythic | [MythicApp/Mythic](https://github.com/MythicApp/Mythic) | `754223978e61` | GPL-3.0 | Open-source macOS launcher that runs Windows games through Wine: an architecture reference for configuration and launching. |
| Playdock | [Jasonilization/Playdock](https://github.com/Jasonilization/Playdock) | `f58b8ef7fb70` | MIT | Describes itself as a free alternative to CrossOver; unreviewed. |
## Reviewed in the integration audit (2026-11-25)
Source read through the GitHub API; nothing executed. Detail and decisions are in [upstream-integration-audit.md](upstream-integration-audit.md).
| Project | Source | Pin (head) | License as reported | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| victory-mac | [skakwy/victory-mac](https://github.com/skakwy/victory-mac) | `22b3f8e45a59` | GPL-3.0 (LICENSE file read) | Per-component review with contributor permission; one memory-guard idea adapted | The maintainer authorized integration of his own work. His runtime targets a leaked console-game dump, so game-facing code is not adopted. Component table in [upstream-integration-audit.md](upstream-integration-audit.md). Reported frame rates are his unverified statements. |
| llvm-mingw | [mstorsjo/llvm-mingw](https://github.com/mstorsjo/llvm-mingw) | release `20261117` | Apache-2.0 with LLVM exceptions plus component licences (LICENSE.TXT; not audited line by line) | External build tool for #364 | Digest verified, used to build original workloads for x86-64 and ARM64; see [hybrid-toolchain.md](hybrid-toolchain.md). |
| MacBox | [aykhanium/MacBox](https://github.com/aykhanium/MacBox) | not pinned | GPL-2.0 (GitHub) | Rejected for reuse | Game-specific XCL layer; GPL-2.0-only is not combinable with GPL-3.0-or-later. Its README states gameplay is unverified. |
| ScarlettMac | [paveledits/ScarlettMac](https://github.com/paveledits/ScarlettMac) | not pinned | GPL-2.0 (GitHub), extra licence files | Rejected for reuse | Game-specific patches and scripts. |
| ossover | [hemkum/ossover](https://github.com/hemkum/ossover) | `5c11bd7be8da` | GPL-3.0-or-later (README, attribution file) | Technical reference | Swift CLI with system-info, Metal HUD log parsing and benchmark harness. Uses reverse-engineered CrossOver internals, which BetterXen does not treat as an interface. |
| Whisky | [Whisky-App/Whisky](https://github.com/Whisky-App/Whisky) | `fd5480a76b3e` | GPL-3.0-or-later (file header read) | Technical reference | Archived 2025-05-11. |
| rum | [lunguini/rum](https://github.com/lunguini/rum) | `657461b194e1` | GPL-3.0 (GitHub) | Technical reference | Active Whisky fork. |
| Game Porting Toolkit licence | copy of `D3DMetal/4.0/License.pdf` in Sikarugir | read | Apple proprietary | User-supplied only | Non-commercial distribution, evaluation purpose, no reverse engineering. See audit file. |
## Not yet researched
Apple's Game Porting Toolkit documentation and license (D3DMetal's actual terms), Rosetta 2's support lifetime, CrossOver's documented command-line interfaces and bottle management, and other established projects. These are issues #349, #350 and #354; nothing is claimed about them here.
## Provenance decision
At this initial discovery review, VIctory-family projects were not adopted. The later shader-only snapshot is recorded above; no broader adoption follows from it. Their GPL grants apply to their own source; they do not establish that the material they were built for is authorized. The registry records them for architecture ideas visible in public documentation (cache identity, upload visibility, test structure). No code, shader corpus, asset or tooling from them enters BetterXen without a recorded per-file review, and anything game-specific or decryption-related is excluded.
VIctory-family projects are not adopted. Their GPL grants apply to their own source; they do not establish that the material they were built for is authorized. The registry records them for architecture ideas visible in public documentation (cache identity, upload visibility, test structure). No code, shader corpus, asset or tooling from them enters BetterXen without a recorded per-file review, and anything game-specific or decryption-related is excluded.
+10 -22
View File
@@ -1,12 +1,10 @@
# victory-shader integration (GFX10 to DXIL recompiler)
This report separates the initial snapshot results from the subsequent [wave investigation and fixes](shader-wave-semantics.md), now included through PR #394 and the top of the split stack, PR #395. All recorded hardware results remain local observations, not independent acceptance. The runner dependencies are separate.
Evidence: classes noted per row. Everything ran on one machine (Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, bottle `betterxen-test`, default backend) and has **not been independently reproduced**. No game, console title or leaked material was used.
## What was integrated
`crates/victory-shader` is a snapshot of `crates/victory-shader/` from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (head `22b3f8e45a59`). It translates GFX10 (RDNA 2) machine code to PC DXIL, shader model 6.6, in pure Rust: a GFX10 decoder with an SP3 printer, control-flow structurizer, register spilling, wave emulation, fp64 by integer operations, its own LLVM 3.7 bitcode writer and DXIL container writer. About 43,500 lines against 4,022 in BetterXen's native `xenora-shader`. The native RDNA-to-Metal compiler is untouched and still paused; the two are different targets (DXIL for D3D12 under CrossOver versus MSL) and nothing was replaced. Provenance, authors, licences, the initial 19 lint-only lines and subsequent wave changes are in [`crates/victory-shader/UPSTREAM.md`](../../crates/victory-shader/UPSTREAM.md). Licensing: GPL-3.0 upstream, GPL-3.0-or-later here, one MIT Mesa-derived table with its notice kept.
`crates/victory-shader` is a snapshot of `crates/victory-shader/` from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (head `22b3f8e45a59`). It translates GFX10 (RDNA 2) machine code to PC DXIL, shader model 6.6, in pure Rust: a GFX10 decoder with an SP3 printer, control-flow structurizer, register spilling, wave emulation, fp64 by integer operations, its own LLVM 3.7 bitcode writer and DXIL container writer. About 43,500 lines against 4,022 in BetterXen's native `xenora-shader`. The native RDNA-to-Metal compiler is untouched and still paused; the two are different targets (DXIL for D3D12 under CrossOver versus MSL) and nothing was replaced. Provenance, authors, licences and the 19 changed lines are in [`crates/victory-shader/UPSTREAM.md`](../../crates/victory-shader/UPSTREAM.md). Licensing: GPL-3.0 upstream, GPL-3.0-or-later here, one MIT Mesa-derived table with its notice kept.
Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game-specific code (one console title's runtime) and their provenance questions; the console shader containers the crate can also parse were not exercised, because no authorized container exists.
@@ -14,7 +12,7 @@ Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game
- `emit::translate_native` (BetterXen addition, `emit/betterxen.rs`): the crate only accepted shaders inside console containers; this entry point takes a compute program as machine code plus root layout, which is what BetterXen has.
- `emit/betterxen_tests.rs`: BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled with LLVM's `llvm-mc`) are wrapped in a short descriptor-table prologue, translated to DXIL, and compared with the expected words in `fixtures/manifest.toml`. Those expectations were derived by hand in the manifest and are checked by BetterXen's independent reference; none comes from the recompiler. Six of the eleven manifest fixtures have input and expected words (add, float-exact, bitwise-branch, or, shifts, ashr); the five graphics-stage fixtures (`x9-*`) have none and are not bridged.
- Running the cross-built Windows test executable under CrossOver is done by `scripts/hybrid/run-shader-gpu-tests.sh` through `betterxen-hybrid run`. The script is in PR #395 on top of the shader crate (#394); the `betterxen-hybrid` runner and stall supervision are separate PRs #384 and #388, absent from that base. The GPU results below were produced with those dependencies present. See the [architecture guide](../architecture.md) and [testing prerequisites](../testing/README.md).
- `scripts/hybrid/run-shader-gpu-tests.sh`: cross-builds the test executable (llvm-mingw, `x86_64-pc-windows-gnullvm`) and runs it through `betterxen-hybrid run`, so the supervision, memory guard, stall detection and JSON record apply.
## Results
@@ -26,33 +24,23 @@ Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game
| BetterXen fixtures run on the GPU: D3D12 under CrossOver 26.3 (D3DMetal) | **6 of 6 output words match the manifest** | via `betterxen-hybrid run`, 2.3 to 2.6 s including bottle start; the GPU is a D3D12 device with shader model 6.6 as upstream's host layer requires |
| Negative control | a flipped expected word is rejected; the output is not the zeroed buffer | `a_wrong_expectation_is_detected` |
| Same GPU tests on DXMT, DXVK and wined3d (no D3D12) | fail with "no SM 6.6 D3D12 hardware device: not verified" | confirms they cannot pass by skipping; upstream's own tests print "skipped" instead |
| Original vendored suite before the wave fixes, under CrossOver (default backend), 229 tests | 224 passed, **2 failed**, 3 ignored | the two failures are explained in `shader-wave-semantics.md` |
| Whole suite with the wave fixes in the integration stack, under CrossOver | **232 tests: 229 passed, 0 failed, 3 ignored** | the 3 additional tests are BetterXen's f64 tests; see below |
| Whole suite under CrossOver (default backend), 229 tests including BetterXen's 4 | 224 passed, **2 failed**, 3 ignored | see below |
| Upstream suite on a backend without D3D12 (DXMT) | 201 passed, 25 failed, 3 ignored | see the classification below |
The initial failures were `whole_wave_f64_sum_and_cvt_f32_f64` (returned 0,
expected `0x40a00000`) and
`a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit`
(returned 0, expected `0x5914`). The later
[wave investigation](shader-wave-semantics.md) supersedes the initial wave-width
hypothesis: it records unsupported native double operations for the first case
and an invalid 64-lane test precondition on a 32-lane device for the second.
The stack now uses integer fp64 addition for the sum and device-aware rejection
for the 64-lane-only case. Neither change establishes Xbox-hardware agreement.
The two failures are `whole_wave_f64_sum_and_cvt_f32_f64` (a wave-wide fp64 sum returned 0, expected `0x40a00000`) and `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (64 lanes: got 0, expected `0x5914`). Both are cross-lane wave reductions of the console's 64-lane waves. Hypothesis, **not verified**: the host's waves are 32 lanes wide (Apple GPU) and D3DMetal does not honour the required wave size or wave operation semantics. The cause, and whether upstream passes them on a Windows GPU, were not investigated.
## Which tests actually executed on the GPU
The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each test was therefore run on the default backend (D3D12 via D3DMetal) and on DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there. After the included wave fixes (232 tests: 225 upstream, 7 BetterXen):
The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each of the 229 tests was therefore run on both the default backend (D3D12 via D3DMetal) and DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there.
| Group | Tests |
| --- | --- |
| Executed on the D3D12 hardware device and passed | **31** (26 of them fail without D3D12; 5 pass only by skipping there) |
| Executed on the D3D12 hardware device and failed | **0** |
| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 201, including 3 ignored |
| Total | 232 |
| Executed on the D3D12 hardware device and passed | 30 (25 of them fail without D3D12; 5 pass only by skipping without it) |
| Executed on the D3D12 hardware device and failed | 2 (they "pass" without D3D12 by skipping, which hides the failure) |
| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 197, including 3 ignored |
| Total | 229 (225 upstream + 4 BetterXen; BetterXen's 2 GPU tests are among the 32 GPU-dependent) |
For the vendored upstream code before the included wave fixes the same method gave 229 tests: 32 GPU-dependent, 30 passed on the device and 2 failed (they "passed" without D3D12 by skipping, which hid the failures), see `shader-wave-semantics.md`. Three of the 31 are BetterXen's GPU tests (fixtures, negative control, bit-exact f64 sums). Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such.
Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such.
## Limits
-2
View File
@@ -1,7 +1,5 @@
# Open Phase 01 risks
**Historical native Phase 01 register.** Owners and next experiments below retain their original candidate scope; they are not current assignments or hybrid priorities. Active hybrid risks and exit conditions are in the [roadmap](roadmap.md), with component boundaries in [architecture.md](architecture.md).
| ID | Risk and impact | Current evidence | Owner and next experiment |
|---|---|---|---|
| R1 | Console shader container, launch state and resource descriptors remain unknown, so the fixture cannot establish console compatibility. | Public related-target specifications, class C | Xbox research. Seek an authorized exact-target specification before proposing a parser. |
+2 -4
View File
@@ -1,7 +1,5 @@
# BetterXen roadmap
The [architecture guide](architecture.md) separates code present in the split integration stack from the separate hybrid runner PRs. Local synthetic results do not satisfy the independent baseline or advance the phase automatically. Issue lists and parked items below record the transition plan; consult current issue state before selecting work.
**This is the single authoritative active roadmap.** GitHub Issues hold the current phase's tasks, the open milestone names the current phase, and this file explains strategy, phase order, parked work and completion criteria. If another document disagrees, this one governs, except [ADR 0005](adr/0005-crossover-hybrid-direction.md) for the decision itself.
## Direction
@@ -26,7 +24,7 @@ Only the current phase has a GitHub milestone and detailed issues. Later phases
## Engineering rules
[AGENTS.md](../AGENTS.md) (`CLAUDE.md` is a symlink to it) was rewritten to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing; ADR 0005 records the decision. The honesty, verification, provenance and clean-room rules are unchanged. The transition is recorded in repository history; use the requested PR base or current `main`, not the former planning branch, for new work.
[AGENTS.md](../AGENTS.md) (`CLAUDE.md` is a symlink to it) was rewritten to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing; ADR 0005 records the decision. The honesty, verification, provenance and clean-room rules are unchanged. Both are on the local branch `planning/hybrid-first-transition` and await maintainer review; nothing has been pushed.
## How progress is reported
@@ -48,7 +46,7 @@ Phase status is one of: Not started, Researching, In development, Blocked, In va
6. A reproducible CrossOver environment and a recorded baseline of CPU, GPU, memory and stability, reproduced by a second contributor ([#355](https://github.com/MacosPorters/betterxen/issues/355)).
7. BetterXen's responsibilities versus CrossOver's recorded in an ADR a maintainer accepts ([#351](https://github.com/MacosPorters/betterxen/issues/351)).
**Transition issue inventory (not a live status query):** #145, #348, #350, #351, #353, #354, #355, #363, #364, #365, plus #346 (project board, needs the GitHub `project` token scope; does not block engineering).
**Open issues:** #145, #348, #350, #351, #353, #354, #355, #363, #364, #365, plus #346 (project board, needs the GitHub `project` token scope; does not block engineering).
**Known risks:** CrossOver is proprietary, so bundling or modifying may be prohibited; integration interfaces may be undocumented (see below); Xbox titles may not run at all.
-2
View File
@@ -1,7 +1,5 @@
# Runtime service registry
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, the static probe and the command-line reports all use it, and they read the import directory with one bounded parser, `import_table::parse_imports`.
| Part | File | Role |
-2
View File
@@ -1,7 +1,5 @@
# Typed runtime services
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
Generated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit.
A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted.
-2
View File
@@ -1,7 +1,5 @@
# Guest threads
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
`crates/loader/src/scheduler.rs` runs guest threads deterministically on one host thread. A guest thread is a CPU context, a guarded stack and a TEB; it is never a host thread. Guest threads never execute at the same time, so no guest memory-ordering model is relied on (#199).
## Scheduling
-2
View File
@@ -1,7 +1,5 @@
# gfx1030 instruction coverage
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
For counts of every gfx1030 form in AMD's metadata against forms Xenora can execute, run `xenora shaders coverage`. Its "discovered" column is metadata coverage, not execution support.
The decoder accepts an explicitly tagged, little-endian gfx1030 Wave32
-2
View File
@@ -1,7 +1,5 @@
# Synthetic compute lowering
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
The compiler accepts explicitly tagged raw gfx1030 code up to 1,024 bytes and requires a whole number of 32-bit words. The verifier checks source initialization, exact resource slots and address operands, immutability of VGPR 0, memory ordering, one completed output store and program termination. VGPR 0 is reserved for resource indexing. Keeping it out of arithmetic means the host's grid position is never exposed as a guest register value.
Verification maps each initialized register to its latest typed temporary. Reads after a load require a load wait. Because generated memory accesses are synchronous expressions within a thread and buffers are disjoint, waits can be discharged during verification. Metal completion is still required before host readback. Store and load aliases between lanes are excluded by the [fixture ABI](../adr/0003-demo-memory-model.md). The output buffer uses Metal index 1 and the read-only input uses index 0.
-2
View File
@@ -1,7 +1,5 @@
# Independent gfx1030 CPU reference
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
`xenora_ref::execute` reads raw little-endian code bytes and input words without dependencies on the production ISA crate, the compiler or Metal. It accepts at most 1024 instruction bytes and 4096 input words. The synthetic ABI gives every invocation its own input and output word. The indexed load and store forms need no host address arithmetic, and V0 is reserved for that indexing. Dispatch indices form Wave32 waves of 32 consecutive invocations, executed in lockstep with shared scalar state. The reference accepts uniform forward branches driven by scalar register state or by a compare mask in VCC_LO. Cross-lane register access other than compare masks, and EXEC derived from lane data, are outside the subset. Floating-point arithmetic is restricted to positive normal inputs and exact normal results.
| AMD RDNA 2 ISA guide instruction | Reference operation |
-2
View File
@@ -1,7 +1,5 @@
# SOP2 scalar ALU subset
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
Xenora decodes and executes thirty-three gfx1030 SOP2 forms. Each takes 32-bit
operands and writes a normal SGPR (s0-s105). The seventeen below set SCC; the
sixteen in [Arithmetic, select and bit-field forms](#arithmetic-select-and-bit-field-forms)
-2
View File
@@ -1,7 +1,5 @@
# SOPK scalar immediate forms
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
Xenora decodes and translates sixteen gfx1030 SOPK integer forms through the
semantic registry (`crates/isa/semantics/rdna2/sopk.toml`, operand rules
`sopk_sgpr` and `sopk_compare`). Each is one 32-bit word: SIMM16 in bits 0-15,
-2
View File
@@ -1,7 +1,5 @@
# Adding an instruction through the semantic registry
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
The semantic registry is a data file that declares what each supported gfx1030
instruction form does. A generator checks it and turns it into Rust tables that
the decoder uses. This page explains where entries live, what each field means,
-2
View File
@@ -1,7 +1,5 @@
# Execution contract: bounded Wave32 VOPC integer compares (issue #186)
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
Status: v2, after independent review (codex-contract.log); findings 1-7 addressed. Scope is the Xenora compute-fixture ABI
(one input word and one output word per dispatched thread; dispatch index `i`
is wave `i / 32`, lane `i % 32`; every wave starts with EXEC_LO = 0xffffffff;
-2
View File
@@ -1,7 +1,5 @@
# Wave32 vector unary integer operations and swap
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
Xenora translates six gfx1030 VOP1 integer forms for the synthetic Wave32 compute
ABI. The AMD RDNA 2 ISA Reference Guide defines the operations in section 12.8,
the encoding in section 13.3.2, and the execution mask (EXEC) in section 3.3.
-2
View File
@@ -1,7 +1,5 @@
# Wave32 vector select, carry and borrow
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
The gfx1030 compute fixture ABI supports four 32-bit vector two-operand
instruction (VOP2) forms that read the vector condition code (VCC).
In Wave32, bit `n` of `VCC_LO` supplies lane `n`'s input `c`.
-78
View File
@@ -1,83 +1,5 @@
# Testing and acceptance
## Select checks by scope
Active hybrid work follows the [architecture guide](../architecture.md).
Preserved native tests remain regression checks, with their original synthetic
scope. Historical Phase 01/02 and G-number acceptance gates are not the current
hybrid phase criteria. The [roadmap](../roadmap.md) controls phase completion.
### Documentation-only changes
Run from the repository root:
```sh
python3 scripts/audit/docs_hygiene.py --require-yaml
python3 scripts/audit/status.py --check
python3 scripts/audit/semantic_coverage.py --check
scripts/audit/claims.sh
scripts/audit/dependencies.sh
git diff --check
```
Hygiene checks tracked relative Markdown file links, conflict markers and
workflow YAML; it does not validate anchors or external URLs. Status and coverage
checks detect drift in generated native tables. These are consistency checks,
not CPU/GPU execution or independent acceptance. API documentation can also be
compiled with `CARGO_BUILD_JOBS=2 cargo +1.100.0 doc --locked --workspace --no-deps`.
### Hybrid shader fixtures
On native ARM64 macOS with Rust 1.100.0 selected, `cargo test --locked -p victory-shader` runs CPU-side
compiler tests. Windows-only GPU tests require a Windows guest executable,
an externally installed CrossOver with a configured bottle and a D3D12-capable
backend. DXIL emission alone is not GPU verification.
The following command additionally requires a checkout containing the
`betterxen-hybrid` runner from [PR #384](https://github.com/MacosPorters/betterxen/pull/384)
and stall supervision from [PR #388](https://github.com/MacosPorters/betterxen/pull/388).
They are absent from the split shader/script stack's base. Install Rust 1.100.0
with `x86_64-pc-windows-gnullvm` and provide an unpacked llvm-mingw toolchain
(the recorded integration used release 20261117):
```sh
scripts/hybrid/run-shader-gpu-tests.sh /path/to/llvm-mingw betterxen-test fixtures
# Optional whole upstream suite, including the wave fixes now in this stack:
scripts/hybrid/run-shader-gpu-tests.sh /path/to/llvm-mingw betterxen-test all
```
`fixtures` filters on `betterxen`; the latest stack adds three fp64 tests to the
original four BetterXen tests. The script still expects the literal summary
`test result: ok. 4 passed`, so that expectation may reject a successful run of
the expanded selection. This documentation PR leaves the script unchanged.
Use `all` for the recorded whole-suite procedure and inspect output and skips. The script obtains the executable from Cargo build messages and
uses `debug/deps` as a fallback. It delegates supervision to the hybrid runner
and writes records under ignored `artifacts/hybrid-runs/`.
Record source revisions, host, CrossOver/bottle/backend, Rust and cross-toolchain
versions, commands, output and pass/fail/skip counts. Inspect whether each test
actually dispatched: some upstream tests return success after skipping when
D3D12, WARP or `dxil.dll` is unavailable. BetterXen's GPU tests fail without the
required hardware device. The [integration report](../research/victory-shader-integration.md)
preserves the original two failures and the included
[wave fixes](../research/shader-wave-semantics.md), which report 229 passed,
0 failed and 3 ignored on the recorded host. The device-width rejection test
is a CPU rejection check on that host, not a verified 64-lane GPU sum. No independent reproduction or
phase completion is claimed.
### Workspace and preserved native regressions
Use `cargo fmt --all -- --check`,
`cargo clippy --locked --workspace --all-targets -- -D warnings` and
`cargo test --locked --workspace` as appropriate to code changes.
`scripts/test-gpu.sh`, `scripts/demo.sh`, the independent semantic review,
fixture assembly, mutation and benchmark procedures below exercise the
preserved native path. They do not launch CrossOver or validate the DXIL path.
A successful native run does not substitute for hybrid workload readback.
Keep unavailable tools, excluded target modules and ignored tests visible.
## Preserved procedures and evidence
- [Migrated pull-request integration review](migration-pr-review.md) — Merge decisions, fixes, native verification and remaining scope limits.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
-2
View File
@@ -1,7 +1,5 @@
# Benchmark protocol
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
The benchmark harness measures each fixture in its manifest that passes its
correctness test in the same run. It never reports a number for a shader that
failed or was skipped.
-2
View File
@@ -1,7 +1,5 @@
# CPU test runtime, shards and coverage map
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
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
-63
View File
@@ -1,63 +0,0 @@
# Hybrid documentation consistency audit
Audited 2026-11-25 for the maintainer's documentation-only alignment task.
Base: `59b6c4db5e2ceba5aecafc947d1f314c8fe0a895`, the head of split integration
[PR #395](https://github.com/MacosPorters/betterxen/pull/395), stacked on
[PR #394](https://github.com/MacosPorters/betterxen/pull/394). The documentation
branch is `docs/hybrid-architecture-alignment`. The base advanced during the audit
to include the wave fixes from #394; the documentation branch was rebased onto
that updated top before final checks. No new issue was requested or
created. This is a documentation consistency review, not independent technical
acceptance of either implementation PR.
## Coverage and disposition
The audit inventories the base's 95 tracked Markdown paths, including the
`CLAUDE.md` symlink, and checks architecture/development references in issue
forms, Cargo metadata, crate API comments and documentation registries. Ignored
experiments and generated local artifacts are outside the published documentation.
| Surface | Disposition |
| --- | --- |
| `AGENTS.md`, `CLAUDE.md`, `CONTRIBUTING.md`, PR template | Point agents and contributors to hybrid boundaries and appropriate checks; preserve the symlink, claim precedence, provenance rules and native pause. Explain direct maintainer assignments and stacked bases. |
| Root README and documentation index | Put hybrid responsibilities and split dependencies first; label retained native diagrams, build procedures and capability counts. |
| Architecture, interfaces and ADRs | Add the current integration guide. Retain native fixture contracts in ADRs 0003/0004 with explicit scope; retain ADR 0005's strategic decision and distinguish subsequent observations from architectural acceptance. |
| Roadmap, milestones and archived plans | Keep Phase 1 active and its exit criteria intact. Mark issue-state inventories as snapshots; preserve already-labelled archived plans and retired milestone data. Remove obsolete local-branch instructions. |
| Crate documentation | Add a workspace crate guide and shader-crate README. Inspect crate-level Rustdoc and manifest descriptions; retain API text and legacy names, with component scope explained in the guides. No Rust sources or manifests changed. |
| CPU, runtime and shader contracts | Label maintained native procedures and inventories as preserved research. Keep generated coverage content unchanged; its native scope is explained by the index, architecture and progress pages. |
| Research, upstream registry and reuse matrix | Distinguish initial discovery decisions from the shader-only snapshot already in the base. Preserve original pins, notices, uncertainty and the requirement for independent provenance review. No broader upstream adoption is authorized. |
| Testing, validation, benchmarks and campaign ledgers | Separate hybrid readback from native regressions and historical acceptance. Mark old next tasks and campaign ownership as historical; retain recorded counts and candidate scope. Explain the expanded BetterXen test selection versus the script’s old four-test expectation. |
| Legal/security/support and attribution | Clarify input policy versus demonstrated execution and the native threat-model boundary. Preserve security reporting, conduct rules, license texts, upstream notices and historical benchmark reports. |
| Workflow/issue forms and machine-readable evidence | Existing hybrid task forms already describe active scope. Leave workflows, claims/status data, retired milestone JSON, fixture manifests and generated evidence untouched. |
Searches covered native-first/native-only language, former bans on Wine,
CrossOver, Rosetta or Vulkan, phase and milestone references, active priorities,
next-task instructions, licensing/reuse assertions and testing guidance. Retained
old terminology is scoped historical evidence or a component identifier, not a
second active roadmap. No external vendor facts were revalidated by this audit;
new architecture statements refer to the checked-in source and recorded PR
observations, with their limits preserved.
## Validation
Commands are listed in the [testing guide](README.md). Repository hygiene,
generated status/semantic coverage, claims, dependency direction and whitespace
checks passed on the aligned tree: hygiene checked 699 tracked files with zero
problems, claims checked 22 records and dependency direction checked five
graphics crates. Generated tables matched and whitespace checks passed. These
checks do not execute workloads, certify upstream
provenance or close a phase gate.
`CARGO_BUILD_JOBS=2 cargo doc --locked --workspace --no-deps` initially stopped
because the default compiler was Rust 1.94.1, below the workspace requirement.
`CARGO_BUILD_JOBS=2 cargo +1.100.0 doc --locked --workspace --no-deps` completed.
It emitted 38 Rustdoc warnings in unchanged sources: 3 in `victory-shader`, 12 in
`xenora-loader`, 16 in `xenora-ref` and 7 in `xenora-isa` (private links,
unresolved bracketed expressions and an unclosed HTML tag). This is a successful
API-documentation build with warnings, not a warning-free build. Logs are under
ignored `artifacts/docs-alignment/`.
CPU, GPU, CrossOver workloads, mutation and performance tests were not rerun for
this documentation-only change. Existing results remain attributed to their
original candidates and hosts. Independent reproduction and acceptance remain
outstanding wherever the source records say so.
-2
View File
@@ -1,7 +1,5 @@
# Gate A: a compiled C program
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
Gate A asks for an independently compiled C program, exercising allocation,
file operations, arithmetic, function calls and error handling, to run through
Xenora. The maintainer split it into two milestones. Gate A is complete only
-2
View File
@@ -1,7 +1,5 @@
# Infrastructure QA tooling
**Scope:** the Phase II/III tooling names below belong to the earlier infrastructure campaign, not the active hybrid roadmap. Native CPU/RDNA2 candidate lists are read-only inventories, not authorized work queues. Use the [hybrid testing guide](../README.md) for current validation scope; reuse these helpers only where applicable.
Standalone helpers under `scripts/qa/` and `scripts/release/`. They do not replace
`scripts/audit/*`, `scripts/benchmark.sh` or `scripts/test-gpu.sh`. New checks are
advisory until reviewed.
@@ -1,7 +1,5 @@
# Phase III compatibility-intelligence checkpoint ledger
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../../architecture.md) for active priorities.
Branch: `feat/infra-phase3-compat`. Issue #277.
Approved paths only. No push without separate authorization.
-2
View File
@@ -1,7 +1,5 @@
# Phase 01 mutation testing
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
The source campaign covers the decoder, fixture parser,
verifier, lowering and reference interpreter through the default CPU workspace
tests. The independent semantic and oracle campaigns are separate requirements.
-2
View File
@@ -1,7 +1,5 @@
# GPU and guest execution evidence
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
The resumed checkout started clean on main at
`4b9a4cecf35c8d4d90d8ecdb9c1510e7bd260102`, tracking origin/main.
The diff since `5c479005b0e0631a608a369b9e41327da61bb61e` contains three
-2
View File
@@ -1,7 +1,5 @@
# Phase 01 assurance checkpoint
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
**NOT RELEASE-READY.** The full source mutation campaign and native
technical evidence in this checkpoint ran from the clean
`aff46b0904a0182a6f0543125e4491ab67270f64` candidate on 2026-11-22. The
-2
View File
@@ -1,7 +1,5 @@
# Phase 01 engineering checkpoint
**Historical native record.** Plans and results below retain their original candidate scope. Native development is paused under [ADR 0005](../adr/0005-crossover-hybrid-direction.md); follow the [hybrid architecture](../architecture.md) for active priorities.
**NOT RELEASE-READY.** The evidence below was recorded on 2026-11-22 against the integrated local working tree based on `9ab5bf9`. The release brief requires evidence against one final candidate commit. Every formal gate therefore remains **NOT MET**. A passing local check is identified separately from outstanding work.
| Gate | Local evidence and remaining requirement |
-2
View File
@@ -1,7 +1,5 @@
# Independent review
**Scope:** retained independent reviews of native synthetic candidates. Their named commits, gates and required follow-ups are historical evidence, not certification of CrossOver or the vendored DXIL compiler. Active validation scope is in the [testing guide](README.md).
## gfx1030 form acceptance
Use the [AMD RDNA2 desktop GPU (gfx1030) form acceptance rule](shader-form-acceptance.md) for entries that
-2
View File
@@ -1,7 +1,5 @@
# AMD RDNA2 desktop GPU (gfx1030) form acceptance
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
This is the promotion rule for AMD RDNA2 desktop GPU (`gfx1030`) instruction
forms in [`docs/status.toml`](../status.toml). It implements the documentation
step of [#302](https://github.com/ranveersoni98/Xenora/issues/302). It does not
-2
View File
@@ -1,7 +1,5 @@
# Persistent resources and translated rendering acceptance
**Preserved native research.** This page governs existing synthetic fixtures and their regression checks. It does not define CrossOver compatibility or authorize native expansion; follow the [hybrid architecture](../architecture.md) for active work.
The upstream observations below describe pinned source inspected for this
milestone. Xenora tests use original fixtures. The upstream tests were not
run here. PASS records a native ARM64 run with assertions, FAIL a reproduced
+1 -7
View File
@@ -1,13 +1,7 @@
# Shader input and execution limits
## Scope
The limits below describe the preserved native fixture/compiler path. They are not a sandbox or security guarantee for CrossOver, Wine, D3DMetal or the vendored shader parser. Hybrid launches add an external process, bottle, selected backend and guest workload; assess those boundaries separately for the exact installed versions. Runner timeouts and resource supervision do not establish isolation or recovery from GPU stalls. The [architecture guide](architecture.md) records which launch dependencies are present.
## Native fixture boundaries
The public demo runs embedded, reviewed synthetic fixtures. The compiler library accepts arbitrary byte slices and requires an explicit gfx1030 target. It checks size and alignment before decoding and rejects unsupported forms, uninitialized registers and resource accesses beyond the fixture ABI. There is no container whose offsets can select host memory. An invalid stream cannot load arbitrary Metal source.
The Metal backend accepts trusted MSL under a two-buffer contract. It checks source size and dispatch dimensions, allocates disjoint buffers, dispatches one thread per word and waits for command completion before copying readback. It does not parse MSL. Treat the native API as a boundary for trusted source. The demo script bounds process runtime at 30 seconds and enables API and shader validation. A process timeout does not guarantee recovery from a hardware stall.
The fuzz harnesses exercise host-side parsers only. Corpus mutations do not reach the GPU. Logs, compiler diagnostics, and local artifacts can contain absolute paths and are kept outside tracked files. This original fixture flow has no capture replay or protected-content input path; it is not an inventory of all current workspace caches or parsers.
The fuzz harnesses exercise host-side parsers only. Corpus mutations do not reach the GPU. Logs, compiler diagnostics, and local artifacts can contain absolute paths and are kept outside tracked files. There is no cache, capture replay or protected-content input path.
-2
View File
@@ -1,7 +1,5 @@
# Synthetic guest execution experiments
**Preserved native research.** This fixture or validation procedure is for the paused independent native path, not CrossOver integration. Retain existing regression checks; proposed expansion is historical unless a specific hybrid need or maintainer decision authorizes it. See the [active architecture](../../docs/architecture.md).
The bounded x86-64 guest interpreter (X1) runs on native ARM64 macOS.
This isolated Cargo workspace implements the original fixtures in the
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build BetterXen's original Windows workloads (issue #364) with a pinned cross toolchain and
# write the results to artifacts/hybrid-workloads/<arch>/. Nothing is executed; the script ends
# by printing `file` and the PE machine type of every output so a build that produced the wrong
# architecture fails here.
#
# scripts/hybrid/build-windows-workloads.sh <llvm-mingw-dir>
#
# <llvm-mingw-dir> is an unpacked llvm-mingw release (https://github.com/mstorsjo/llvm-mingw,
# Apache-2.0 with LLVM exceptions); see docs/research/hybrid-toolchain.md for the pinned
# release and checksum. Rust workloads use the x86_64-pc-windows-gnullvm and
# aarch64-pc-windows-gnullvm targets (rustup target add ...) linked with that toolchain.
set -eu
TC=${1:?usage: $0 <llvm-mingw-dir>}
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
OUT="$ROOT/artifacts/hybrid-workloads"
RUSTC_TC=${RUSTUP_TOOLCHAIN_FOR_WORKLOADS:-1.100.0}
[ -x "$TC/bin/x86_64-w64-mingw32-clang" ] || { echo "no llvm-mingw at $TC" >&2; exit 1; }
for arch in x86_64 aarch64; do
d="$OUT/$arch"; mkdir -p "$d"
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$d/selfcheck-c.exe" "$ROOT/workloads/win-selfcheck-c/selfcheck.c"
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$d/d3d11-clear.exe" "$ROOT/workloads/d3d11-clear/d3d11_clear.c" -ld3d11 -ldxgi
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$d/d3d11-frameloop.exe" "$ROOT/workloads/d3d11-frameloop/frameloop.c" -ld3d11 -ldxgi -ldxguid -ld3dcompiler -lm
env_arch=$(echo "$arch" | tr a-z A-Z)
(
export PATH="$TC/bin:$PATH"
export "CARGO_TARGET_${env_arch}_PC_WINDOWS_GNULLVM_LINKER=$TC/bin/$arch-w64-mingw32-clang"
cd "$ROOT/workloads/win-selfcheck-rust"
CARGO_TARGET_DIR="$OUT/rust-target" rustup run "$RUSTC_TC" cargo build --release --target "$arch-pc-windows-gnullvm" -q
)
cp "$OUT/rust-target/$arch-pc-windows-gnullvm/release/win-selfcheck-rust.exe" "$d/selfcheck-rust.exe"
done
fail=0
for f in "$OUT"/x86_64/*.exe "$OUT"/aarch64/*.exe; do
want=$(basename "$(dirname "$f")")
desc=$(file -b "$f")
case "$want:$desc" in
x86_64:*"PE32+"*"x86-64"*) ok=ok ;;
aarch64:*"PE32+"*"Aarch64"*|aarch64:*"PE32+"*"ARM64"*) ok=ok ;;
*) ok=WRONG; fail=1 ;;
esac
echo "$ok $f: $desc"
done
exit $fail
+2 -20
View File
@@ -21,26 +21,8 @@ rustup run 1.100.0 cargo build -q -p betterxen-hybrid
export PATH="$TC/bin:$PATH"
export CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER="$TC/bin/x86_64-w64-mingw32-clang"
export CARGO_TARGET_DIR="$ROOT/artifacts/victory-win"
# Build the Windows test executable and take its path from cargo's own build message. It normally
# lands in <target>/x86_64-pc-windows-gnullvm/debug/deps/, but cargo's layout can differ with the
# build configuration, so the path is not guessed; `deps/` is only the fallback.
EXE=$(rustup run 1.100.0 cargo test -q -p victory-shader --target x86_64-pc-windows-gnullvm --no-run \
--message-format=json | python3 -I -c '
import json, sys
exe = None
for line in sys.stdin:
try:
m = json.loads(line)
except ValueError:
continue
if m.get("reason") == "compiler-artifact" and m.get("profile", {}).get("test") \
and m.get("target", {}).get("name") in ("victory_shader", "victory-shader") and m.get("executable"):
exe = m["executable"]
print(exe or "")')
if [ -z "$EXE" ]; then
EXE=$(ls -t "$CARGO_TARGET_DIR"/x86_64-pc-windows-gnullvm/debug/deps/victory_shader-*.exe 2>/dev/null | head -1)
fi
[ -n "$EXE" ] && [ -f "$EXE" ] || { echo "could not find the victory-shader test executable" >&2; exit 1; }
rustup run 1.100.0 cargo test -q -p victory-shader --target x86_64-pc-windows-gnullvm --no-run
EXE=$(ls -t "$CARGO_TARGET_DIR"/x86_64-pc-windows-gnullvm/debug/build/victory-shader/*/out/victory_shader-*.exe | head -1)
file "$EXE" | grep -q "PE32+ executable.*x86-64" || { echo "not an x86-64 PE: $EXE" >&2; exit 1; }
B="$ROOT/target/debug/betterxen-hybrid"
if [ "$WHICH" = all ]; then
+30 -1
View File
@@ -15,7 +15,7 @@ def dump(obj, path):
WF = os.path.join(ROOT, ".github", "workflows")
QUEUE_WORKFLOWS = ["agent-claims.yml"]
QUEUE_WORKFLOWS = ["agent-claims.yml", "agent-pr-checks.yml"]
USER_TEXT = re.compile(r"\$\{\{\s*github\.event\.(comment|issue|pull_request)\.(body|title)|github\.head_ref")
@@ -58,6 +58,11 @@ class Workflows(unittest.TestCase):
bad = "jobs:\n a:\n steps:\n - run: |\n echo ${{ github.event.comment.body }}\n"
self.assertTrue(any(re.search(r"\$\{\{", b) for b in run_blocks(bad)))
def test_pr_workflow_never_checks_out_pr_code(self):
text = self.read("agent-pr-checks.yml")
self.assertNotRegex(text, r"github\.event\.pull_request\.head|ref:\s*\$\{\{")
self.assertIn("pull_request_target", text)
def job(self, name, job):
"""Text of one job block: from ` <job>:` to the next two-space-indented key."""
m = re.search(r"(?ms)^ %s:\n(.*?)(?=^ \S|\Z)" % re.escape(job), self.read(name))
@@ -69,7 +74,9 @@ class Workflows(unittest.TestCase):
def test_only_command_comments_start_runs(self):
# Ordinary comments must not start a claim run or a verification re-run.
self.assertIn("startsWith(github.event.comment.body, '/verified')", self.job_if("agent-pr-checks.yml", "verify"))
self.assertIn("startsWith(github.event.comment.body, '/')", self.job_if("agent-claims.yml", "command"))
self.assertNotIn("issue_comment", self.job_if("agent-pr-checks.yml", "check"))
def test_claim_jobs_share_one_group_and_replay(self):
for job in ("command", "audit"):
@@ -80,6 +87,15 @@ class Workflows(unittest.TestCase):
self.assertIn("--recent-commands", text, job)
self.assertNotIn("agent_queue decide", self.job("agent-claims.yml", "command"))
def test_rerun_needs_an_accepted_verification(self):
text = self.job("agent-pr-checks.yml", "verify")
self.assertIn('if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi', text)
self.assertLess(text.index("agent_queue should-rerun"), text.index("agent_queue pr-check"))
# The check is evaluated in this job: pull_request_target runs cannot be found by head SHA.
self.assertNotIn("gh run", text)
self.assertNotIn("actions: write", text)
self.assertIn("::warning title=Agent PR check (advisory)::", text)
def test_should_rerun_exit_codes(self):
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "a.json")
@@ -88,6 +104,19 @@ class Workflows(unittest.TestCase):
dump(actions, p)
self.assertEqual(Cli.run_cli(self, "should-rerun", "--actions", p).returncode, code, actions)
def test_verify_runs_one_at_a_time_per_pull_request(self):
text = self.job("agent-pr-checks.yml", "verify")
self.assertRegex(text, r"group: agent-verify-\$\{\{ github\.event\.issue\.number \}\}\n\s+cancel-in-progress: false")
def test_pr_check_is_advisory(self):
# Exit status 1 (problems found) only warns until the live smoke test and issue migration.
text = self.job("agent-pr-checks.yml", "check")
found = re.search(r'if \[ "\$status" -eq 1 \]; then\n(.*?)\n\s+elif \[ "\$status" -ne 0 \]; then\n\s+exit "\$status"', text, re.S)
self.assertIsNotNone(found, text)
self.assertIn("::warning title=Agent PR check (advisory)::", found.group(1))
self.assertNotIn("exit", found.group(1))
self.assertEqual(text.count("exit "), 1)
def test_actions_pinned_by_sha(self):
for name in QUEUE_WORKFLOWS:
for use in re.findall(r"uses:\s*(\S+)", self.read(name)):
-2
View File
@@ -1,7 +1,5 @@
# Synthetic PE32+ import fixtures
**Preserved native research.** This fixture or validation procedure is for the paused independent native path, not CrossOver integration. Retain existing regression checks; proposed expansion is historical unless a specific hybrid need or maintainer decision authorizes it. See the [active architecture](../../docs/architecture.md).
Run `tests/compat_fixtures/build.sh` on ARM64 macOS with native LLVM and LLD.
The script writes two x86-64 guest executables and their import listings under
`artifacts/compat-fixtures/`. Both variants come from the original C source
-2
View File
@@ -1,7 +1,5 @@
# Original AVX integer fixture specification
**Preserved native research.** This fixture or validation procedure is for the paused independent native path, not CrossOver integration. Retain existing regression checks; proposed expansion is historical unless a specific hybrid need or maintainer decision authorizes it. See the [active architecture](../../../docs/architecture.md).
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
-2
View File
@@ -1,7 +1,5 @@
# Native semantic mutation
**Preserved native research.** This fixture or validation procedure is for the paused independent native path, not CrossOver integration. Retain existing regression checks; proposed expansion is historical unless a specific hybrid need or maintainer decision authorizes it. See the [active architecture](../../docs/architecture.md).
Run serially on the native Apple Silicon gate machine.
```sh
-2
View File
@@ -1,7 +1,5 @@
# Independent review of the first RDNA2 fixture
**Preserved native research.** This fixture or validation procedure is for the paused independent native path, not CrossOver integration. Retain existing regression checks; proposed expansion is historical unless a specific hybrid need or maintainer decision authorizes it. See the [active architecture](../../docs/architecture.md).
AMD's RDNA2 ISA reference §8.1 defines indexed buffer addressing and the four-SGPR resource operand. Under Xenora's synthetic descriptors, the first instruction reads input word `i` into v1 and the store writes word `i` of the independent output. The vector memory wait permits the read's result to be consumed before the add. Section 12 gives the VOP1 move and carry-free unsigned addition semantics, so v2 receives `0x12345678` and v1 receives the sum reduced modulo `2^32`. The SOPK store wait completes the outstanding store. The SOPP end instruction also implicitly waits on RDNA2. Requiring both explicit waits is a conservative policy of this fixture compiler. These semantics are class B for RDNA2 and do not establish Xbox-specific applicability. [AMD RDNA2 ISA Reference Guide](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture)
LLVM 23.1.6 and the production decoder agreed on all seven fixture instructions, including their bytes, lengths, offsets and printed operands. AMD defines hardware semantics. LLVM is class E evidence for the tool's encoding and decoding behavior.
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more