Compare commits

..
Author SHA1 Message Date
ates a648cdecc7 A collaborator only says 'work': the agent makes the machine ready itself
AGENTS.md section 0, step 1 told an agent whose preflight failed to stop
and hand the setup back to its person. It now fixes what it can and
stops only for what it cannot supply.

bx-cli setup --find searches the home folder and saves both settings:
- the GDK is recognised by its d3d12_xs.h and remembered as the first
  folder below Documents, Downloads, Desktop, Developer or Projects (or
  below home);
- the target build is recognised by structure, never by name: a PE32+
  file of at least 16 MiB that imports d3d12_xs.dll;
- executables inside the GDK folder are its own tools, not titles;
- byte-identical copies are one build, and the copy kept is the one
  with the most of its imported DLLs beside it, which is the
  installation rather than a stray copy;
- hidden folders, Library, application bundles and build folders are
  not searched, and the walk is bounded.
A target build is saved only when exactly one distinct build is found;
choosing between builds is the collaborator's decision.

The agent may also install mingw-w64, cmake and gh with Homebrew and
free disk space by removing its own scratch. It stops for: no Apple
Silicon Mac, CrossOver not installed, the build or the GDK not on the
machine, or more than one distinct build.

On the authoring Mac the search took about a second and chose the
installation among four identical copies and two GDK tools.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 15:42:41 +03:00
Ateş 911c27f62b Merge pull request #688 from MacosPorters/process/pr-first-required-materials
[Process] Pull requests are the unit of work; the target build and the GDK are required
2026-11-29 15:36:48 +03:00
ates 9b9c3c63ee bx-cli setup: remember where the target build and the GDK are
Environment variables have to be set in every shell, and an agent's
shell often does not inherit them. bx-cli setup --target-exe <path>
--gdk-root <folder> checks each path with the same rules as preflight
and saves it in ~/.config/betterxen/local.conf (or under
XDG_CONFIG_HOME): outside every checkout, so it cannot be committed,
and shared by every worktree, shell and agent session of that user.
Preflight reads it; BX_TARGET_EXE and BX_GDK_ROOT still override it for
one command. With no arguments, setup shows what is saved as present or
missing without printing a path.

The repository cannot find the target build itself, because it must
never contain the build's file name; the collaborator names it once.

AGENTS.md section 0 and the working method describe setup. The unit
test covers writing and reading the settings, unknown keys, comments
and the override order.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 15:35:08 +03:00
ates b16bdc1d4a Rules: pull requests are the unit of work; the target build and GDK are required
Two decisions by the repository owner:

1. No agent works without the target build and the GDK. bx-cli preflight
   (new) fails unless the host is an Apple Silicon Mac with CrossOver,
   D3DMetal and mingw-w64, BX_TARGET_EXE names the target build's
   executable, BX_GDK_ROOT is a folder holding the GDK (its d3d12_xs.h is
   found by a bounded walk), and 10 GiB of disk is free. It prints no
   local path. AGENTS.md section 0 makes it step 1: if it fails, the
   agent stops and does no work.

2. A blocker an agent can fix gets a pull request, not an issue. The
   agent runs the build, takes the first signature no open pull request
   covers, and claims it with a draft pull request titled with that
   signature. Issues remain for handoffs (label handoff), decisions for
   a person, and the ladder status. Claim comments and the 7-day stale
   window are removed; an idle draft may be taken over after 3 days.

The working method is rewritten to match and explains why: an issue of
the form 'the build stops at X' is a fact about one run on one machine,
while the conformance test holds everywhere.

