mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 13:21:12 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a648cdecc7 | ||
|
|
911c27f62b | ||
|
|
9b9c3c63ee | ||
|
|
b16bdc1d4a | ||
|
|
21700c2869 | ||
|
|
da82407073 | ||
|
|
2e55cf2259 | ||
|
|
ef58b18147 | ||
|
|
2deada1f9d | ||
|
|
e57046a17d |
No files matched your search
@@ -8,55 +8,83 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
**"Work" authorizes, for the one item you pick:** posting a claim or a review, committing with DCO sign-off, pushing a branch, and opening a pull request. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
**"Work" authorizes, for the one item you pick:** opening a draft pull request, posting a review, committing with DCO sign-off, and pushing a branch. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
|
||||
### Step 1 — Preflight
|
||||
### Step 1 — Preflight: make the machine ready yourself
|
||||
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`. If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`). Verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor`. It must report the toolchain, CrossOver, at least 10 GB of free disk space, and no other game run on this machine.
|
||||
- Work in your own worktree and your own bottle. Never use a bottle another session is using.
|
||||
```sh
|
||||
cargo build --locked -p bx-cli && target/debug/bx-cli preflight
|
||||
```
|
||||
|
||||
`bx-cli preflight` must print `Ready to work.` It requires **all** of:
|
||||
|
||||
| Required | How it is found |
|
||||
| --- | --- |
|
||||
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
|
||||
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
|
||||
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
|
||||
| At least 10 GiB of free disk space | Measured |
|
||||
|
||||
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
|
||||
|
||||
| `MISSING` line | What you do |
|
||||
| --- | --- |
|
||||
| Target build, GDK | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header and the build by its structure (never by name), and saves both. |
|
||||
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
|
||||
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
|
||||
|
||||
**Stop only for what an agent cannot supply**, and say exactly which:
|
||||
|
||||
- the host is not an Apple Silicon Mac;
|
||||
- CrossOver is not installed (it is licensed software; do not install it);
|
||||
- `setup --find` reports that the target build or the GDK is not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
|
||||
|
||||
In those cases do not work around it: no fixes, tests or reviews "for someone else to verify". Work here is found by running the target build and checked against the GDK; an agent without them is guessing.
|
||||
|
||||
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
|
||||
|
||||
`bx-cli setup` remembers the two locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build or the GDK into a commit, issue or pull request (Section 6).
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
Take the first that applies. Do not skip ahead because a later one looks more interesting.
|
||||
Take the first that applies.
|
||||
|
||||
1. **Your person's pull requests that need attention.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,isDraft,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
If one has requested changes, unresolved review comments, failing checks or conflicts: fix that pull request. Resolve every review point, re-run Section 8, push, and reply to each point.
|
||||
Requested changes, unresolved review comments, failing checks, conflicts, or a draft you opened and have not finished: do that. Resolve every review point, re-run Section 8, push, and reply to each point.
|
||||
|
||||
2. **Review someone else's pull request.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
|
||||
```
|
||||
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test, confirm the test fails without the fix, read its proof, and post an approval or a change request with what you ran. If it needs deep review (the list is in the working method) and you can give one, do. If it is approved, green and not your person's, merge it (Section 7).
|
||||
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test **twice in a row**, confirm the test fails without the fix, and post an approval or a change request with what you ran. If it is approved, green and not your person's, merge it (Section 7).
|
||||
|
||||
3. **Fix one blocker of the current stage.**
|
||||
3. **A handoff issue of the current stage.**
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label blocker --label "stage: <current>" --json number,title,labels,comments
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label handoff --label "stage: <current>" --json number,title,labels
|
||||
```
|
||||
The current stage is named on the pinned issue labelled `ladder`. Take the top unclaimed blocker: those labelled `first`, then lowest number. A blocker is claimed if it has a `Claiming —` comment less than 3 days old or an open pull request. Then follow Step 3.
|
||||
A handoff is something a collaborator found and could not finish. The current stage is named on the pinned issue labelled `ladder`. Take the lowest-numbered one that no open pull request mentions, and follow Step 3.
|
||||
|
||||
4. **Discover.** If the current stage has no unclaimed blocker, run the stage's gate check (ten runs, [run protocol](docs/process/working-method.md#run-protocol)). For each signature in the report that has no issue, open or closed, file a blocker issue in the fixed shape. If the gate passes, post the ten-run result on the ladder issue and label it `needs-human`.
|
||||
4. **Run the target build and fix the first thing it stops on.** Run it under the [run protocol](docs/process/working-method.md#run-protocol) and read `bx-cli report`. Take the first signature in the report that no open pull request is titled with or mentions, and follow Step 3. A blocker you can see and fix needs **no issue**: the pull request is the record.
|
||||
|
||||
5. **Nothing applies.** Say so and stop. Do not invent work, open research documents, or start on a later stage's blockers while the current stage has claimed, unfinished ones — unless your person tells you to.
|
||||
5. **The run stops on nothing.** Make the stage's gate check (ten runs). If it passes, post the result on the ladder issue and label it `needs-human`; a person confirms the stage change. Then stop.
|
||||
|
||||
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
|
||||
|
||||
### Step 3 — Work one blocker
|
||||
|
||||
1. **Claim:** comment `Claiming — branch: track-<a..f>/<issue>-<slug>` and branch from `origin/main`.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. If you cannot explain the blocker in this session, write what you learned on the issue, release the claim, and stop. Do not guess a fix.
|
||||
1. **Claim with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. Check the contract against the GDK where the GDK covers it.
|
||||
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix.
|
||||
5. **Verify:** every command in Section 8. Without CrossOver you can still run the Rust checks, `scripts/build-shims.sh` and the docs check; say plainly which live checks were not run. Never report an unrun check as passed.
|
||||
6. **Proof:** ten runs before and ten after, every run reported, with the machine and the `main` commit.
|
||||
7. **Pull request:** one blocker; the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof); `Closes #<issue>`; DCO sign-off; no AI trailers. Watch CI until `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row. The test is what holds on every machine; your run is only why you looked.
|
||||
5. **Verify:** every command in Section 8.
|
||||
6. **Proof:** runs before and after on your machine, every run reported, with the machine and the `main` commit. Another collaborator's machine may never take the path yours took; say which path your runs took.
|
||||
7. **Finish:** fill in the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof), sign off, no AI trailers, mark the pull request ready. Do not wait for CI before moving on.
|
||||
8. **Stop.** The next "work" starts again at Step 2.
|
||||
|
||||
Nothing from the target build goes into a commit, issue or pull request (Section 6): keep run logs, dumps and captures in your private evidence folder outside the repository.
|
||||
**If you cannot fix what you found** (too large, out of session, or it needs a decision): close your draft, file one **handoff issue** labelled `handoff` and `stage: <name>`, titled `[handoff] <signature>`, with what you saw, what you tried and what is still unknown. That is the only time a blocker gets an issue.
|
||||
|
||||
---
|
||||
|
||||
@@ -128,10 +156,10 @@ _Reserved — policy migration in progress._
|
||||
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. A draft with no push for 3 days may be taken over. Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
2. **Isolate with branches or worktrees:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
git worktree add ../wt-<slug> -b track-<a..f>/<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
|
||||
@@ -10,6 +10,9 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **A collaborator only has to say "work"** (AGENTS.md §0, step 1). When `bx-cli preflight` fails, the agent makes the machine ready itself: the new `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (a large PE32+ file that imports `d3d12_xs.dll`; never by name), ignores the GDK's own tools, treats byte-identical copies as one build and keeps the copy with its imported DLLs beside it, and saves both settings. The agent may install `mingw-w64`, `cmake` and `gh` with Homebrew and free disk space by removing its own scratch. It stops only for what it cannot supply: no Apple Silicon Mac, no CrossOver, the build or the GDK not on the machine, or more than one distinct build.
|
||||
- **Working rules: the pull request is the unit of work, and the target build and the GDK are required** (AGENTS.md §0, [working method](docs/process/working-method.md)). An agent told to "work" first runs the new `bx-cli preflight`, which fails unless the host is an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`, the target build's executable and the GDK folder are known, and 10 GiB of disk is free. A collaborator records the two locations once with the new `bx-cli setup --target-exe <path> --gdk-root <folder>`, which checks them and keeps them in `~/.config/betterxen/local.conf`, outside the repository (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it). If preflight fails the agent stops and does no work. A blocker the agent can fix no longer gets an issue: it is claimed by a draft pull request titled with its run-report signature. Issues are kept for handoffs (label `handoff`), decisions for a person, and the ladder status. Claims by comment and the 7-day stale window are gone; an idle draft may be taken over after 3 days.
|
||||
- **BetterXen is no longer a clean-room project** (repository owner's decision, #650). `CONTRIBUTING.md` now says that material the project is authorized to use, such as the GDK and its compilers, may be used and that facts derived from it may be committed, while the material and its outputs are never committed. Leaked or unauthorized material remains forbidden.
|
||||
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
|
||||
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
|
||||
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
|
||||
@@ -23,6 +26,7 @@ remains unsupported.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- Shader corpus, Phase 0 of the console shader translator (#649). `shader-transpiler/corpus/hlsl/` holds eight BetterXen-authored compute kernels covering integer and float ALU, divergent branches, loops, groupshared memory, wave operations, atomics and system values. `scripts/shader-corpus/build.sh` compiles each one locally with the console `xdxc` (a title-style container: `DXIL` plus `ACCC`/`FSPX`), the console PIX compiler (Microsoft's ISA listing) and the public PC DXC (DXIL for a D3DMetal reference run). `extract_code.py` then takes the code from the `FSPX` kind-6 section, skips the leading `v_nop_xbox_data` words and disassembles it with LLVM's public `gfx1030` decoder. All eight kernels build and decode cleanly. The extractor has nine unit tests on synthetic containers that need no GDK. Compiler outputs stay in the git-ignored `target/shader-corpus/`. One open question is recorded: a `v_cmp_class_f16` in the `wave` kernel's ballot sequence.
|
||||
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
|
||||
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
|
||||
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
|
||||
|
||||
+2
-2
@@ -31,10 +31,10 @@ python3 scripts/audit/docs_hygiene.py
|
||||
|
||||
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
|
||||
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
## Licensing & Provenance Policy
|
||||
|
||||
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
- BetterXen is **not** a clean-room project (repository owner's decision, 2026-11-29, #650). Material the project is authorized to use, such as the Microsoft GDK and its compilers under the project's authorization, may be used by contributors, and facts derived from it (layouts, slot orders, flag values, binary conventions) may be committed. The material itself, and its outputs, are never committed. **Leaked or unauthorized material is still forbidden:** anyone who has used it for this work must not contribute what they learned from it. Do not post details of restricted material in issues or PRs.
|
||||
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
|
||||
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
|
||||
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
|
||||
|
||||
@@ -23,7 +23,7 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
|
||||
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
|
||||
|
||||
> [!CAUTION]
|
||||
> **Clean-room and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
> **Provenance and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-1
@@ -27,6 +27,7 @@
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
@@ -34,7 +35,7 @@
|
||||
## Governance, Security & Legal
|
||||
|
||||
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, provenance policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
|
||||
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
|
||||
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Clean-room scope
|
||||
# Legal scope
|
||||
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, vendor documentation and tools the project is authorized to use (never committed; see [CONTRIBUTING](../CONTRIBUTING.md)), its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
|
||||
## User-provided game files
|
||||
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
# Working Method: the Blocker Queue
|
||||
# Working Method: Run, Fix, Pull Request
|
||||
|
||||
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
|
||||
|
||||
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
|
||||
BetterXen is built by collaborators who each have the project-authorized target build and the GDK, and who work by pointing a coding agent at this repository and saying **"work"**. This document answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
|
||||
|
||||
There are no meetings, no rotating roles and no plan to interpret. The state of the project is in GitHub; the rules are here and in AGENTS.md.
|
||||
The short answer: run the build, fix the first thing it stops on, and open a pull request. The pull request is the unit of work. There are no meetings, no rotating roles and no backlog to interpret.
|
||||
|
||||
## What you must have
|
||||
|
||||
No agent works without all of these. `bx-cli preflight` checks them and fails if one is missing:
|
||||
|
||||
- an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`;
|
||||
- **the project-authorized target build**;
|
||||
- **the GDK**, headers and compilers, under the project's authorization;
|
||||
- at least 10 GiB of free disk space.
|
||||
|
||||
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (never by name), and saves both in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
|
||||
|
||||
Work here is found by running the build and checked against the GDK. Without them an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build or the GDK is not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
|
||||
|
||||
## Why this shape
|
||||
|
||||
@@ -24,49 +37,58 @@ The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **B
|
||||
|
||||
## Where the state lives
|
||||
|
||||
| What | Where | Who writes it |
|
||||
| --- | --- | --- |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) | Any agent that runs the gate check |
|
||||
| Everything the build is known to stop on | One **blocker issue** each (label `blocker`, plus `stage: <name>` and a track label) | The agent that found it |
|
||||
| Who is working on what | A claim comment on the blocker issue | The claiming agent |
|
||||
| What needs a person | Label `needs-human` | Any agent |
|
||||
| Rules | AGENTS.md and this document | Maintainers, by pull request |
|
||||
| What | Where |
|
||||
| --- | --- |
|
||||
| A blocker someone is fixing | An open pull request titled with its signature (a draft while in progress) |
|
||||
| A blocker someone found and could not finish | A **handoff issue** (label `handoff`, plus `stage: <name>`) |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) |
|
||||
| What needs a person | Label `needs-human` |
|
||||
| Rules | AGENTS.md and this document, changed by pull request |
|
||||
|
||||
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
|
||||
|
||||
### Blocker issues
|
||||
### Why a blocker gets a pull request and not an issue
|
||||
|
||||
A blocker issue is small and has a fixed shape, so that two agents that find the same thing file the same issue.
|
||||
An agent that runs the build and sees what it stops on usually knows the fix a few minutes later. Writing an issue, claiming it and then opening a pull request that closes it is three steps where one does the job. And an issue of the form "the build stops at X" is a fact about one run on one machine: the build takes different start-up paths from run to run, so another collaborator may never see it.
|
||||
|
||||
- **Title:** `[blocker] <signature>`. The signature is taken from the run report, not invented: for example `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll (write, unmapped)`, `exit status 1 after save query`, `stall: presenting thread in trapped instruction`. Before filing, search open and closed issues for the signature.
|
||||
- **Body:** the stage it blocks; how many of ten runs hit it; the run-report lines; what is known and not known. No bytes, names, hashes or addresses from the build.
|
||||
- **Order:** within a stage, the label `first` marks blockers that every run hits before any other; after those, lower issue number first.
|
||||
What holds on every machine is the **test**: "the console does X for this call, and this test fails without the fix". The run is why you looked; the test is the proof.
|
||||
|
||||
So:
|
||||
|
||||
- **You can fix it:** open a draft pull request titled with the signature, before writing the fix. The draft is the claim.
|
||||
- **You cannot fix it** (too large, out of session, needs a decision): file one handoff issue with what you saw, what you tried and what is unknown.
|
||||
|
||||
### Signatures
|
||||
|
||||
A signature is the fixed string `bx-cli report` prints for something a run stopped on: `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll`, `exit status 5`. Pull requests and handoff issues are titled with it (`[Boot] unimplemented IXUser slot 3`), so searching open pull requests for a signature tells you whether someone is already on it.
|
||||
|
||||
## What an agent does when told "work"
|
||||
|
||||
AGENTS.md §0 has the binding version. In short, in strict order:
|
||||
|
||||
1. **Preflight.** Tools, login, disk space, an own bottle, a current `main`.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks or conflicts on a pull request your person opened.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Review it, and merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
|
||||
4. **Then one blocker.** The top unclaimed blocker of the current stage. Claim it, and do only that.
|
||||
5. **Then discover.** If the current stage has no unclaimed blocker, run the stage's gate check and file what it finds. If the gate passes, post the result on the ladder issue and label it `needs-human`: a person confirms the stage change.
|
||||
6. **Otherwise stop.** Report that the queue is empty. Do not invent work.
|
||||
1. **Preflight.** `bx-cli preflight` must pass. If it does not, stop.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks, conflicts, or a draft you have not finished.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
|
||||
4. **Then a handoff issue** of the current stage that no pull request covers.
|
||||
5. **Then run the build** and fix the first thing it stops on that no open pull request covers.
|
||||
6. **If the run stops on nothing,** make the stage's ten-run gate check and post it on the ladder issue with `needs-human`.
|
||||
|
||||
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
|
||||
|
||||
## Working one blocker
|
||||
|
||||
```text
|
||||
claim → evidence → smallest fix + test → ten runs → pull request → (someone else reviews and merges)
|
||||
run → signature → draft pull request (the claim) → evidence → smallest fix + test → runs before and after → ready → someone else reviews and merges
|
||||
```
|
||||
|
||||
1. **Claim.** Comment `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue. A claim with no commits or pull request after 3 days is free to take; say so in a comment when you take it.
|
||||
2. **Evidence before code.** Find what the build asked for and what it got. Use the run report, then the diagnostics (thread sampler, fault context, call trace). If that does not explain it within the session, write what was learned on the issue and release the claim; do not guess a fix.
|
||||
3. **Smallest fix.** Only what removes this blocker, inside the track directories it needs. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
4. **A test for the contract.** Every contract the fix teaches a shim gets a synthetic conformance test that fails without the fix.
|
||||
5. **Proof.** Ten runs before and ten after. Report every run.
|
||||
6. **Pull request.** One blocker, five short parts (below). Then stop: the next "work" starts from the top of the list.
|
||||
1. **Claim with a draft pull request.** Check open pull requests for the signature. If nobody has it, branch from `origin/main`, push, and open a draft titled `[<Stage>] <signature>`. A draft with no push for 3 days may be taken over.
|
||||
2. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
|
||||
3. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
4. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
|
||||
5. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
|
||||
6. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
|
||||
|
||||
If the blocker turns out to be more than you can finish, close the draft and file a handoff issue.
|
||||
|
||||
### Pull-request description
|
||||
|
||||
@@ -116,7 +138,7 @@ Until the launcher does, the offline-run procedure and the diagnostic switches a
|
||||
- pipelines drawn with: translated, passed through, skipped;
|
||||
- on a stall: every thread's stack.
|
||||
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings blocker issues are titled with.
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings pull requests and handoff issues are titled with.
|
||||
|
||||
## Sources of truth
|
||||
|
||||
@@ -158,7 +180,7 @@ From the Menus stage on, the build no longer stops by itself at the next missing
|
||||
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
|
||||
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
|
||||
|
||||
Findings enter the queue as blocker issues with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
|
||||
Findings become pull requests (or handoff issues, when they cannot be fixed at once) with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
|
||||
|
||||
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
|
||||
|
||||
@@ -173,28 +195,6 @@ People are needed for exactly four things, each marked `needs-human`:
|
||||
|
||||
Everything else is the queue.
|
||||
|
||||
## Starting the queue
|
||||
## The first handoffs
|
||||
|
||||
The queue starts with what the first target-build runs already found. Each line was filed as an issue on 2026-11-29 (#664–#680); the table is kept as a record of the starting point, and the issues are the live state.
|
||||
|
||||
| Stage | Signature or task | Track |
|
||||
| --- | --- | --- |
|
||||
| Boot | Run tooling in the repository: offline runner, per-run report with signatures, ten-run summary, thread sampler, machine-wide run lock, per-session bottle | A |
|
||||
| Boot | `stall: presenting thread in trapped CLZERO loop` | A |
|
||||
| Boot | `unimplemented IXUser slot 3` (handle duplication) | E |
|
||||
| Boot | `unimplemented IXGameRuntimeCore slots 6, 13, 14, 15` (async run; task-queue composite, port, duplicate) | E |
|
||||
| Boot | `unimplemented IXGameSaveImpl slot 13` (container info; and slot 15) | E |
|
||||
| Boot | `fault in XCRDAPI.dll (write, unmapped)` — page remapping is not atomic | B |
|
||||
| Boot | `serialized-pipeline calls succeed with a null pipeline` — they must fail and be logged | C |
|
||||
| Boot | `exit status 1, nothing logged` (1 run in 5) | A |
|
||||
| Picture | D3DMetal capability checks: direct heap indexing, 64-lane compute through the translator, 64-bit atomics, mesh and amplification shaders | D, F |
|
||||
| Picture | Vendor the upstream translator with provenance entries; amend ADR 0008 | D |
|
||||
| Picture | Translator behind `bx_shader_bridge.dll`; host pipelines created on first use | C, D |
|
||||
| Picture | `placed texture contents not uploaded` | C |
|
||||
| Picture | `build waits after sign-in with nothing unimplemented` — needs evidence | E |
|
||||
| Picture | Reference images for the first screens | `needs-human` |
|
||||
| Menus | Input record and replay in the `GameInput` shim; routes as ten-run regression tests | E, A |
|
||||
| Menus | Play-session recording in the launcher: input stream, starting saves, mark hotkey | A |
|
||||
| Fidelity | Frame capture in `d3d12_xs` and an offline frame replayer | C |
|
||||
|
||||
Fixes for several Boot lines exist on a local experiment branch; they still go through the queue, one pull request each, with tests and ten-run proof.
|
||||
When this method started, the first target-build runs had already found more than could be fixed at once. Those were filed as issues #664–#680. The ones that were only "a blocker with a fix on the way" close as their pull requests merge; the ones that remain open as handoffs are the larger pieces: the run tooling, the D3DMetal capability checks, the translator, the reference images and the record-and-replay tools.
|
||||
@@ -63,6 +63,8 @@ fn usage_text() -> &'static str {
|
||||
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
|
||||
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
|
||||
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
|
||||
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] Remember where the target build and the GDK are on this machine (saved outside the repository); --find searches the home folder for them\n\
|
||||
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, disk space. Fails if anything is missing\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
|
||||
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
|
||||
@@ -136,6 +138,537 @@ fn cmd_doctor() -> ExitCode {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// One preflight requirement: its name and what was found, or why it is not met.
|
||||
type Requirement = (&'static str, Result<String, String>);
|
||||
|
||||
/// A check of one local setting: what was found, or why it is not usable.
|
||||
type SettingCheck = fn(Option<&str>) -> Result<String, String>;
|
||||
|
||||
/// The GDK header BetterXen's Xbox-layout tables are generated from. Finding it under
|
||||
/// `BX_GDK_ROOT` is the evidence that the GDK is really there. The walk is bounded so a wrong
|
||||
/// root (a home directory, say) cannot make preflight crawl a disk.
|
||||
const GDK_MARKER: &str = "d3d12_xs.h";
|
||||
|
||||
fn find_gdk_marker(root: &Path) -> Option<PathBuf> {
|
||||
const MAX_DEPTH: usize = 8;
|
||||
const MAX_ENTRIES: usize = 200_000;
|
||||
let mut seen = 0usize;
|
||||
let mut stack = vec![(root.to_path_buf(), 0usize)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
seen += 1;
|
||||
if seen > MAX_ENTRIES {
|
||||
return None;
|
||||
}
|
||||
let path = entry.path();
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
if kind.is_file() && entry.file_name() == GDK_MARKER {
|
||||
return Some(path);
|
||||
}
|
||||
if kind.is_dir() && depth < MAX_DEPTH {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Where this machine's local settings live: outside every checkout, so they cannot be
|
||||
/// committed, and shared by every worktree, shell and agent session of this user.
|
||||
fn local_config_path() -> Option<PathBuf> {
|
||||
let base = env::var_os("XDG_CONFIG_HOME")
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
|
||||
Some(base.join("betterxen").join("local.conf"))
|
||||
}
|
||||
|
||||
/// `key = value` lines; `#` starts a comment. Unknown keys are kept by [`write_local_config`].
|
||||
fn parse_local_config(text: &str) -> BTreeMap<String, String> {
|
||||
text.lines()
|
||||
.filter_map(|line| {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
let (key, value) = line.split_once('=')?;
|
||||
Some((key.trim().to_owned(), value.trim().to_owned()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_local_config(path: &Path) -> BTreeMap<String, String> {
|
||||
fs::read_to_string(path)
|
||||
.map(|text| parse_local_config(&text))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write_local_config(path: &Path, values: &BTreeMap<String, String>) -> std::io::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
let mut text = String::from(
|
||||
"# BetterXen local settings for this machine (written by `bx-cli setup`).\n\
|
||||
# Never commit this file or its contents.\n",
|
||||
);
|
||||
for (key, value) in values {
|
||||
let _ = writeln!(text, "{key} = {value}");
|
||||
}
|
||||
fs::write(path, text)
|
||||
}
|
||||
|
||||
/// A local setting: the environment variable wins (a one-off override), then the saved file.
|
||||
fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -> Option<String> {
|
||||
env::var(env_name)
|
||||
.ok()
|
||||
.filter(|v| !v.is_empty())
|
||||
.or_else(|| config.get(key).cloned())
|
||||
}
|
||||
|
||||
const TARGET_EXE_KEY: &str = "target_exe";
|
||||
const GDK_ROOT_KEY: &str = "gdk_root";
|
||||
|
||||
/// An Xbox Series title's executable is recognised by structure, never by name: a large PE32+
|
||||
/// file that imports the console's D3D12 library. BetterXen's own test executables import it
|
||||
/// too, but they are small and live in build folders the search skips.
|
||||
const TITLE_IMPORT: &str = "d3d12_xs.dll";
|
||||
const TITLE_MIN_BYTES: u64 = 16 << 20;
|
||||
|
||||
fn looks_like_title(path: &Path) -> bool {
|
||||
let large = fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() >= TITLE_MIN_BYTES);
|
||||
if !large {
|
||||
return false;
|
||||
}
|
||||
let Ok(bytes) = fs::read(path) else {
|
||||
return false;
|
||||
};
|
||||
probe_pe32_plus(&bytes).is_ok_and(|pe| {
|
||||
pe.imports
|
||||
.keys()
|
||||
.any(|dll| dll.eq_ignore_ascii_case(TITLE_IMPORT))
|
||||
})
|
||||
}
|
||||
|
||||
/// The folder to remember for a GDK header found at `header`: the first folder below a
|
||||
/// well-known top-level folder of `home` (Documents, Downloads, ...), or below `home` itself.
|
||||
fn gdk_root_for(home: &Path, header: &Path) -> Option<PathBuf> {
|
||||
const TOP_LEVEL: &[&str] = &["Documents", "Downloads", "Desktop", "Developer", "Projects"];
|
||||
let relative = header.strip_prefix(home).ok()?;
|
||||
let mut parts = relative.components();
|
||||
let first = parts.next()?.as_os_str().to_owned();
|
||||
let mut root = home.join(&first);
|
||||
if TOP_LEVEL.iter().any(|name| first == *name) {
|
||||
root = root.join(parts.next()?.as_os_str());
|
||||
}
|
||||
(root.is_dir() && root != header).then_some(root)
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
struct Found {
|
||||
gdk_roots: Vec<PathBuf>,
|
||||
target_exes: Vec<PathBuf>,
|
||||
/// The search gave up before visiting everything.
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
/// Searches `home` for the GDK (by its header) and for Xbox Series executables (by structure).
|
||||
/// Hidden folders, `Library`, application bundles and build folders are skipped, and the walk is
|
||||
/// bounded so it always ends.
|
||||
fn search_for_materials(home: &Path) -> Found {
|
||||
const MAX_DEPTH: usize = 14;
|
||||
const MAX_ENTRIES: usize = 3_000_000;
|
||||
const SKIP: &[&str] = &[
|
||||
"Library",
|
||||
"node_modules",
|
||||
"target",
|
||||
"build-shims",
|
||||
"Applications",
|
||||
];
|
||||
let mut found = Found::default();
|
||||
let mut seen = 0usize;
|
||||
let mut stack = vec![(home.to_path_buf(), 0usize)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
seen += 1;
|
||||
if seen > MAX_ENTRIES {
|
||||
found.truncated = true;
|
||||
return found;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name_text = name.to_string_lossy();
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
let path = entry.path();
|
||||
if kind.is_dir() {
|
||||
let skip = name_text.starts_with('.')
|
||||
|| name_text.ends_with(".app")
|
||||
|| name_text.ends_with(".photoslibrary")
|
||||
|| SKIP.iter().any(|s| name_text == *s);
|
||||
if !skip && depth < MAX_DEPTH {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
} else if kind.is_file() {
|
||||
if name_text == GDK_MARKER {
|
||||
if let Some(root) = gdk_root_for(home, &path)
|
||||
&& !found.gdk_roots.contains(&root)
|
||||
&& check_gdk_root(root.to_str()).is_ok()
|
||||
{
|
||||
found.gdk_roots.push(root);
|
||||
}
|
||||
} else if name_text.to_ascii_lowercase().ends_with(".exe")
|
||||
&& looks_like_title(&path)
|
||||
{
|
||||
found.target_exes.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found.gdk_roots.sort();
|
||||
found.target_exes.sort();
|
||||
// The GDK ships tools that import the same library; they are not titles.
|
||||
let roots = found.gdk_roots.clone();
|
||||
found
|
||||
.target_exes
|
||||
.retain(|exe| !roots.iter().any(|root| exe.starts_with(root)));
|
||||
found.target_exes = distinct_builds(std::mem::take(&mut found.target_exes));
|
||||
found
|
||||
}
|
||||
|
||||
fn content_hash(path: &Path) -> Option<(u64, u64)> {
|
||||
let bytes = fs::read(path).ok()?;
|
||||
// FNV-1a: only to tell copies of one file from different files, never recorded anywhere.
|
||||
let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| {
|
||||
(h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3)
|
||||
});
|
||||
Some((bytes.len() as u64, hash))
|
||||
}
|
||||
|
||||
/// How many of the DLLs an executable imports are present in its own folder. A title ships some
|
||||
/// of its DLLs beside it, so the real installation scores higher than a stray copy of the file.
|
||||
fn companion_dlls(path: &Path) -> usize {
|
||||
let Some(dir) = path.parent() else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(bytes) = fs::read(path) else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(pe) = probe_pe32_plus(&bytes) else {
|
||||
return 0;
|
||||
};
|
||||
let present: Vec<String> = fs::read_dir(dir)
|
||||
.map(|entries| {
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().to_ascii_lowercase())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
pe.imports
|
||||
.keys()
|
||||
.filter(|dll| present.contains(&dll.to_ascii_lowercase()))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Byte-identical copies are one build. Of the copies, the one with the most of its imported
|
||||
/// DLLs beside it is kept: that is the installation, and the others are stray copies of the file.
|
||||
fn distinct_builds(candidates: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
distinct_builds_by(candidates, companion_dlls)
|
||||
}
|
||||
|
||||
fn distinct_builds_by(candidates: Vec<PathBuf>, siblings: impl Fn(&Path) -> usize) -> Vec<PathBuf> {
|
||||
let mut builds: Vec<((u64, u64), PathBuf)> = Vec::new();
|
||||
for path in candidates {
|
||||
let Some(identity) = content_hash(&path) else {
|
||||
continue;
|
||||
};
|
||||
match builds.iter_mut().find(|(known, _)| *known == identity) {
|
||||
Some((_, kept)) => {
|
||||
if siblings(&path) > siblings(kept) {
|
||||
*kept = path;
|
||||
}
|
||||
}
|
||||
None => builds.push((identity, path)),
|
||||
}
|
||||
}
|
||||
builds.into_iter().map(|(_, path)| path).collect()
|
||||
}
|
||||
|
||||
/// `bx-cli setup --find`: fills in whichever of the two settings is not already valid. A GDK is
|
||||
/// a GDK, so the first one found is used. A target build is saved only when exactly one is found:
|
||||
/// which build to use is the collaborator's choice, not the tool's.
|
||||
fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
|
||||
let need_target = check_target_exe(config.get(TARGET_EXE_KEY).map(String::as_str)).is_err();
|
||||
let need_gdk = check_gdk_root(config.get(GDK_ROOT_KEY).map(String::as_str)).is_err();
|
||||
if !need_target && !need_gdk {
|
||||
return false;
|
||||
}
|
||||
let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
|
||||
eprintln!("--find: no HOME to search");
|
||||
return false;
|
||||
};
|
||||
println!(
|
||||
"Searching the home folder for the GDK and the target build (this can take a minute)..."
|
||||
);
|
||||
let found = search_for_materials(&home);
|
||||
let mut changed = false;
|
||||
if need_gdk {
|
||||
match found.gdk_roots.first() {
|
||||
Some(root) => {
|
||||
config.insert(GDK_ROOT_KEY.to_owned(), root.to_string_lossy().into_owned());
|
||||
changed = true;
|
||||
println!(" GDK : found and saved");
|
||||
}
|
||||
None => println!(" GDK : not found in the home folder"),
|
||||
}
|
||||
}
|
||||
if need_target {
|
||||
match found.target_exes.as_slice() {
|
||||
[only] => {
|
||||
config.insert(
|
||||
TARGET_EXE_KEY.to_owned(),
|
||||
only.to_string_lossy().into_owned(),
|
||||
);
|
||||
changed = true;
|
||||
println!(" target build : found and saved");
|
||||
}
|
||||
[] => println!(" target build : no Xbox Series executable found in the home folder"),
|
||||
several => {
|
||||
println!(
|
||||
" target build : {} Xbox Series executables found; choose one with --target-exe:",
|
||||
several.len()
|
||||
);
|
||||
for path in several {
|
||||
println!(" {}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if found.truncated {
|
||||
println!(" (the search stopped early: the home folder has too many entries)");
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// `bx-cli setup`: checks the given paths with the same rules as preflight and remembers them.
|
||||
/// `--find` searches the home folder for whatever is not set. With no arguments it shows what
|
||||
/// is saved, as present or missing, without printing a path.
|
||||
fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
let Some(path) = local_config_path() else {
|
||||
eprintln!("error: no HOME or XDG_CONFIG_HOME to keep local settings in");
|
||||
return ExitCode::FAILURE;
|
||||
};
|
||||
let mut config = read_local_config(&path);
|
||||
let mut i = 0;
|
||||
let mut changed = false;
|
||||
let mut find = false;
|
||||
while i < args.len() {
|
||||
if args[i] == "--find" {
|
||||
find = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let (key, check): (&str, SettingCheck) = match args[i].as_str() {
|
||||
"--target-exe" => (TARGET_EXE_KEY, check_target_exe),
|
||||
"--gdk-root" => (GDK_ROOT_KEY, check_gdk_root),
|
||||
other => {
|
||||
eprintln!("error: unknown argument: {other}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let Some(value) = args.get(i + 1) else {
|
||||
eprintln!("error: {} needs a path", args[i]);
|
||||
return ExitCode::FAILURE;
|
||||
};
|
||||
// Saved as an absolute path, so it means the same thing from every directory.
|
||||
let absolute = fs::canonicalize(value).unwrap_or_else(|_| PathBuf::from(value));
|
||||
let absolute = absolute.to_string_lossy().into_owned();
|
||||
if let Err(why) = check(Some(&absolute)) {
|
||||
eprintln!("error: {} was not saved: {why}", args[i]);
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
config.insert(key.to_owned(), absolute);
|
||||
changed = true;
|
||||
i += 2;
|
||||
}
|
||||
if find {
|
||||
changed |= find_materials(&mut config);
|
||||
}
|
||||
if changed && let Err(e) = write_local_config(&path, &config) {
|
||||
eprintln!("error: could not save local settings: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let state = |key: &str, check: SettingCheck| match config.get(key) {
|
||||
Some(value) => check(Some(value)).unwrap_or_else(|why| format!("saved, but {why}")),
|
||||
None => "not set".to_owned(),
|
||||
};
|
||||
println!(
|
||||
"Local settings ({}):",
|
||||
if changed { "saved" } else { "unchanged" }
|
||||
);
|
||||
println!(
|
||||
" target build : {}",
|
||||
state(TARGET_EXE_KEY, check_target_exe)
|
||||
);
|
||||
println!(" GDK : {}", state(GDK_ROOT_KEY, check_gdk_root));
|
||||
println!("They are kept outside the repository. Run `bx-cli preflight` to check everything.");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// The target build: the setting must name a readable PE file.
|
||||
fn check_target_exe(value: Option<&str>) -> Result<String, String> {
|
||||
let path = value.filter(|v| !v.is_empty()).ok_or(
|
||||
"not set; run `bx-cli setup --find`, or `bx-cli setup --target-exe <path to the target build's executable>`",
|
||||
)?;
|
||||
let mut magic = [0u8; 2];
|
||||
let read = fs::File::open(path).and_then(|mut f| std::io::Read::read_exact(&mut f, &mut magic));
|
||||
match read {
|
||||
Ok(()) if &magic == b"MZ" => Ok("present".to_owned()),
|
||||
Ok(()) => Err("the saved path does not name a Windows executable".to_owned()),
|
||||
Err(e) => Err(format!("the saved path cannot be read: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The GDK: the setting must be a folder that contains the GDK's `d3d12_xs.h`.
|
||||
fn check_gdk_root(value: Option<&str>) -> Result<String, String> {
|
||||
let root = value
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or("not set; run `bx-cli setup --find`, or `bx-cli setup --gdk-root <folder that holds the GDK>`")?;
|
||||
let root = Path::new(root);
|
||||
if !root.is_dir() {
|
||||
return Err("the saved path is not a folder".to_owned());
|
||||
}
|
||||
match find_gdk_marker(root) {
|
||||
Some(_) => Ok(format!("present ({GDK_MARKER} found)")),
|
||||
None => Err(format!(
|
||||
"no {GDK_MARKER} under it: that folder does not hold the GDK"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Free space on the volume holding `path`, in GiB.
|
||||
fn free_gib(path: &Path) -> Option<u64> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
|
||||
// SAFETY: `c_path` is a valid NUL-terminated path and `stat` is a zeroed out-parameter
|
||||
// that statvfs fills on success.
|
||||
let stat = unsafe {
|
||||
let mut stat: libc::statvfs = std::mem::zeroed();
|
||||
(libc::statvfs(c_path.as_ptr(), &raw mut stat) == 0).then_some(stat)
|
||||
}?;
|
||||
Some(u64::from(stat.f_bavail).saturating_mul(stat.f_frsize) / (1 << 30))
|
||||
}
|
||||
|
||||
const MIN_FREE_GIB: u64 = 10;
|
||||
|
||||
fn render_preflight(requirements: &[Requirement]) -> (String, bool) {
|
||||
let mut out = String::from("=== BetterXen Preflight ===\n");
|
||||
let mut ready = true;
|
||||
for (name, result) in requirements {
|
||||
match result {
|
||||
Ok(found) => {
|
||||
let _ = writeln!(out, "ok {name:<22}: {found}");
|
||||
}
|
||||
Err(why) => {
|
||||
ready = false;
|
||||
let _ = writeln!(out, "MISSING {name:<22}: {why}");
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(if ready {
|
||||
"Ready to work.\n"
|
||||
} else {
|
||||
"Not ready. Fix what you can yourself (AGENTS.md section 0, step 1): `bx-cli setup --find` for the \
|
||||
target build and the GDK, Homebrew for missing tools, your own scratch files for disk space. \
|
||||
Stop only for what is not on this machine.\n"
|
||||
});
|
||||
(out, ready)
|
||||
}
|
||||
|
||||
/// `bx-cli preflight`: everything AGENTS.md section 0 requires before any work. Unlike `doctor`,
|
||||
/// which only reports, this fails when something is missing.
|
||||
fn cmd_preflight() -> ExitCode {
|
||||
let arch = run_capture("uname", &["-m"]).unwrap_or_default();
|
||||
let crossover = run_capture(
|
||||
"defaults",
|
||||
&[
|
||||
"read",
|
||||
"/Applications/CrossOver.app/Contents/Info.plist",
|
||||
"CFBundleShortVersionString",
|
||||
],
|
||||
);
|
||||
let d3dmetal = Path::new(
|
||||
"/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/lib64/apple_gptk/external/D3DMetal.framework",
|
||||
)
|
||||
.exists();
|
||||
let mingw = run_capture("which", &["x86_64-w64-mingw32-g++"]);
|
||||
let free = env::current_dir().ok().and_then(|dir| free_gib(&dir));
|
||||
let config = local_config_path()
|
||||
.map(|path| read_local_config(&path))
|
||||
.unwrap_or_default();
|
||||
let requirements: Vec<Requirement> = vec![
|
||||
(
|
||||
"Apple Silicon host",
|
||||
if arch == "arm64" {
|
||||
Ok(arch)
|
||||
} else {
|
||||
Err(format!("this host is '{arch}', not arm64"))
|
||||
},
|
||||
),
|
||||
(
|
||||
"CrossOver",
|
||||
crossover.ok_or_else(|| "not installed".to_owned()),
|
||||
),
|
||||
(
|
||||
"D3DMetal",
|
||||
if d3dmetal {
|
||||
Ok("present".to_owned())
|
||||
} else {
|
||||
Err("not found in CrossOver".to_owned())
|
||||
},
|
||||
),
|
||||
(
|
||||
"mingw-w64 g++",
|
||||
mingw
|
||||
.map(|_| "present".to_owned())
|
||||
.ok_or_else(|| "missing (brew install mingw-w64)".to_owned()),
|
||||
),
|
||||
(
|
||||
"Target build",
|
||||
check_target_exe(local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config).as_deref()),
|
||||
),
|
||||
(
|
||||
"GDK",
|
||||
check_gdk_root(local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config).as_deref()),
|
||||
),
|
||||
(
|
||||
"Free disk space",
|
||||
match free {
|
||||
Some(gib) if gib >= MIN_FREE_GIB => Ok(format!("{gib} GiB")),
|
||||
Some(gib) => Err(format!(
|
||||
"{gib} GiB free; at least {MIN_FREE_GIB} GiB is needed"
|
||||
)),
|
||||
None => Err("could not be measured".to_owned()),
|
||||
},
|
||||
),
|
||||
];
|
||||
let (text, ready) = render_preflight(&requirements);
|
||||
print!("{text}");
|
||||
if ready {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_probe(path: &str) -> ExitCode {
|
||||
let data = match fs::read(path) {
|
||||
Ok(d) => d,
|
||||
@@ -1191,7 +1724,9 @@ impl<'a> Dispatch<'a> {
|
||||
};
|
||||
match sub.as_str() {
|
||||
"--help" | "-h" | "help" => Dispatch::Help,
|
||||
"doctor" | "probe" | "shader" | "trace" | "run" => Dispatch::Sub(sub.as_str()),
|
||||
"doctor" | "setup" | "preflight" | "probe" | "shader" | "trace" | "run" => {
|
||||
Dispatch::Sub(sub.as_str())
|
||||
}
|
||||
_ => Dispatch::Unknown(sub.as_str()),
|
||||
}
|
||||
}
|
||||
@@ -1220,6 +1755,8 @@ fn main() -> ExitCode {
|
||||
Dispatch::NoArgs | Dispatch::Unknown(_) => ExitCode::FAILURE,
|
||||
Dispatch::Sub(sub) => match sub {
|
||||
"doctor" => cmd_doctor(),
|
||||
"setup" => cmd_setup(&args[1..]),
|
||||
"preflight" => cmd_preflight(),
|
||||
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
|
||||
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
|
||||
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
|
||||
@@ -1939,7 +2476,15 @@ sub setup_bottle_wineprefix {
|
||||
);
|
||||
assert!(bogus.is_usage_error(), "an unknown subcommand is an error");
|
||||
|
||||
for real in ["doctor", "probe", "shader", "trace", "run"] {
|
||||
for real in [
|
||||
"doctor",
|
||||
"setup",
|
||||
"preflight",
|
||||
"probe",
|
||||
"shader",
|
||||
"trace",
|
||||
"run",
|
||||
] {
|
||||
let argv = args(&[real]);
|
||||
let dispatch = Dispatch::classify(&argv);
|
||||
assert_eq!(dispatch, Dispatch::Sub(real), "{real} is a real subcommand");
|
||||
@@ -1948,6 +2493,188 @@ sub setup_bottle_wineprefix {
|
||||
}
|
||||
}
|
||||
|
||||
/// Preflight: the target build and the GDK are required, and a missing one is named.
|
||||
#[test]
|
||||
fn preflight_requires_the_target_build_and_the_gdk() {
|
||||
let dir = env::temp_dir().join(format!("bx-preflight-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(dir.join("a/b/include")).unwrap();
|
||||
|
||||
// Target build: unset, missing, not a PE, a PE.
|
||||
assert!(check_target_exe(None).unwrap_err().contains("not set"));
|
||||
assert!(check_target_exe(Some("")).unwrap_err().contains("not set"));
|
||||
assert!(
|
||||
check_target_exe(None)
|
||||
.unwrap_err()
|
||||
.contains("bx-cli setup --find")
|
||||
);
|
||||
let missing = dir.join("none.exe");
|
||||
assert!(
|
||||
check_target_exe(missing.to_str())
|
||||
.unwrap_err()
|
||||
.contains("cannot be read")
|
||||
);
|
||||
let text = dir.join("text.exe");
|
||||
fs::write(&text, b"not a program").unwrap();
|
||||
assert!(
|
||||
check_target_exe(text.to_str())
|
||||
.unwrap_err()
|
||||
.contains("not name a Windows executable")
|
||||
);
|
||||
let pe = dir.join("title.exe");
|
||||
fs::write(&pe, b"MZ\x90\x00").unwrap();
|
||||
assert_eq!(check_target_exe(pe.to_str()), Ok("present".to_owned()));
|
||||
|
||||
// GDK: unset, not a folder, a folder without the header, a folder with it nested.
|
||||
assert!(check_gdk_root(None).unwrap_err().contains("not set"));
|
||||
assert!(
|
||||
check_gdk_root(pe.to_str())
|
||||
.unwrap_err()
|
||||
.contains("not a folder")
|
||||
);
|
||||
assert!(
|
||||
check_gdk_root(dir.to_str())
|
||||
.unwrap_err()
|
||||
.contains("does not hold the GDK")
|
||||
);
|
||||
fs::write(dir.join("a/b/include").join(GDK_MARKER), b"// header").unwrap();
|
||||
assert!(check_gdk_root(dir.to_str()).unwrap().contains("found"));
|
||||
|
||||
// One missing requirement makes the whole preflight not ready, and says so.
|
||||
let (text, ready) = render_preflight(&[
|
||||
("Target build", Ok("present".to_owned())),
|
||||
("GDK", Err("not set".to_owned())),
|
||||
]);
|
||||
assert!(!ready);
|
||||
assert!(text.contains("MISSING GDK"), "{text}");
|
||||
assert!(text.contains("Fix what you can yourself"), "{text}");
|
||||
let (text, ready) = render_preflight(&[("Target build", Ok("present".to_owned()))]);
|
||||
assert!(ready && text.contains("Ready to work."), "{text}");
|
||||
|
||||
assert!(
|
||||
free_gib(&dir).is_some(),
|
||||
"free space is measurable for an existing folder"
|
||||
);
|
||||
|
||||
// Local settings: written, read back, unknown keys kept, comments ignored; the
|
||||
// environment variable wins over the saved value.
|
||||
let conf = dir.join("conf/local.conf");
|
||||
let mut values = BTreeMap::new();
|
||||
values.insert(TARGET_EXE_KEY.to_owned(), pe.to_string_lossy().into_owned());
|
||||
values.insert("future_key".to_owned(), "kept".to_owned());
|
||||
write_local_config(&conf, &values).unwrap();
|
||||
let read = read_local_config(&conf);
|
||||
assert_eq!(read, values);
|
||||
assert!(
|
||||
fs::read_to_string(&conf)
|
||||
.unwrap()
|
||||
.starts_with("# BetterXen local settings")
|
||||
);
|
||||
assert_eq!(read_local_config(&dir.join("absent.conf")), BTreeMap::new());
|
||||
assert_eq!(
|
||||
local_setting(
|
||||
"BX_TEST_UNSET_VARIABLE_FOR_PREFLIGHT",
|
||||
TARGET_EXE_KEY,
|
||||
&read
|
||||
)
|
||||
.as_deref(),
|
||||
pe.to_str()
|
||||
);
|
||||
assert_eq!(
|
||||
local_setting("BX_TEST_UNSET_VARIABLE_FOR_PREFLIGHT", GDK_ROOT_KEY, &read),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
parse_local_config("# c\n\n a = 1 \nbroken line\nb=2=3\n").len(),
|
||||
2
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `setup --find`: the GDK is recognised by its header and remembered as the first folder
|
||||
/// below Documents; build folders and hidden folders are not searched; a small executable
|
||||
/// is not taken for a title.
|
||||
#[test]
|
||||
fn find_recognises_the_gdk_and_skips_what_is_not_a_title() {
|
||||
let home = env::temp_dir().join(format!("bx-find-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&home);
|
||||
let header_dir = home.join("Documents/sdk/pkg/xbox/include/gen9");
|
||||
fs::create_dir_all(&header_dir).unwrap();
|
||||
fs::write(header_dir.join(GDK_MARKER), b"// header").unwrap();
|
||||
// The same header in places the search must not look.
|
||||
for skipped in [
|
||||
".hidden/x",
|
||||
"Library/x",
|
||||
"Documents/proj/build-shims/x",
|
||||
"Documents/proj/target/x",
|
||||
] {
|
||||
fs::create_dir_all(home.join(skipped)).unwrap();
|
||||
fs::write(home.join(skipped).join(GDK_MARKER), b"// header").unwrap();
|
||||
}
|
||||
// A small PE-looking file and a non-PE .exe: neither is a title.
|
||||
fs::create_dir_all(home.join("Documents/game")).unwrap();
|
||||
fs::write(home.join("Documents/game/small.exe"), b"MZ\x90\x00").unwrap();
|
||||
|
||||
let found = search_for_materials(&home);
|
||||
assert_eq!(found.gdk_roots, vec![home.join("Documents/sdk")]);
|
||||
assert!(found.target_exes.is_empty());
|
||||
assert!(!found.truncated);
|
||||
|
||||
assert_eq!(
|
||||
gdk_root_for(&home, &home.join("sdk2/include/d3d12_xs.h")),
|
||||
None,
|
||||
"a folder that does not exist is not a root"
|
||||
);
|
||||
fs::create_dir_all(home.join("sdk2/include")).unwrap();
|
||||
assert_eq!(
|
||||
gdk_root_for(&home, &home.join("sdk2/include/d3d12_xs.h")),
|
||||
Some(home.join("sdk2")),
|
||||
"directly below home, the first folder is the root"
|
||||
);
|
||||
assert!(!looks_like_title(&home.join("Documents/game/small.exe")));
|
||||
assert!(!looks_like_title(&home.join("Documents/game/absent.exe")));
|
||||
|
||||
// Identical copies are one build, kept where the folder is fullest; a different file is
|
||||
// another build.
|
||||
let full = home.join("Documents/install");
|
||||
let stray = home.join("Downloads");
|
||||
fs::create_dir_all(&full).unwrap();
|
||||
fs::create_dir_all(&stray).unwrap();
|
||||
fs::write(full.join("title.exe"), b"same bytes").unwrap();
|
||||
fs::write(full.join("data1.pak"), b"x").unwrap();
|
||||
fs::write(full.join("data2.pak"), b"x").unwrap();
|
||||
fs::write(stray.join("title.exe"), b"same bytes").unwrap();
|
||||
fs::write(home.join("Documents/game/other.exe"), b"other bytes").unwrap();
|
||||
// Synthetic files are not PE images, so the folder is scored here by its entry count;
|
||||
// real candidates are scored by the imported DLLs found beside them.
|
||||
let entries = |path: &Path| {
|
||||
path.parent()
|
||||
.and_then(|dir| fs::read_dir(dir).ok())
|
||||
.map_or(0, Iterator::count)
|
||||
};
|
||||
let kept = distinct_builds_by(
|
||||
vec![
|
||||
stray.join("title.exe"),
|
||||
full.join("title.exe"),
|
||||
home.join("Documents/game/other.exe"),
|
||||
],
|
||||
entries,
|
||||
);
|
||||
assert_eq!(
|
||||
companion_dlls(&full.join("title.exe")),
|
||||
0,
|
||||
"not a PE image: no companions"
|
||||
);
|
||||
assert_eq!(
|
||||
kept,
|
||||
vec![
|
||||
full.join("title.exe"),
|
||||
home.join("Documents/game/other.exe")
|
||||
]
|
||||
);
|
||||
let _ = fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
/// The usage text must name every subcommand, so the classifier above is
|
||||
/// not testing a table that nothing prints.
|
||||
#[test]
|
||||
@@ -1957,7 +2684,15 @@ sub setup_bottle_wineprefix {
|
||||
text.contains("BetterXen Hybrid CLI"),
|
||||
"usage carries the banner"
|
||||
);
|
||||
for sub in ["doctor", "probe", "shader", "trace", "run"] {
|
||||
for sub in [
|
||||
"doctor",
|
||||
"setup",
|
||||
"preflight",
|
||||
"probe",
|
||||
"shader",
|
||||
"trace",
|
||||
"run",
|
||||
] {
|
||||
assert!(text.contains(sub), "usage documents {sub}");
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Build the shader corpus (#649) locally. For every kernel in shader-transpiler/corpus/hlsl:
|
||||
# <name>.xs.cso / .xs.lst console container (DXIL + ACCC/FSPX) and listing, from xdxc
|
||||
# <name>.pix.lst console ISA listing with encodings, from the PIX compiler
|
||||
# <name>.pc.cso DXIL from the public PC DXC, for a D3DMetal reference run
|
||||
# <name>.code.bin / .aco.s console machine code extracted from the ACCC chunk, and its
|
||||
# llvm-mc gfx1030 disassembly
|
||||
# Outputs go to $OUT (default target/shader-corpus, which git ignores) and must not be
|
||||
# committed: they are compiler outputs from authorized GDK tools (see the corpus README).
|
||||
#
|
||||
# Required environment:
|
||||
# WINE a CrossOver/Wine loader that accepts --bottle (CrossOver's bin/wine)
|
||||
# BOTTLE a scratch bottle for the compilers (never a title's bottle)
|
||||
# XDXC the console xdxc.exe (GDK, xbox/bin/gen9)
|
||||
# PIX_DXC the console PIX dxc.exe (GDK, bin/Scarlett/pixsc)
|
||||
# DXC the PC dxc.exe from DXC release v1.9.2609
|
||||
# LLVM_MC llvm-mc built with the AMDGPU target
|
||||
set -euo pipefail
|
||||
|
||||
for var in WINE BOTTLE XDXC PIX_DXC DXC LLVM_MC; do
|
||||
if [ -z "${!var:-}" ]; then
|
||||
echo "error: set $var (see the header of $0)" >&2
|
||||
exit 2
|
||||
fi
|
||||
done
|
||||
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
src="$root/shader-transpiler/corpus/hlsl"
|
||||
out=${OUT:-$root/target/shader-corpus}
|
||||
mkdir -p "$out"
|
||||
|
||||
# Wine takes Windows paths; Z: maps the host root.
|
||||
win() { printf 'Z:%s' "$1"; }
|
||||
compile() { WINEDEBUG=-all "$WINE" --bottle "$BOTTLE" "$@"; }
|
||||
|
||||
failures=0
|
||||
for hlsl in "$src"/*.hlsl; do
|
||||
name=$(basename "$hlsl" .hlsl)
|
||||
log="$out/$name.log"
|
||||
: > "$log"
|
||||
if ! compile "$XDXC" -T cs_6_6 -E main -Fo "$(win "$out/$name.xs.cso")" -Fc "$(win "$out/$name.xs.lst")" \
|
||||
"$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: xdxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$PIX_DXC" -T cs_6_6 -E main -Fc "$(win "$out/$name.pix.lst")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PIX dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$DXC" -nologo -T cs_6_6 -E main -Fo "$(win "$out/$name.pc.cso")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PC dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! python3 "$root/scripts/shader-corpus/extract_code.py" "$out/$name.xs.cso" \
|
||||
--bin "$out/$name.code.bin" --asm "$out/$name.aco.s" --llvm-mc "$LLVM_MC"; then
|
||||
echo "FAIL $name: code extraction or decode (see $out/$name.aco.s)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$failures" -ne 0 ]; then
|
||||
echo "FAIL: shader corpus ($failures kernel(s) failed)"
|
||||
exit 1
|
||||
fi
|
||||
# Sums of the compiled inputs, so two people with the compilers can confirm they hold the same
|
||||
# corpus (README, "Reproducibility"). Local only, like every other output.
|
||||
(cd "$out" && shasum -a 256 ./*.xs.cso ./*.pc.cso > SHA256SUMS)
|
||||
echo "PASS: shader corpus built in $out"
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Extract the RDNA 2 code from a console-compiled DXBC container (#649).
|
||||
|
||||
The layout below was derived from containers the console compiler produced for BetterXen's own
|
||||
corpus kernels (shader-transpiler/corpus/README.md). Every assumption is checked; anything that
|
||||
does not match raises instead of guessing.
|
||||
|
||||
- DXBC: chunk count at byte 28, chunk offsets from byte 32; each chunk is a FourCC, a u32 size
|
||||
and the payload. The console code is in the `ACCC` chunk.
|
||||
- FSPX (the ACCC payload): a 16-byte header (magic `FSPX`, version, section count, total size),
|
||||
then one 16-byte entry per section: kind, offset, size, reserved (0). Offsets are relative to
|
||||
the start of the payload.
|
||||
- Section kind 6 holds the code. It starts with `v_nop_xbox_data` instructions that carry the
|
||||
shader hash, followed by gfx1030 machine code ending in `s_endpgm`. A `v_nop_xbox_data` is the
|
||||
public VOP3 `v_nop` opcode (top 16 bits of the first word 0xD580) whose third source operand is
|
||||
a 32-bit literal (operand value 255), which makes it 12 bytes; the public decoder rejects that
|
||||
form. A plain `v_nop` (8 bytes, no literal) is ordinary code and is not skipped.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
FSPX_MAGIC = b"FSPX"
|
||||
CODE_SECTION_KIND = 6
|
||||
XBOX_DATA_NOP_HIGH = 0xD580 # VOP3 v_nop, top 16 bits of the first word
|
||||
XBOX_DATA_NOP_BYTES = 12 # two VOP3 words and one 32-bit literal
|
||||
VOP3_SRC2_SHIFT = 18 # second word: src0 [8:0], src1 [17:9], src2 [26:18]
|
||||
VOP3_OPERAND_MASK = 0x1FF
|
||||
OPERAND_LITERAL = 255 # public gfx10 operand value for "a 32-bit literal follows"
|
||||
S_ENDPGM = 0xBF810000
|
||||
|
||||
|
||||
class LayoutError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def chunk(container, fourcc):
|
||||
if container[:4] != b"DXBC" or len(container) < 32:
|
||||
raise LayoutError("not a DXBC container")
|
||||
count = struct.unpack_from("<I", container, 28)[0]
|
||||
if 32 + 4 * count > len(container):
|
||||
raise LayoutError("chunk table overruns the container")
|
||||
for i in range(count):
|
||||
offset = struct.unpack_from("<I", container, 32 + 4 * i)[0]
|
||||
if offset + 8 > len(container):
|
||||
raise LayoutError(f"chunk {i} header overruns the container")
|
||||
size = struct.unpack_from("<I", container, offset + 4)[0]
|
||||
if container[offset:offset + 4] == fourcc:
|
||||
if offset + 8 + size > len(container):
|
||||
raise LayoutError(f"{fourcc.decode()} chunk overruns the container")
|
||||
return container[offset + 8:offset + 8 + size]
|
||||
raise LayoutError(f"no {fourcc.decode()} chunk")
|
||||
|
||||
|
||||
def sections(payload):
|
||||
if payload[:4] != FSPX_MAGIC or len(payload) < 16:
|
||||
raise LayoutError("ACCC payload does not start with FSPX")
|
||||
_version, count, total = struct.unpack_from("<III", payload, 4)
|
||||
if total != len(payload):
|
||||
raise LayoutError(f"FSPX total size {total} != payload size {len(payload)}")
|
||||
table_end = 16 + 16 * count
|
||||
if table_end > len(payload):
|
||||
raise LayoutError("FSPX section table overruns the payload")
|
||||
result = []
|
||||
for i in range(count):
|
||||
kind, offset, size, reserved = struct.unpack_from("<IIII", payload, 16 + 16 * i)
|
||||
if reserved != 0:
|
||||
raise LayoutError(f"FSPX section {i} reserved word is {reserved:#x}, not 0")
|
||||
if offset < table_end or offset + size > len(payload):
|
||||
raise LayoutError(f"FSPX section {i} [{offset}, {offset + size}) is out of bounds")
|
||||
result.append((kind, offset, size))
|
||||
return result
|
||||
|
||||
|
||||
def code_section(payload):
|
||||
matches = [(o, s) for k, o, s in sections(payload) if k == CODE_SECTION_KIND]
|
||||
if len(matches) != 1:
|
||||
raise LayoutError(f"expected one kind-{CODE_SECTION_KIND} section, found {len(matches)}")
|
||||
offset, size = matches[0]
|
||||
return payload[offset:offset + size]
|
||||
|
||||
|
||||
def is_xbox_data_nop(code):
|
||||
"""True when `code` starts with a v_nop whose third source operand is a literal."""
|
||||
if len(code) < XBOX_DATA_NOP_BYTES:
|
||||
return False
|
||||
first, second = struct.unpack_from("<II", code, 0)
|
||||
return (first >> 16 == XBOX_DATA_NOP_HIGH
|
||||
and (second >> VOP3_SRC2_SHIFT) & VOP3_OPERAND_MASK == OPERAND_LITERAL)
|
||||
|
||||
|
||||
def strip_xbox_data(code):
|
||||
"""Return (machine code, number of v_nop_xbox_data skipped)."""
|
||||
skipped = 0
|
||||
while is_xbox_data_nop(code):
|
||||
code = code[XBOX_DATA_NOP_BYTES:]
|
||||
skipped += 1
|
||||
return code, skipped
|
||||
|
||||
|
||||
def until_endpgm(code):
|
||||
"""Cut after the first dword-aligned s_endpgm. A literal that happens to equal it is not
|
||||
excluded here; the disassembler run is the authority on instruction boundaries."""
|
||||
for i in range(0, len(code) - 3, 4):
|
||||
if struct.unpack_from("<I", code, i)[0] == S_ENDPGM:
|
||||
return code[:i + 4]
|
||||
raise LayoutError("no s_endpgm in the code section")
|
||||
|
||||
|
||||
def extract(container):
|
||||
code, skipped = strip_xbox_data(code_section(chunk(container, b"ACCC")))
|
||||
return until_endpgm(code), skipped
|
||||
|
||||
|
||||
def disassemble(code, llvm_mc):
|
||||
text = " ".join(f"0x{b:02x}" for b in code)
|
||||
run = subprocess.run(
|
||||
[llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "--disassemble", "-show-encoding"],
|
||||
input=text, capture_output=True, text=True, check=False,
|
||||
)
|
||||
lines = [ln.strip() for ln in run.stdout.splitlines() if ln.strip() and not ln.strip().startswith(".")]
|
||||
problems = [ln for ln in run.stderr.splitlines() if "invalid" in ln.lower() or "warning" in ln.lower()]
|
||||
return lines, problems
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("container", help="console-compiled .cso (DXBC with an ACCC chunk)")
|
||||
parser.add_argument("--bin", help="write the extracted machine code here")
|
||||
parser.add_argument("--asm", help="write the llvm-mc disassembly here (needs --llvm-mc)")
|
||||
parser.add_argument("--llvm-mc", help="path to llvm-mc with the AMDGPU target")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
code, skipped = extract(open(args.container, "rb").read())
|
||||
except LayoutError as error:
|
||||
print(f"error: {args.container}: {error}", file=sys.stderr)
|
||||
return 2
|
||||
if args.bin:
|
||||
open(args.bin, "wb").write(code)
|
||||
status = 0
|
||||
summary = f"{len(code)} code bytes, {skipped} v_nop_xbox_data skipped"
|
||||
if args.llvm_mc:
|
||||
lines, problems = disassemble(code, args.llvm_mc)
|
||||
summary += f", {len(lines)} instructions"
|
||||
if problems or not lines or "s_endpgm" not in lines[-1]:
|
||||
summary += ", DECODE PROBLEMS"
|
||||
status = 1
|
||||
if args.asm:
|
||||
open(args.asm, "w").write("\n".join(lines + problems) + "\n")
|
||||
print(f"{args.container}: {summary}")
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,106 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Unit tests for extract_code.py on synthetic containers (no GDK or compiler needed)."""
|
||||
|
||||
import importlib.util
|
||||
import struct
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location("extract_code", Path(__file__).with_name("extract_code.py"))
|
||||
ec = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(ec)
|
||||
|
||||
S_NOP = struct.pack("<I", 0xBF800000) # public gfx10 encoding of s_nop 0
|
||||
S_ENDPGM = struct.pack("<I", 0xBF810000)
|
||||
# Synthetic, not compiler output: the v_nop opcode with made-up low bits, a second word whose
|
||||
# third source operand is 255 (literal) with made-up low bits, and a made-up literal.
|
||||
XBOX_DATA = struct.pack("<III", 0xD5801111, 0x03FC2222, 0x33333333)
|
||||
# The public VOP3 encoding of a plain `v_nop` (llvm-mc -mcpu=gfx1030): 8 bytes, no literal.
|
||||
V_NOP_E64 = struct.pack("<II", 0xD5800000, 0x02010080)
|
||||
|
||||
|
||||
def fspx(sections, total=None):
|
||||
"""sections: list of (kind, bytes). Builds an FSPX payload with the parsed layout."""
|
||||
count = len(sections)
|
||||
offset = 16 + 16 * count
|
||||
table, body = b"", b""
|
||||
for kind, data in sections:
|
||||
table += struct.pack("<IIII", kind, offset + len(body), len(data), 0)
|
||||
body += data
|
||||
size = 16 + len(table) + len(body)
|
||||
return b"FSPX" + struct.pack("<III", 1, count, size if total is None else total) + table + body
|
||||
|
||||
|
||||
def dxbc(chunks):
|
||||
"""chunks: list of (fourcc, bytes)."""
|
||||
header = 32 + 4 * len(chunks)
|
||||
offsets, body = [], b""
|
||||
for fourcc, data in chunks:
|
||||
offsets.append(header + len(body))
|
||||
body += fourcc + struct.pack("<I", len(data)) + data
|
||||
total = header + len(body)
|
||||
head = b"DXBC" + b"\0" * 16 + struct.pack("<III", 1, total, len(chunks))
|
||||
return head + b"".join(struct.pack("<I", o) for o in offsets) + body
|
||||
|
||||
|
||||
class ExtractTests(unittest.TestCase):
|
||||
def test_extracts_code_after_xbox_data_nops(self):
|
||||
code = XBOX_DATA * 3 + S_NOP + S_ENDPGM + b"\0" * 8
|
||||
container = dxbc([(b"DXIL", b"x" * 12), (b"ACCC", fspx([(0, b"a" * 28), (6, code), (7, b"b" * 8)]))])
|
||||
extracted, skipped = ec.extract(container)
|
||||
self.assertEqual(skipped, 3)
|
||||
self.assertEqual(extracted, S_NOP + S_ENDPGM)
|
||||
|
||||
def test_plain_v_nop_is_code_not_xbox_data(self):
|
||||
# A plain v_nop at the start of the code must not be skipped as 12 bytes, which would
|
||||
# misalign everything after it.
|
||||
code = V_NOP_E64 + S_NOP + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (code, 0))
|
||||
|
||||
def test_plain_v_nop_after_xbox_data_is_kept(self):
|
||||
code = XBOX_DATA * 2 + V_NOP_E64 + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (V_NOP_E64 + S_ENDPGM, 2))
|
||||
|
||||
def test_no_xbox_data_nops(self):
|
||||
container = dxbc([(b"ACCC", fspx([(6, S_NOP + S_ENDPGM)]))])
|
||||
self.assertEqual(ec.extract(container), (S_NOP + S_ENDPGM, 0))
|
||||
|
||||
def test_missing_accc(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no ACCC chunk"):
|
||||
ec.extract(dxbc([(b"DXIL", b"x" * 4)]))
|
||||
|
||||
def test_not_fspx(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "does not start with FSPX"):
|
||||
ec.extract(dxbc([(b"ACCC", b"ABCD" + b"\0" * 12)]))
|
||||
|
||||
def test_total_size_mismatch(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "total size"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM)], total=999))]))
|
||||
|
||||
def test_section_inside_table_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 4, 4) # section offset points into the header
|
||||
with self.assertRaisesRegex(ec.LayoutError, "out of bounds"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_nonzero_reserved_word_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 12, 1)
|
||||
with self.assertRaisesRegex(ec.LayoutError, "reserved word"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_needs_exactly_one_code_section(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 0"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(0, S_ENDPGM)]))]))
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 2"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM), (6, S_ENDPGM)]))]))
|
||||
|
||||
def test_code_without_endpgm(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no s_endpgm"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_NOP * 4)]))]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,110 @@
|
||||
# Shader corpus (Phase 0, #649)
|
||||
|
||||
A corpus of BetterXen-authored compute kernels compiled for the console, so the RDNA 2 shader
|
||||
translator ([ADR 0008](../../docs/adr/0008-m2-shader-format-gate.md), Branch D2) can be tested
|
||||
against inputs whose correct behaviour is known independently of the translator
|
||||
([AGENTS.md](../../AGENTS.md) §5).
|
||||
|
||||
For each kernel in [`hlsl/`](hlsl), three compilers produce:
|
||||
|
||||
- the **console container** a title would ship: DXBC with `DXIL` **and** an `ACCC` chunk whose
|
||||
payload is an `FSPX` package holding the RDNA 2 code;
|
||||
- **the console compiler's listing** of the RDNA 2 code for the same source, with encodings (compiler output, not
|
||||
Microsoft documentation);
|
||||
- **PC DXIL** from the public DXC, which runs on D3DMetal today and gives the reference result.
|
||||
|
||||
## What is committed and what is not
|
||||
|
||||
| Committed | Not committed |
|
||||
|---|---|
|
||||
| The HLSL kernels in `hlsl/` (original BetterXen code, GPL-3.0-or-later) | Every compiler output: containers, listings, extracted code and disassembly |
|
||||
| [`scripts/shader-corpus/build.sh`](../../scripts/shader-corpus/build.sh) and [`extract_code.py`](../../scripts/shader-corpus/extract_code.py) with its unit tests | The GDK, its compilers, and any file from it |
|
||||
| Layout facts derived from our own outputs (below) | |
|
||||
|
||||
The console compilers come from authorized GDK material and run on BetterXen's own HLSL only.
|
||||
Their outputs stay in `target/shader-corpus/` (git-ignored) and are never committed. Run the
|
||||
compilers in a scratch bottle, never in a title's bottle.
|
||||
|
||||
The layout facts below are derived from those outputs and **are** published in this file. On
|
||||
2026-11-29 the repository owner reported that the team had approved publishing them, and decided
|
||||
that BetterXen is no longer a clean-room project ([CONTRIBUTING](../../CONTRIBUTING.md), #650):
|
||||
contributors may use the GDK compilers and read this file. The compilers, their outputs and the
|
||||
GDK itself are still never committed.
|
||||
|
||||
## Reproducibility
|
||||
|
||||
The corpus can only be rebuilt by someone who has the GDK compilers. CI cannot rebuild it, and a
|
||||
contributor without the GDK cannot reproduce its inputs. That limits what the corpus proves: it
|
||||
checks a translator against shaders with known source, on the word of whoever built it.
|
||||
|
||||
To let two people with access confirm they hold the same inputs, `build.sh` writes
|
||||
`target/shader-corpus/SHA256SUMS` with the SHA-256 of every `.xs.cso` and `.pc.cso`. The sums are
|
||||
not listed here yet: they are worth committing only once two independent builds agree, which
|
||||
also shows whether the compilers' output is deterministic.
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
WINE=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine \
|
||||
BOTTLE=<scratch bottle> \
|
||||
XDXC=<GDK>/…/xbox/bin/gen9/xdxc.exe \
|
||||
PIX_DXC=<GDK>/…/bin/Scarlett/pixsc/dxc.exe \
|
||||
DXC=<DXC v1.9.2609>/bin/x64/dxc.exe \
|
||||
LLVM_MC=$(brew --prefix llvm)/bin/llvm-mc \
|
||||
scripts/shader-corpus/build.sh
|
||||
```
|
||||
|
||||
All eight kernels currently build, and every kernel's console code extracts and decodes with
|
||||
LLVM's public `gfx1030` disassembler (2026-11-28, Apple Silicon, CrossOver 26.3):
|
||||
|
||||
| Kernel | What it exercises | Console instructions |
|
||||
|---|---|---|
|
||||
| `fill` | integer ALU | 11 |
|
||||
| `branch` | divergent if/else | 17 |
|
||||
| `loop` | per-lane trip count, early exit | 60 |
|
||||
| `lds` | groupshared memory, barriers, tree reduction | 58 |
|
||||
| `wave` | `WaveActiveSum`, `WavePrefixSum`, `WaveReadLaneFirst`, `WaveActiveBallot` | 47 |
|
||||
| `atomic` | global `InterlockedAdd` / `InterlockedMax` with returned values | 57 |
|
||||
| `floatmath` | `mad`, `sqrt`, `rcp`, float/uint conversion | 22 |
|
||||
| `groupid` | 2D groups, `SV_GroupID`, `SV_GroupThreadID`, `SV_GroupIndex` | 17 |
|
||||
|
||||
`extract_code.py`'s unit tests use synthetic containers and need no GDK:
|
||||
`python3 -m unittest scripts/shader-corpus/test_extract_code.py`.
|
||||
|
||||
## Layout facts (derived from our own outputs)
|
||||
|
||||
- **Container:** `xdxc` keeps the `DXIL` chunk and adds `ACCC`. Title containers can be `ACCC`-only;
|
||||
the `ACCC` format is the same. `bx-cli shader` rejects these containers with the same `FSPX`
|
||||
error as a title's console-only shaders, so the corpus is a faithful stand-in for that format.
|
||||
- **`FSPX`:** a 16-byte header (magic `FSPX`, version `1`, section count, total size equal to the
|
||||
payload size), then one 16-byte entry per section: kind, offset from the start of the payload,
|
||||
size, and a reserved `0`. The corpus containers have four sections, of kinds 0, 1, 6 and 7.
|
||||
- **Code:** section kind 6. It starts with `v_nop_xbox_data` instructions that carry the shader
|
||||
hash: the public VOP3 `v_nop` opcode (top 16 bits `0xD580`) with a literal as its third source
|
||||
operand, 12 bytes each, a form the public decoder rejects. A plain `v_nop` (8 bytes) is ordinary
|
||||
code. Every corpus kernel has three `v_nop_xbox_data`. They are followed by `gfx1030` machine code ending in `s_endpgm`, then
|
||||
padding.
|
||||
- **Two console backends.** `xdxc`'s `ACCC` code comes from its ACO step; the PIX compiler's
|
||||
listing comes from its NewBE step. They generate different code for the same source (for example,
|
||||
the inline buffer descriptor's word 3 is `0x31016fac` from ACO and `0x11014fac` from NewBE). The
|
||||
NewBE listing documents the console ABI (#638); the ACO code is what `ACCC` containers carry.
|
||||
Both use the root UAV address in `s[4:5]` here.
|
||||
|
||||
## Observations so far
|
||||
|
||||
- `wave` compiles to the cross-lane instructions that matter for running 64-wide waves on 32-wide
|
||||
Apple GPUs: DPP `row_shr` and `quad_perm`, `v_permlanex16`, `v_readlane` and `v_readfirstlane`.
|
||||
- **Open question:** in `wave`, LLVM decodes one instruction in the ballot sequence as
|
||||
`v_cmp_class_f16` with literal `0x7c01`, although the kernel has no half-precision code. Either
|
||||
ACO genuinely emits it there, or the console gives that opcode a meaning the public `gfx1030`
|
||||
decoder does not know. The reference runs below should tell.
|
||||
|
||||
## Next steps
|
||||
|
||||
1. A reference runner: dispatch each kernel's PC DXIL on D3DMetal with fixed inputs and record
|
||||
the output buffers as expected results, plus CPU-computed expectations where the result is a
|
||||
pure function of the inputs.
|
||||
2. The decoder (Phase 1), checked instruction by instruction against LLVM's disassembly and the
|
||||
NewBE listings.
|
||||
3. More kernels as the decoder grows: textures and samplers, structured control flow with nested
|
||||
loops, 64-bit atomics, and wave32 versus wave64 variants.
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Global atomics: add and max into shared counters, with returned old values.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint before;
|
||||
InterlockedAdd(output[0], x, before);
|
||||
InterlockedMax(output[1], x);
|
||||
output[2u + tid.x] = before;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Divergent control flow: lanes take different sides of an if/else.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint r;
|
||||
if ((x & 1u) != 0u) { r = x * 3u + 1u; } else { r = x >> 1; }
|
||||
output[tid.x] = r;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Integer ALU: multiply, shift, xor-add (no memory reads).
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint v = tid.x * 0x9e3779b1u;
|
||||
output[tid.x] = (v ^ (v >> 15)) + 0x01234567u;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Float ALU and conversions: fma, sqrt, rcp, float<->uint.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
float f = (float)input[tid.x] * asfloat(c0);
|
||||
float g = mad(f, 0.5f, 1.0f);
|
||||
float h = sqrt(abs(g)) + rcp(g + 2.0f);
|
||||
output[tid.x] = asuint(h) ^ (uint)floor(h * 256.0f);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// System values: group id, group thread id and flattened indices with a 2D group.
|
||||
[RootSignature(BX_RS)] [numthreads(8, 8, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID, uint gi : SV_GroupIndex) {
|
||||
uint idx = (gid.y * c0 + gid.x) * 64u + gi;
|
||||
output[idx] = (gtid.x << 24) | (gtid.y << 16) | (tid.x << 8) | tid.y;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Groupshared memory and barriers: a per-group tree reduction.
|
||||
groupshared uint scratch[64];
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID) {
|
||||
scratch[gtid.x] = input[tid.x];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
for (uint s = 32u; s > 0u; s >>= 1) {
|
||||
if (gtid.x < s) { scratch[gtid.x] += scratch[gtid.x + s]; }
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
if (gtid.x == 0u) { output[gid.x] = scratch[0]; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Loop with a per-lane, data-dependent trip count and an early exit.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint n = input[tid.x] % (c0 + 1u);
|
||||
uint acc = 0u;
|
||||
for (uint i = 0u; i < n; ++i) {
|
||||
acc += i * c1;
|
||||
if (acc > c2) { break; }
|
||||
}
|
||||
output[tid.x] = acc;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Cross-lane wave operations: the costly case when a 64-wide wave runs as two 32-wide halves.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint sum = WaveActiveSum(x);
|
||||
uint prefix = WavePrefixSum(x);
|
||||
uint first = WaveReadLaneFirst(x);
|
||||
uint4 ballot = WaveActiveBallot((x & 1u) != 0u);
|
||||
output[tid.x * 4u + 0u] = sum;
|
||||
output[tid.x * 4u + 1u] = prefix;
|
||||
output[tid.x * 4u + 2u] = first;
|
||||
output[tid.x * 4u + 3u] = countbits(ballot.x) + countbits(ballot.y);
|
||||
}
|
||||
Reference in new issue
Block a user