A unit test covers the target-build and GDK checks and the not-ready
verdict.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 15:31:16 +03:00
Ateş 21700c2869 Merge pull request #683 from MacosPorters/docs/working-method-accepted
[Process] The working method is in effect; point to the ladder issue
2026-11-29 14:56:57 +03:00
Ateş da82407073 Merge pull request #650 from MacosPorters/track-d/649-shader-corpus
[M3-D3] shader-transpiler: Phase 0 corpus of console-compiled kernels with known source
2026-11-29 13:01:13 +03:00
ates 2e55cf2259 Merge main; BetterXen is no longer a clean-room project (#650)
Merges current main (conflict: CHANGELOG.md only) and records the
repository owner's decisions of 2026-11-29 that resolve review point 1:
- the team approved publishing layout facts derived from the GDK
  compilers' output for BetterXen's own source;
- BetterXen is no longer a clean-room project. CONTRIBUTING.md says
  that material the project is authorized to use 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 stays
  forbidden. README.md, docs/README.md and docs/legal.md no longer call
  the project clean-room; the corpus README states the decision.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 13:00:39 +03:00
ates 4cb858e6f5 docs: the working method is in effect; point to the ladder issue
#662 is merged, so the working method no longer says 'proposed'. It
names the pinned ladder issue (#663) and notes that the starting queue
was filed as #664-#680.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:49:50 +03:00
Ateş b36e397681 Merge pull request #638 from MacosPorters/track-f/637-console-shader-abi
[M2-F17] docs: console compute shader entry ABI observed from the Series X|S compiler
2026-11-29 11:48:27 +03:00
ates 5bc4ff5cf4 Merge remote-tracking branch 'origin/main' into fix-638
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:48:08 +03:00
Ateş 5e204bd883 Merge pull request #662 from MacosPorters/docs/game-ladder-roadmap
[Process] Stage-based roadmap and the blocker queue: what an agent does when told "work"
2026-11-29 11:47:11 +03:00
Ateş 5c2e2c9b63 Merge pull request #659 from MacosPorters/track-a/bringup-veh-diagnostics
[M2-A] runtime_veh: opt-in fault context, watches, breakpoints and sampler
2026-11-29 11:36:16 +03:00
ates 77dd9ffef3 Merge remote-tracking branch 'origin/main' into fix-659 2026-11-29 11:35:25 +03:00
Ateş abecde1c39 Merge pull request #635 from MacosPorters/track-a/634-veh-breakpoint
[M2-A16] runtime_veh: record breakpoints and assertion failures a guest crash reporter hides
2026-11-29 11:35:09 +03:00
ates e532fc56ba Merge remote-tracking branch 'origin/main' into fix-635
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:22:18 +03:00
ates ef58b18147 shader corpus: skip only literal-form v_nop; synthetic test words; reproducibility
Review of #650:
- extract_code.py treated every leading word with top bits 0xD580 as a
  12-byte v_nop_xbox_data. A plain v_nop (8 bytes) there would have been
  skipped as 12 and misaligned the rest. It now requires the literal
  operand (third source operand 255) that makes the instruction 12
  bytes. Two unit tests cover a plain v_nop at the start and after
  hash words.
- The test's hash words are replaced by obviously synthetic values of
  the same shape.
- README: the reproducibility limit is stated; build.sh writes
  SHA256SUMS of the compiled inputs for cross-checking between people
  with the compilers. Wording: the v_nop opcode is public, its literal
  form is what the public decoder rejects; the listing is compiler
  output, not Microsoft documentation. The contradiction about
  publishing is replaced by a plain statement that the layout facts are
  published and that this waits for a maintainer decision.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:16:58 +03:00
ates 2deada1f9d Merge remote-tracking branch 'origin/main' into fix-650-corpus
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:15:49 +03:00
ates 04148f77f8 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:06:54 +03:00
ates 5a6e786850 docs: console shader ABI review fixes: provenance, class U, NewBE scope
Review on #638:
- a Provenance section records the maintainer's statement that
  Microsoft's authorization covers publishing these derived observations,
  that the material is never committed, and that only a contributor with
  the same authorization can reproduce them;
- CLAIM-XBOX-CS-ENTRY-ABI moves from class A to U (no public source
  establishes it; not yet independently reproduced), names the NewBE
  backend, root buffer descriptors, and the exact host and tool versions;
- the page, changelog and index are scoped to the PIX/NewBE path; the ACO
  comparison cites #650, where it is recorded, instead of #647, and D2 is
  told the ABI is a candidate, not accepted;
- word 3 is decoded from the public GFX10 layout for both 0x11014fac and
  0x31016fac (FORMAT 20/22, OOB_SELECT 1/3), which also explains why the
  record count -1 disables the bounds check;
- eleven probes, not ten; table buffer descriptors 32 bytes apart;
  STRIDE bits 29:16; D3DMetal 4.0b3 named (3.0 not measured); wave64 as
  the default with no declared wave size; odd-SGPR alignment, the
  overflow threshold and ACCC-only output listed as open.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:06:54 +03:00
ates 34f744aa5d CHANGELOG: runtime_veh diagnostic hardening and fixture
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:04:44 +03:00
ates afc093ee54 Merge remote-tracking branch 'origin/track-a/634-veh-breakpoint' into track-a/bringup-veh-diagnostics 2026-11-29 07:03:55 +03:00
ates 224586917f runtime_veh, bx-cli trace: breakpoint record follow-ups from review
From the reviews on #635 (none blocking):
- log_breakpoint saves and restores the thread's last-error value, so a
  resumed first-chance exception leaves the guest's error state as it was
  (test_veh_breakpoint checks it; it fails without the restore);
- past the cap the counter is not advanced again, so it cannot wrap;
- bx-telemetry parses the record's address and bx-cli trace prints it,
  which locates a breakpoint outside any image (module ?);
- the cap note appears when any record reached the cap, not only the
  last line, since threads or processes can write records out of order.

Deduplicating repeated sites stays with #651.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:03:36 +03:00
ates 2af3e7d10a Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:02:00 +03:00
ates 17e2e2a835 runtime_veh: review fixes for the opt-in diagnostics; a fixture for them
Review on #659:
1. the AV context spec is scanned without strtok (no shared cursor
   across faulting threads);
2. every VirtualProtect is checked: a watch or range watch that cannot
   unprotect a page disarms, logs diagnostic_disarmed and passes the
   access violation on instead of looping; failed re-protection, code
   byte restores and int3 re-insertion are logged and disarm;
3. AV context and sampler lines use bounded appends (no length past the
   buffer), JSON-escape the spec and module names, and take module names
   through GetModuleFileNameW and UTF-8;
4. helper threads check a stop flag; detach disarms every diagnostic
   (pages, code bytes, TLS) without waiting, and keeps the log handle and
   lock alive while any helper was started;
5. BX_VEH_AV_CONTEXT/AV_ALL are read once at attach, so with them unset
   an access violation costs nothing;
6. bx-cli lets the named BX_VEH_* switches through its isolated guest
   environment (DIAGNOSTIC_ENV_ALLOWLIST), with a unit test that other
   variables and secrets still do not pass;
7. test_veh_diagnostics runs each mode in a child process (the switches
   are read at attach) and checks the log: no records when off; 16 capped
   av_context records from 4 threads, valid JSON with the spec escaped;
   a non-ASCII module name in UTF-8; one watched write with its value,
   and a failed protection change that disarms and reaches the guest; two
   code hits with a safe string argument; sampler records and a clean
   exit. 21 checks pass; the previous runtime_veh fails 6 of them.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:01:31 +03:00
ates f7748387da runtime_veh: opt-in fault context, watches, breakpoints and sampler
All off by default: BX_VEH_AV_CONTEXT / BX_VEH_AV_ALL log an access
violation's memory type, protection, allocation base and unwound stack;
BX_VEH_WATCH and BX_VEH_WATCH_RANGE watch writes to an address, a range
or a pointer chain; BX_VEH_HIT sets software code breakpoints that log
registers and string arguments; BX_VEH_SAMPLE samples every thread.
They were used to find the target build's startup blockers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
jelly013 84f4370227 Merge main into track-f/637-console-shader-abi
Resolve the CHANGELOG.md conflict under Added by keeping both sides.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-28 17:28:14 +01:00
ates e57046a17d shader-transpiler: Phase 0 corpus of console-compiled kernels with known source (#649)
Eight BetterXen-authored compute kernels, a build script that compiles each locally with the console xdxc (DXIL + ACCC/FSPX), the console PIX compiler (ISA listing) and the PC DXC (DXIL), and an extractor that takes the FSPX kind-6 code section, skips v_nop_xbox_data and disassembles it with llvm-mc gfx1030. All eight build and decode cleanly. Compiler outputs stay in the git-ignored target/shader-corpus/. The extractor has unit tests on synthetic containers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 19:11:57 +03:00
ates 79e1906c27 docs: note that the console ABI probes describe the NewBE compiler path (#637)
The ACO compiler that emits ACCC containers generates different code for
the same HLSL; its root-buffer descriptor word 3 differs (#647).

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 19:01:10 +03:00
ates d65c12f6a9 Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 19:01:07 +03:00
ates 3f2f2732ed Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 17:49:29 +03:00
ates 7c807d8b3a runtime_veh: address jelly013's review of breakpoint logging
- Say precisely which guest handlers run after bx_veh_handler: the top-level filter and vectored handlers the guest registers last.
- Write module names as UTF-8 via GetModuleFileNameW and WideCharToMultiByte, so a non-ASCII name cannot make the JSONL line invalid.
- bx-telemetry parses record/limit, and bx-cli trace notes when the per-process cap was reached.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 17:49:28 +03:00
ates ca2ad143f9 docs: record the console compute shader entry ABI (#637)
Add the compute entry conventions observed from Microsoft's Series X|S
HLSL compiler, used under Microsoft's authorization, on eleven
project-authored probes: wave64 code, root data from s4 in parameter
order, the root-data address in s0:s1 on overflow, IDs after the root
data, inline root buffer descriptors without bounds, table descriptor
sizes and per-load binding metadata. Register roles are marked as
inferences. CLAIM-XBOX-CS-ENTRY-ABI (class A) records the measurement.
No compiler output, binary or documentation text is included.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:25:54 +03:00
ates 0b474941f0 runtime_veh: record breakpoints a guest crash reporter hides (#634)
A guest with its own crash reporter replaces the top-level filter
installed at attach, so its assertions never reached
unhandled_exception. The vectored handler, which runs before any guest
handler, now records EXCEPTION_BREAKPOINT and STATUS_ASSERTION_FAILURE
as breakpoint_exception records with module name, base and RVA. They
are first-chance, handling is unchanged, and at most 16 are written per
process. bx-telemetry parses them and bx-cli trace lists them.

test_veh_breakpoint replaces the top-level filter, resumes from its own
vectored handler and checks the records against the RVA of a labelled
int3 site; it fails against the previous bx_runtime_veh.dll.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:26:19 +03:00
28 changed files with 3172 additions and 93 deletions

No files matched your search

+52 -24
View File
@@ -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.
+14
View File
@@ -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,17 @@ 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`);
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
- `AcpHal.dll`:
+2 -2
View File
@@ -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).
+1 -1
View File
@@ -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.
---
+4 -2
View File
@@ -4,7 +4,7 @@
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
- [Working Method](process/working-method.md) — Proposed: what an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
@@ -27,13 +27,15 @@
- [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.
## 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.
+10
View File
@@ -268,3 +268,13 @@ retrieved = "2026-11-22"
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
test = "Read slides 12 and 13. No console execution."
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
[[claim]]
id = "CLAIM-XBOX-CS-ENTRY-ABI"
class = "U"
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
sources = ["docs/research/console-shader-abi.md"]
retrieved = "2026-11-28"
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
+2 -2
View File
@@ -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
+55 -55
View File
@@ -1,10 +1,23 @@
# Working Method: the Blocker Queue
# Working Method: Run, Fix, Pull Request
**Status: proposed**, together with the matching change to [AGENTS.md §0](../../AGENTS.md).
**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 becomes a blocker issue or a tooling issue when this proposal is accepted.
| 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.
+75
View File
@@ -0,0 +1,75 @@
# Console compute shader entry ABI (probe results)
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
What this is:
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
## Method
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
| Probe | Root signature | Shader |
| --- | --- | --- |
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
## Observations
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
- A root constant takes one SGPR (p01: `s4`–`s7`).
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
**Descriptor tables.** Descriptors are loaded from the table address:
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
## Consequences
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
## Open
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
- **`s0`–`s3`:** what they hold when root data fits in registers.
- **One compiler build, one host:** a different GDK version may differ.
## Provenance
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
+864 -4
View File
@@ -41,6 +41,21 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
"XPC_SERVICE_NAME",
];
/// Opt-in `bx_runtime_veh.dll` diagnostic switches. They carry addresses and counts, never
/// credentials, so the isolated guest environment lets them through by name; every other
/// variable is still stripped.
const DIAGNOSTIC_ENV_ALLOWLIST: &[&str] = &[
"BX_VEH_AV_CONTEXT",
"BX_VEH_AV_ALL",
"BX_VEH_WATCH",
"BX_VEH_WATCH_RANGE",
"BX_VEH_WATCH_RANGE_MAX",
"BX_VEH_HIT",
"BX_VEH_HIT_ALL",
"BX_VEH_HIT_RDX",
"BX_VEH_SAMPLE",
];
fn usage_text() -> &'static str {
"BetterXen Hybrid CLI (bx-cli)\n\
\n\
@@ -48,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"
@@ -121,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,
@@ -375,6 +923,40 @@ fn render_trace(text: &str) -> String {
);
}
}
if !summary.breakpoint_exceptions.is_empty() {
let _ = writeln!(
out,
"\nBreakpoint/assert exceptions, first chance ({}):",
summary.breakpoint_exceptions.len()
);
for hit in &summary.breakpoint_exceptions {
let _ = writeln!(
out,
" code={} {} + RVA={} (module_base={} address={})",
hit.exception_code.as_deref().unwrap_or("unknown"),
hit.module.as_deref().unwrap_or("?"),
hit.rva.as_deref().unwrap_or("unknown"),
hit.module_base.as_deref().unwrap_or("unknown"),
hit.address.as_deref().unwrap_or("unknown"),
);
}
// Any record at the cap counts: concurrent threads, or several processes appending to one
// log, can write the capped record before a lower-numbered one.
if let Some(limit) =
summary
.breakpoint_exceptions
.iter()
.find_map(|hit| match (hit.record, hit.limit) {
(Some(record), Some(limit)) if limit > 0 && record >= limit => Some(limit),
_ => None,
})
{
let _ = writeln!(
out,
" cap of {limit} records reached; later breakpoints were not recorded"
);
}
}
if !summary.unimpl_apis.is_empty() {
let _ = writeln!(out, "\nUnimplemented APIs:");
for (api, count) in &summary.unimpl_apis {
@@ -402,7 +984,7 @@ where
{
let mut env_map = BTreeMap::new();
env_map.insert("PATH".to_string(), SAFE_CHILD_PATH.to_string());
for &key in HOST_ENV_ALLOWLIST {
for &key in HOST_ENV_ALLOWLIST.iter().chain(DIAGNOSTIC_ENV_ALLOWLIST) {
if let Some(val) = lookup(key) {
env_map.insert(key.to_string(), val);
}
@@ -1142,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()),
}
}
@@ -1171,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]),
@@ -1657,6 +2243,26 @@ sub setup_bottle_wineprefix {
assert!(!child.contains_key("CX_GRAPHICS_BACKEND"));
}
#[test]
fn isolated_env_passes_only_the_named_veh_diagnostics() {
let host = BTreeMap::from([
("BX_VEH_AV_CONTEXT", "1"),
("BX_VEH_SAMPLE", "5"),
("BX_VEH_UNKNOWN", "x"),
("BX_LOG_FILE", "/tmp/elsewhere.jsonl"),
("GH_TOKEN", "secret_token"),
]);
let child = collect_isolated_host_env(|k| host.get(k).map(|s| (*s).to_string()));
assert_eq!(
child.get("BX_VEH_AV_CONTEXT").map(String::as_str),
Some("1")
);
assert_eq!(child.get("BX_VEH_SAMPLE").map(String::as_str), Some("5"));
assert!(!child.contains_key("BX_VEH_UNKNOWN"));
assert!(!child.contains_key("BX_LOG_FILE"));
assert!(!child.contains_key("GH_TOKEN"));
}
#[test]
fn converts_unix_path_to_wine_z_drive() {
assert_eq!(
@@ -1723,6 +2329,62 @@ sub setup_bottle_wineprefix {
assert_eq!(format_shader_gate_section(&summarize_jsonl(log)), "");
}
#[test]
fn renders_breakpoint_exceptions_with_module_and_rva() {
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(
"\nBreakpoint/assert exceptions, first chance (1):\n code=0x80000003 \
title.exe + RVA=0x0000000002236178 (module_base=0x0000000140000000 \
address=0x0000000142236178)\n"
),
"{rendered}"
);
assert!(!rendered.contains("Unhandled exceptions"), "{rendered}");
assert!(
!rendered.contains("cap of"),
"one of 16 records is not the cap: {rendered}"
);
}
#[test]
fn notes_when_the_breakpoint_record_cap_is_reached() {
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
"{rendered}"
);
}
#[test]
fn notes_the_cap_when_a_capped_record_is_not_the_last_line() {
// Two threads (or processes) appending: the capped record lands before record 15.
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
{"ts_ms":6,"tid":8,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
"{rendered}"
);
}
#[test]
fn prints_the_address_of_a_breakpoint_outside_any_image() {
let log = r#"{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains("address=0x0000000000410000"),
"{rendered}"
);
}
#[test]
fn renders_decisions_kinds_stages_gaps_and_missing_bridge() {
// Realistic records, matching the emitter in shims/d3d12_xs/shader_gate.cpp.
@@ -1814,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");
@@ -1823,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]
@@ -1832,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}");
}
}
+71
View File
@@ -18,6 +18,9 @@ pub struct TraceSummary {
pub amd_traps: BTreeMap<String, TrapCount>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
pub breakpoint_exceptions: Vec<BreakpointException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
@@ -182,6 +185,30 @@ pub struct UnhandledException {
pub rip: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct BreakpointException {
pub exception_code: Option<String>,
pub module: Option<String>,
pub module_base: Option<String>,
pub rva: Option<String>,
/// The faulting address, which locates a breakpoint outside any image (module `?`).
pub address: Option<String>,
/// 1-based index of this record and the per-process cap, so a reader can tell a run
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
pub record: Option<u32>,
pub limit: Option<u32>,
}
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
let needle = format!("\"{key}\":");
let start = line.find(&needle)? + needle.len();
let digits: &str = &line[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
@@ -344,6 +371,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
});
}
"breakpoint_exception" => {
summary.breakpoint_exceptions.push(BreakpointException {
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
module: extract_json_str(trimmed, "module").map(str::to_owned),
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
address: extract_json_str(trimmed, "address").map(str::to_owned),
record: extract_json_u32(trimmed, "record"),
limit: extract_json_u32(trimmed, "limit"),
});
}
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
"unimpl_vtable" => {
*summary
@@ -420,6 +458,39 @@ mod tests {
assert_eq!(summary.clwb_trap_lower_bound, None);
}
#[test]
fn collects_breakpoint_exceptions_in_log_order() {
let log = r#"
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
"#;
let summary = summarize_jsonl(log);
assert!(summary.unhandled_exceptions.is_empty());
assert_eq!(
summary.breakpoint_exceptions,
[
BreakpointException {
exception_code: Some("0x80000003".into()),
module: Some("title.exe".into()),
module_base: Some("0x0000000140000000".into()),
rva: Some("0x0000000002236178".into()),
address: Some("0x0000000142236178".into()),
record: Some(1),
limit: Some(16),
},
BreakpointException {
exception_code: Some("0xc0000420".into()),
module: Some("?".into()),
module_base: Some("0x0000000000000000".into()),
rva: Some("0x0000000000000000".into()),
address: Some("0x0000000000410000".into()),
record: Some(2),
limit: Some(16),
},
]
);
}
#[test]
fn collects_unhandled_exceptions_in_log_order() {
let log = r#"
+66
View File
@@ -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"
+158
View File
@@ -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())
+106
View File
@@ -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()
+110
View File
@@ -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.
+17
View File
@@ -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;
}
+16
View File
@@ -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;
}
+14
View File
@@ -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;
}
+20
View File
@@ -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]; }
}
+19
View File
@@ -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;
}
+21
View File
@@ -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);
}
+893 -3
View File
@@ -1,8 +1,12 @@
#include <windows.h>
#include <tlhelp32.h>
#include <atomic>
#include <cstdio>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <initializer_list>
#include <intrin.h>
#include "bx_config.h"
@@ -18,6 +22,12 @@ LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
std::atomic_flag g_crash_logged{};
std::atomic<bool> g_crash_in_flight{false};
std::atomic<uint64_t> g_clwb_traps{0};
std::atomic<uint32_t> g_breakpoint_records{0};
// Breakpoint and assertion-failure records per process, so a guest that uses int3 on purpose
// cannot flood the log.
constexpr uint32_t kMaxBreakpointRecords = 16;
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
// counts reach the JSONL trace only: the frozen .def has no export for them.
@@ -354,11 +364,874 @@ LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
return disposition;
}
// A guest with its own crash reporter replaces the top-level filter installed at attach, so
// log_unhandled_exception never sees its assertions. The vectored handler runs before the
// guest's top-level filter and before any vectored handler the guest registers last; a handler
// the guest registers first can resume the exception before this one sees it. It records
// breakpoints and assertion failures with their module offset. They are first-chance, so the
// guest may still handle them; handling is left unchanged.
void log_breakpoint(const EXCEPTION_RECORD& record) {
// Past the cap the counter is not advanced again, so it cannot wrap around to 1.
if (g_breakpoint_records.load(std::memory_order_relaxed) >= kMaxBreakpointRecords) {
return;
}
const uint32_t index = g_breakpoint_records.fetch_add(1, std::memory_order_relaxed) + 1;
if (index > kMaxBreakpointRecords) {
return;
}
// The calls below can change the thread's last-error value; a resumed first-chance exception
// must leave the guest's error state as it was.
const DWORD last_error = GetLastError();
const uintptr_t address = reinterpret_cast<uintptr_t>(record.ExceptionAddress);
MEMORY_BASIC_INFORMATION region{};
uintptr_t module_base = 0;
char module[MAX_PATH] = "?";
if (VirtualQuery(record.ExceptionAddress, &region, sizeof(region)) &&
region.Type == MEM_IMAGE) {
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
// Wide API plus an explicit UTF-8 conversion: the ANSI form returns the name in the
// active code page, which would make a non-ASCII module name invalid UTF-8 in the JSON.
wchar_t path[MAX_PATH];
const DWORD length =
GetModuleFileNameW(reinterpret_cast<HMODULE>(module_base), path, MAX_PATH);
if (length > 0 && length < MAX_PATH) {
const wchar_t* slash = std::wcsrchr(path, L'\\');
const wchar_t* name = slash ? slash + 1 : path;
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, module, sizeof(module), nullptr, nullptr) == 0) {
std::snprintf(module, sizeof(module), "?");
}
}
}
char line[1024];
const int length = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\","
"\"event\":\"breakpoint_exception\",\"exception_code\":\"0x%08lx\","
"\"module\":\"%s\",\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
"\"address\":\"0x%016llx\",\"record\":%u,\"limit\":%u}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
record.ExceptionCode, module, static_cast<unsigned long long>(module_base),
static_cast<unsigned long long>(module_base ? address - module_base : 0),
static_cast<unsigned long long>(address), index, kMaxBreakpointRecords);
if (length > 0 && length < static_cast<int>(sizeof(line))) {
write_log_line(line, static_cast<size_t>(length));
}
SetLastError(last_error);
}
// Diagnostics (off unless BX_VEH_AV_CONTEXT is set): the first access violations in an image
// are logged with the general registers and, for each address in the variable, 64 bytes of
// memory. An entry "*ADDR+OFF" first reads the pointer at ADDR, then dumps at pointer + OFF.
// Reads are guarded by VirtualQuery; handling is left unchanged (first chance, search continues).
bool readable_bytes(uintptr_t address, size_t size) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) || region.State != MEM_COMMIT ||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
return false;
}
return address + size <= reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
// A JSONL line built with bounded appends: an append that does not fit is dropped and marks the
// line truncated, so the length never passes the buffer. Four bytes stay reserved for the closing
// "\"}\n". Text from the environment or module names goes through add_escaped.
class LineBuf {
public:
LineBuf(char* p, size_t cap) : p_(p), cap_(cap - 4) { p_[0] = '\0'; }
void add(const char* fmt, ...) {
if (truncated_) return;
va_list ap;
va_start(ap, fmt);
const int n = std::vsnprintf(p_ + len_, cap_ - len_, fmt, ap);
va_end(ap);
if (n < 0 || static_cast<size_t>(n) >= cap_ - len_) {
p_[len_] = '\0'; // drop the partial append
truncated_ = true;
return;
}
len_ += static_cast<size_t>(n);
}
// JSON string escaping for " \ and control characters; other bytes (UTF-8) pass through.
void add_escaped(const char* text, size_t max) {
for (size_t i = 0; text[i] && i < max && !truncated_; ++i) {
const unsigned char ch = static_cast<unsigned char>(text[i]);
if (ch == '"' || ch == '\\') add("\\%c", ch);
else if (ch < 0x20) add("\\u%04x", ch);
else add("%c", ch);
}
}
bool room(size_t n) const { return !truncated_ && cap_ - len_ > n; }
// Closes the JSON string and object and writes the line.
void finish() {
std::memcpy(p_ + len_, "\"}\n", 4);
write_log_line(p_, len_ + 3);
}
private:
char* p_;
size_t cap_;
size_t len_ = 0;
bool truncated_ = false;
};
// A module's file name (without the directory) in UTF-8, or "?" when it cannot be read.
void module_name_utf8(uintptr_t base, char* out, size_t size) {
wchar_t path[MAX_PATH];
const DWORD n = base ? GetModuleFileNameW(reinterpret_cast<HMODULE>(base), path, MAX_PATH) : 0;
if (n == 0 || n >= MAX_PATH) {
std::snprintf(out, size, "?");
return;
}
const wchar_t* slash = std::wcsrchr(path, L'\\');
const wchar_t* name = slash ? slash + 1 : path;
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, out, static_cast<int>(size), nullptr, nullptr) == 0) {
std::snprintf(out, size, "?");
}
}
// BX_VEH_AV_CONTEXT and BX_VEH_AV_ALL, read once when runtime_veh attaches. With the context
// switch unset the access-violation path does nothing at all.
char g_av_spec[512];
bool g_av_context_on = false;
bool g_av_all = false;
void read_av_switches() {
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_CONTEXT", g_av_spec, sizeof(g_av_spec));
g_av_context_on = n > 0 && n < sizeof(g_av_spec);
char v[4];
const DWORD k = GetEnvironmentVariableA("BX_VEH_AV_ALL", v, sizeof(v));
g_av_all = k > 0 && k < sizeof(v) && v[0] == '1';
}
void log_av_context(const EXCEPTION_POINTERS& ep) {
static std::atomic<uint32_t> logged{0};
if (!g_av_context_on || logged.fetch_add(1) >= 16) return;
const CONTEXT& c = *ep.ContextRecord;
char line[1600];
LineBuf out(line, sizeof(line));
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"av_context\","
"\"detail\":\"rip=%llx fault=%llx rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx "
"rsp=%llx r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)c.Rip,
(unsigned long long)(ep.ExceptionRecord->NumberParameters >= 2 ? ep.ExceptionRecord->ExceptionInformation[1] : 0),
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx,
(unsigned long long)c.Rdx, (unsigned long long)c.Rsi, (unsigned long long)c.Rdi,
(unsigned long long)c.Rbp, (unsigned long long)c.Rsp, (unsigned long long)c.R8,
(unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14,
(unsigned long long)c.R15);
// The comma-separated spec, scanned without shared state (several threads can fault at once).
for (const char* cursor = g_av_spec; *cursor && out.room(220);) {
const char* comma = std::strchr(cursor, ',');
const size_t length = comma ? static_cast<size_t>(comma - cursor) : std::strlen(cursor);
char item[64];
const size_t take = length < sizeof(item) - 1 ? length : sizeof(item) - 1;
std::memcpy(item, cursor, take);
item[take] = '\0';
cursor += length + (comma ? 1 : 0);
// "*A+O": dump at [A]+O. "**A+O1+O2": dump at [[A]+O1]+O2.
const int derefs = item[0] == '*' ? (item[1] == '*' ? 2 : 1) : 0;
char* rest = nullptr;
uintptr_t address = static_cast<uintptr_t>(std::strtoull(item + derefs, &rest, 16));
uintptr_t offsets[2] = {0, 0};
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
bool ok = true;
for (int k = 0; k < derefs && ok; ++k) {
ok = readable_bytes(address, 8);
if (ok) address = *reinterpret_cast<const uintptr_t*>(address) + offsets[k];
}
out.add(" | ");
out.add_escaped(item, sizeof(item));
if (!ok) {
out.add(" unresolved");
continue;
}
if (derefs == 0) address += offsets[0];
out.add(" @%llx:", (unsigned long long)address);
MEMORY_BASIC_INFORMATION mbi{};
if (VirtualQuery(reinterpret_cast<void*>(address), &mbi, sizeof(mbi))) {
out.add(" [type=%lx prot=%lx alloc=%llx region=%llx+%llx]", static_cast<unsigned long>(mbi.Type),
static_cast<unsigned long>(mbi.Protect), (unsigned long long)reinterpret_cast<uintptr_t>(mbi.AllocationBase),
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.BaseAddress), (unsigned long long)mbi.RegionSize);
}
if (!readable_bytes(address, 64)) {
out.add(" unreadable");
continue;
}
const auto* q = reinterpret_cast<const uint64_t*>(address);
for (int i = 0; i < 8; ++i) out.add(" %llx", (unsigned long long)q[i]);
}
// The faulting thread's stack: up to eight frames, unwound from its context, as module+offset.
out.add(" | stack:");
CONTEXT walk = c;
for (int i = 0; i < 8 && walk.Rip && out.room(64); ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(walk.Rip), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char name[96] = "anon";
if (base) module_name_utf8(base, name, sizeof(name));
out.add(" ");
out.add_escaped(name, 24);
out.add("+%llx", (unsigned long long)(walk.Rip - base));
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) {
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) break;
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
out.finish();
}
// A diagnostic that had to stop (a protection change failed): logged once per kind.
void log_disarmed(const char* what, uintptr_t address) {
char line[256];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"diagnostic_disarmed\","
"\"detail\":\"%s address=%llx error=%lu\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), what,
(unsigned long long)address, GetLastError());
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
// Set when runtime_veh detaches: helper threads stop at their next step and log nothing more.
std::atomic<bool> g_diag_stop{false};
std::atomic<int> g_diag_threads{0};
// Diagnostics (off unless BX_VEH_WATCH=ADDR:LEN, hex): a software write watch. A helper thread
// makes the page holding [ADDR, ADDR+LEN) read-only as soon as that page is committed. Each
// write fault in the page is allowed by restoring write access and single-stepping the writing
// instruction; writes inside the range are logged with the instruction's module offset and the
// value after the write, then the page is protected again. Writes by other threads while the
// page is briefly writable are not seen, and system calls that write into the page fail while
// it is protected, so this is for diagnosis only.
uintptr_t g_watch_begin = 0, g_watch_end = 0, g_watch_page = 0;
std::atomic<bool> g_watch_armed{false};
std::atomic<uint32_t> g_watch_logged{0};
DWORD g_watch_tls = TLS_OUT_OF_INDEXES;
// The watched address: "A:LEN", or a pointer chain "*A+O:LEN" / "**A+O1+O2:LEN" that the helper
// thread resolves once every pointer in it is non-null and readable.
uintptr_t g_watch_root = 0, g_watch_offsets[2] = {0, 0}, g_watch_length = 8;
int g_watch_derefs = 0;
bool resolve_watch(uintptr_t* out) {
uintptr_t address = g_watch_root;
for (int k = 0; k < g_watch_derefs; ++k) {
if (!readable_bytes(address, 8)) return false;
const uintptr_t next = *reinterpret_cast<const uintptr_t*>(address);
if (!next) return false;
address = next + g_watch_offsets[k];
}
if (g_watch_derefs == 0) address += g_watch_offsets[0];
*out = address;
return true;
}
DWORD WINAPI watch_arm_thread(LPVOID) {
for (int i = 0; i < 600000 && !g_watch_armed.load() && !g_diag_stop.load(); ++i) {
uintptr_t begin = 0;
DWORD old = 0;
if (resolve_watch(&begin) && readable_bytes(begin, g_watch_length)) {
g_watch_begin = begin;
g_watch_end = begin + g_watch_length;
g_watch_page = begin & ~static_cast<uintptr_t>(4095);
char line[512];
int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watch_armed\","
"\"detail\":\"address=%llx contents:",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)begin);
for (uintptr_t a = begin; a + 8 <= g_watch_end && len < static_cast<int>(sizeof(line)) - 24; a += 8) {
len += std::snprintf(line + len, sizeof(line) - len, " %llx",
(unsigned long long)*reinterpret_cast<const uint64_t*>(a));
}
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
if (VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
g_watch_armed = true;
} else {
log_disarmed("watch: could not protect the page", g_watch_page);
}
break;
}
Sleep(1);
}
return 0;
}
void start_write_watch() {
char spec[96];
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_watch_derefs = spec[0] == '*' ? (spec[1] == '*' ? 2 : 1) : 0;
char* rest = nullptr;
g_watch_root = static_cast<uintptr_t>(std::strtoull(spec + g_watch_derefs, &rest, 16));
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) g_watch_offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
if (rest && *rest == ':') g_watch_length = static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16));
g_watch_tls = TlsAlloc();
if (g_watch_tls == TLS_OUT_OF_INDEXES) return;
if (HANDLE t = CreateThread(nullptr, 0, watch_arm_thread, nullptr, 0, nullptr)) {
++g_diag_threads;
CloseHandle(t);
}
}
void log_watched_write(uintptr_t rip, uintptr_t address, uint64_t value) {
if (g_watch_logged.fetch_add(1) >= 64) return;
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(rip), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char line[256];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watched_write\","
"\"detail\":\"rip=%llx module_base=%llx address=%llx value_after=%llx\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)rip, (unsigned long long)base, (unsigned long long)address,
(unsigned long long)value);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
// Returns true when the exception belonged to the write watch and was handled.
bool handle_write_watch(PEXCEPTION_POINTERS ep) {
if (!g_watch_armed.load() || g_watch_tls == TLS_OUT_OF_INDEXES) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
if ((address & ~static_cast<uintptr_t>(4095)) != g_watch_page) return false;
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old)) {
// Fail open: the write cannot be allowed, so the guest gets its access violation.
g_watch_armed = false;
log_disarmed("watch: could not unprotect the page", g_watch_page);
return false;
}
// Remember the write for the single-step that follows it (+1 so 0 means "none").
TlsSetValue(g_watch_tls, reinterpret_cast<void*>(address + 1));
ep->ContextRecord->EFlags |= 0x100;
return true;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_watch_tls));
if (!pending) return false;
TlsSetValue(g_watch_tls, nullptr);
const uintptr_t address = pending - 1;
if (address >= g_watch_begin && address < g_watch_end) {
const uintptr_t slot = address & ~static_cast<uintptr_t>(7);
log_watched_write(static_cast<uintptr_t>(reinterpret_cast<uintptr_t>(r.ExceptionAddress)), address,
*reinterpret_cast<const uint64_t*>(slot));
}
DWORD old = 0;
if (!g_watch_armed.load() || !VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
if (g_watch_armed.exchange(false)) log_disarmed("watch: could not re-protect the page", g_watch_page);
}
return true;
}
return false;
}
// Diagnostics (off unless BX_VEH_WATCH_RANGE=A:LEN, hex, at most 16 MiB): a write watch over a
// range of pages, for data whose exact address moves between runs. A helper thread makes each
// read-write page in the range read-only as soon as it is committed. A write fault is allowed by
// restoring the page and single-stepping the instruction; the write is logged with its address,
// the value after it and up to six frames of the writing thread, unwound from its context. After
// 64 logged writes the whole range is made writable again and the watch stops.
constexpr size_t kRangeWatchPages = 4096;
uintptr_t g_rw_begin = 0, g_rw_end = 0;
std::atomic<uint8_t> g_rw_armed[kRangeWatchPages];
std::atomic<bool> g_rw_on{false};
std::atomic<uint32_t> g_rw_logged{0};
DWORD g_rw_tls = TLS_OUT_OF_INDEXES;
void range_watch_stop() {
g_rw_on = false;
for (size_t i = 0; i < kRangeWatchPages; ++i) {
if (g_rw_armed[i].exchange(0)) {
DWORD old = 0;
VirtualProtect(reinterpret_cast<void*>(g_rw_begin + i * 4096), 4096, PAGE_READWRITE, &old);
}
}
}
// "*A+O:LEN": the range starts at [A] + O, resolved once the pointer at A is readable and non-zero.
uintptr_t g_rw_root = 0, g_rw_offset = 0, g_rw_length = 0;
DWORD WINAPI range_watch_thread(LPVOID) {
if (g_rw_root) {
for (int i = 0; i < 600000; ++i) {
if (g_diag_stop.load()) return 0;
if (readable_bytes(g_rw_root, 8) && *reinterpret_cast<const uintptr_t*>(g_rw_root)) break;
Sleep(1);
}
if (!readable_bytes(g_rw_root, 8) || !*reinterpret_cast<const uintptr_t*>(g_rw_root)) return 0;
const uintptr_t begin = (*reinterpret_cast<const uintptr_t*>(g_rw_root) + g_rw_offset) & ~static_cast<uintptr_t>(4095);
g_rw_end = (begin + g_rw_length + 4095) & ~static_cast<uintptr_t>(4095);
g_rw_begin = begin;
char line[200];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_watch_resolved\","
"\"detail\":\"begin=%llx end=%llx\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)g_rw_begin, (unsigned long long)g_rw_end);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
const size_t pages = (g_rw_end - g_rw_begin) / 4096;
for (int round = 0; round < 600000 && g_rw_on.load() && !g_diag_stop.load(); ++round) {
bool all = true;
for (size_t i = 0; i < pages && g_rw_on.load(); ++i) {
if (g_rw_armed[i].load()) continue;
all = false;
const uintptr_t page = g_rw_begin + i * 4096;
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(page), &region, sizeof(region)) || region.State != MEM_COMMIT ||
region.Protect != PAGE_READWRITE) {
continue;
}
DWORD old = 0;
if (VirtualProtect(reinterpret_cast<void*>(page), 4096, PAGE_READONLY, &old)) g_rw_armed[i] = 1;
}
if (all) break;
Sleep(1);
}
return 0;
}
void start_range_watch() {
char spec[64];
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
char* rest = nullptr;
const bool chain = spec[0] == '*';
const uintptr_t first = static_cast<uintptr_t>(std::strtoull(spec + (chain ? 1 : 0), &rest, 16));
uintptr_t offset = 0;
if (chain && rest && *rest == '+') offset = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
const uintptr_t length = rest && *rest == ':' ? static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16)) : 0;
if (!first || !length || length > kRangeWatchPages * 4096) return;
g_rw_tls = TlsAlloc();
if (g_rw_tls == TLS_OUT_OF_INDEXES) return;
if (chain) {
g_rw_root = first;
g_rw_offset = offset;
g_rw_length = length;
} else {
g_rw_begin = first & ~static_cast<uintptr_t>(4095);
g_rw_end = (g_rw_begin + length + 4095) & ~static_cast<uintptr_t>(4095);
}
g_rw_on = true;
if (HANDLE t = CreateThread(nullptr, 0, range_watch_thread, nullptr, 0, nullptr)) {
++g_diag_threads;
CloseHandle(t);
}
}
void log_range_write(const CONTEXT& c, uintptr_t address) {
uintptr_t frames[6]{};
int count = 0;
CONTEXT walk = c;
for (; count < 6 && walk.Rip; ++count) {
frames[count] = static_cast<uintptr_t>(walk.Rip);
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) {
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) { ++count; break; }
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
char line[640];
int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_write\","
"\"detail\":\"address=%llx value_after=%llx frames:",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)address,
(unsigned long long)*reinterpret_cast<const uint64_t*>(address & ~static_cast<uintptr_t>(7)));
for (int i = 0; i < count && len < static_cast<int>(sizeof(line)) - 48; ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
len += std::snprintf(line + len, sizeof(line) - len, " %llx+%llx", (unsigned long long)base,
(unsigned long long)(frames[i] - base));
}
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
write_log_line(line, static_cast<size_t>(len));
}
}
// Returns true when the exception belonged to the range watch and was handled.
bool handle_range_watch(PEXCEPTION_POINTERS ep) {
if (g_rw_tls == TLS_OUT_OF_INDEXES) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
if (address < g_rw_begin || address >= g_rw_end) return false;
const size_t index = (address - g_rw_begin) / 4096;
if (!g_rw_armed[index].load()) return false;
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READWRITE, &old)) {
g_rw_armed[index] = 0; // fail open: the guest gets its access violation
log_disarmed("range watch: could not unprotect a page", g_rw_begin + index * 4096);
return false;
}
TlsSetValue(g_rw_tls, reinterpret_cast<void*>(address + 1));
ep->ContextRecord->EFlags |= 0x100;
return true;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_rw_tls));
if (!pending) return false;
TlsSetValue(g_rw_tls, nullptr);
const uintptr_t address = pending - 1;
static const uint32_t cap = [] {
char v[16];
const DWORD k = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE_MAX", v, sizeof(v));
const unsigned long want = (k > 0 && k < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
return static_cast<uint32_t>(want == 0 ? 64 : (want > 200000 ? 200000 : want));
}();
const uint32_t n = g_rw_logged.fetch_add(1);
if (n < cap) log_range_write(*ep->ContextRecord, address);
if (n + 1 >= cap) {
range_watch_stop();
} else if (g_rw_on.load()) {
DWORD old = 0;
const size_t index = (address - g_rw_begin) / 4096;
if (g_rw_armed[index].load() &&
!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READONLY, &old)) {
g_rw_armed[index] = 0;
log_disarmed("range watch: could not re-protect a page", g_rw_begin + index * 4096);
}
}
return true;
}
return false;
}
// Diagnostics (off unless BX_VEH_HIT=A1,A2,..., hex, at most 8): software code breakpoints in this
// process. Each address gets an int3 when runtime_veh attaches; a hit logs the registers, puts the
// original byte back, single-steps that instruction and re-inserts the int3. The first 16 hits per
// address are logged, then every 256th. Other threads can pass an address unseen while its byte is
// restored, so this is for diagnosis only.
struct CodeHit {
uintptr_t address;
uint8_t original;
std::atomic<uint32_t> hits;
};
CodeHit g_code_hits[8];
int g_code_hit_count = 0;
DWORD g_code_hit_tls = TLS_OUT_OF_INDEXES;
// False when the byte could not be written. A failure to restore the page's original protection
// is logged: the page then stays writable, which the log record makes visible.
bool write_code_byte(uintptr_t address, uint8_t value) {
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, PAGE_EXECUTE_READWRITE, &old)) return false;
*reinterpret_cast<volatile uint8_t*>(address) = value;
DWORD unused = 0;
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, old, &unused)) {
log_disarmed("code hit: could not restore the page protection", address);
}
FlushInstructionCache(GetCurrentProcess(), reinterpret_cast<void*>(address), 1);
return true;
}
// Diagnostics (off unless BX_VEH_SAMPLE=MS, decimal): a sampling profiler for every thread in the
// process. Every MS milliseconds a helper thread visits each other thread: while it is suspended
// only its context and up to 64 KiB of its stack are copied (no heap or loader calls, so a thread
// suspended inside either cannot deadlock the sampler). After it resumes, up to eight frames are
// unwound against the copy with the images' unwind data and logged as module base + offset, with
// the thread id. At most 20000 samples are logged. For diagnosis only.
DWORD g_sample_interval = 0;
DWORD g_sample_self = 0;
alignas(16) uint8_t g_sample_stack[64 * 1024];
void sample_thread(DWORD tid) {
HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, tid);
if (!h) return;
CONTEXT c{};
c.ContextFlags = CONTEXT_FULL;
uintptr_t stack_lo = 0;
size_t copied = 0;
bool got = false;
if (SuspendThread(h) != static_cast<DWORD>(-1)) {
got = GetThreadContext(h, &c) != FALSE;
MEMORY_BASIC_INFORMATION region{};
if (got && VirtualQuery(reinterpret_cast<void*>(c.Rsp), &region, sizeof(region)) && region.State == MEM_COMMIT) {
stack_lo = static_cast<uintptr_t>(c.Rsp);
const uintptr_t end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
copied = end - stack_lo < sizeof(g_sample_stack) ? end - stack_lo : sizeof(g_sample_stack);
std::memcpy(g_sample_stack, reinterpret_cast<const void*>(stack_lo), copied);
}
ResumeThread(h);
}
CloseHandle(h);
if (!got) return;
// Unwind against the copy: stack addresses (rsp, and rbp when it points into the stack) are
// rebased into g_sample_stack; return addresses read from it are the thread's real ones.
const uintptr_t copy = reinterpret_cast<uintptr_t>(g_sample_stack);
auto in_stack = [&](DWORD64 a) { return a >= stack_lo && a < stack_lo + copied; };
CONTEXT walk = c;
walk.Rsp = copy;
if (in_stack(c.Rbp)) walk.Rbp = copy + (c.Rbp - stack_lo);
uintptr_t frames[8]{};
int count = 0;
for (; count < 8 && walk.Rip; ++count) {
frames[count] = static_cast<uintptr_t>(walk.Rip);
if (walk.Rsp < copy || walk.Rsp + 8 > copy + copied) { ++count; break; }
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) { // leaf function: the return address is at rsp
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
char line[760];
LineBuf out(line, sizeof(line));
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"sample\",\"detail\":\"thread=%lu",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), tid);
for (int i = 0; i < count && out.room(64); ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
// The thread runs again, so the loader lock taken by GetModuleFileNameW cannot be held by it.
char name[96] = "anon";
if (base) module_name_utf8(base, name, sizeof(name));
out.add(" ");
out.add_escaped(name, 24);
out.add("+%llx", (unsigned long long)(frames[i] - base));
}
if (!g_diag_stop.load()) out.finish();
}
DWORD WINAPI sampler_main(LPVOID) {
const DWORD pid = GetCurrentProcessId();
for (int logged = 0; logged < 20000 && !g_diag_stop.load();) {
Sleep(g_sample_interval);
if (g_diag_stop.load()) break;
DWORD tids[256];
int n = 0;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (snap == INVALID_HANDLE_VALUE) continue;
THREADENTRY32 te{};
te.dwSize = sizeof(te);
for (BOOL ok = Thread32First(snap, &te); ok && n < 256; ok = Thread32Next(snap, &te)) {
if (te.th32OwnerProcessID == pid && te.th32ThreadID != g_sample_self) tids[n++] = te.th32ThreadID;
}
CloseHandle(snap);
for (int i = 0; i < n; ++i, ++logged) sample_thread(tids[i]);
}
return 0;
}
void start_sampler() {
char spec[16];
const DWORD n = GetEnvironmentVariableA("BX_VEH_SAMPLE", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_sample_interval = static_cast<DWORD>(std::strtoul(spec, nullptr, 10));
if (g_sample_interval == 0) return;
if (HANDLE t = CreateThread(nullptr, 0, sampler_main, nullptr, 0, &g_sample_self)) {
++g_diag_threads;
CloseHandle(t);
}
}
void start_code_hits() {
char spec[256];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_code_hit_tls = TlsAlloc();
if (g_code_hit_tls == TLS_OUT_OF_INDEXES) return;
for (const char* item = spec; *item && g_code_hit_count < 8;) {
char* end = nullptr;
const uintptr_t address = static_cast<uintptr_t>(std::strtoull(item, &end, 16));
const char* comma = std::strchr(item, ',');
item = comma ? comma + 1 : item + std::strlen(item);
MEMORY_BASIC_INFORMATION region{};
if (!address || !VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) ||
region.Type != MEM_IMAGE || region.State != MEM_COMMIT) {
continue;
}
CodeHit& hit = g_code_hits[g_code_hit_count];
hit.address = address;
hit.original = *reinterpret_cast<const uint8_t*>(address);
if (write_code_byte(address, 0xCC)) ++g_code_hit_count;
}
char line[160];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hits_armed\","
"\"detail\":\"count=%d\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), g_code_hit_count);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
void log_code_hit(const CodeHit& hit, uint32_t count, const CONTEXT& c) {
char line[2048];
int len = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hit\","
"\"detail\":\"address=%llx hit=%u rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx rsp=%llx "
"r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), (unsigned long long)hit.address, count,
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx, (unsigned long long)c.Rdx,
(unsigned long long)c.Rsi, (unsigned long long)c.Rdi, (unsigned long long)c.Rbp, (unsigned long long)c.Rsp,
(unsigned long long)c.R8, (unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14, (unsigned long long)c.R15);
// The first 16 bytes behind the three argument registers, when they point at readable memory.
const struct {
const char* name;
DWORD64 value;
} args[] = {{"rcx", c.Rcx}, {"rdx", c.Rdx}, {"r8", c.R8}};
for (const auto& a : args) {
if (len <= 0 || len >= static_cast<int>(sizeof(line)) - 64 || !readable_bytes(static_cast<uintptr_t>(a.value), 16)) continue;
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(a.value));
len += std::snprintf(line + len, sizeof(line) - len, " [%s]=%016llx %016llx", a.name, (unsigned long long)q[0],
(unsigned long long)q[1]);
// Printable text (a path or name argument): up to 96 characters of it.
const auto* s = reinterpret_cast<const unsigned char*>(static_cast<uintptr_t>(a.value));
if (s[0] >= 0x20 && s[0] < 0x7f && s[1] >= 0x20 && s[1] < 0x7f && readable_bytes(static_cast<uintptr_t>(a.value), 96)) {
char text[97];
int n = 0;
while (n < 96 && s[n] >= 0x20 && s[n] < 0x7f) {
text[n] = (s[n] == '"' || s[n] == '\\') ? '_' : static_cast<char>(s[n]);
++n;
}
text[n] = '\0';
if (len < static_cast<int>(sizeof(line)) - 120) {
len += std::snprintf(line + len, sizeof(line) - len, " [%s]s=%s", a.name, text);
}
}
}
// BX_VEH_HIT_RDX=LEN (hex, at most 0x200): also dump LEN bytes of the object rdx points to.
static const size_t rdx_len = [] {
char v[16];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_RDX", v, sizeof(v));
if (n == 0 || n >= sizeof(v)) return static_cast<size_t>(0);
const size_t want = static_cast<size_t>(std::strtoull(v, nullptr, 16)) & ~static_cast<size_t>(7);
return want > 0x200 ? static_cast<size_t>(0x200) : want;
}();
if (rdx_len && len > 0 && readable_bytes(static_cast<uintptr_t>(c.Rdx), rdx_len)) {
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(c.Rdx));
len += std::snprintf(line + len, sizeof(line) - len, " rdx_obj:");
for (size_t i = 0; i < rdx_len / 8 && len < static_cast<int>(sizeof(line)) - 24; ++i) {
len += std::snprintf(line + len, sizeof(line) - len, " %llx", (unsigned long long)q[i]);
}
}
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
write_log_line(line, static_cast<size_t>(len));
}
}
// Returns true when the exception belonged to a code breakpoint and was handled.
bool handle_code_hit(PEXCEPTION_POINTERS ep) {
if (g_code_hit_count == 0) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
CONTEXT& c = *ep->ContextRecord;
if (r.ExceptionCode == EXCEPTION_BREAKPOINT) {
const uintptr_t at = reinterpret_cast<uintptr_t>(r.ExceptionAddress);
for (int i = 0; i < g_code_hit_count; ++i) {
CodeHit& hit = g_code_hits[i];
if (at != hit.address && c.Rip - 1 != hit.address) continue;
const uint32_t count = hit.hits.fetch_add(1) + 1;
static const bool every = [] {
char v[4];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_ALL", v, sizeof(v));
return n > 0 && n < sizeof(v) && v[0] == '1';
}();
if (count <= 16 || count % 256 == 0 || (every && count <= 20000)) log_code_hit(hit, count, c);
if (!write_code_byte(hit.address, hit.original)) {
// The original instruction cannot be put back: stop handling this address and let
// the breakpoint reach the guest instead of looping on it.
log_disarmed("code hit: could not restore the original byte", hit.address);
hit.address = 0;
return false;
}
c.Rip = hit.address;
c.EFlags |= 0x100;
TlsSetValue(g_code_hit_tls, reinterpret_cast<void*>(static_cast<uintptr_t>(i + 1)));
return true;
}
return false;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_code_hit_tls));
if (!pending) return false;
TlsSetValue(g_code_hit_tls, nullptr);
CodeHit& hit = g_code_hits[pending - 1];
if (hit.address && !g_diag_stop.load() && !write_code_byte(hit.address, 0xCC)) {
log_disarmed("code hit: could not re-insert the breakpoint", hit.address);
hit.address = 0;
}
return true;
}
return false;
}
// Restores every page and code byte the diagnostics changed (used at detach).
void disarm_diagnostics() {
if (g_watch_armed.exchange(false)) {
DWORD old = 0;
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old);
}
if (g_rw_on.load() || g_rw_begin) range_watch_stop();
for (int i = 0; i < g_code_hit_count; ++i) {
CodeHit& hit = g_code_hits[i];
if (hit.address && *reinterpret_cast<const volatile uint8_t*>(hit.address) == 0xCC) {
write_code_byte(hit.address, hit.original);
}
hit.address = 0;
}
for (DWORD* tls : {&g_watch_tls, &g_rw_tls, &g_code_hit_tls}) {
if (*tls != TLS_OUT_OF_INDEXES) {
TlsFree(*tls);
*tls = TLS_OUT_OF_INDEXES;
}
}
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
return EXCEPTION_CONTINUE_SEARCH;
}
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
if (handle_code_hit(ep)) return EXCEPTION_CONTINUE_EXECUTION;
if (handle_range_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
if (handle_write_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
log_breakpoint(*ep->ExceptionRecord);
return EXCEPTION_CONTINUE_SEARCH;
}
if (code == EXCEPTION_ACCESS_VIOLATION) {
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
MEMORY_BASIC_INFORMATION region{};
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, &region, sizeof(region)) && region.Type == MEM_IMAGE)) {
log_av_context(*ep);
}
return EXCEPTION_CONTINUE_SEARCH;
}
if (code != EXCEPTION_ILLEGAL_INSTRUCTION) {
return EXCEPTION_CONTINUE_SEARCH;
}
@@ -479,6 +1352,15 @@ const bx_runtime_config_t* bx_get_runtime_config(void) {
int bx_veh_install(void) {
if (!g_veh_handle) {
g_veh_handle = AddVectoredExceptionHandler(1, bx_veh_handler);
if (g_veh_handle) {
read_av_switches();
// The helper threads below start running only after the loader lock is released; nothing
// here waits for them. They check g_diag_stop and stop at detach.
start_write_watch();
start_code_hits();
start_sampler();
start_range_watch();
}
}
return g_veh_handle != nullptr ? 1 : 0;
}
@@ -503,15 +1385,23 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
if (current_filter != log_unhandled_exception) {
SetUnhandledExceptionFilter(current_filter);
}
// Stop the diagnostics and take them out of the guest's memory: restore watched pages and
// original code bytes. Nothing waits for the helper threads (that would deadlock on the
// loader lock); they stop at their next step.
g_diag_stop = true;
disarm_diagnostics();
if (g_veh_handle) {
RemoveVectoredExceptionHandler(g_veh_handle);
g_veh_handle = nullptr;
}
if (g_log_handle != INVALID_HANDLE_VALUE) {
// A helper thread may still be inside write_log_line when this runs. While any helper was
// started, the log handle and its lock are left alive (the process is ending, or the DLL is
// being unloaded with threads that only touch them); otherwise they are released.
if (g_diag_threads.load() == 0 && g_log_handle != INVALID_HANDLE_VALUE) {
CloseHandle(g_log_handle);
g_log_handle = INVALID_HANDLE_VALUE;
}
if (g_log_lock_ready) {
if (g_diag_threads.load() == 0 && g_log_lock_ready) {
DeleteCriticalSection(&g_log_lock);
g_log_lock_ready = false;
}
@@ -0,0 +1,2 @@
add_executable(test_veh_breakpoint main.cpp)
target_link_libraries(test_veh_breakpoint PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,155 @@
/*
* runtime_veh records breakpoints and assertion failures even when the guest has replaced the
* top-level exception filter, as a title with its own crash reporter does.
*
* The test installs its own top-level filter and a last-registered vectored handler that
* resumes after each int3, then raises breakpoints at a labelled site and one
* STATUS_ASSERTION_FAILURE. The expected RVA is the label's address minus this module's base,
* computed here, not by the shim. Needs BX_LOG_FILE (bx-cli --log).
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <string>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
extern "C" void bx_breakpoint_site(void);
__asm__(".text\n"
".globl bx_breakpoint_site\n"
"bx_breakpoint_site:\n"
" int3\n"
" ret\n");
namespace {
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
constexpr int kRecordLimit = 16;
int g_failures = 0;
volatile LONG g_resumed = 0;
volatile LONG g_filter_calls = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "FAIL: test_veh_breakpoint: %s\n", what);
++g_failures;
}
}
LONG WINAPI guest_filter(PEXCEPTION_POINTERS) {
InterlockedIncrement(&g_filter_calls);
return EXCEPTION_CONTINUE_SEARCH;
}
LONG CALLBACK resume(PEXCEPTION_POINTERS ep) {
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT) {
ep->ContextRecord->Rip =
reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) + 1;
InterlockedIncrement(&g_resumed);
return EXCEPTION_CONTINUE_EXECUTION;
}
if (code == kStatusAssertionFailure) {
InterlockedIncrement(&g_resumed);
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
std::string read_log_from(long offset) {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* file = std::fopen(path, "rb")) {
if (std::fseek(file, offset, SEEK_SET) == 0) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
}
std::fclose(file);
}
return text;
}
long log_size() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return -1;
long size = 0;
if (FILE* file = std::fopen(path, "rb")) {
if (std::fseek(file, 0, SEEK_END) == 0) size = std::ftell(file);
std::fclose(file);
}
return size < 0 ? 0 : size;
}
int count_lines_with(const std::string& log, const char* a, const char* b = nullptr) {
int count = 0;
size_t start = 0;
while (start < log.size()) {
size_t end = log.find('\n', start);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(start, end - start);
if (line.find(a) != std::string::npos && (!b || line.find(b) != std::string::npos)) {
++count;
}
start = end + 1;
}
return count;
}
} // namespace
int main() {
// Keep a static import on bx_runtime_veh.dll so its handler is installed at attach.
volatile uint64_t attached = bx_veh_get_clwb_trap_count();
(void)attached;
const long mark = log_size();
if (mark < 0) {
std::fprintf(stderr, "FAIL: test_veh_breakpoint: BX_LOG_FILE must be set\n");
return 1;
}
// A title's crash reporter takes over the top-level filter after runtime_veh attached.
SetUnhandledExceptionFilter(guest_filter);
PVOID handler = AddVectoredExceptionHandler(0, resume);
check(handler != nullptr, "AddVectoredExceptionHandler");
// A recorded breakpoint leaves the guest thread's last-error value as it was.
SetLastError(0x12345678);
bx_breakpoint_site();
check(GetLastError() == 0x12345678, "a recorded breakpoint preserves the thread's last-error value");
RaiseException(kStatusAssertionFailure, 0, 0, nullptr);
for (int i = 0; i < kRecordLimit + 4; ++i) bx_breakpoint_site();
RemoveVectoredExceptionHandler(handler);
check(g_resumed == kRecordLimit + 6, "every exception reached the guest's own handler");
check(g_filter_calls == 0, "no exception went unhandled");
const uintptr_t base = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
const uintptr_t site = reinterpret_cast<uintptr_t>(&bx_breakpoint_site);
char rva[64];
std::snprintf(rva, sizeof(rva), "\"rva\":\"0x%016llx\"",
static_cast<unsigned long long>(site - base));
const std::string log = read_log_from(mark);
const int records = count_lines_with(log, "\"event\":\"breakpoint_exception\"");
check(records == kRecordLimit, "records stop at the per-process limit of 16");
check(count_lines_with(log, "\"exception_code\":\"0x80000003\"", rva) == kRecordLimit - 1,
"each recorded int3 names the labelled site's RVA");
check(count_lines_with(log, "\"exception_code\":\"0xc0000420\"") == 1,
"the assertion failure is recorded");
// RaiseException reports an address inside kernelbase, so only the int3 records name this
// module.
check(count_lines_with(log, "\"module\":\"test_veh_breakpoint.exe\"") == kRecordLimit - 1,
"int3 records name this module");
check(count_lines_with(log, "\"event\":\"unhandled_exception\"") == 0,
"nothing was reported as unhandled");
if (g_failures) return 1;
std::printf("PASS: test_veh_breakpoint (%d records, cap %d)\n", records, kRecordLimit);
return 0;
}
@@ -0,0 +1,6 @@
add_executable(test_veh_diagnostics main.cpp)
target_include_directories(test_veh_diagnostics PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_veh_diagnostics PRIVATE bx_runtime_veh kernel32)
# A fixed image base: the parent passes its own code address to the child's BX_VEH_HIT, which is
# armed before the child's main runs.
target_link_options(test_veh_diagnostics PRIVATE -Wl,--disable-dynamicbase)
@@ -0,0 +1,389 @@
// Conformance test for bx_runtime_veh.dll's opt-in diagnostics (BX_VEH_AV_CONTEXT, BX_VEH_AV_ALL,
// BX_VEH_WATCH, BX_VEH_HIT, BX_VEH_SAMPLE).
//
// The switches are read when runtime_veh attaches, before main, so the parent starts this same
// executable as a child once per mode with that mode's environment, then reads the shared JSONL
// log (BX_LOG_FILE) for the records the child produced. Expected values come from what each child
// does, not from runtime_veh. Every record must be valid JSON and valid UTF-8.
//
// Run under `bx-cli run --log`. Exit 0: all checks passed. Exit 1: a check failed. Exit 77: the
// host cannot run a mode (logged as SKIP).
#include <windows.h>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <string>
#include <vector>
extern "C" __declspec(dllimport) uint64_t bx_veh_get_clwb_trap_count(void);
// A store whose length the child's handler knows (mov [rcx], rdx = 48 89 11), used to make a
// write fault the child can step over.
extern "C" void store_qword(volatile uint64_t* at, uint64_t value);
asm(".globl store_qword\n"
"store_qword:\n"
" movq %rdx, (%rcx)\n"
" ret\n");
// The code-breakpoint target. Not inlined, so the child calls the address the parent passes.
extern "C" __attribute__((noinline)) int hit_target(const char* text) {
volatile int sum = 0;
for (const char* c = text; *c; ++c) sum += *c;
return sum;
}
namespace {
int g_failures = 0;
int g_checks = 0;
void check(bool ok, const char* what) {
++g_checks;
if (!ok) {
++g_failures;
std::printf("FAIL: test_veh_diagnostics: %s\n", what);
}
}
constexpr uintptr_t kWatchBase = 0x7A0000000ull; // the child's watched allocation
// --- Child side --------------------------------------------------------------------------------
volatile LONG g_child_avs = 0;
LONG CALLBACK child_handler(PEXCEPTION_POINTERS ep) {
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return EXCEPTION_CONTINUE_SEARCH;
InterlockedIncrement(&g_child_avs);
// A real fault in store_qword: step over its 3-byte store.
if (reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) == reinterpret_cast<uintptr_t>(&store_qword)) {
ep->ContextRecord->Rip += 3;
}
return EXCEPTION_CONTINUE_EXECUTION; // a raised (continuable) one resumes after RaiseException
}
void raise_av() {
const ULONG_PTR info[2] = {1, 0x1234};
RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 2, info);
}
DWORD WINAPI raise_many(LPVOID) {
for (int i = 0; i < 8; ++i) raise_av();
return 0;
}
int child(const char* mode, const char* arg) {
(void)bx_veh_get_clwb_trap_count(); // keeps the runtime_veh import
AddVectoredExceptionHandler(0, child_handler); // after runtime_veh's own handler
if (!std::strcmp(mode, "off")) {
for (int i = 0; i < 4; ++i) raise_av();
return g_child_avs == 4 ? 0 : 2;
}
if (!std::strcmp(mode, "av")) {
HANDLE threads[4];
for (auto& t : threads) t = CreateThread(nullptr, 0, raise_many, nullptr, 0, nullptr);
WaitForMultipleObjects(4, threads, TRUE, 10000);
for (auto t : threads) CloseHandle(t);
return g_child_avs == 32 ? 0 : 2;
}
if (!std::strcmp(mode, "watch")) {
auto* base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(kWatchBase), 0x10000,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
if (base != reinterpret_cast<uint8_t*>(kWatchBase)) return 77;
// The helper thread protects the page once it is committed.
MEMORY_BASIC_INFORMATION mbi{};
for (int i = 0; i < 2000; ++i) {
if (VirtualQuery(base, &mbi, sizeof(mbi)) && mbi.Protect == PAGE_READONLY) break;
Sleep(1);
}
if (mbi.Protect != PAGE_READONLY) return 3;
*reinterpret_cast<volatile uint64_t*>(base + 0x10) = 0x1122334455667788ull; // watched: logged
*reinterpret_cast<volatile uint64_t*>(base + 0x200) = 7; // same page, not watched
if (*reinterpret_cast<volatile uint64_t*>(base + 0x10) != 0x1122334455667788ull) return 4;
// Decommit the watched page: the next write faults, and runtime_veh cannot unprotect the
// page, so it must disarm and pass the fault on (to child_handler) rather than loop.
if (!VirtualFree(base, 0x1000, MEM_DECOMMIT)) return 5;
const LONG before = g_child_avs;
store_qword(reinterpret_cast<volatile uint64_t*>(base + 0x10), 9);
return g_child_avs == before + 1 ? 0 : 6;
}
if (!std::strcmp(mode, "hit")) {
const uintptr_t expected = static_cast<uintptr_t>(std::strtoull(arg, nullptr, 16));
if (expected != reinterpret_cast<uintptr_t>(&hit_target)) return 77; // image relocated
hit_target("quote\" back\\ path");
hit_target("second call");
return 0;
}
if (!std::strcmp(mode, "sample")) {
const DWORD until = GetTickCount() + 300;
volatile uint64_t spin = 0;
while (GetTickCount() < until) spin = spin + 1;
return spin ? 0 : 2;
}
return 2;
}
// --- Parent side -------------------------------------------------------------------------------
std::wstring widen(const char* s) {
std::wstring out;
while (*s) out.push_back(static_cast<wchar_t>(static_cast<unsigned char>(*s++)));
return out;
}
std::string read_log_from(const char* path, uint64_t offset) {
std::string text;
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
if (f == INVALID_HANDLE_VALUE) return text;
LARGE_INTEGER at;
at.QuadPart = static_cast<LONGLONG>(offset);
SetFilePointerEx(f, at, nullptr, FILE_BEGIN);
char buf[65536];
DWORD got = 0;
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
CloseHandle(f);
return text;
}
uint64_t file_size(const char* path) {
WIN32_FILE_ATTRIBUTE_DATA data{};
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &data)) return 0;
return (static_cast<uint64_t>(data.nFileSizeHigh) << 32) | data.nFileSizeLow;
}
// A JSONL record: one object whose strings use only JSON escapes and no raw control characters,
// in valid UTF-8.
bool valid_record(const std::string& line) {
if (line.size() < 2 || line.front() != '{' || line.back() != '}') return false;
bool in_string = false;
for (size_t i = 0; i < line.size(); ++i) {
const unsigned char c = static_cast<unsigned char>(line[i]);
if (c >= 0x80) { // UTF-8 sequence
const int extra = (c & 0xE0) == 0xC0 ? 1 : (c & 0xF0) == 0xE0 ? 2 : (c & 0xF8) == 0xF0 ? 3 : -1;
if (extra < 0 || i + extra >= line.size()) return false;
for (int k = 1; k <= extra; ++k) {
if ((static_cast<unsigned char>(line[i + k]) & 0xC0) != 0x80) return false;
}
i += extra;
continue;
}
if (!in_string) {
if (c == '"') in_string = true;
continue;
}
if (c < 0x20) return false;
if (c == '"') {
in_string = false;
} else if (c == '\\') {
if (i + 1 >= line.size()) return false;
const char e = line[++i];
if (e == 'u') {
if (i + 4 >= line.size()) return false;
for (int k = 1; k <= 4; ++k) {
if (!std::isxdigit(static_cast<unsigned char>(line[i + k]))) return false;
}
i += 4;
} else if (!std::strchr("\"\\/bfnrt", e)) {
return false;
}
}
}
return !in_string;
}
std::vector<std::string> records(const std::string& text, const char* event) {
std::vector<std::string> out;
const std::string needle = std::string("\"event\":\"") + event + "\"";
size_t start = 0;
while (start < text.size()) {
size_t end = text.find('\n', start);
if (end == std::string::npos) end = text.size();
std::string line = text.substr(start, end - start);
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.find(needle) != std::string::npos) out.push_back(line);
start = end + 1;
}
return out;
}
struct ChildRun {
DWORD exit_code = 0xFFFFFFFF;
std::string log;
};
// Starts `exe` as a child in `mode` with the extra environment variables, waits for it, and
// returns its exit code and the log lines it appended.
ChildRun run_child(const std::wstring& exe, const char* mode, const char* arg,
const std::vector<std::wstring>& extra_env, const char* log_path) {
ChildRun run;
std::wstring block;
if (wchar_t* env = GetEnvironmentStringsW()) {
for (const wchar_t* p = env; *p; p += std::wcslen(p) + 1) {
std::wstring entry(p);
if (entry.rfind(L"BX_VEH_", 0) == 0) continue; // only this mode's switches
block += entry;
block.push_back(L'\0');
}
FreeEnvironmentStringsW(env);
}
for (const auto& e : extra_env) {
block += e;
block.push_back(L'\0');
}
block.push_back(L'\0');
std::wstring cmd = L"\"" + exe + L"\" child " + widen(mode) + L" " + widen(arg);
STARTUPINFOW si{};
si.cb = sizeof(si);
PROCESS_INFORMATION pi{};
const uint64_t before = file_size(log_path);
if (!CreateProcessW(exe.c_str(), cmd.data(), nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT, block.data(),
nullptr, &si, &pi)) {
return run;
}
if (WaitForSingleObject(pi.hProcess, 60000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &run.exit_code);
else TerminateProcess(pi.hProcess, 9);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
run.log = read_log_from(log_path, before);
return run;
}
bool all_valid(const std::vector<std::string>& lines) {
for (const auto& l : lines) {
if (!valid_record(l)) {
std::printf(" invalid record: %.200s\n", l.c_str());
return false;
}
}
return true;
}
int parent(const char* log_path) {
wchar_t self[MAX_PATH];
GetModuleFileNameW(nullptr, self, MAX_PATH);
const std::wstring exe(self);
int skipped = 0;
// Off: synthetic access violations produce no av_context record.
{
ChildRun r = run_child(exe, "off", "-", {}, log_path);
check(r.exit_code == 0, "off: child handled its access violations (exit 0)");
check(records(r.log, "av_context").empty(), "off: no av_context record without BX_VEH_AV_CONTEXT");
}
// AV context from four threads at once, with a spec containing a quote, a backslash and a
// control character and far too long for one line: 16 records (the cap), each valid JSON.
std::wstring spec = L"BX_VEH_AV_CONTEXT=zz\"q\\b\x01,";
for (int i = 0; i < 80; ++i) spec += L"*10+8,";
{
ChildRun r = run_child(exe, "av", "-", {spec, L"BX_VEH_AV_ALL=1"}, log_path);
const auto lines = records(r.log, "av_context");
check(r.exit_code == 0, "av: every access violation reached the child (exit 0)");
check(lines.size() == 16, "av: 16 av_context records from 32 faults (the cap)");
check(all_valid(lines), "av: every av_context record is valid JSON");
bool escaped = false;
for (const auto& l : lines) escaped = escaped || l.find("zz\\\"q\\\\b\\u0001") != std::string::npos;
check(escaped, "av: the spec token is JSON-escaped");
bool stack = true;
for (const auto& l : lines) stack = stack && l.find("| stack:") != std::string::npos;
check(stack, "av: a truncated spec still leaves room for the stack");
}
// A non-ASCII module name in the stack must stay valid UTF-8.
{
std::wstring dir = exe.substr(0, exe.find_last_of(L'\\') + 1);
const std::wstring copy = dir + L"veh_ünïcode.exe";
if (CopyFileW(exe.c_str(), copy.c_str(), FALSE)) {
ChildRun r = run_child(copy, "av", "-", {L"BX_VEH_AV_CONTEXT=1", L"BX_VEH_AV_ALL=1"}, log_path);
const auto lines = records(r.log, "av_context");
check(r.exit_code == 0 && !lines.empty(), "unicode: the renamed child logged av_context");
check(all_valid(lines), "unicode: records with a non-ASCII module name are valid JSON and UTF-8");
bool named = false;
for (const auto& l : lines) named = named || l.find("veh_\xc3\xbc" "n\xc3\xaf" "code") != std::string::npos;
check(named, "unicode: the module name is written in UTF-8");
DeleteFileW(copy.c_str());
} else {
std::printf("SKIP: unicode mode: could not copy the executable\n");
++skipped;
}
}
// Write watch: one logged write, a write outside the range not logged, and a protection
// failure that disarms the watch and lets the fault reach the guest.
{
wchar_t watch[64];
std::swprintf(watch, 64, L"BX_VEH_WATCH=%llx:8", static_cast<unsigned long long>(kWatchBase + 0x10));
ChildRun r = run_child(exe, "watch", "-", {watch}, log_path);
if (r.exit_code == 77) {
std::printf("SKIP: watch mode: the fixed test address is not free in this process\n");
++skipped;
} else {
const auto writes = records(r.log, "watched_write");
const auto disarmed = records(r.log, "diagnostic_disarmed");
check(r.exit_code == 0, "watch: the write to the decommitted page reached the child (exit 0)");
check(writes.size() == 1 && writes[0].find("address=7a0000010") != std::string::npos &&
writes[0].find("value_after=1122334455667788") != std::string::npos,
"watch: exactly the watched write is logged, with its value");
check(disarmed.size() == 1 && disarmed[0].find("watch: could not unprotect") != std::string::npos,
"watch: a failed protection change disarms the watch and is logged");
check(all_valid(writes) && all_valid(disarmed), "watch: records are valid JSON");
}
}
// Code breakpoint: two calls, two hits (the breakpoint is re-armed), the string argument safe.
{
char address[32];
std::snprintf(address, sizeof(address), "%llx", static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(&hit_target)));
std::wstring hit = L"BX_VEH_HIT=" + widen(address);
ChildRun r = run_child(exe, "hit", address, {hit}, log_path);
if (r.exit_code == 77) {
std::printf("SKIP: hit mode: the child's image was relocated\n");
++skipped;
} else {
const auto hits = records(r.log, "code_hit");
check(r.exit_code == 0, "hit: the child ran through both breakpoint hits (exit 0)");
check(hits.size() == 2, "hit: both calls are logged (the breakpoint is re-armed)");
check(all_valid(hits), "hit: code_hit records are valid JSON");
bool text = false;
for (const auto& l : hits) text = text || l.find("[rcx]s=quote_ back_ path") != std::string::npos;
check(text, "hit: a string argument is logged with quote and backslash made safe");
}
}
// Sampler: records while the child runs, valid JSON, and a clean exit.
{
ChildRun r = run_child(exe, "sample", "-", {L"BX_VEH_SAMPLE=5"}, log_path);
const auto samples = records(r.log, "sample");
check(r.exit_code == 0, "sample: the child exits normally with the sampler running");
check(!samples.empty(), "sample: sample records are written");
check(all_valid(samples), "sample: sample records are valid JSON");
}
if (g_failures) {
std::printf("FAIL: test_veh_diagnostics (%d of %d checks failed)\n", g_failures, g_checks);
return 1;
}
if (skipped) {
std::printf("SKIP: test_veh_diagnostics: %d mode(s) could not run on this host (%d checks passed)\n", skipped, g_checks);
return 77;
}
std::printf("PASS: test_veh_diagnostics (%d checks: off, AV context, UTF-8 module names, write watch, code hit, sampler)\n",
g_checks);
return 0;
}
} // namespace
int main(int argc, char** argv) {
if (argc >= 4 && !std::strcmp(argv[1], "child")) return child(argv[2], argv[3]);
char log_path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
if (n == 0 || n >= sizeof(log_path)) {
std::printf("FAIL: test_veh_diagnostics: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
return 1;
}
return parent(log_path);
}