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 4c5cd55884 Merge remote-tracking branch 'origin/main' into docs/game-ladder-roadmap
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:11:08 +03:00
Ateş ec3dea9942 Merge pull request #661 from MacosPorters/track-f/bringup-review-process
[M2-F] docs: development cycle and review for target-build bring-up
2026-11-29 10:55:05 +03:00
ates 1fed04a80c Merge remote-tracking branch 'origin/main' into fix-661
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 10:51:45 +03:00
Ateş a9efeffc6f Merge pull request #658 from MacosPorters/track-e/bringup-xgameruntime
[M2-E] xgameruntime: offline XPackage installation monitor and enumeration
2026-11-29 10:51:22 +03:00
ates 365b411fed Merge remote-tracking branch 'origin/main' into fix-658
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 10:47:35 +03:00
Ateş 1b4b1bf7d7 Merge pull request #657 from MacosPorters/track-e/bringup-acphal
[M2-E] acphal: IAcpHal slot order and shape contexts
2026-11-29 10:47:06 +03:00
Ateş aeac1892c1 Merge pull request #656 from MacosPorters/track-c/bringup-xg-contract
[M2-C] xg_xs: the documented XG contract, replacing the clean-room interface
2026-11-29 10:46:44 +03:00
Ateş a9674bf9c7 Merge pull request #655 from MacosPorters/track-b/bringup-dstorage-queues
[M2-B] xcrdapi: zlib file requests and AutoSubmitDisabled on Xbox queues
2026-11-29 10:46:14 +03:00
ates eee9a4fcdc docs: how blockers are found once the target build runs
Working method: people play with recording on, agents replay short
routes through the input shim as ten-run regression tests, and picture
bugs are worked on from captured frames replayed offline. Lists the
signals a problem is recognised by and adds the three tools to the
starting queue.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:27:51 +03:00
ates fe28c5c2af docs: rework the proposal for an agent-driven team; stages replace milestone numbers
Collaborators work by telling a coding agent to "work", so the method
now answers what an agent does next without meetings or roles:
- AGENTS.md section 0 is rewritten as that instruction: preflight, then
  exactly one of own pull requests, review, one blocker of the current
  stage, or discovery; "work" authorizes commit, push and a pull request
  for the one item picked.
- docs/process/working-method.md: state lives in GitHub (a pinned ladder
  issue, one blocker issue per signature, claim comments, needs-human),
  the run protocol with per-session bottles and a machine-wide run lock,
  ranked sources of truth, the five-part pull request, and the starting
  queue.
- docs/roadmap.md: the ladder's rungs are named stages (Boot, Picture,
  Menus, World, Fidelity, Playable) instead of M3-M8.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:09:49 +03:00
ates e21f41ae24 docs: propose the game-ladder roadmap and the blocker-loop working method
docs/roadmap.md: M0-M2 become the foundation; M3-M8 are rungs the
project-authorized target build reaches (reliable boot, first correct
picture, front end, into the world, the world renders correctly,
playable), each judged on ten recorded runs on a 16 GB Mac, with
decision gates for the back end, reference images, memory and frame
rate, and a step-forward test for what belongs on main.

docs/process/working-method.md (proposed): the blocker loop, the run
protocol and run report, lanes beside tracks, ranked sources of truth,
one-blocker pull requests with a five-part description, the first two
weeks of work, and the AGENTS.md changes this needs. AGENTS.md itself
is not changed here.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:05:49 +03:00
ates 506defdd45 tests: AcpHal's 64 MB default APU heap in a fresh process
Review on #657: test_audio_input creates its own heap before allocating
shape contexts, so the default-heap branch never ran. The new fixture
allocates shape contexts with no ApuCreateHeap: 64 MiB + 64 bytes fails
with E_OUTOFMEMORY, exactly 64 MiB succeeds as an APU heap allocation,
a later ApuCreateHeap reports busy, and apu_default_heap is logged once.
A 32 MiB or 128 MiB default, or no default heap, each fail it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:15:33 +03:00
ates 64141e9ae6 Merge remote-tracking branch 'origin/main' into track-e/bringup-acphal
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:13:52 +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 3ec40ba7fb docs: target-build review: recorded authorization, reproducible offline run
Review on #661:
- authorization is a recorded private note (build, evidence class,
  approving maintainer, lawful access, no circumvention); approval alone
  is not enough, and its ID goes into the PR template and every review;
- a reviewer needs their own recorded authorization for the same
  evidence class and re-derives from their own source;
- the ladder is renamed bring-up checkpoints and stated not to set
  milestone status, which only docs/roadmap.md defines;
- the offline run is copyable: wineserver restart, a curl probe that
  must print BLOCKED inside the profile, and the full bx-cli command
  with --exe, --profile and --inherit-env under env -i (and why);
  sandbox-exec's deprecation is noted;
- the diagnostics table lists only switches on main;
- the rules are cited from CONTRIBUTING.md and docs/legal.md, and the
  hash rule is narrowed to title-derived identifiers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:53:51 +03:00
ates b3aad0d948 Merge remote-tracking branch 'origin/main' into track-f/bringup-review-process
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:52:34 +03:00
ates 277edd592a Merge remote-tracking branch 'origin/main' into track-e/bringup-xgameruntime
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:51:07 +03:00
ates d4996ba9fd xgameruntime: installation monitors in the package state; enumerate this game
Review on #658:
- monitors move to package.cpp, into the mount handles' tagged table
  under mount_mutex: creation checks the runtime generation, rejects a
  null or foreign identifier, closing is idempotent, a closed or stale
  handle reports empty progress and registration on it fails with the
  stale-handle error, and the last uninitialize releases them;
- progress registration is logged as accepted and never fired, with a
  distinct token per registration; unregister reports whether the token
  existed;
- XPackageEnumeratePackages reports this game (its identifier, kind
  Game) for XPackageKind::Game, as documented for ThisOnly, and no
  packages for Content or PublisherContent; invalid kind/scope or a
  null callback is refused.

test_xgameruntime_saves covers slots 5-10 and 28/35/39 through the
public IXPackageImpl object: null and foreign arguments, the progress
values, tokens, double close, closed-handle behaviour, the registration
log record, enumeration per kind, and monitors made stale by
uninitialize.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:51:06 +03:00
ates ca2b48ef83 CHANGELOG: XG tiling per dimension and resource limits
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:45:39 +03:00
ates dc41f00cb3 Merge remote-tracking branch 'origin/main' into track-c/bringup-xg-contract 2026-11-29 06:45:31 +03:00
ates 1b04d6e237 xg_xs: review fixes: comments, 3D bounds, D3D12 limits, tiling per dimension
Review on #656:
- the header comments said other swizzle modes and multi-tile SW_64KB_S
  were refused; they are laid out linearly and reported as LINEAR;
- a 3D subresource past the mip count aliased onto mip 0 in
  CopyInto/FromSubresource; it is refused (E_INVALIDARG);
- XGCreateTextureComputer applies the public D3D12 limits (16384 for
  1D/2D, 2048 for 3D and array sizes) and a 64-bit bound for buffers,
  so widths are never truncated and pitches cannot overflow;
- GetResourceTiling uses the D3D12 standard 3D tile shapes (64x32x32
  one-byte elements down to 16x16x16) with depth tiles, a 64 KiB element
  row for 1D textures and 64 KiB for buffers, instead of 2D shapes.

test_xg_xbox (65 checks) adds hand-computed GetResourceTiling cases for a
2D array with a packed tail, a 3D texture and a 1D texture, the 3D copy
bound, the limits, AddRef/Release, IsTiledResource and the two E_NOTIMPL
methods. Each code fix is caught by the new checks when reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:45:31 +03:00
ates 9116c0a39e Merge remote-tracking branch 'origin/main' into track-b/bringup-dstorage-queues
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:41:34 +03:00
ates b96a9b5978 xcrdapi: a full AutoSubmitDisabled queue stalls until Submit
Review on #655: AutoSubmitDisabled only switched off the half-capacity
submit; a full blocking queue still submitted what was pending before
waiting, so commands ran before the title's Submit. A full queue now
submits by itself only when auto-submit is on. With it off, the enqueuer
waits until Submit is called on another thread and the drain frees a
slot, as DSTORAGE_QUEUE_OPTIONS documents.

test_xcrdapi_xbox fills a capacity-4 disabled queue from a worker
thread: the enqueue past its three slots waits, no destination changes
until Submit, Submit releases the waiter and every request then runs.
It fails with the old full-queue submit.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:41:34 +03:00
Ateş dcec248837 Merge pull request #660 from MacosPorters/track-c/bringup-xbox-first-frame
[M2-C] d3d12_xs: Xbox-layout objects through a target build's frame loop
2026-11-29 06:21:15 +03:00
ates 40b5ee7a8e Merge remote-tracking branch 'origin/main' into HEAD 2026-11-29 06:17:57 +03:00
Ateş b975e6335b Merge pull request #654 from MacosPorters/track-b/bringup-xmem-pages
[M2-B] xmem: page numbers in 4 KiB frames, run mapping, GPU-only windows
2026-11-29 06:17:51 +03:00
ates 8f4786e436 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:14:04 +03:00
Ateş 0c398214fa Merge pull request #645 from MacosPorters/track-c/644-xbox-device-tables
[M2-C14] d3d12_xs: Xbox-layout D3D12 objects, Phase 1 (ADR 0009)
2026-11-29 06:10:40 +03:00
ates 78b56747fb Merge remote-tracking branch 'origin/main' into HEAD 2026-11-29 06:06:38 +03:00
Ateş 63bd059182 Merge pull request #643 from MacosPorters/track-b/636-xmem-signatures
[M2-B6] xmem: follow the documented physical-page and XMemVirtualAlloc signatures
2026-11-29 06:06:24 +03:00
ates 24b124e144 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	tests/conformance/test_m2_first_frame/main.cpp
2026-11-29 06:05:20 +03:00
Ateş cff3e754a9 Merge pull request #640 from MacosPorters/track-c/639-xbox-create-device
[M2-C13] d3d12_xs: D3D12XboxCreateDevice takes the documented four parameters
2026-11-29 06:04:56 +03:00
ates 27bfa17cb1 xgameruntime: offline XPackage installation monitor and enumeration
The installation monitor reports the running package fully installed,
launchable and complete (progress never changes, so registered callbacks
are not called). XPackageEnumeratePackages succeeds offline and reports
no other packages. Both replace stubs a project-authorized target build
calls at startup. The save-container mount path ends with the drive-root
separator; test_xgameruntime_saves expects it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:45 +03:00
ates 261d71d8d1 docs: development cycle and review for target-build bring-up
How any number of contributors run a project-authorized target build
offline, turn each finding into a single-track PR with a conformance
test, and review it independently: roles, the cycle, a PR template,
what a reviewer re-derives, the offline-run procedure, the diagnostic
switches, and what never enters the repository.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:32 +03:00
ates 2cc64bd617 d3d12_xs: Xbox-layout objects through a target build's frame loop
On the Xbox-layout device: descriptor heaps with title-visible storage,
committed and placed resources in title memory with copy coherence,
samplers, page pools, pipelines through the shader gate, opt-in null
rendering (BX_NULL_RENDER=1), fences at GPU addresses, GPU value
writes, PresentX onto a DXGI swapchain, console page mappings
(CopyPageMappingsX/BatchX, ClearPageMappingsX) and the full 1384-byte
Xbox command-list area. BX_PRESENT_DUMP=<folder> dumps presented frames.

With the stacked xmem, XCRDAPI, XG, AcpHal and xgameruntime changes, a
project-authorized target build reaches its frame loop with null
rendering (thousands of frames). test_d3d12_xbox_layout checks the page
mappings (all four range types) and that writing every title-owned
command-list field leaves the list usable; each fails with its fix
reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:32 +03:00
ates d99e35ad42 acphal: IAcpHal slot order and shape contexts
IAcpHal is not COM (authorized GDK documentation): its slots are
Connect, Disconnect, SubmitCommand, PopMessage, GetNumMessages and
Release. AcpHalAllocateShapeContexts and AcpHalReleaseShapeContexts
allocate the documented SHAPE_CONTEXTS arrays from the APU heap, and a
second allocation fails with ACP_E_ALREADY_ALLOCATED; the default APU
heap is 64 MB. A project-authorized target build needs both to start.

test_audio_input checks the slots and the allocation lifecycle;
test_integration_boot releases IAcpHal through its sixth slot instead
of IUnknown::Release.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25: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
ates 28a9c868e6 xg_xs: the documented XG contract, replacing the clean-room interface
xg_xs.dll now implements XGCreateTextureComputer and XGSuggestSwizzleMode
with the documented XG_RESOURCE_DESC and 14-method computer (authorized
GDK documentation): linear layouts by BetterXen's rule, single-tile
SW_64KB_S, other requested swizzles laid out linearly and reported as
LINEAR (refusing crashed a title that ignores the result), and
GetResourceTiling with standard tile shapes and a packed mip tail.

The clean-room xg_xs.cpp, xg_texture.h and test_xg_xs are removed.
test_xg_xbox (42 checks: 32 bpp offsets against the public D3D12
standard swizzle, 8- and 16-byte bijections, BC blocks, linear
fallbacks) replaces them; test_integration_boot stage 13 uses the
documented contract.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 6cfade83fe xcrdapi: zlib file requests and AutoSubmitDisabled on Xbox queues
Zlib requests now get the file handle (every compressed file request
failed), the Xbox request options are decoded and zlib streams inflated.
Xbox CreateQueueX honours DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled
(flags bit 0): such a queue runs nothing before Submit, so a title's
writes no longer land in pages it has not mapped yet; without the flag
the queue submits once half full. BX_DSTORAGE_TRACE=1 traces requests.

test_xcrdapi_xbox covers a file-source zlib request at an offset and
both queue behaviours; each check fails with its fix reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates c963b9bc1a xmem: page numbers in 4 KiB frames, run mapping, GPU-only windows
Physical page numbers count 4 KiB frames (multiples of 16 for 64 KiB
pages, allocations aligned to 0x1000 frames): callers that keep
number >> 4 collapsed 16 consecutive numbers into one page. Pages are
mapped as runs, one view per run, which brought a project-authorized
target build's startup from 36 s to 6 s. Allocation goes through the
title's registered hooks; GPU-only large-page reservations become
mappable placeholders for console page mappings; BX_XMEM_TRACE=1 logs
allocations, frees and maps.

test_xmem_physical checks the page-number units (it fails with
kFramesPerPage = 1); test_xmem_hooks checks the hooks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 30197aa236 d3d12_xs: refuse Xbox-layout objects the host cannot back
bx_xbox_wrap returned the PC object when the host object lacked the
interface an Xbox table forwards to, and D3D12XboxCreateDevice then
logged device=xbox_function_tables and returned S_OK. On vkd3d, which
stops at ID3D12Device9, a title would have called Xbox slot numbers on
a PC table. The wrap now releases the object, logs xbox_wrap_refused and
fails with E_NOINTERFACE for every wrapped family; device creation and
QueryInterface pass that result on.

test_d3d12_xbox_layout verifies the refusal (E_NOINTERFACE, null out
pointer) on such a host and skips with exit 77; on D3DMetal it passes.
With the old fallback restored it fails on vkd3d.

ADR 0009 now states that the fixture's slot numbers come from the same
header as the generator, so it shows agreement, not correctness, and
records the frame-pacing limits (host Sleep, detached thread).

Addresses review points 2 and 4 on #645.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:11:02 +03:00
ates 957b8efb21 d3d12_xs: shadow resources for title-address placed resources (#644)
CreatePlacedResourceX and CreatePlacedResourceX1 place a resource at a
GPU address the title chose. D3DMetal cannot create a resource over
existing memory, so each gets a host shadow: buffers a committed buffer
in a CPU-visible write-back heap filled from the title's memory,
textures a committed texture (contents not filled, logged). The
resource reports the title's address from GetGPUVirtualAddress, and the
record is dropped when the resource is destroyed.

Ongoing synchronisation, GPU-to-CPU copies and address translation in
GPU calls are not implemented yet. test_d3d12_xbox_layout places a
buffer at a title address, checks the reported address and copies its
contents through the GPU.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates e04a3b3f62 d3d12_xs: Xbox-layout command lists and frame pacing, Phase 2 (#644)
Command lists become Xbox objects (ID3D12GraphicsCommandList8, 150
slots) created through CreateCommandListX or CreateCommandList. Their
Xbox field area (put buffer, CPU state, root packet headers) is zeroed,
so the inline fast paths fail their room checks and call through the
table. ResourceBarrier and CopyTextureRegion unwrap the interface
pointers inside their structures.

SetFrameIntervalX, ScheduleFrameEventX and WaitFrameEventX are
emulated from the recorded interval by a host timer that signals the
origin, vblank and flip events and hands out frame tokens.

The generator now handles CRLF lines, a table whose end the boundary
pattern ran past (it hid GraphicsCommandList1), nested SAL arguments and
FLOAT. test_d3d12_xbox_layout records a copy through Xbox command
objects, runs it on the GPU and checks frame pacing.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates ea29d3fc56 d3d12_xs: give titles Xbox-layout D3D12 objects, Phase 1 (#644)
A title built against the Xbox Series D3D12 header calls through
function tables whose slot order differs from PC D3D12, so the PC-layout
proxies sent its calls to the wrong methods. Titles (which set Version
in the device parameter block) now get BxXboxObjects: the Xbox object
layout with m_OutOfLineFlags set and Xbox-order tables that forward to
the existing PC proxies.

tools/gen_xbox_tables.py generates the tables from the Xbox header (slot
order, names, IIDs and types only; the header is not committed) and the
toolchain's <d3d12.h>: typed forwarders where the signatures match,
logged stubs otherwise. Phase 1 covers the device chain to Device11 and
the objects it creates, and implements CreateCommandQueueX. Command
lists follow in Phase 2.

ADR 0009 records the decision. test_d3d12_xbox_layout calls the Xbox
slots by number and fails against the previous DLL.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates d724c6c013 xmem: accept MEM_64K_PAGES as the 64 KB physical-page flag
XMemAllocatePhysicalPages refused MEM_64K_PAGES, which Microsoft's
public samples pass for 64 KB pages: its MEM_PHYSICAL bit was outside
the accepted mask, and its MEM_2MB_PAGES bit reads as XMEM_2MB_CLUSTERS.
MEM_64K_PAGES is MEM_2MB_PAGES | MEM_PHYSICAL, so both bits together now
mean 64 KB pages; the 2 MB bit alone is still XMEM_2MB_CLUSTERS, which
stays unimplemented and logged.

test_xmem_physical adds the samples' shape: a MEM_64K_PAGES page mapped
into a mappable reservation made with PAGE_READWRITE |
PAGE_WRITECOMBINE | PAGE_GRAPHICS_READWRITE (0x2404). It passes on the
D3DMetal and vkd3d hosts and fails with the flag handling reverted.

Addresses review point 1 on #643; point 2 (graphics protection on
mapping) was fixed by the previous commit.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:07:21 +03:00
ates 43cb1aab54 xmem: title-managed placeholders and 32-bit graphics addresses (#636)
A title lays out its descriptor memory by reserving a placeholder with
XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
XMEM_GRAPHICS_32BIT_ADDRESS), splitting it with VirtualFree and
MEM_PRESERVE_PLACEHOLDER, and turning parts into mappable 64 KB ranges
with MEM_REPLACE_PLACEHOLDER | XMEM_MAPPABLE before mapping physical
pages in. All of that is documented; the shim stripped the placeholder
bits and made an ordinary reservation, so the split failed.

Placeholder reservations now honour the 32-bit address limit, a replaced
part is adopted as a mappable range if it is still a placeholder, and
PAGE_GRAPHICS_* protection bits are dropped for the host view. Replacing
a placeholder with committed memory stays a logged stub.
test_xmem_physical replays the sequence.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:05:28 +03:00
ates af869008a0 xmem: follow the documented physical-page and XMemVirtualAlloc signatures (#636)
The authorized GDK documentation gives XMemAllocatePhysicalPages(XMemFlags,
NumberOfPages, PageArray), XMemFreePhysicalPages(NumberOfPages, PageArray),
XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray),
XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)
and the five-argument XMemVirtualAlloc. A title calling them as documented
had its arguments misread, and its XMemAllocatePhysicalPages check broke
into its crash reporter.

Pages are 64 KB; the bandwidth values are accepted; 2 MB clusters and
2 MB-page mappings are stubs. XMEM_MAPPABLE reservations are placeholders
that pages map into, unmap back into, and can be remapped. Scatter
validates every entry before changing any. A NULL map address stays a
BetterXen extension for synthetic fixtures.

test_xmem_physical is rewritten against the documented contracts and
fails against the previous DLL; the other fixtures use the documented
signatures.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:05:28 +03:00
ates 8627285a59 tests: call D3D12XboxCreateDevice with its documented four parameters
test_d3d12_presentx, test_d3d12_vmem_xbox and test_m2_first_frame still
used the old three-argument form. They now pass a NULL adapter and a
zeroed parameter block (Version 0), which keeps the PC-layout proxy they
are written against (ADR 0009). All three pass on the D3DMetal backend.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:00:58 +03:00
ates aec6766b4d d3d12_xs: take the documented four D3D12XboxCreateDevice parameters (#639)
The documented form is (pAdapter, pParameters, riid, ppDevice); the shim
took (params, riid, ppv), so a documented call had its riid written
through as the out pointer. A NULL parameter block now fails with
E_INVALIDARG; a non-NULL adapter is logged and the default host adapter
used; only Version is read from the parameter block. Fixtures pass a
zeroed 80-byte block, and test_d3d12_xs checks the NULL refusal.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:00:40 +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
Bartosz Szczepański b325320549 [M2-C10/C11] d3d12_xs: validate placement on every heap and all three CreatePlacedResource entry points (#554, #572)
CreatePlacedResource (slot 29) validated alignment, extent, buffer clear
value and the UPLOAD/READBACK initial state only on the backing heap.
CreatePlacedResource1 (ID3D12Device8 slot 70) and CreatePlacedResource2
(ID3D12Device10 slot 77) were generated pass-throughs with no validation
and no kPlacedResourceHeap retention, so the shim heap wrapper and its
xmem charge could be dropped while the placed resource was still alive.

All three now share create_placed_common in vmem.cpp. gen_proxy.py gains
a HANDOFF table so the generated slots 70/77 keep their trace and
null-host stub and pass the host interface and unmodified arguments to
vmem.cpp; proxy_generated.{h,cpp} are regenerated. No new vtable slot is
patched.

test_d3d12_placed adds misaligned, aligned-overhang, valid-offset and
UPLOAD-state cases on an ordinary heap for each entry point and runs the
heap-charge retention check through all three.

Closes #554
Closes #572

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 18:39:25 +03:00
atharvranjan 9f8b4c7f69 Merge pull request #646 from MacosPorters/track-e/xsystem-analytics-hdr
[M2-E7] xgameruntime: serve XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode
2026-11-28 09:17:40 -06:00
ates 2e5fbc70b1 xgameruntime: serve XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode through QueryApiImpl
A project-authorized target title requests both during System Init; they were logged as unsupported QueryApiImpl keys. The keys and vtable slots were derived from authorized GDK material; the function contracts follow the public XSystem.h and XDisplay.h documentation.

- XSystemGetAnalyticsInfo (slot 3, returns the 144-byte structure by value): family Xbox, a profile-dependent form, and a synthetic 10.0.26100.0 OS version.
- XDisplayTryEnableHdrMode (slot 4): Disabled, since BetterXen presents SDR. The optional luminance output is cleared.
- test_xgameruntime calls both through QueryApiImpl and checks the public contract.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 18:02:11 +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
Ateş a2d153605d Merge pull request #534 from MacosPorters/track-c/465-presentx-timeout-budget
[M2-C2] Fix PresentX timeouts and post-present fence errors
2026-11-28 11:09:24 +03:00
ates 4a34ec3e50 Integrate main and fix PresentX timeout and recovery handling
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 11:04:23 +03:00
Ateş 2e96d93439 Merge pull request #592 from MacosPorters/track-c/vmem-xbox-config
d3d12_xs: add 32-byte Xbox decoder for D3D12ConfigureVirtualMemoryX
2026-11-28 10:47:39 +03:00
Ateş 30e666b86c Merge pull request #494 from MacosPorters/track-f/469-m2-first-frame-gate
Add end-to-end M2 first-frame conformance fixture
2026-11-28 10:46:04 +03:00
Ateş 41bc72887b Merge pull request #630 from MacosPorters/maint/finish-budget-hook
Finish the combined title budget hook and carry two reviewed PRs
2026-11-28 10:45:31 +03:00
ates c206a3f85d Merge current main into the virtual-memory integration
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:45:08 +03:00
ates c893436269 Combine the virtual memory decoder and shared budget logging
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:44:54 +03:00
Ateş 00b8344a40 Merge pull request #596 from MacosPorters/track-b/xcrdapi-xbox-dstorage
xcrdapi: add Xbox DirectStorage COM interfaces (IDStorage*X)
2026-11-28 10:43:23 +03:00
ates 451c6308c0 Preserve first-frame documentation while merging current main
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:42:40 +03:00
ates 4d69562b59 Merge current main into the combined budget hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:42:29 +03:00
Ateş 656eff8459 Merge pull request #628 from MacosPorters/track-a/627-xbox-drive-map
[M2-A15] bx-cli: map the Xbox title drives G: and T: before launch
2026-11-28 10:41:26 +03:00
Ateş 3ba0eb20d5 Merge pull request #626 from MacosPorters/maint/carry-reviewed-prs
Carry nine reviewed PRs whose head repositories were deleted
2026-11-28 10:41:13 +03:00
ates 8a00743d99 Leave unverified Xbox DirectStorage error output untouched
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:36:28 +03:00
ates ce1940d84c Merge current main into the virtual memory review update
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:35:34 +03:00
ates bd744727bd Validate BXVM inputs before read-only fallback
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:43 +03:00
ates b141c4b261 Count skipped graphics and xmem pairing checks
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:32 +03:00
ates c7a4b4cf19 Clarify conformance exit codes and evidence classes
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:32 +03:00
ates b88ea24a30 Guard the drive manifest temporary file and clarify fixture scope
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:29:37 +03:00
ates b2ae7a604e Merge current main and document the verified M2 pixel control
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:29:35 +03:00
Ateş 901b68ffba Merge pull request #471 from MacosPorters/track-c/465-d3d12-presentx
[M2-C2] Add D3D12 presentation bridge and verified frame conformance fixture
2026-11-28 09:59:09 +03:00
ates 3eb8900442 Merge origin/main into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	tests/conformance/test_audio_input/main.cpp
2026-11-28 09:39:15 +03:00
ates 335e3e4d60 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 09:38:48 +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
Ateş c345ada8e9 Merge pull request #631 from elforeign/track-f/audio-input-log-required
[M2-F] test_audio_input: require BX_LOG_FILE instead of a temp log it can't fill
2026-11-28 09:24:57 +03:00
ates 3154497424 xcrdapi: address devil8blade's review of the Xbox DirectStorage adapters
- IDStorageFactoryX::SetStagingBufferSize logs that the size has no effect, as the public factory does, instead of 'accepted'.
- CreateQueueX documents that the queue priority is ignored on purpose: the Xbox range is not part of the inferred contract.
- test_xcrdapi_xbox requires BX_LOG_FILE and reads only what its own run appended.
- New error-path checks: a memory request on a file queue, a size mismatch, an out-of-range status index, and an enqueue after Close.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:22:06 +03:00
ates 6eaf8faa95 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:19:04 +03:00
ates 3c1ee93df5 Merge origin/main into track-a/627-xbox-drive-map
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:15:51 +03:00
ates 87a03d0421 bx-cli: write the drive manifest atomically and lock the prefix before staging
- write_manifest writes a temporary file and renames it over .bx-drives, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. New test: an interrupted write keeps the previous manifest, and the retry re-points g:.
- The prefix lock is taken before system32 staging, so a refused run has not touched the shared prefix. Runs sharing a prefix are serial, as the changelog now says.
- drives.rs and test_xbox_drives describe the G:/T: roles as an observation of one title plus an inference.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:15:51 +03:00
ates bf9dd7b383 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:11:25 +03:00
ates b59696975a Address devil8blade's review of the budget hook carry
- test_d3d12_placed: the 512 MiB pairing check prints SKIP with the command that runs it, instead of returning silently at other caps.
- vmem.cpp: the release_charge comment and the #552 changelog entry no longer claim the mirror check stops a double release while other heaps are alive. Each wrapper releasing once is what prevents that.
- vmem.cpp: the config log record's xmem_used= is renamed cap_used=, since it already includes graphics heaps.
- test_veh_clwb: parse record fields with a checked strtoull so a malformed record cannot throw.
- CHANGELOG: drop the stale overflow-guard and not-executed lines.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:11:25 +03:00
ates 43bb5636bf test_m2_first_frame: drain the GPU on failure, report the Present HRESULT, reject a malformed control value
- A GpuDrain guard declared just before ExecuteCommandLists signals the queue and waits (bounded) before the queue, back buffer and output resource are released after a failure.
- A failed PresentX reports its HRESULT instead of a fixed message.
- BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH must be unset or exactly 1. Any other value fails, so a mis-armed control cannot pass as an ordinary run, and an armed control is announced.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:05:28 +03:00
ates b7a660d4b9 Address devil8blade's review of the carried PRs
- test_win32_bridge: parse context= from the value, not the key, so the carried #520 round-trip check can pass (it read 0xc for every record).
- test_shader_gate: require every key before comparing positions; a missing hr= was npos and satisfied the order check.
- test_audio_input: a missing BX_LOG_FILE fails instead of printing SKIP and exiting 0.
- acphal: the zero-capacity comments no longer claim ApuAlloc accepted an allocation.
- bx-cli: tests/usage.rs runs the built binary and checks exit codes and output streams for the usage paths.
- CHANGELOG: getpgrp is Perl's built-in, and the new tests are recorded.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:04:11 +03:00
Eterna 10f78645cb win32_bridge: assert the PSM context pointer round-trips
context is observable in the JSONL. But the test only counted
callback_unfired records, so a dropped (context=0x0), swapped or
mis-tagged context would have passed unnoticed -- which makes the
storage decorative.

Parse context=0x<hex> out of the registration records (strtoull base
16; %llx prints lowercase with no leading zeros) and assert:

- every logged context on both families is non-zero and present in
  the set of &entry pointers the test passed;
- at least two distinct pointers appear per family, so one
  registration cannot overwrite another's stored context;
- each family's set covers the whole &entry set, which catches a
  swap or mis-tag between families;
- a record with a missing or malformed context= fails.

Limit, stated rather than asserted: the unregister records carry
only a detail string, so context-drop on unregister is not
observable in the log. The test documents that and prints a note if
a future shim starts logging context there.

Sits on #514, which introduces the context= field; rebases cleanly
once that merges. All existing checks kept and ANDed with the new
result. Cross-compiled and export-verified only; no live CrossOver
run.

Closes #519

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
(cherry picked from commit fa745d5211)
2026-11-28 09:01:48 +03:00
ates 8c4610b51c Merge origin/main into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:54:47 +03:00
ates 3b1d168de7 d3d12_xs: decode the documented Xbox virtual-memory configuration
Replace the inferred segment-count layout with
D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION as the authorized GDK
documentation describes it: flags, a GPU page-table size in 4 MB units
(clamped to 33), a frame-buffer preserve size (clamped to 64 MiB, -1
for the legacy size) and two output addresses. The decoder now writes
the outputs (minimum 2 GiB; maximum 159.375 GiB at the default size,
scaled linearly otherwise and logged as max_estimated=1) and fails with
E_FAIL once a device exists. It still only records the configuration
and keeps BX_STUB_LOG, since the host sizes no GPU page tables.

The fixture checks the documented values instead of the shim's own
constants and fails against the previous decoder.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:54:10 +03:00
Ateş 7a380bd3d7 Merge pull request #633 from EternaPeptix/track-f/632-heading-link-slugs
[M2-F17] docs_hygiene: slug a heading's rendered text, not its link URL
2026-11-28 08:51:26 +03:00
ates 931c09c6af xcrdapi: fill CommandType in the Xbox queue's error record
IDStorageQueueX::RetrieveErrorRecord left FirstFailure.CommandType zeroed. Share the public queue's command-kind mapping and fill it.

test_xcrdapi_xbox now asserts the error record for a rejected request and a rejected signal. DSTORAGE_COMMAND_TYPE_REQUEST is 0, so only the signal case tells a filled-in command kind from a zeroed one; it fails on the previous shim and passes now.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:39:49 +03:00
Eterna 186836e1d6 docs_hygiene: leave link syntax inside code spans literal
GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
the slug. Substituting links first changed `code-xy-span` to
`code-x-span`. Code spans are now set aside before the substitution
and restored afterwards.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:33:39 -07:00
ates 133ffd4c97 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:30:49 +03:00
atharvranjan 0d9997ce66 Merge origin/main into track-c/vmem-xbox-config
Resolve the CHANGELOG.md Added conflict by keeping both the #592
Xbox virtual-memory entry and main's #597 xcrdapi ABI entry. No
technical files changed in this merge.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:29:29 -06:00
ates bfbc84d251 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:27:31 +03:00
ates e96de7c455 Merge origin/main into track-a/627-xbox-drive-map
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:27:25 +03:00
atharvranjan 4b2985114a docs: clarify fixture skip and log evidence
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:26:25 -06: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
atharvranjan fe749b1436 fix(bx-cli): protect shared Xbox drive mappings
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:25:27 -06:00
Eterna b76066eafb docs_hygiene: slug a heading's rendered text, not its link URL
GitHub slugs the rendered heading, so an inline link contributes only
its text. Slugging the raw source appended the URL, which made a
heading with a link disagree with GitHub's anchor -- including
README.md:53 -- so the first real link to it would be reported as a
broken fragment.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:25:13 -07:00
atharvranjan b7bb7615d8 Merge origin/main into track-c/465-d3d12-presentx
Merge current main (2b2a9e15) with no manual conflict resolution; only
main's additions are brought in.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:20:46 -06:00
Ateş 2b2a9e15a6 Merge pull request #629 from EternaPeptix/track-b/597-xcrdapi-vtable-abi
validate: derive the xcrdapi public DirectStorage slot order and staged-copy fence lifetime (#597)
2026-11-28 08:18:03 +03:00
atharvranjan 3c65b393a4 Merge origin/main into track-c/465-d3d12-presentx
Resolve the proxy.cpp include conflict by keeping main's <vector> (stream
PSO gate) alongside this branch's <type_traits> and presentx.h.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:14:59 -06:00
Eterna 67f3b618ab test: verify xcrdapi public DirectStorage vtable ABI
Closes #597

Derives the public DirectStorage slot order from dstorage.h 1.4.0,
cross-checks it against Silk.NET, records the staged-copy lifetime
finding, and adds a test that calls every slot through a raw C vtable.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:13:07 -07:00
atharvranjan b0e40e29ea Merge remote-tracking branch 'origin/main' into pr592-technical-audit
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-27 23:12:23 -06:00
atharvranjan 90dc310b61 fix(d3d12): write VMEM output before applying config
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:11:05 -06:00
ates 4bf52b14a3 test_veh_clwb: require BX_LOG_FILE instead of a temp log it can't fill
The fixture imports bx_runtime_veh.dll, which reads BX_LOG_FILE once in DLL_PROCESS_ATTACH before main runs, so the temp-log fallback could never receive records. Fail with a clear message instead, as #631 does for test_audio_input.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:08:45 +03:00
ates bc7b622018 tmp
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:07:09 +03:00
atharvranjan d8fea7b351 Merge latest origin/main into Xbox drive mapping PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:06:48 -06:00
ates fe50a8edff Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:06:39 +03:00
atharvranjan d47eac809f test: avoid duplicate audio fixture log path
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:06:31 -06:00
atharvranjan 8db5552e32 Merge remote-tracking branch 'origin/main' into pr592-technical-audit
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-27 23:06:17 -06:00
Ateş 297251fb00 Merge pull request #611 from EternaPeptix/track-c/576-stream-pso-gate
[M2-C12] d3d12_xs: run stream pipeline states through the shader gate
2026-11-28 08:06:16 +03:00
atharvranjan 030c63f8c9 Merge origin/main into Xbox drive mapping PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:04:52 -06:00
atharvranjan 9a6f71abbc fix(bx-cli): record Xbox drive ownership before linking
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:04:35 -06:00
atharvranjan ad4bcc66b1 fix: correct carried PR claims and validate chunk offsets
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:03:56 -06:00
atharvranjan 3d244ddcb0 Merge remote-tracking branch 'origin/main' into maint/carry-reviewed-prs
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	launcher/crates/bx-cli/src/main.rs
#	tests/conformance/test_audio_input/main.cpp
2026-11-27 23:03:28 -06:00
ates b29ccc60e1 test_shader_gate: restore the wave64 refusal assertions from #609
The rebase onto main kept the pre-#609 assertions (wave64 PSO only printed, record expected as pass_dxil), so the fixture failed against main's shim. Restore #609's checks: the wave64 PSO returns E_NOTIMPL with no object, and the shader_gate record is reject_wave_wide. The stream PSO checks are unchanged.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:02:59 +03:00
ates 5f8235f607 Merge origin/main into track-c/576-stream-pso-gate
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:00:33 +03:00
Ateş c1b3edf9ba Merge pull request #621 from EternaPeptix/track-c/505-xg-sw64kb-s
[M3-C4] xg_xs: implement SW_64KB_S tiled layout from public AddrLib + D3D12 standard swizzle
2026-11-28 07:59:48 +03:00
Eterna 1eecf6a20c xg_xs: bound each copy offset by the buffer it belongs to
The CopyFromSubresource direction passes the caller's linear image as
`resource` and the tiled resource as `image`, so the old bounds check
compared the image offset against the tiled size. A short destination
with a wide row pitch passed and the copy wrote past the caller's
buffer. Bounds now follow the direction; test_xg_xs gains a
short-readback case that must return E_INVALIDARG.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:56:33 -07:00
elforeign ceaad9aee9 test_audio_input: require BX_LOG_FILE instead of a temp log it can't fill
When BX_LOG_FILE was unset, main created a temp file and set the
variable so the dispatcher log checks had something to read. That is too
late: AcpHal.dll imports bx_runtime_veh.dll, which reads BX_LOG_FILE once
in DLL_PROCESS_ATTACH before main runs. The temp file stayed empty and
the checks failed for the wrong reason.

Fail with a message naming the fix (run under bx-cli run --log) instead.
Also correct the comments that said the log checks catch a leaked
dispatcher: Release updates the counter before delete this, so a missing
delete this leaves the log unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-27 22:52:48 -06:00
ates 6bf2b9ab95 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:50:24 +03:00
ates 527cd6208f Merge #540 into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:50:14 +03:00
Eterna 93a1f12bc6 docs_hygiene: detect the diff3 base marker and gate the unit tests
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
(cherry picked from commit ea9c883fcb)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:50:14 +03:00
Eterna 32b371e55f xg_xs: implement the SW_64KB_S BC family layout
Closes #505

Adds 8-byte (BC1/BC4) and 16-byte (BC2/3/5/6H/7) block addressing to the
SW_64KB_S tile math, and fixes the fixture that scaled every format by the
BC block dimension.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:49:59 -07:00
Eterna e48454bdd3 d3d12_xs: run stream pipeline states through the shader gate
Closes #576

Carries the ADR 0008 wording recording stream PSOs as covered
by the shader gate (#578).

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:49:06 -07:00
atharvranjan 55dfa39600 docs: document M2 pixel mismatch control
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 22:48:26 -06:00
ates c39d33821e xmem/d3d12_xs: apply review fixes to the external charge hook (#550, #552)
Apply the fixes 1Bartosz suggested on #551 and #553:

- Report external charges in XMemGetWorkingSetStatistics and
  bx_xmem_get_internal_stats so reported usage matches the cap.
- Refuse an over-release instead of zeroing other owners' charges.
- Log a failed bookkeeping refresh instead of reporting it as a budget
  rejection.
- Let the xmem hook alone admit graphics heaps; the local pre-check used a
  snapshot outside usage_lock and would count live heaps twice.
- Check the diagnostic mirror before crediting xmem on release.
- Add test_xmem_external_charge and correct the changelog entries.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:46:05 +03:00
Ateş e17a8281eb Merge pull request #609 from EternaPeptix/track-c/591-wave64-stance
[M3-D1b] d3d12_xs: refuse a wave wider than 32 lanes at PSO creation
2026-11-28 07:42:19 +03:00
ates 355197c4ac Merge origin/main into track-c/591-wave64-stance
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:40:24 +03:00
Ateş 01ef819910 Merge pull request #606 from EternaPeptix/track-a/590-trace-gap-detail
[M3-A1] bx-telemetry: group shader_d3dmetal_gap by (pso, stage)
2026-11-28 07:40:15 +03:00
ates 085e0d450e Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:39:47 +03:00
ates 2d2ee990a7 Merge origin/main into track-a/590-trace-gap-detail
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:37:58 +03:00
Ateş 1f3e45eaf7 Merge pull request #622 from EternaPeptix/track-e/500-gameinput-dispatcher
[M2-E4] gameinput: implement IGameInput::CreateDispatcher and IGameInputDispatcher v0
2026-11-28 07:37:50 +03:00
ates a4742dd137 Merge origin/main into track-e/500-gameinput-dispatcher
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:35:13 +03:00
Ateş d5eb5ae97d Merge pull request #620 from EternaPeptix/track-a/507-bx-probe-hardening
[M2-A4] bx-probe: harden PE32+ parsing (wrapping offset, unvalidated section count) and add coverage
2026-11-28 07:35:05 +03:00
ates 2fc6c16f9d Merge origin/main into track-a/507-bx-probe-hardening
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:32:27 +03:00
Ateş cb6688c836 Merge pull request #619 from EternaPeptix/track-e/515-delayed-callback
[M2-E5] xgameruntime: XTaskQueueSubmitDelayedCallback ignores a non-zero delay and still returns S_OK
2026-11-28 07:32:19 +03:00
ates f1db93e2b4 Merge origin/main into track-e/515-delayed-callback
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:29:41 +03:00
Ateş 71fa30c29b Merge pull request #617 from EternaPeptix/track-f/527-bridge-export-check
[M2-F4] test_shim_exports: load bx_shader_bridge.dll so the fixture covers all 17 shipped DLLs
2026-11-28 07:29:33 +03:00
ates 050b0b279c Merge origin/main into track-f/527-bridge-export-check
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:27:17 +03:00
Ateş 162ed81eaf Merge pull request #616 from EternaPeptix/track-f/537-anchor-validation
[M2-F7] docs_hygiene: validate Markdown link fragments, not just the file they point at
2026-11-28 07:27:08 +03:00
ates dcd0a5127d Merge origin/main into track-f/537-anchor-validation
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:24:11 +03:00
Ateş f644569578 Merge pull request #613 from EternaPeptix/track-f/547-padded-vtable-slots
[M2-F11] test_d3d12_xs: check the padded vtable slot boundaries, the guard against console-only methods
2026-11-28 07:24:03 +03:00
ates 5b015a2b9e Merge origin/main into track-f/547-padded-vtable-slots
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:21:46 +03:00
Ateş 2549d724dd Merge pull request #624 from MacosPorters/fix/test-d3d12-placed-host-identity
Fix test_d3d12_placed device-host identity check
2026-11-28 07:14:42 +03:00
ates 9bcb121322 Merge origin/main into fix/test-d3d12-placed-host-identity
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:11:52 +03:00
ates 48378f8c35 bx-cli: map the Xbox title drives G: and T: before launch (#627)
An Xbox title opens its package on G: and writes crash logs to T:.
A Wine prefix has neither, so the title stops at startup. bx-cli run
now links dosdevices/g: to the executable's directory and t: to
drive_c/bx_temp. A .bx-drives manifest records the tool's own links;
a mapping it did not make is reported and left unchanged.

test_xbox_drives reads its own executable through G: and round-trips
a file on T:; it fails when G: is absent.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:06:03 +03:00
Ateş 88e6cf00b9 Merge pull request #602 from MacosPorters/track-d/dxbc-accc-nobc-header-only
[M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
2026-11-28 07:05:13 +03:00
ates 0521ea0c6c CHANGELOG: drop the duplicate #535 entry
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:01:52 +03:00
ates ce23d0b2b9 Merge #536 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates d17525c165 Merge #564 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 3cfb9ed690 Merge #556 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 51ac3bd766 Merge #522 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates e816c16495 Merge #514 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 076b354d61 Merge #533 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	launcher/crates/bx-cli/src/main.rs
2026-11-28 07:01:52 +03:00
ates 0bd188e602 Merge #510 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
ates b86be87576 Merge #581 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
ates 62290b2f21 Merge #560 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
Ateş 2d8685681b Merge pull request #610 from EternaPeptix/track-d/586-timeout-overflow
[M2-D6] d3dmetal-harness: saturate an overflowing timeout deadline
2026-11-28 06:56:41 +03:00
ates 25d5240dd0 Merge remote-tracking branch 'origin/main' into pr-610
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 06:52:58 +03:00
Ateş 97a2ad5d8b Merge pull request #612 from EternaPeptix/track-a/573-staging-manifest-orphan
[M2-A14] bx-cli: roll back a published shim when the manifest write fails
2026-11-28 06:52:33 +03:00
atharvranjan d93a3f3084 test(d3d12): fix placed host identity check
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 21:44:46 -06:00
atharvranjan 30c071845f Merge origin/main and enforce M2 first-frame gate
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 21:41:58 -06:00
atharvranjan 781f473ea3 fix(d3d12): safely probe virtual memory config
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 21:33:42 -06:00
Eterna 6b83bbbd8b gameinput: isolate the dispatcher log assertions (#504 review)
bx-cli run appends to the supplied BX_LOG_FILE, but the conformance
test read the ENTIRE file and only searched for the presence of
live_dispatchers=1/0 and the two modes. Re-running the fixture with
the same log could pass from stale lines even if this run emitted
none.

Capture the log's byte length before the run (log_file_size) and
assert only on the bytes appended by this run
(read_log_file_from(log_path, log_start)). The same offset-slicing
works whether the path came from the runner or from the temp file
the fixture creates when BX_LOG_FILE is unset.

Cross-compiled and export-verified only; live CrossOver execution
was not run on this host.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:10:26 -07:00
Eterna 9f81aadc49 gameinput: assert the dispatcher's live-reference count
devil8blade's review of #504 noted that removing `delete this` was
not caught by the tests: `Release` returning 0 proves the count
reached zero, not that the object was freed.

`dispatch_mode` already logs `mode=manual live_dispatchers=N` on
each transition, so the count IS observable -- the test just never
read it. It now reads the JSONL log and requires
live_dispatchers=1, live_dispatchers=0, mode=manual and
mode=automatic. A `delete this` removal that leaks the dispatcher
would leave live_dispatchers=1 behind and fail.

The fixture also creates its own temp BX_LOG_FILE at the top of
main() when the runner has not set one, so the assertions work
standalone instead of reading an empty file and failing for the
wrong reason.

Cross-compiled and export-verified only; no live CrossOver run on
this host.

Closes #500

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:07:14 -07:00
Eterna 724347fd98 gameinput: name the INFINITE-wait limit and soften the destruction claim (#504 review)
Two review findings on the dispatcher:

- OpenWaitHandle creates a non-signaled manual-reset event and this
  shim never signals it, since there is no background input work to
  make it ready. The code comment and the CHANGELOG now say that a
  caller waiting INFINITE blocks, and should poll with a timeout or
  call Dispatch instead. The request was to name the limits, not to
  change behaviour.
- The CHANGELOG claimed the test exercises 'dispatcher destruction at
  refcount zero'. The test asserts that the last Release returns 0,
  which is the refcount, not the deallocation. The wording now says
  exactly that.

No behaviour change; the shim still builds and GameInput.dll still
exports exactly GameInputCreate @1.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:07:04 -07:00
Eterna 6f588bc862 gameinput: implement IGameInput::CreateDispatcher and IGameInputDispatcher v0
Replace the E_NOTIMPL stub at IGameInput slot 14 with a real
IGameInputDispatcher object: IUnknown plus Dispatch and OpenWaitHandle
at slots 3 and 4, matching the public GameInput v0 contract on
Microsoft Learn (gdk-2610).

Dispatch returns false for every quota, including 0, because this
shim has no real background input work; the documented 'flush at
least one item even at quota 0' shape is honoured trivially and no
real work is implied. OpenWaitHandle returns a fresh manual-reset
event per call, caller-owned. QueryInterface serves only
IID_IUnknown: the v0 dispatcher IID is not published in the public
documentation, so no GUID was invented and other ids are logged.

A live dispatcher counter logs dispatch_mode on each manual and
automatic transition, matching the documented lifetime rule.

test_audio_input.exe now exercises slot 14 and the dispatcher slots.
GameInput.dll still exports exactly GameInputCreate @1.

Cross-compiled and export-verified only; the EXE was not run under
CrossOver on this host.

Closes #500

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:06:50 -07:00
ates 74fffaa350 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Resolve the CHANGELOG conflict and reword the provenance of the Xbox
IDStorage*X contracts as inferences from call-site observation of a
project-authorized target build, pending maintainer review. No
behaviour change.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 05:56:04 +03:00
Eterna 23de596a23 bx-probe: validate the import data directory against its declared bounds
The import entry (data-directory index 1, an RVA/size pair) was read
without checking that it fits in SizeOfOptionalHeader, so a short
optional header made the read fall into the section table. The
descriptor walk was also only bounded by the containing section, so a
declared directory Size shorter than the section still reported
descriptors outside the directory.

Validate the index against NumberOfRvaAndSizes and the entry's 8 bytes
against SizeOfOptionalHeader before reading it. Bound the 20-byte
IMAGE_IMPORT_DESCRIPTOR walk by BOTH the declared Size and the
section's raw bytes, whichever ends first, stopping at a null
terminator or when the next descriptor would exceed the directory.

Add synthetic regressions for a short SizeOfOptionalHeader that puts
the entry out of range, NumberOfRvaAndSizes == 1, and a directory Size
shorter than the section.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:53:47 -07:00
Eterna 00e1b2fce9 xgameruntime: clamp Sleep chunks so INFINITE delays stay finite
delay_ms is a uint32_t, so 0xFFFFFFFF is a valid delay. When the
remaining time was exactly 0xFFFFFFFF, wait_until passed INFINITE to
Win32 Sleep, which waits forever: the loop never re-checked the
deadline and the callback never fired on the lanes that sleep out the
remainder themselves.

Factor the chunk calculation into finite_sleep_chunk_ms in
task_queue.h, which clamps every chunk to at most INFINITE - 1
(0xFFFFFFFE) and is always positive. The test asserts the clamp for a
0xFFFFFFFF remainder without waiting 49 days, and that a 0xFFFFFFFF
delay is accepted and its callback fires on the parallel and manual
lanes.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:53:40 -07:00
Eterna 846690befc docs: move the 17-DLL shim_exports claim to the unverified list
The reviewer's blocking evidence correction: the README placed the new
test_shim_exports.exe runtime claim under "Verified (local Apple M5,
... CrossOver 26.3)", but that fixture's 17-DLL / 28-check run was
never executed under CrossOver on this revision. Compiling and linking
the fixture, and scripts/build-shims.sh finding the bridge's three
exports, do not establish that LoadLibraryA/GetProcAddress passed for
bx_shader_bridge.dll.

The verified bullet now states only what was run: the 16 mingw-w64 C++
shim DLLs and their 25 runtime exports inside CrossOver/Wine. A new
"Not yet verified at runtime" bullet keeps the fixture description --
the added bridge entries, the 17-DLL / 28-check table, the counted
summary line -- and states plainly that the run is pending, that
compiling/linking/export agreement are not a runtime result, and that
the check would only show load-and-resolve, not that the bridge works
(test_shader_gate.exe covers that).

README only; no code, test or abi change.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:49:36 -07:00
atharvranjan 04ad81ee26 Merge branch 'track-c/465-d3d12-presentx' into track-c/465-presentx-timeout-budget
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:49:10 -06:00
atharvranjan e0f8b0e8f6 d3d12_xs: preserve device removal after Present and budget WaitForIdle before Signal
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:45:46 -06:00
atharvranjan 2fc82c4d58 d3d12_xs: distinguish post-present fence wait failures and require WaitForIdle
When wait_locked fails after a successful host Present and signal for a reason other than timeout, log the underlying wait HRESULT as present_next_buffer_wait_failed, require WaitForIdle to succeed before further Present calls (BX_PRESENT_E_NEEDS_IDLE), and return BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED (0x80040205) so callers can distinguish post-present wait failures from pre-present wait failures.

Update test_d3d12_presentx with test-side SetEventOnCompletion E_OUTOFMEMORY fault injection on both sides of host Present, verifying distinct return codes, host present counts, log records, and WaitForIdle recovery, plus a skip-wait-fault negative control in run_controls.sh.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:43:46 -06:00
Eterna c33199264a test_shim_exports: load bx_shader_bridge.dll, covering all 17 DLLs
The fixture that exists to prove every shipped shim loads and
resolves its exports covered 16 DLLs -- the mingw-w64 C++ shims --
and skipped bx_shader_bridge.dll, the Rust-built 17th DLL from
#484. That was the gap #526 documented.

Add the bridge's three frozen exports from
abi/defs/bx_shader_bridge.def: bx_shader_inspect,
bx_shader_prepare_for_d3dmetal and bx_shader_free_buffer. The
existing loop, failure counting and output format are untouched;
the table is simply extended, so all 25 previous checks stay.

The summary line now reports the DLL count as well as the check
count, computed from the table by a small DistinctDllCount helper
rather than hardcoded, so it cannot drift again. It prints
"PASS: test_shim_exports (28 checks verified across 17 shim DLLs)".

README updated to match: the fixture loads all 17 shipped DLLs and
resolves 28 runtime exports (25 + 3), keeping the distinction
between the 16 CMake-built shims and the 1 cargo-built bridge. It
also says plainly that this is a load-and-resolve check only and
does not show the bridge works -- test_shader_gate.exe exercises it
functionally.

abi/ unchanged. Verified on this revision: build-shims.sh ->
Verified 17 PE32+ shim DLLs (111 exact exports);
ls build-shims/bin/*.dll | wc -l -> 17; docs_hygiene 0 problems.
No live CrossOver run on this host.

Closes #527

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:40:03 -07:00
Eterna 82ec02e754 docs_hygiene: validate link fragments, not just the file
check_links() only confirmed that a relative link's target file was
tracked; a `#fragment` was never checked, so a link to a renamed or
reworded heading still passed the audit.

Add markdown_slugs(), which reproduces GitHub's heading-slug rules
(lowercase, drop punctuation, spaces to hyphens, underscore and hyphen
kept) and ignores headings inside fenced code blocks. Every link whose
target is a tracked Markdown file now has its fragment checked against
that file's headings; in-page `](#foo)` links are checked against the
same file. External URLs and bare `#` links are still not fetched.

Suffix generation tracks the set of slugs already emitted globally, not
just a count per base: for headings `Foo`, `Foo-1`, `Foo` the third
must be `foo-2`, because a literal `# Foo-1` heading already owns
`foo-1`. Counting identical bases alone handed the third heading
`foo-1` too, so the audit accepted a link to the wrong heading.

Covered by the new scripts/audit/test_docs_hygiene.py (23 tests), which
fails 3 tests against the previous counting-only suffix logic.

Closes #537

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:38:46 -07:00
Eterna 6cd94140b1 bx-probe: strengthen the defect tests so they discriminate
Two of the tests added in b15c33e passed against the ORIGINAL
parser, because their fixtures never reached the changed code. They
did not prove the fixes.

- bounds_unterminated_import_descriptor_walk now builds a
  two-section image: the descriptor section holds exactly two
  descriptors with no terminator, and a third valid descriptor sits
  just past the section boundary. The original parser imports
  THREE.DLL past the section; the fixed one stops at TWO.DLL.
- rejects_truncated_import_directory now truncates after two of the
  four data-directory bytes, which the original parser accepted as
  'no imports'. It also asserts the exact error variant.
- rejects_section_count_larger_than_file asserts the new
  'truncated section table' error rather than any error.

Verified by compiling the untouched original parser from
origin/main against the new test module: 4 of 10 tests fail
(wrap panic, section-table error mismatch, truncated import
accepted, THREE.DLL imported past the section). All 10 pass with
the fixes.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:23 -07:00
Eterna c08571ac74 bx-probe: bound the import descriptor walk by the section
The previous fix bounded the descriptor walk by the whole image size.
A section-bounded walk is more correct: an import directory that
starts inside a section must not read past that section's raw data,
even when the image has more bytes after it.

rva_to_off_bounded returns the mapped offset plus how many raw bytes
remain in the section, and the descriptor loop runs while at least 20
bytes remain. rva_to_off keeps its old signature for other callers.

Also drop the now-unneeded assert_eq! on the Result in the PE32
magic test (it compares the error variant directly), which removes
the PartialEq requirement the earlier test introduced.

All 10 bx-probe tests pass, and the wrap test still fails when the
u32 add is re-introduced.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:23 -07:00
Eterna d57aba26b9 bx-probe: harden PE32+ parsing and add real coverage
probe_pe32_plus parses attacker-controlled bytes and drives every
bx-cli import report and the system32 staging dependency walk, yet
it had no test at all (the crate's one test covered classify_dll).

Four defects fixed:

1. rva_to_off computed s.raw_ptr + delta as a u32 add, which wraps
   on a crafted image: 0xFFFFFFF0 + 0x20 -> 0x10, a byte offset near
   the start of the file instead of ~4 GiB. Now a checked 64-bit-safe
   add returning None on overflow.
2. Vec::with_capacity(section_count) allocated from an unvalidated
   u16 before the section table was bounds-checked. The table is now
   validated to fit first.
3. u32_le(...).unwrap_or(0) on the import data-directory read treated
   a truncated directory as 'no imports', indistinguishable from a
   genuine zero. Now a real error.
4. The import descriptor walk is bounded by the image size and by a
   checked desc_off increment, so a malformed table cannot run past
   the end of the image.

Nine new unit tests built from synthetic byte buffers: a minimal
valid PE32+, a two-DLL import table (one by name, one by ordinal),
truncation at every header boundary, a section whose raw_ptr would
wrap, section_count larger than the file, a PE32 image, and an import
directory outside all sections. The wrap test was confirmed to fail
when the u32 add is re-introduced and to pass with the fix.

PeSummary now derives PartialEq/Eq for the assertions. Every public
signature is unchanged for bx-cli; cargo test --locked --workspace
passes.

Closes #507

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:23 -07:00
Eterna de0d5bd7d9 xgameruntime: one queue per delay scenario, and assert no spin
The tests shared a single manual queue across scenarios. A 60 s
delayed task at the head then held the lane for every later case,
which made the FIFO and timeout assertions test the wrong thing.
Each scenario now creates and closes its own queue.

Also tightened while here: the finite-timeout case now submits a
2500 ms delay and asserts the 500 ms dispatch returns before the
deadline AND that the wall clock stayed under half the timeout, so
"did not spin" is checked rather than assumed. FIFO uses an explicit
OrderRecord so the order of the two callbacks is compared, not just
their counts. The context/cancelled case keeps the 0xA5 canary.

Margins are unchanged: 10 ms early / 250 ms late against a 100 ms
deadline.

Verified on a native harness that compiles the real task_queue.cpp
against a stub windows.h, since there is no CrossOver on this host:
all six scenarios pass, and a negative control with the delay
discarded fails exactly at the "not yet due" assert, so the tests
discriminate.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:16 -07:00
Eterna f48c42fd20 xgameruntime: gate every lane on the delay, not just dispatch
The first revision gated XTaskQueueDispatch only. Three other gateways
could still run a delayed callback early:

- the parallel/serialized threadpool worker, which popped and ran the
  head as soon as it was pushed;
- immediate mode, which ran the callback on the submitting thread
  without waiting out the deadline;
- a closed manual lane, which drains pending work on close.

All now wait out the deadline. schedule_serial() no longer requires
due() to schedule a worker: a delayed serial tail must still get a
worker that will wake for it, so the due check belongs in the worker,
not in the scheduling condition.

Every wait is saturating on due_ms - now, since the deadline can pass
between the check and the clock read and an unsigned wrap there would
block for ~584 million years.

The tests now cover what the first revision missed: context and
cancelled=true/false delivery checked with a canary, a dispatch
timeout shorter than the deadline ending on the timeout rather than
the deadline, FIFO (a later immediate task cannot overtake a delayed
head), close-before-due running the task as a cancel rather than a
normal run, and the pool path itself. Margins are 10 ms early /
250 ms late against a 100 ms deadline.

abi/defs/xgameruntime.def unchanged (49 exports). Cross-compiled and
export-verified only; no live CrossOver run.

Closes #515

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:16 -07:00
Eterna 2217eb83a1 xgameruntime: honour the delay in XTaskQueueSubmitDelayedCallback
core_tq_submit_delayed discarded delay_ms and fell through to
XTaskQueueSubmitCallback, which has no delay parameter, so the
callback ran on the next dispatch and the call still returned S_OK.
A caller scheduling a backoff or deferred teardown was told the delay
succeeded when it had not happened.

- Each queued task carries a GetTickCount64 deadline (Task::due_ms,
  zero meaning due now). XTaskQueueSubmitDelayedCallback sets it;
  XTaskQueueSubmitCallback forwards with delay_ms == 0, so the common
  immediate path is unchanged. Dispatch gates on the deadline: a
  delayed head holds FIFO order until it is due, and
  XTaskQueueDispatch waits exactly until that deadline (or the
  caller's timeout) rather than spinning.
- The log record now names the consequence ('queued delay_ms=N')
  instead of the old '(nonzero_delay)' text, which named only the
  symbol. It is emitted at INFO rather than as a stub warning, since
  the delay is now implemented.
- The wait computes due_ms - now, and the deadline can pass between
  the due check and the clock read; the subtraction is saturating,
  because an unsigned wrap there would block for ~584 million years.
- test_xgameruntime.exe reaches slot 19 through QueryApiImpl's
  IXGameRuntimeCore COM object (it is not an export) and checks that
  delay_ms == 0 still runs on the next dispatch, that a 100 ms delay
  does not run on a dispatch pass at ~0 ms or after a 10 ms sleep,
  and that it does run after a 250 ms sleep. Those margins are
  deliberately wide so a slow host is not flaky.

abi/defs/xgameruntime.def unchanged (49 exports); the delayed entry
point is a COM slot, not a new export. Cross-compiled and
export-verified only; no live CrossOver run.

Closes #515

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:16 -07:00
Eterna 63f5640a99 test_d3d12_xs: check the padded vtable slot boundaries
gen_proxy.py appends 32 BxBeyondPublicVtableNN stubs after each
generated proxy's public vtable (PAD_SLOTS = 32) so a caller
indexing past the interface it was handed lands on a logged
E_NOTIMPL stub instead of unrelated memory. That is the guard for
exactly the console-only-method case, and no fixture called one:
grepping the test for E_NOTIMPL, beyond_public or pad returned
nothing. So the E_NOTIMPL return, the log record, and the presence
of the 32 slots were all unverified -- the generator could have
stopped emitting them and no test would have noticed.

Indices derived from the generated code, not guessed: device 79,
queue 19, allocator 9, list 81. Cross-checked by parsing
proxy_generated.cpp for the BX_VTABLE_STUB_LOG("<leaf>", N u,
"beyond_public_vtable") calls: all four have exactly 32.

Coverage is boundary-only: for each of the four proxies the fixture
calls just the first (BxBeyondPublicVtable00) and last
(BxBeyondPublicVtable31) padded slot -- 8 calls in total, not all
128 -- and requires E_NOTIMPL without a crash, plus a BX_LOG_FILE
unimpl_vtable record naming the slot and beyond_public_vtable. If
BX_LOG_FILE is unset the log check skips, matching the fixture's
existing behaviour.

abi/ and gen_proxy.py unchanged. test_d3d12_xs.exe was NOT executed:
no CrossOver on this host.

Closes #547

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:35:23 -07:00
Ateş 4509911df0 Merge pull request #605 from MacosPorters/docs/trim-provenance-rules
docs: remove provenance-first and never-obtain bullets from AGENTS.md
2026-11-28 05:18:57 +03:00
Eterna 76c81468c7 d3dmetal-harness: give the probe no deadline when the timeout is unrepresentable
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:16:29 -07:00
Eterna f3976b24f4 d3dmetal-harness: saturate an overflowing timeout deadline
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:16:29 -07:00
Eterna 0f5a2ab6fd bx-cli trace: say kind/stage, not pipeline identity
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:14:18 -07:00
Eterna 987b404a4e bx-cli: snapshot the replaced file before publishing
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:13:16 -07:00
Eterna fa06be79b7 bx-cli: roll back a published shim when the manifest write fails
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:12:00 -07:00
ates 427f1b6cfa docs: remove remaining provenance and legal-boundary rules
Complete the policy trim started in baced397 by removing §4's third-party
licensing and proprietary-component rules, §6's Conditions for target
builds (including the unknown-condition stop rule), the Repository &
clean-tree boundary and Legal boundary. §4 is left as a placeholder
pending the replacement policy; the §6 authorized-evidence and §5
honesty rules remain. CHANGELOG records that other project documents
still describe the previous policy.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 05:11:52 +03:00
Eterna 56a27dfd80 d3d12_xs: keep the wave64 gap record shape and refresh the fixture
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:08:47 -07:00
Eterna 8d904a7f69 d3d12_xs: refuse a wave wider than 32 lanes at PSO creation
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:08:47 -07:00
Eterna 1300eb7892 bx-telemetry: make the (pso, stage) grouping test discriminate
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:07:52 -07:00
Eterna 1894ef23b7 bx-telemetry: group shader_d3dmetal_gap by (pso, stage) (#590)
Extend the bx-cli trace shader_d3dmetal_gap summary with an additive
grouped view: one entry per distinct (pso, stage) pair, in deterministic
first-seen order, reporting the group's count plus every distinct
(wave_lanes_min, atomic64_flags) constraint set. The #496 per-record
list and every existing summary line are unchanged.

A record with a missing or empty pso, stage, wave_lanes_min or
atomic64_flags is grouped under 'unknown' and counted (gaps w/o
pso/stage, gaps w/o constraints) rather than dropped or guessed; nothing
panics.

The summary only reflects records a run wrote; it adds no live run.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:07:52 -07:00
ates baced39764 docs: remove provenance-first and never-obtain bullets from AGENTS.md
Remove the "Provenance first" bullet from section 4 and the "Never
obtain or use" bullet from section 6. The section 6 conditions for
target builds and the repository clean-tree boundary are unchanged.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 04:57:54 +03:00
atharvranjan 989abbdc2c [M2-D] dxbc-accc: deduplicate DXIL state and add NOBC bounds tests
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:29:56 -06:00
atharvranjan 140dce0be1 Merge remote-tracking branch 'origin/main' into track-d/dxbc-accc-nobc-header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:27:40 -06:00
ates 1b25f3422b Merge origin/main into track-f/469-m2-first-frame-gate
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 03:47:21 +03:00
ates 766055e948 Merge origin/main into track-c/vmem-xbox-config
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 03:47:21 +03:00
Ateş 2faadeef7e Merge pull request #600 from MacosPorters/docs/merge-eligibility-policy
Clarify pull request merge eligibility
2026-11-28 03:32:26 +03:00
atharvranjan ce5968a2db Merge pull request #601 from 1Bartosz/track-d/599-fspx-layout-mismatch
[M3-D2] dxbc-accc: report an FSPX layout mismatch apart from out-of-bounds (#599)
2026-11-27 18:30:40 -06:00
atharvranjan 494e53b8fb [M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:29:50 -06:00
ates 54b87f613c test_m2_first_frame: fence the readback, name config fields, state limits
Wait on a queue fence before the CPU reads the backing map instead of
relying on WaitForIdle alone, assign the BXVM config by field name so a
reorder in vmem.h cannot compile silently, tie the expected pixel formula
to fill_cs66.hlsl, and record the fixture's limitations in its header.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:28:58 +03:00
ates bbd3b8a9d4 Merge origin/main into track-c/vmem-xbox-config
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:26:21 +03:00
ates 32d02efc33 d3d12_xs: record the Xbox vmem block without claiming it applied
Nothing consumes the decoded virtual-segment count yet, so the Xbox path
now logs vmem_config_recorded (applied=0 recorded_only=1), keeps
BX_STUB_LOG, and leaves the BXVM record and its cached backing heap
alone instead of evicting it.

Name the source of the layout as a project-authorized target build with
provenance pending review, and have the fixture read only the log bytes
appended by each step, so fixtures sharing one log cannot satisfy or
break its checks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:26:08 +03:00
atharvranjan ac82a55039 Keep PresentX test hook table alive on failure
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:19:39 -06:00
Bartosz Szczepański d6586b1fa3 docs: name FspxLayoutMismatch where ADR 0008 and the roadmap cite the FSPX scan (#599)
ADR 0008 and the roadmap (#588) say dxbc-accc rejects the 29 scanned
FSPX containers with FspxSectionOutOfBounds. The cause they record, a
descriptor offset inside the reserved header-plus-table region, is
FspxLayoutMismatch after this branch. Both now say which error the scan
saw, which one the same cause maps to now, and that the scan was not
re-run. The C ABI still returns BX_SHADER_ERR_INVALID_BLOB for both.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 01:10:37 +01:00
Bartosz Szczepański ceb1095139 Merge remote-tracking branch 'origin/main' into track-d/599-fspx-layout-mismatch
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 01:10:37 +01:00
atharvranjan e40d7293f8 Merge main into M2 first-frame fixture PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:09:56 -06:00
Ateşandatharvranjan 2ef175c0ce Roadmap: prioritize startup diagnosis and define first-frame acceptance (#588)
* docs: prioritize startup diagnosis and define first-frame acceptance

Signed-off-by: ates <ahmetrizaates@hotmail.com>

* docs: clarify roadmap verification and memory scope

Signed-off-by: ates <ahmetrizaates@hotmail.com>

* docs: record the target-workload shader corpus scan

Add the verified 2026-11-28 read-only container scan of an authorized
local test workload to the roadmap, ADR 0008 and the changelog: 52 DXIL
SM 6.5 compute containers with LLVM bitcode in the XboxBvhBuilder
component, 29 ACCC-only FSPX containers in the AMD FidelityFX upscaler
component, and 10 SM 6.6 DXIL containers whose DXIL chunks carry
four-byte NOBC payloads in the main executable. The packaged shader
archive remains unclassified. dxbc-accc accepts all 62 DXIL containers
(including the 10 NOBC programs) and rejects all 29 FSPX containers
because their section tables do not match the clean-room layout. The
roadmap keeps D1, gates D2 on runtime submission of an ACCC-only
container, and records both parser gaps as Track D prerequisites.
Build-specific details stay in a local evidence note; runtime use is
unmeasured.

Signed-off-by: ates <ahmetrizaates@hotmail.com>

---------

Signed-off-by: ates <ahmetrizaates@hotmail.com>
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
Co-authored-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:40:16 -06:00
atharvranjan e016cc1259 Add changelog entry for merge eligibility
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:40:07 -06:00
atharvranjan 083505ba1b Clarify pull request merge eligibility
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:39:56 -06:00
Bartosz Szczepański 1600d3f70f [M3-D2] dxbc-accc: report an FSPX layout mismatch apart from out-of-bounds (#599)
An FSPX descriptor whose offset lands inside the 16-byte header or the
descriptor table was reported as FspxSectionOutOfBounds, the same error as
a section that runs past the payload end. The reserved region cannot hold
section data under the synthetic layout, so such a table does not follow
that layout; it is not merely truncated or corrupt.

walk_sections now returns FspxError::LayoutMismatch for that case, surfaced
as ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }.
Both parse_fspx and scan_fspx share the walker, so inspect_dxbc and the C
ABI's summarize_dxbc classify it the same way. The container is still
refused: the C ABI is unchanged and returns BX_SHADER_ERR_INVALID_BLOB.

One existing case (offset 0 in a one-section table) now expects the new
variant. New tests cover the reserved-region boundary, the out-of-bounds
case, the unchanged C ABI refusal, and seeded random FSPX tables.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 00:28:47 +01:00
Jelly 9d4f7dffff Merge pull request #598 from MacosPorters/docs/agents-authorized-compatibility
docs: update AGENTS.md with 3-tier agent task priorities and authorized evidence rules
2026-11-28 00:14:59 +01:00
atharvranjan c126b94182 docs: tighten evidence conditions and add agent efficiency policy
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:08:29 -06:00
ates 257aa1651a docs: add 3-tier agent task priority order to AGENTS.md
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 02:06:49 +03:00
ates 6c243259d9 docs: permit project-authorized compatibility evidence in AGENTS.md
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:59:37 +03:00
ates 981bd3c64e xcrdapi: add Xbox DirectStorage COM interfaces (IDStorage*X)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:55:06 +03:00
Bartosz Szczepański 58b209a71b [M2-B2] xcrdapi: serve the public PC DirectStorage interfaces (#483)
DStorageGetFactory now accepts IDStorageFactory and IDStorageFactory1 and
logs any other requested IID with its value next to BX_STUB_LOG.

The public IDStorageFactory1, IDStorageFile, IDStorageQueue..4 and
IDStorageStatusArray objects wrap the existing queue engine. WorkQueue
gains an optional blocking enqueue, automatic submission and a failure
entry so the void enqueue methods report rejections in queue order. The
synthetic bx::storage behaviour is unchanged.

dstorage.h and dstorageerr.h from Microsoft.Direct3D.DirectStorage 1.4.0
(MIT per file) are vendored unmodified; dstorage_mingw.h restates their
IIDs for MinGW. Provenance is recorded in the upstream registry, the reuse
matrix and THIRD_PARTY_NOTICES.md. The Xbox IDStorage*X interfaces are
out of scope.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 01:49:18 +03:00
ates 63b5f5dac6 d3d12_xs: add 32-byte Xbox decoder for D3D12ConfigureVirtualMemoryX
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:28:00 +03:00
Eterna b96aa5c0b8 [M2-D5] judge reported shader model
Reviewed current head and checks; no remaining blockers.
2026-11-27 15:53:16 -06:00
Eterna 6484cb70a3 acphal: reject a zero-capacity APU heap
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:46:14 -07:00
Eterna 87da1752ad docs: keep the results table contiguous after the exit-code note
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 1bc42fcaec docs: move the exit-code note below the results table
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 25ceb05230 docs: define the conformance exit-77 skip protocol
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 2bc97a4f68 bx-cli: avoid ps in cleanup process-group test
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:34 -07:00
Eterna f2efeaf79d docs: define claims.toml evidence classes A/B/D/E/U (#549)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:33 -07:00
EternaandEterna 463169f72c [M2-A3] bx-cli trace: summarize shader_gate, D3DMetal-gap and bridge-missing records (#497)
* bx-cli trace: summarize shader-gate records

bx-telemetry now parses the shader_gate, shader_d3dmetal_gap and
shader_bridge_missing records that d3d12_xs.dll logs, aggregating
per-decision, per-kind and per-stage counts and keeping the
individual records. bx-cli trace renders the summary, and stays
byte-identical for logs with no gate records.

Closes the telemetry-summary gap ADR 0008 listed under 'Not covered
by the gate yet'. Summarizes records a run wrote; no live CrossOver
run was performed for this change.

Closes #496

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* bx-cli trace: address shader-gate review comments (#496)

From the #497 reviews:

- parse_key_values now takes a stop_at_free_text flag. Only the
  shader_d3dmetal_gap record appends free text, so a stray token ends
  the parse there; for shader_gate a stray token is skipped and
  parsing continues, so one unexpected word can no longer silently
  drop every later field.
- ShaderGateSummary gains missing_decision, counting parsed records
  that carry no decision. decision buckets + unparsed +
  missing_decision now reconcile against total, so the breakdown can
  never quietly add up to less than the total.
- bx-cli trace renders the individual non-pass decisions with pso,
  stage, decision and hr, so a rejected pipeline is named rather than
  only counted. This also makes ShaderGateSummary::records read
  outside tests.

Tests added for all three: a stray token keeping later fields, two
spaced atomic64 flags, a record with no decision, and a reconciliation
check over a mixed log.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* bx-cli: restore the doc comment on format_shader_gate_section

Arths17's re-verification of 93a309f noted that
format_non_pass_decisions was inserted between
format_shader_gate_section and its doc comment, so the comment
documented the wrong function. Split the two: the non-pass helper
keeps its own comment, and the section function gets its comment
back. No behaviour change; fmt, clippy and the 47 bx-cli tests pass.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* bx-telemetry: pin the two #497 review cases with tests and a note

devil8blade's review raised two parsing concerns. Both behaviour
changes were already in 796ed36; this adds the tests that name them
and the comment that explains why the two paths differ.

1. parse_key_values: a token without "=" stops the structured part
   when stop_at_free_text is set, and is skipped otherwise. The gate
   path passes false, so a value containing a space does not turn
   every later field into None. New test: a stray token does not
   drop later gate fields. Also documents that the emitter writes no
   spaces inside a value today, so this is robustness rather than a
   fix for current output.

2. A shader_gate record with fields but no decision is counted in
   missing_decision, so the decisions breakdown can be seen not to
   add up to the total. New test: a record without a decision is
   counted as missing. A third test pins the opposite free-text
   behaviour for the gap record.

cargo test -p bx-telemetry: 19 passed (was 17).

Closes #496

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

---------

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:43:04 -06:00
sahib453 a6dc3faf50 Never block on a --log path that is not a regular file (#503)
log_mark and read_log opened the --log path and read it to the end,
which waits forever on a FIFO nobody writes to (#502, from the review
of #475). The path is now opened with O_NONBLOCK and only a regular
file, checked on the open handle, is marked or summarized. Adds the
missing test for the file-identity half of the replaced-log check and
documents when a Ctrl-Z between supervised phases takes effect.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 15:39:30 -06:00
EternaandEterna 56650b91c2 bx-cli: propagate the guest numeric exit code (#566)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:37:54 -06:00
EternaandEterna 2505bc3a5b [M2-D3] docs: dxbc-accc README lists shipped ABI/staging/PSO-telemetry work as 'Not done' (#499)
* docs: dxbc-accc README lists shipped work as outstanding

The 'Not done here' section recorded the bx_shader_bridge.def
export list, scripts/build-shims.sh staging, and the d3d12_xs
PSO hook with JSONL telemetry as not yet done. All three shipped:
#445/#484 (.def + staging) and #466 (PSO hook + bx_log_emit
records). Replace the section with an accurate account of what
each one does and which issue delivered it.

The bx-cli trace summary of those records (#496, PR #497) is
NOT yet on main, so it is listed as the one item still open,
with the ADR 0008 telemetry note it leaves in place.

Documentation only; no code, ABI, test, or behavior change.

Closes #498

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* docs: decouple dxbc-accc README from PR state (#498 review)

Address review comments on #499:

- Drop the PR number, branch name and ADR-status sentence from the
  trace-summary bullet. It now points at #496 and says only what is
  true on main, so it cannot go stale in either merge order.
- Reword the intro: these are pieces around this crate, not pieces
  the crate depends on.
- Reword the closing line so it means this change rather than a
  claim about #445.
- Add #445 to the CHANGELOG citation to match the README.

Re-verified against main b8724bf: BxShaderGate::admit in proxy.cpp
covers VS/PS/DS/HS/GS and CS; build-shims.sh copies dxbc_accc.dll
to bx_shader_bridge.dll; the verifier checks the export directory
name against the .def.

Documentation only.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* dxbc-accc: drop the PR-state dependency from the README

devil8blade's review of #499 point 1: the last bullet said #497
was open and that bx-cli trace did not summarize the records. Once
#497 merges those sentences become wrong and nobody is assigned to
fix them.

Reworded to describe the split of responsibility only: the trace
summary work is tracked in #496, and the bullet no longer asserts
anything about that issue's status or about what bx-cli trace does
today. The crate's own behaviour is unaffected either way.

Also shortened the CHANGELOG entry to one sentence pointing at the
README, keeping #445 alongside #484 and #466 as the review asked.

Points 2, 3 and 5 were already addressed in 653e751: the intro says
"pieces around this crate", the closing line says "this change does
not touch the crate's code or tests", and the four factual claims
(proxy.cpp, shader_gate.cpp, BxShaderGate::admit, cargo naming the
built file dxbc_accc.dll) were verified against main before this
commit.

Documentation only; docs_hygiene.py 0 problems.

Closes #498

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

---------

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:06:17 -06:00
EternaandEterna 01f5590e88 docs: correct the stale shim-DLL counts (16/102 -> 17/111) (#526)
scripts/build-shims.sh verifies 17 PE32+ DLLs with 111 exact exports,
but several documents still said 16 DLLs and 102 exports. The 17th is
bx_shader_bridge.dll, added by #484 so d3d12_xs's shader gate can
classify stages.

The wording now distinguishes the 16 mingw-w64 C++ shims built by the
CMake superbuild from the Rust bx_shader_bridge.dll built by cargo for
x86_64-pc-windows-gnu, rather than swapping 16 for 17 and calling all
seventeen "cross-compiled C++ shims", which would also be wrong.

Corrected: AGENTS.md (onboarding and the Section 8 comment),
README.md (abi row, build comment, verified-scope list, the
test_shim_exports claim, and the M0 roadmap-table row),
docs/roadmap.md (the diagram and the M0 exit gate) and
docs/architecture/parallel-tracks.md (M1).

test_shim_exports.exe still loads only the 16 C++ shims (25 checks)
and does NOT load the bridge; the README now says so and points at
test_shader_gate.exe, which does cover it. Extending the fixture is
named as a follow-up, not done here. Also dropped an unverified
"zero warnings" claim.

The docs/roadmap.md M0 exit-gate text is a stale-count correction to
a RECORDED gate (#406), not a re-opening of M0. Status stays Verified
complete.

Documentation only; no code, test or abi change. Verified on this
revision: build-shims.sh -> Verified 17 PE32+ shim DLLs (111 exact
exports); ls build-shims/bin/*.dll | wc -l -> 17;
grep -c bx_shader_bridge test_shim_exports -> 0; docs_hygiene 0
problems.

Closes #525

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:05:47 -06:00
EternaandEterna 21323cab80 docs: point ADR 0005 at the archived progress.md (#570)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:04:59 -06:00
Erkin Taş ab81b0beca d3d12_xs: distinguish fence wait failures after Present
Signed-off-by: Erkin Taş <erkinemreta@gmail.com>
2026-11-27 23:41:29 +03:00
Eterna b16797f576 test_d3d12_placed: exercise the graphics-first xmem pairing (#552)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 10:38:00 -07:00
Eterna 3409bf4ec0 d3d12_xs: charge graphics heaps through the xmem hook
After #550, xmem could see an external charge, but d3d12_xs still
kept its own private ledger and never registered one, so the
graphics-first overcommit remained. try_charge now calls
bx_xmem_try_charge_external and release_charge calls
bx_xmem_release_charge_external, so both allocation orders obey one
combined cap.

The overflow guards are kept, not traded away. try_charge still
rejects on bytes > cap, xmem_used > cap and
charged_private_bytes > cap - xmem_used before either unsigned
subtraction, and the comment now names which guard protects which
wrap and shows that the two additions cannot overflow given the
guards.

g_record.charged_private_bytes stays as a diagnostic mirror;
xmem's external_bytes is authoritative. release_charge releases
the xmem charge first, which logs and clamps on underflow, then
keeps the mirror in sync.

Lock order checked: try_charge and release_charge hold g_section
and then call into xmem, which takes usage_lock. xmem never calls
back into d3d12_xs (its only mention is a comment), so
g_section -> usage_lock is never inverted.

abi/, xmem.dll and d3d12_xs.dll export counts unchanged (17 / 4).
test_d3d12_placed.exe was NOT executed: no CrossOver on this host.
The two-order arithmetic was checked by simulation, not on host.

Closes #552

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 09:10:51 -07:00
Eterna 420c2329b7 abi: expose an xmem charge hook for the combined title budget
The combined Lockhart/Anaconda budget was one-way. try_charge in
shims/d3d12_xs/vmem.cpp read bx_xmem_get_internal_stats and
subtracted CPU usage before admitting a graphics heap, but
can_commit in shims/xmem/xmem.cpp summed only heap, virtual and
physical bytes and never saw the graphics charge. So graphics-first
(6 GiB) then CPU (3 GiB) admitted 9 GiB against an 8 GiB cap, while
xmem-first was rejected correctly. The header exposed no way for a
second owner to register a charge, so the fix could not live in one
shim; this is the [ABI] change that lands first.

Add bx_xmem_try_charge_external and bx_xmem_release_charge_external
to bx_xmem_internal.h, exported from xmem.dll (15 -> 17). Admission
is atomic under the same usage_lock can_commit takes, so two threads
cannot both pass, and it returns 0 rather than silently succeeding.
The new external_bytes counter is folded into can_commit and
update_peak, so both allocation orders now obey one cap. Release
clamps to zero and logs on underflow, mirroring release_charge.

bx_runtime_config_t is unchanged and there is no ABI version bump:
this is additive only.

shims/d3d12_xs/vmem.cpp still keeps its private
g_record.charged_private_bytes. Switching it to these functions is
the consumer change, a separate PR.

Verified: build-shims.sh reports Verified 17 PE32+ shim DLLs
(113 exact exports) with OK xmem.dll (17 exact exports verified);
fmt, clippy and test pass; docs_hygiene 0 problems; the header
compiles from both C and C++ with -Wall -Wextra -Werror. No live
CrossOver run: none on this host.

Closes #550

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 08:57:57 -07:00
Eterna ae869522ce test_veh_clwb: assert the decoded clwb length, not just the count
The fixture emitted six clwb forms and asserted only delta == 6.
But decode_clwb_length decides len, and the handler does
Rip += len: a wrong len lands the guest mid-instruction while the
trap count stays at 6. The log already carried len=%zu, and no test
read it.

log_sampled_trap logs only counts 1, 2, 4, 8, ..., so six traps
produce exactly three records with total_traps = 1, 2, 4. Assert on
those sampled records only (option (a)); forms 3, 5, 6 are NOT
covered by a len= assertion, and the comment and CHANGELOG say so.

Mapping, re-derived by assembling with x86_64-w64-mingw32-as and
disassembling with x86_64-w64-mingw32-objdump -d:

  total_traps=1 -> clwb (%rax)        -> len 4
  total_traps=2 -> clwb 0x40(%rax)    -> len 5
  total_traps=4 -> clwb (%r8)         -> len 5

clwb (%r8) is 66 41 0f ae 30, ModRM 0x30, confirmed from the
disassembly rather than guessed.

Add a BX_LOG_FILE reader (the fixture did not read it before),
creating a temp log when the variable is unset, initialized before
the clwb block. The AVX2/FMA block runs first but does not trap, so
the first clwb is trap #1. Also assert len >= 4 on every observed
record. The existing delta == 6 check is unchanged.

test_veh_clwb.exe was NOT executed: no CrossOver on this host. The
log-parsing logic was sanity-checked on the host against a synthetic
JSONL sample; a live CrossOver + Rosetta 2 pass is still required.

Closes #539

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 06:55:03 -07:00
Eterna 6e3ef5459b test_shader_gate: assert the log's shape, not a hand reading of it
The bx-cli trace fixtures were typed by hand from reading the
snprintf in shader_gate.cpp. A reviewer asked for a real log; one
was supplied in a PR comment and confirmed the parser, but that
confirmation lived nowhere in the repo, so the next fixture could
drift unnoticed.

This asserts the shape of the log the fixture itself writes:

- at least one shader_gate and one shader_d3dmetal_gap record exist;
- every gate record writes pso=, stage=, decision= and hr= in that
  order, which is the order the summarizer extracts them in;
- an *_unclassified record carries no kind=;
- every gap record has pso=, stage=, wave_lanes_min= and the colon
  that ends its structured part, which is the boundary
  parse_key_values(..., true) needs;
- no key=value value is split by a space, which is what
  parse_key_values(..., false) assumes for the gate records.

Shape, not counts: decision and kind totals vary by GPU. It is the
field order and token boundaries that a hand-typed fixture could get
wrong without any test noticing.

Verified: the assertions compile and link, and their logic was run
in a native harness against a sample log, including a negative
control where an atomic64 value containing a space correctly trips
the check. test_shader_gate.exe itself was not run here -- no
CrossOver on this host.

Closes #535

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 06:35:41 -07:00
Eterna bec15f43b6 bx-cli: test the usage paths in-process, not by spawning the binary
The previous test located the built bx-cli by guessing a path from
current_exe(). That worked locally but failed in CI with
"spawn bx-cli: No such file or directory", because cargo does not
guarantee the bin sits next to the test binary.

Replace it with a testable dispatch: Dispatch::classify(args) returns
Help / NoArgs / Unknown / Sub, plus usage_on_stdout() and
is_usage_error(). main() is now a thin shell over that, so the exit
and stream choices are asserted in-process with no binary lookup and
no dependency on the build layout.

usage_text() returns the string; main() prints it to the stream the
dispatch selects. The five real subcommands are asserted to be
neither usage errors nor usage-printing, and a second test checks
the usage text names every subcommand so the classifier is not
testing a table nothing prints.

Behaviour is unchanged from the intended fix: --help/-h/help exit 0
on stdout, a bare invocation exits 1 on stderr, an unknown
subcommand exits 1 on stderr.

Closes #532

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 05:59:40 -07:00
Erkin Taş 7dde71e2fd d3d12_xs: share the PresentX idle timeout budget
Signed-off-by: Erkin Taş <erkinemreta@gmail.com>
2026-11-27 15:54:54 +03:00
Eterna 33d439f828 bx-cli: fix the inverted help and usage exit codes
--help and -h were never matched, so they fell into the
unknown-subcommand arm: usage text on stderr and exit 1. Meanwhile a
bare bx-cli with no arguments printed usage and returned 0. Both
halves were wrong, and in opposite directions.

--help, -h and help now print usage on stdout and exit 0, so
`bx-cli --help | less` and `bx-cli --help && ...` both work. A bare
invocation is a usage error: text on stderr, exit 1. An unknown
subcommand still exits 1, unchanged.

print_usage takes a UsageStream so the caller chooses the stream
instead of the function hardcoding eprintln!. The subcommand
behaviour of doctor/probe/shader/trace/run is untouched.

Test help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error
runs the built binary and asserts exit code, stdout and stderr for
--help, -h, no arguments and a bogus subcommand. Mutation-checked:
restoring the old dispatch makes it fail at exactly
"--help must exit 0".

Closes #532

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 05:53:12 -07:00
Eterna a27284ab26 dxbc-accc: expose a bounds-checked chunk-lookup API
dxbc-accc already parsed the DXBC chunk table into
ChunkInfo { fourcc, offset, size }, but exposed no public lookup, so
shims/d3d12_xs/shader_gate.cpp:94 re-implements the same
bounds-checked walk in C++ (find_chunk), plus a second variant
has_chunk_tag that ignores the declared size. Two parsers for one
container is how a fix lands in one and not the other.

Add an additive API on ShaderInspection:

- chunk_payload(&container, &fourcc) returns the payload of the
  first chunk tagged fourcc. It reuses the already-parsed chunks
  vector rather than re-walking the raw table, and validates
  offset + 8 + size against BOTH container_size and container.len()
  with checked arithmetic, returning None instead of panicking.
  offset points at the 8-byte chunk header, so the payload begins
  at offset + 8. A zero-size chunk yields Some(&[]); callers needing
  a minimum size must check the returned length. When several chunks
  share a FourCC, the first in table order wins, matching the C++
  find_chunk.
- has_chunk_tag(&fourcc) answers presence WITHOUT trusting the
  declared size, mirroring the C++ has_chunk_tag.

Scope: the C++ gate is NOT migrated here -- find_chunk and
has_chunk_tag in shader_gate.cpp stay for now, and the PR names the
migration as a follow-up, since it is a larger change needing a live
run. abi/defs/bx_shader_bridge.def unchanged (3 exports).

Seven new unit tests: SFI0 and PSV0 payloads returned exactly; a
declared size past the container -> None; an absent FourCC -> None
and has_chunk_tag == false; a zero-size chunk -> Some(&[]); an
exact-fit chunk at the container end (no off-by-one); a truncated
container slice -> None; and duplicate FourCCs -> first wins.

Closes #521

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 04:53:52 -07:00
Eterna 311f4124fa win32_bridge: store the PSM callback and say it is never fired
register_notification validated callback for null and then dropped it:
nothing stored it, nothing ever invoked it, and the context pointer was
discarded as PVOID /*context*/. So ERROR_SUCCESS meant 'token
allocated', not 'you will be notified', and neither the code nor the
log said so.

- Each registration now keeps a (token, callback, context) record
  under the existing SRWLOCK, capped at a fixed kMaxRecords (256) so
  no allocator is needed. The exported wrappers thread context
  through. Unregistering drops the record, so no later event can
  reach a retired registration.
- A comment on register_notification and the JSONL detail (now
  'registered_offline callback_unfired') both state that the callbacks
  are accepted and currently never invoked, because this shim has no
  source of app-state or constrained-change events and the console
  firing contract is not publicly documented. No firing policy was
  invented: the callback is deliberately left unfired rather than
  called spuriously to look implemented.
- test_win32_bridge.exe now also asserts that no callback fires, and
  that every registration's detail carries callback_unfired, counted
  separately for state and constrained. The existing per-event JSONL
  counts still pass, since the detail grep is a substring match.

abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def and -l1-1-1.def are
unchanged at 2 exports each; all six API-set DLLs keep their original
export counts. Cross-compiled and export-verified only; no live
CrossOver run.

Closes #513

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 03:35:42 -07:00
Eterna 46a6a4baca acphal: stop reporting success for shape-context work not done
AcpHalAllocateShapeContexts and AcpHalReleaseShapeContexts logged a
stub and returned a bare S_OK. Allocate discarded its only argument
(unnamed) and Release takes no argument at all, so neither could be
held to anything: a caller was told the work succeeded when nothing
had happened. This is the silent-fallback case AGENTS.md section 5
names.

Both now return E_NOTIMPL and keep their BX_STUB_LOG record, so
bx-cli trace still surfaces the call while a caller is told to fall
back instead of being told the work happened. Release mutates no
state, so calling it twice is safe.

The public Microsoft Learn page for AcpHal is NDA-gated (HTTP 200
with only the membership gate), so the true signatures and the
context layout are unknown, including whether Release should take an
argument. E_NOTIMPL is therefore BetterXen's choice, not the
console's; no signature was invented and abi/defs/AcpHal.def is
unchanged at 9 exports.

test_audio_input.exe now calls both through the DLL: null and
sentinel pointers return E_NOTIMPL without crashing, a second
Release call returns E_NOTIMPL, and when BX_LOG_FILE is set it
asserts both symbols still appear on unimpl_api lines (printing an
explicit SKIP when the variable is unset rather than claiming a
pass).

Cross-compiled and export-verified only; no live CrossOver run.

Closes #509

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 00:56:02 -07:00
atharvranjan 8245c30b56 d3d12_xs: keep Present from blocking and recover from a failed signal
Present no longer waits for the swapchain lock, which its holder may keep
across a host Present that depends on the caller's thread. It returns
BX_PRESENT_E_BUSY with nothing presented.

When the fence signal after a host Present fails, return
BX_PRESENT_E_COMPLETION_UNCONFIRMED and refuse further presents with
BX_PRESENT_E_NEEDS_IDLE until WaitForIdle succeeds, so a buffer is not
reported reusable on the strength of an older fence value.

The fixture injects both faults from the test side.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 22:27:19 -06:00
atharvranjan be647332cb Merge main into the PresentX branch
Keep both new d3d12_xs source files in CMakeLists.txt and both sets of CHANGELOG entries.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 22:27:19 -06:00
Ateş b8724bf04f Merge pull request #486 from devil8blade/track-c/464-d3d12-vmem-placed
[M2-C1] Back configured D3D12 regions with one WRITE_BACK heap (#464)
2026-11-27 06:35:00 +03:00
ates fbd2f8cf43 Gate the M2 fixture target on its provider headers
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 06:00:35 +03:00
ates 40a9cebb83 [M2-C1] Retain heap charges for live placed resources
Attach the charged heap to each base placed resource, describe the backing map lifetime, and serialize shared vtable installation before device publication. Exercise dependent heap charges and parallel device creation under the 512 MiB title cap.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 05:45:52 +03:00
ates 6a1451b265 Clarify M2 frame readback and test pixel mismatches
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 05:38:34 +03:00
ates 7056671c19 [M2-C1] Reject stale D3D12 backing heap publication
Validate the configuration generation at cache lookup and publication. Return a retry result and release any allocation if reconfiguration supersedes the request. Drop the extra fixture references so detached heaps are credited before the budget checks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 05:31:32 +03:00
devil8blade bd546d8a39 [M2-C1] Address review: detach, unwrap, and one final release (#464)
A backing heap that leaves the cache drops its weak device pointer under
the same lock, so a caller who still holds it gets E_FAIL from GetDevice.
CreatePlacedResource1 and CreatePlacedResource2 unwrap that wrapper.
Weak GetDevice acquires a reference only when the count is non-zero, and
the 1-to-0 release clears weak pointers in that same critical section.
Handing out the cached heap checks the host and the size, retargets, and
takes the caller's reference before the lock is released.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 02:07:50 +00:00
devil8blade db193a3d16 Merge remote-tracking branch 'origin/main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 02:02:27 +00:00
Skakwy cd945ba749 Emulate AMD instruction traps in the Windows guest runtime (#470)
Closes #451.

Add AMD instruction emulation and conformance coverage using the
AMD Architecture Programmer's Manual, volumes 3 and 4. The final
decoder and fixture replace the earlier VIctory-macOS-derived work.
The earlier PR cited 64bitMango/VIctory-macOS at 841c1b8. The
maintainer's provenance decision accepts the AMD-manual replacement.

Verification on the PR head: both CI workflows passed, and the local
Apple Silicon CrossOver 26.3 run passed 28 AMD-instruction assertions.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 04:34:27 +03:00
devil8blade 8381f57204 [M2-C1] Address review: lock the weak heap GetDevice (#464)
The backing heap reads device_ and AddRefs the proxy while holding
g_section, the same lock that clears that pointer. An ordinary heap
still reads its owning pointer without the lock. If GetDevice AddRefs
after Release has observed zero, Release leaves the proxy alive.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:25:35 +00:00
devil8blade 0b48688c13 [M2-C1] Address review: retarget cached heap, own ordinary heaps (#464)
The cached backing heap keeps a weak device pointer. ensure_backing points
it at the proxy receiving the heap, and BxDeviceProxy::Release clears it
when that proxy is destroyed. Ordinary heaps AddRef the proxy and Release
it after the wrapper is destroyed, matching BxChildProxy.

The placed-resource test forces the second proxy onto the cached host device.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:22:54 +00:00
ates c64534fb21 Add end-to-end M2 first-frame conformance fixture
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 04:21:26 +03:00
devil8blade c878ad5875 [M2-C1] Address review: proxy GetDevice and per-device backing heap (#464)
BxChargedHeap::GetDevice returns the creating BxDeviceProxy and does not
AddRef it, so the cached backing heap cannot keep that device alive.
The cache is keyed by the host ID3D12Device. CreateHeap on a different
host device releases the old heap, its buffer, and that budget charge,
then builds a new one.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:17:10 +00:00
devil8blade 291047834a Merge branch 'main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:13:58 +00:00
jelly013 f07a24c28c xgameruntime: mount with UI through XAsync, answer IXError slot 3
Address the review of #492:

- XPackageMountWithUiAsync / XPackageMountWithUiResult (IXPackageImpl2
  slots 37-38) mount through the XAsync engine. The async call checks
  the package identity, and the result creates the same mount handle
  XPackageMount returns. A foreign identifier is reported as the
  operation status, ERROR_NOT_FOUND. The identity and path code is
  shared with XPackageMount.
- IXError slot 3 returns false instead of the E_NOTIMPL stub, whose
  low byte read as true. xgameruntime-docs lists the slot as unknown;
  the behaviour follows the review's interop observation. No
  parameters are read, and the first call is logged.
- test_xgameruntime_saves covers both mount slots through the public
  vtable, and slot 3's answer.
- Record xodus-gaming/xgameruntime-docs at 7090008 in the upstream
  registry and component reuse matrix, pending maintainer provenance
  acceptance.

Refs #468

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-27 03:07:49 +03:00
devil8blade aedd338980 [M2-E2] Wire XGameSave and XPackage into xgameruntime COM dispatch (#468)
QueryApiImpl now serves the offline XGameSave and XPackage objects from
#472 on the public COM class and interface ids, through const vtables in
com_dispatch.cpp. The ids, inheritance and slot order are facts from
xodus-gaming/xgameruntime-docs commit 7090008692569aa6081e30dfdd9de58237741e24
(GPL-3.0). Signatures follow the Microsoft Learn GDK reference.

Slots the existing save and package logic can answer call it, including
synchronous XGameSaveInitializeProvider, XGameSaveReadBlobData and
XGameSaveSubmitUpdate built on the async operations, and
XPackageIsPackagedProcess. Every other slot logs with BX_VTABLE_STUB_LOG.
The synthetic keys keep working. Storage stays under C:\bx_pls\<hash>\saves\.
abi/defs/xgameruntime.def is unchanged at 49 exports.

test_xgameruntime_saves gains a public-id round trip: QueryApiImpl and
QueryInterface across both interface chains, a save write and byte-exact
read back, enumeration, package identifier, kind and mount path, stubbed
slots and refused ids.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 03:07:49 +03:00
Ateş e61e27055f Merge pull request #491 from soggyramennoodle/track-c/450-direct3d-acceptance-failures
Document independent Direct3D acceptance results for #450
2026-11-27 02:15:40 +03:00
Ateş 0edb548e3d Merge pull request #485 from devil8blade/track-b/467-xcrdapi-gpu-batch
[M2-B1] Batch XCRDAPI transfers into D3D12 buffers (#467)
2026-11-27 02:15:02 +03:00
devil8blade c13f9c7665 Merge branch 'main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:51:11 +00:00
devil8blade c219636ae2 Merge branch 'main' into track-b/467-xcrdapi-gpu-batch
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:50:57 +00:00
atharvranjan 0bd385cf05 Merge pull request #478 from jelly013/track-d/466-shader-format-gate
[M2-D2] M2 Shader Format Gate: dxbc-accc in d3d12_xs PSO creation, ADR 0008 (#466)
2026-11-26 16:47:55 -06:00
devil8blade 38a21c2da1 Merge branch 'main' into track-b/467-xcrdapi-gpu-batch
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:46:08 +00:00
devil8blade c44ae4e221 Merge branch 'main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:45:52 +00:00
devil8blade af940476c6 [M2-C1] Address review: explicit backing heap, forwarded ordinary heaps (#464)
CreateHeap returns the backing heap only for an explicit request. The config
block must set BX_D3D12_VMEM_FLAG_BACKING_HEAP and the desc must be CUSTOM,
WRITE_BACK, L0, flags NONE, at the configured size. Every other CreateHeap and
CreatePlacedResource is forwarded unchanged to the host. Only the live-heap
budget wrapper remains, and it answers ID3D12Heap1 when the host heap does.

D3D12ConfigureVirtualMemoryX reads an 8-byte BXVM magic and size header
before anything else, copies the block, and never keeps the caller's pointer.
cpu_pointer is written only during the call. A second call with the same
region returns the map address once the backing heap exists.

test_d3d12_placed covers same-size UPLOAD and DEFAULT plus DENY_BUFFERS
heaps, a 100000-byte UPLOAD heap, 4 KiB small-resource placement,
ID3D12Heap1, and a config block that is gone before CreateHeap.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:45:26 +00:00
devil8blade 6eaa594ae4 [M2-B1] Address review: keep unconfirmed staged copies alive (#467)
After ExecuteCommandLists, a staged copy whose completion is not confirmed
no longer releases the upload buffer, command list, allocator, queue, fence,
or destination. It logs a warning and keeps them alive, unless the device was
removed or the fence already completed. test_xcrdapi forces that path with
BX_XCRDAPI_COPY_TIMEOUT_MS=0 and BX_XCRDAPI_DEFER_COPY=1.

WIDL_EXPLICIT_AGGREGATE_RETURNS is now a compile definition on the xcrdapi
and test_xcrdapi targets, because a define in synthetic_storage.h came after
windows.h had already set it.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:45:24 +00:00
Adeeb Rahman f0eb940504 Document Direct3D acceptance reproductions for #450
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-26 17:03:47 -05:00
jelly013 d30b676813 d3d12_xs: refuse ACCC-only shaders even without the bridge
Review of #478: with no bx_shader_bridge.dll, the gate passed every
shader through, and the structural check now accepts an ACCC chunk, so
an ACCC-only container reached D3DMetal, which crashed the process
(access violation) instead of returning an error.

- Without the bridge, a container with an ACCC chunk tag and no DXIL
  chunk that fits is refused with E_NOTIMPL. This uses a bounds-checked
  chunk scan and is logged as decision=reject_accc_only_unclassified.
  Other shaders still pass unclassified.
- Drop the bare-name LoadLibraryW fallback. The bridge is loaded only
  by full path beside d3d12_xs.dll, where build-shims.sh now stages it
  (#484), so the EXE directory and PATH cannot supply another copy.
- test_shader_gate reruns itself with --no-bridge from a scratch
  directory holding d3d12_xs.dll and its imports but no bridge. DXIL
  must still run there and ACCC-only must get E_NOTIMPL. Removing the
  new refusal brings back the crash, and the fixture reports it.
- ADR 0008 and the changelog describe the no-bridge behaviour and the
  build-shims staging.

Refs #466

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:33:07 +01:00
Ateş 4a585a79c6 Merge pull request #475 from sahib453/track-a/461-run-signal-cleanup
Closes #461

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 00:32:26 +03:00
ates b95b2c92a8 Merge current main and retain both changelog entries
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 00:29:39 +03:00
Ateş d38c5253c6 Merge pull request #490 from MacosPorters/track-d/479-harness-pid-path
[Track D] Handle apostrophes in the harness test PID path
2026-11-27 00:28:19 +03:00
jelly013 077e7d2f4e Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 22:27:42 +01:00
Ateş 6fb171b247 Merge pull request #489 from jelly013/track-a/484-bridge-staging
[ABI] + [M2-A] Build, stage and verify bx_shader_bridge.dll in build-shims (#484)
2026-11-27 00:26:55 +03:00
ates 482293fd35 Pass the harness PID file as a probe argument
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 00:25:28 +03:00
atharvranjan 993cd222a4 Merge pull request #480 from sahib453/track-d/479-harness-test-timing
[Track D] Stop d3dmetal-harness runner tests racing probe start-up (#479)
2026-11-26 15:24:29 -06:00
jelly013 54b295434e Merge remote-tracking branch 'upstream/main' into track-a/484-bridge-staging
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 22:09:36 +01:00
jelly013 8141b8e282 build-shims: build, stage and verify bx_shader_bridge.dll
scripts/build-shims.sh builds shader-transpiler/crates/dxbc-accc for
x86_64-pc-windows-gnu, linked with abi/defs/bx_shader_bridge.def, and
places it in build-shims/bin as bx_shader_bridge.dll. The existing
verifier then checks it like every shim: export directory name, exact
exports, ordinals, no forwarders, no MinGW runtime imports. It now
reports 17 DLLs and 111 exports.

cargo and rustc are resolved through rustup when present, and the
build always goes to <repo>/target. A rustc without std for the
Windows target stops the script with the rustup command to run; the
bridge is never skipped. The CI job installs that target with its
pinned toolchain.

d3d12_xs's shader format gate (#466) can then load the bridge from
build-shims/bin without a manual copy.

Closes #484

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:08:29 +01:00
jelly013 ba9a053b5c [ABI] Add the bx_shader_bridge.dll export list
abi/defs/bx_shader_bridge.def freezes the three entry points of
abi/include/bx_shader_bridge.h for bx_shader_bridge.dll, the x86-64
Windows build of shader-transpiler/crates/dxbc-accc (#445). Linking
with it also gives the DLL its export directory name. abi/README.md
notes that this is the one .def whose DLL is not under shims/.

build-shims.sh verifies every .def against a built DLL, so this
commit lands together with the next one, which builds the bridge.

Refs #484

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:08:29 +01:00
jelly013 f6e0afeab1 Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 22:07:58 +01:00
sahib453 f34b70dd45 Merge main and keep both changelog entries
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:34:37 +05:30
sahib453 e71fca720a Merge main and keep both changelog entries
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:34:27 +05:30
atharvranjan 83391f57be Merge pull request #487 from MacosPorters/track-e/481-gameinput-callbacks
[M2-E3] gameinput: implement IGameInput callback lifecycle and SetFocusPolicy (#481)
2026-11-26 15:04:06 -06:00
atharvranjan 8877bff9f2 Merge pull request #488 from MacosPorters/track-a/482-stage-gameinput
[M2-A2] bx-cli: stage GameInput.dll in system32 with safe Wine builtin stub replacement (#482)
2026-11-26 15:02:15 -06:00
sahib453 68d4b449f2 Merge main and combine the timeout and staging changes in cmd_run
Resolves the conflict with #477: staged names are still collected, the
guest's share of --timeout is computed from active (non-suspended) time
and still refuses to launch when initialization used all of it, and the
diagnostics #477 added after the signal handlers are installed go
through the non-panicking helper.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:27:52 +05:30
sahib453 daeeaeae34 Merge main; correct the changelog claim and clean up after a failed kill test
Addresses review of #480: the changelog no longer says the old kill
test passed with only the kill removed (it passed only with both the
kill and the wait removed). A PidFile guard removes the pid file and
kills the recorded process when the test fails.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:26:47 +05:30
sahib453 3b3e9f1c05 Record the CrossOver Preview confirmation in the changelog
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:22:22 +05:30
ates f016960021 [M2-A2] bx-cli: stage GameInput.dll in system32 with Wine stub backup (#482)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 23:47:33 +03:00
ates cd72ef8ec3 [M2-E3] gameinput: implement device-callback lifecycle and SetFocusPolicy (#481)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 23:47:28 +03:00
devil8blade 6308fdc046 [M2-C1] Back configured D3D12 regions with one WRITE_BACK heap (#464)
The configured region is one shared WRITE_BACK/L0 heap with a persistent map. CreateHeap of that size returns it, and cpu_pointer in the config block publishes the address. An unrecognised parameter block stays a logged S_OK and is left unchanged.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 20:45:40 +00:00
devil8blade cf084e246b [M2-B1] Batch XCRDAPI transfers into D3D12 buffers (#467)
One Submit runs queued file reads in order into CPU memory, mapped upload
buffers, and default buffers. LZ, BCPack, and GDeflate complete as E_NOTIMPL.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 20:45:28 +00:00
jelly013 1571cf75c0 Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:44:27 +01:00
Ateş 52e786664d Merge pull request #476 from jelly013/track-d/445-guest-shader-bridge
[M2-D] dxbc-accc: reach Windows guests as bx_shader_bridge.dll (#445)
2026-11-26 23:40:30 +03:00
Ateş b22ec27c79 Merge pull request #477 from sahib453/track-a/474-staging-ownership
[Track A] Keep system32 shim staging from overwriting files it did not create (#474)
2026-11-26 23:39:16 +03:00
sahib453 0749dcf236 Address review: stub visibility, link entries, partial staging
A bottle that launched from a different prefix fails the run only when
the staged shims cannot be found with the same contents there; a
private stub linking back to the managed prefix is accepted. The
destination entry is inspected without following links, so a dangling
symbolic link is a foreign entry and is left alone. New files are
installed without replacing anything. Temporary copies are all written
first and each installed file is recorded in the manifest before the
next, so a later failure leaves earlier files owned.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:06:27 +05:30
sahib453 01a7435d35 Address review: budget pauses across phases, detect replaced logs
A pause during wineboot is no longer charged to the guest's share of
--timeout: supervise reports total suspended time and cmd_run subtracts
it from the wall clock. The trace summary recognizes the pre-run log by
file identity and by the bytes before the old end instead of by size,
so a log replaced by an equal or larger file is summarized in full.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:04:08 +05:30
atharvranjan b096424f33 d3d12_xs: fix presentation timeout semantics and strengthen the frame test
Present now waits for the current buffer before calling the host, so
ERROR_TIMEOUT means nothing was presented. A timeout after the host
Present returns BX_PRESENT_E_NEXT_BUFFER_BUSY. WaitForIdle counts lock
acquisition against its timeout, and same-thread re-entry is refused. The
leak-on-timeout path now returns the queue proxy reference.

The fixture checks host buffer identity, per-frame present counts, both
timeout results, the leak path, rejection log records and the swapchain
release count against a host-only control. run_controls.sh checks each
negative control's failing stage.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 14:33:13 -06:00
sahib453 2cc44b8318 Stop d3dmetal-harness runner tests racing probe start-up
kills_a_probe_that_exceeds_the_timeout and
a_descendant_holding_the_pipes_cannot_outlast_the_deadline gave a
freshly written script 300 ms and 500 ms to start and print, and the
first failed intermittently with empty stdout (#479). Both now use a
2 s deadline. The kill test also checks that the probe ran until the
deadline and that its process is gone afterwards. Test-only change.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:00:21 +05:30
jelly013 ec65d79726 test_shader_gate: require the bridge from d3d12_xs.dll's directory
Check that bx_shader_bridge.dll was loaded from the directory of
d3d12_xs.dll rather than through the EXE's directory, so running the
fixture with the EXE outside the shim directory exercises the lookup
the shim is meant to use (review of #476).

Refs #466

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 21:28:43 +01:00
jelly013 238daa6b25 dxbc-accc: tighten the guest build and check from review
guest/build.sh:
- Always build into, and copy from, <repo>/target, whatever
  CARGO_TARGET_DIR says, so a stale DLL can no longer be packaged.
- Resolve cargo and rustc through rustup, check that this rustc has std
  for x86_64-pc-windows-gnu, and print which rustc was used.
- Check the whole Export Address Table the way build-shims.sh does:
  every populated entry must be a direct RVA owned by one of the three
  names, so an ordinal-only extra or a forwarder fails. Imports must be
  Wine-provided system DLLs from an allowlist.

guest/check_bridge.c:
- Load the DLL by full path from the EXE's own directory.
- Check the exact DXIL and ACCC chunk sizes and the root signature
  flag, derived from the program's own chunk-table walk, and the
  digest against header bytes 4..20 for every container.
- Add a container with trailing bytes, checking that only the declared
  container is reported and copied.

The README documents how a calling shim must locate the bridge: by
full path from its own directory, not by bare name. It also records
that CI does not build the bridge yet.

Refs #445

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 21:27:51 +01:00
jelly013 7815a947e5 Merge remote-tracking branch 'upstream/main' into track-d/445-guest-shader-bridge
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:27:01 +01:00
jelly013 77dde94aa8 Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:23:19 +01:00
Jelly 99bfbc26ef [M2-E2] Offline XGameSave and XPackage through QueryApiImpl (#472)
QueryApiImpl now serves offline XGameSave and XPackage as COM IUnknown
objects under BetterXen synthetic keys (shims/xgameruntime/synthetic_keys.h),
backed by bottle-local storage. Public Microsoft.GDK.Windows com_dispatch.cpp
wiring remains tracked in #468.

- XGameSave: provider init, containers, updates, blob writes, async submit
  and read, enumeration, and parent-child handle cascade close. Saves are
  isolated per SCID under C:\bx_pls\<exe_hash>\saves\<scid_hash>\ with
  atomic temp-file + MoveFileExW replacement, cross-process named mutex
  serialization, FILE_SHARE_DELETE readers, strict BXGS format validation,
  256-byte blob-name limits counted toward the 16 MiB update cap, and
  E_GS_OUT_OF_LOCAL_STORAGE mapping.
- XPackage: treats the running executable's directory as the installed
  package (BXPKG<16 hex> identifier, XPackageKind::Game, and mount queries).
- Lifetimes & XAsync: generic AsyncOp support with runtime generation guard
  before execute(), disjoint handle tag ranges, and full handle/result
  cleanup on final XGameRuntimeUninitialize.
- Tests: tests/conformance/test_xgameruntime_saves covering round-trip,
  SCID isolation, crafted corrupt files, atomic replace, 64 threaded +
  160 cross-process submits, uninitialize memory release, and UTF-8 paths.

Refs #468

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 23:21:19 +03:00
jelly013 884f5398e7 d3d12_xs: M2 shader format gate at pipeline creation
CreateComputePipelineState and CreateGraphicsPipelineState now pass
every stage through bx_shader_bridge.dll (#445) and log one
shader_gate JSONL record per stage: container kind, stage, shader
model, chunk sizes, SFI0 feature flags and PSV0 wave lane range.

DXIL and dual containers reach the host as the bridge's prepared
copy. ACCC-only containers are refused with E_NOTIMPL before the host
is called. Legacy DXBC and unclassifiable input pass unchanged. Stages
needing a wave wider than 32 lanes or 64-bit atomics also log
shader_d3dmetal_gap, the cases #453 measured as created but not run.
The bridge is loaded at run time; when it is missing, that is logged
once and shaders pass unclassified.

tests/conformance/test_shader_gate runs a real DXC SM 6.6 compute
shader through d3d12_xs with a full readback check, requires E_NOTIMPL
for ACCC-only compute and graphics shaders, and checks the logged
wave64 and 64-bit-atomic constraints.

docs/adr/0008 records the evidence and proposes Branch D1 for M3.

Closes #466

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 21:19:28 +01:00
sahib453 1ec92916b9 Keep system32 shim staging from overwriting files it did not create
Fixes the three points of #474 in bx-cli run. Staging records what it
wrote in a .bx-staged manifest (one SHA-256 per file) and replaces only
files listed there and unchanged since; any other same-named file stops
the run before anything is written. For a named bottle the prefix is
re-resolved after the run and a launch in a different prefix is
reported and fails the run. When initialization uses the whole
--timeout the guest is not started. Adds 9 unit tests.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 01:19:53 +05:30
jelly013 9d504d12d7 dxbc-accc: reach Windows guests as bx_shader_bridge.dll
Shims that see shader bytecode run as x86-64 PE32+ DLLs inside
CrossOver and cannot load the arm64 host library. Build this same crate
for x86_64-pc-windows-gnu instead: its cdylib becomes
bx_shader_bridge.dll, exporting exactly the three bx_shader_bridge.h
entry points, with no MinGW runtime DLL dependency. There is no second
implementation to keep in sync.

guest/build.sh builds the DLL, checks its exports and imports, and
builds check_bridge.exe, a C guest program compiled against the frozen
header. It sends a real DXC SM 6.6 blob and seven synthetic containers
through the DLL, checks classification, prepare and free, and prints a
DXIL vs. ACCC count. It passes under CrossOver 26.3 in a prefix and a
D3DMetal bottle.

The abi/defs export list, staging in build-shims and the d3d12_xs PSO
hook (#466) are separate changes.

Closes #445

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 20:43:56 +01:00
sahib453 e75b4131a3 Make bx-cli run cleanup robust to signals and closed streams
Fixes the six points of #461: the environment's wineserver is stopped
before anything is reported, and stop-path diagnostics no longer use
panicking print macros; signals inherited as ignored stay ignored;
SIGQUIT stops the guest group and environment like SIGINT; SIGTSTP is
passed to the guest group and suspended time does not count against
--timeout; cleanup wineserver commands run in their own process group;
the trace summary covers only what this run appended; and
THIRD_PARTY_NOTICES.md names libc consistently and includes its MIT
text. Adds 7 unit tests with stub launchers and servers.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 01:11:47 +05:30
Ateş f7fb52bc56 Merge pull request #455 from Scarlet-Noble/track-f/453-d3dmetal-gpu-limits
[M2-F] D3DMetal GPU limits research and test_d3dmetal_gpu_limits fixture (#453)
2026-11-26 22:22:22 +03:00
atharvranjan ec2170d480 Merge main into track-f/453-d3dmetal-gpu-limits
Bring in main at cc5ce59 and resolve three documentation conflicts:

- CHANGELOG.md: keep the #453 entry above the entries added on main.
- docs/README.md: keep both new research links (swapchain references
  and D3DMetal GPU limits).
- docs/roadmap.md: take main's milestone table, including the verified
  M0/M1 status and the expanded M2 row, and append only the two
  measured-constraint links from this branch to the M2 and M3 rows.

No source, shader, header or research-note content changes relative to
either parent.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 13:16:44 -06:00
atharvranjan f2af367da6 [M2-C2] d3d12_xs: add a swapchain presentation bridge and frame conformance test
The proxied command queue answers a BetterXen-defined IID with a tear-off
that creates a flip-model swapchain on a Win32 window over the host's
IDXGISwapChain3. This is not the console's PresentX and claims no binary
compatibility with it. No export or abi/ file changes.

The bridge waits (bounded) for the next back buffer, waits for the GPU
before releasing, and refuses presents that D3DMetal 3.0 was observed to
accept with S_OK (sync interval above 4, any flag, destroyed window).

test_d3d12_presentx renders and presents 12 frames, checks every read-back
pixel against CPU-computed values, and compares swapchain lifetime with a
host-DXGI control.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 12:46:56 -06:00
Ateş cc5ce59d21 Merge pull request #463 from MacosPorters/track-f/m2-docs-sync
[M2-F] Update README and roadmap for M1 completion and M2 kickoff
2026-11-26 21:35:40 +03:00
ates 61fc3590b2 Merge remote-tracking branch 'origin/main' into track-f/m2-docs-sync
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:34:31 +03:00
Ateş 58fc63c7ec Merge pull request #462 from MacosPorters/track-e/456-query-api-impl-dispatch
[M2-E] Public GDK COM QueryApiImpl dispatch in xgameruntime.dll (#456)
2026-11-26 21:33:40 +03:00
ates 600a0ab08f Merge remote-tracking branch 'origin/main' into track-f/m2-docs-sync
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:31:51 +03:00
ates cda66a57f2 Merge remote-tracking branch 'origin/main' into track-e/456-query-api-impl-dispatch
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:31:48 +03:00
ates a5c1995f21 Link Wave 2 M2 issues (#464-#469) in README progress board
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:25:25 +03:00
atharvranjan 868444ed30 Merge pull request #458 from Scarlet-Noble/track-a/457-system32-staging
[M1-A] Stage xgameruntime.dll and its shim imports into system32 (#457)
2026-11-26 12:22:56 -06:00
atharvranjan 510b6d1d66 Supervise wineboot and tolerate partial shim folders in system32 staging (#457)
A --shims folder without xgameruntime.dll made every bx-cli run fail; it is now reported and skipped.

wineboot --init ran before the signal handlers and outside --timeout, so Ctrl-C during a first run left wineserver and its services running. It now runs under the supervisor and shares the --timeout budget.

The temporary staging file name is now per process, so concurrent runs cannot publish each other's partial write.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 12:22:42 -06:00
ates 92c2ff7add Update README and roadmap for M1 completion and M2 kickoff
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:19:26 +03:00
ates 39baf092a3 Wire offline IXUser change-event and query slots in com_dispatch
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:17:41 +03:00
ates 0a30562cde Implement public GDK COM QueryApiImpl dispatch in xgameruntime.dll (#456)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:15:21 +03:00
Vicente Abarca fb56805459 Stage xgameruntime.dll and its shim imports into system32 (#457)
GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll",
NULL, LOAD_LIBRARY_SEARCH_SYSTEM32), which never searches WINEPATH, so
the bootstrap failed with E_GAMERUNTIME_DLL_NOT_FOUND before the #441
loader exports were reached.

bx-cli run now copies xgameruntime.dll into the environment's
drive_c/windows/system32 before launch. It also copies every BetterXen
shim that DLL imports, found with bx-probe (today bx_runtime_veh.dll),
because the restricted search also applies to a DLL's own imports.
Copies are idempotent and replaced through a rename, and bx-cli prints
what it staged. A bare --prefix with no system32 is initialized with
wineboot --init under the same isolated environment. A bottle with no
system32 fails with a hint.

Adds 8 unit tests for staging and the dependency walk, and
tests/conformance/test_system32_staging with a --expect-missing
negative control.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 15:00:38 -03:00
Vicente Abarca 1eb963d883 Address review of test_d3dmetal_gpu_limits and its note (#453)
Fixture:
- check_lock64 keeps its upload buffer alive until the list that copies
  from it has run.
- The spin lock takes an acquire DeviceMemoryBarrier after winning the
  lock, before reading the data, as well as the release barrier.
- A check that fails partway through recording closes and resets the
  list (abandon) instead of leaving stale commands for the next check.
- wave.control checks what D3D12 guarantees: one wave width for every
  thread, and lane indices forming a permutation within each wave, with
  waves identified by WaveReadLaneFirst(id.x). It no longer assumes
  lane == i % width.
- Skips with exit 77 when shader model 6.6 is unavailable or the query
  fails.
- submit checks Signal, SetEventOnCompletion and the Reset calls.
  Resources the GPU may still use are leaked rather than released after
  a hung or removed queue.

Note: the measured constraints are separated from the reports taken
from a commercial title. The reports move to an "Unverified reports
(not evidence)" section, each with the synthetic workload that would
verify it. The M2-gate inference is dropped, and the roadmap rows link
only the measured section. The results are re-measured after the fixes:
with the acquire fence, the 64-try cap drops 96-108 of 512 updates. The
1024-try cap is still exact.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 14:53:44 -03:00
Ateş ac0fd2e502 Merge pull request #454 from MacosPorters/track-a/408-bx-cli-supervision
[M1-A1] Supervised timeout, cleanup and trace summary for bx-cli run
2026-11-26 20:45:44 +03:00
ates 73c190d725 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 20:43:46 +03:00
ates f3c2b7fe34 Re-resolve bottle prefix on timeout/signal cleanup for managed first-launch stubs
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:43:20 +03:00
Ateş 4333a7cc5e Merge pull request #452 from skakwy/track-a/437-api-set-shims
Add API-set resolution fixture and ADR 0007 (#437)
2026-11-26 20:42:35 +03:00
ates 66e9351410 Require valid module lookups in test_apiset_resolution and accept ADR 0007
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:42:05 +03:00
Ateş 060083cc56 Merge pull request #441 from devil8blade/track-e/439-xgameruntime-dynamic-api-impl
[M1-E3][ABI] Dynamic GDK loader exports in xgameruntime.dll
2026-11-26 20:36:09 +03:00
Vicente Abarca 120a5ec5f6 Document D3DMetal GPU limits and add test_d3dmetal_gpu_limits (#453)
Adds docs/research/d3dmetal-gpu-limits.md: the D3DMetal and Apple GPU
constraints a shader translator has to handle (wave64 splitting, 64-bit
atomics and lock emulation, the 32 KiB mesh output limit, an Apple
shader compiler crash on early-merged output stores, and
OpenExistingHeapFromAddress). Each item is marked as either measured by
the new fixture or reported from local builds of a commercial title. It
is linked from the M2 and M3 roadmap rows and from the docs index.

Adds tests/conformance/test_d3dmetal_gpu_limits: an original D3D12
compute fixture that talks to the host d3d12.dll directly. It has four
original HLSL kernels with committed DXC 1.9.2609 output, and
shaders/compile.sh regenerates them. Expected values are computed on
the CPU.

On an Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from
source, D3DMetal 4.0b3) the WaveSize(64) pipeline and the kernels using
SM 6.6 64-bit atomics are created but never run. The bounded lock
emulation is exact at a 1024-try cap and drops updates at 64 tries.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 14:32:09 -03:00
atharvranjan 7d7249ee8b Clean up the bottle CrossOver actually launches; limit --backend to bottles
- Locate --bottle through CrossOver's CXBottle module with the launch's
  environment, so CX_BOTTLE_PATH, configured paths and managed bottles are
  stopped correctly. Refuse to launch if it cannot be located.
- Require --bottle for --backend: a bare prefix loads Wine's own D3D12.

Both reproduced by atesahmet0 on #454.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:19:36 -06:00
atharvranjan d0395a61da Add supervised timeout and cleanup to bx-cli run (#408)
- --timeout, and cleanup on timeout, SIGINT, SIGTERM or SIGHUP: stop the
  launcher process group, then wineserver for the selected bottle or prefix.
  wineserver -k exit 1 (nothing running) is accepted only if -w succeeds.
- Pass shim overrides with bin/wine --dll and --backend with --env in bottle
  mode, because bin/wine discards WINEDLLOVERRIDES and applies bottle
  settings over the environment. First found by jelly013.
- Print the trace summary after a run with --log.
- Record the libc dependency and a one-host D3D12 swapchain observation.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:01:28 -06:00
skakwyandClaude Sonnet 5.5 2eb59e033b Add API-set resolution fixture and ADR 0007 (#437)
test_apiset_resolution imports one export from each of the six win32_bridge
API-set DLLs through the PE import directory and reports, per name, whether a
BetterXen shim file or a host module serves it, and which module the import
address table slot is bound to. --expect host (default) or --expect shim
selects the outcome that passes.

On CrossOver 26.0 all six names are served by the host (twinapi.appcore.dll
for PSM, user32.dll for ntuser) and +loaddll shows no Loaded record for any
shim file. ADR 0007 proposes relying on Wine's built-ins and records that
evidence; a CrossOver 26.3 re-run is still needed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: skakwy <nils_0805@icloud.com>
2026-11-26 17:53:14 +01:00
devil8blade e7899574ab Keep XErrorReport logs valid UTF-8 and record loader provenance
Invalid bytes are written as \u00XX and a multi-byte character is not
split when the detail buffer fills. The six loader prototypes are
recorded as BetterXen-defined. The two changelog notes are one entry.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:25:51 +00:00
devil8blade 18178da12c Address review: surface unsupported QueryApiImpl in trace, null out on failure
Unsupported and mismatched QueryApiImpl queries keep their structured log
and also call BX_STUB_LOG so bx-cli trace lists them. Failure paths clear
the output pointer. XErrorReport uses the public void signature.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:05:11 +00:00
devil8blade 2e895e0f9b Export GDK dynamic loader entry points from xgameruntime.dll
The static loader resolves InitializeApiImpl, InitializeApiImplEx,
InitializeApiImplEx2, UninitializeApiImpl, QueryApiImpl, and XErrorReport
with GetProcAddress. Those initialize entry points share the existing
runtime refcount with XGameRuntimeInitialize and
XGameRuntimeInitializeWithOptions. UninitializeApiImpl releases that same
state. QueryApiImpl dispatches the offline families this DLL already
implements and logs any other class or interface. XErrorReport records
the code and message and does not terminate the process.

Closes #439

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 15:38:34 +00:00
257 changed files with 43636 additions and 11346 deletions

No files matched your search

+1 -5
View File
@@ -31,7 +31,7 @@ jobs:
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install Rust toolchain
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
rustc -vV
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
run: |
@@ -42,10 +42,6 @@ jobs:
binary=target/aarch64-apple-darwin/debug/bx-cli
file "$binary"
test "$(lipo -archs "$binary")" = arm64
- name: Check hybrid script syntax (no CrossOver on the runner, nothing launched)
run: |
for script in scripts/hybrid/*.sh tests/conformance/test_*/build.sh; do sh -n "$script"; done
python3 -c 'import ast, glob; [ast.parse(open(f).read(), f) for f in glob.glob("scripts/hybrid/*.py") + glob.glob("tests/conformance/test_*/*.py")]'
- name: Install mingw-w64 and CMake
env:
HOMEBREW_NO_AUTO_UPDATE: 1
+2
View File
@@ -29,6 +29,8 @@ jobs:
fetch-depth: 0
- name: Install PyYAML
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
- name: Unit-test the hygiene checks
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
- name: Check documentation and workflow files
run: python3 scripts/audit/docs_hygiene.py --require-yaml
- name: Remind about the changelog (advisory)
+27
View File
@@ -0,0 +1,27 @@
name: Merge policy audit
# Detects a pull request merged by its own author (AGENTS.md §7, "Merge
# eligibility"). GitHub rulesets cannot block this, so the run fails after the
# merge. It is not a required check and never checks out pull request code.
on:
pull_request_target:
types: [closed]
branches: [main]
permissions: {}
jobs:
author-merge:
name: Author did not merge
if: github.event.pull_request.merged == true && github.event.pull_request.merged_by.login == github.event.pull_request.user.login
runs-on: ubuntu-24.04-arm
timeout-minutes: 2
steps:
- name: Report a self-merge
env:
PR: ${{ github.event.pull_request.number }}
AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
echo "::error::Pull request #$PR was merged by its own author, $AUTHOR. A maintainer other than the author must merge (AGENTS.md section 7)."
exit 1
+122 -45
View File
@@ -4,34 +4,87 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
---
## 0. First-Time Contributor Onboarding
## 0. What to Do When Told "Work"
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
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).
1. **Preflight host & tools:**
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
2. **Discover & pick an unclaimed issue:**
- Query ready issues in the active milestone:
```sh
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
```
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
3. **Claim & isolate:**
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
4. **Implement strictly in scope:**
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
5. **Verify locally (including hosts without CrossOver):**
- Run every command in Section 8 and fix all warnings/failures before stopping.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
6. **Review & submit PR:**
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
**"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: make the machine ready yourself
```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.
1. **Your person's pull requests that need attention.**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,isDraft,reviewDecision,statusCheckRollup,mergeStateStatus
```
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 **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. **A handoff issue of the current stage.**
```sh
gh issue list --repo MacosPorters/betterxen --state open --label handoff --label "stage: <current>" --json number,title,labels
```
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. **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. **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 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 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.
**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.
---
@@ -64,8 +117,8 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
### Cross-Track `[ABI]` Rule
- Never edit another track's directory inside a feature PR.
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
- For issue-claimed contributor work, stay inside your issue's track directory; if your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first so provider and consumer tracks can implement in parallel.
- Maintainer-directed compatibility and startup-unblocking tasks may touch the required shim and `tests/conformance/` directories across tracks without a pre-existing issue claim. They must not overlap another contributor's active claim or open PR without that contributor's or a maintainer's recorded agreement, any new cross-DLL helper or export still goes through an `abi/`-only `[ABI]` PR first, and independent review (Section 5) still applies.
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
---
@@ -81,9 +134,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
## 4. Dependencies, Licensing & Provenance
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
_Reserved — policy migration in progress._
---
@@ -97,26 +148,34 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
---
## 6. Legal & Clean-Room Rules
## 6. Compatibility Evidence & Legal Boundaries
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
---
## 7. Claiming, Git Safety & Changelog
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
3. **Isolate with branches or worktrees:**
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
```
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
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.
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
### Merge eligibility
Four roles are separate: the **original author** (who opened the PR), **corrective contributors** (who later push to its branch), **independent approvers**, and the **merger**.
- The original author never merges their own PR. Any other maintainer may merge once required checks pass, at least one approval is current and blocking review conversations are resolved.
- Maintainers may resolve conflicts, correct defects, update documentation and push fixes to a contributor's PR branch where GitHub permissions allow. Doing so does not disqualify them from merging.
- Any push that changes the PR dismisses earlier approvals. After a **routine** push (conflict resolution that changes no behaviour, changelog correction, minor documentation fix), one new approval is enough and may come from the maintainer who pushed it, if they are not the original author. No further approval is required beyond the ruleset.
- **Substantive** implementation changes need independent review (Section 5): the approval must come from someone who did not write them. A maintainer who wrote substantive corrections may merge after another person has approved those corrections, but may not approve them. If in doubt, treat a change as substantive.
- A coding agent acts as the person it works for and merges only with that person's authorization.
The `Protect main` ruleset enforces pull requests, one approval, dismissal of stale approvals, resolved conversations, the required CI checks and no force push or deletion, with no bypass actors. GitHub cannot enforce two rules above: who may merge (`Merge policy audit` only fails after an author self-merge) and whether an approver wrote part of the change.
---
@@ -129,8 +188,9 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
# 2. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust bx_shader_bridge.dll, and
# build the auto-discovered conformance EXEs
# (strictly verifies all 17 .edata Export Directories: names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
scripts/build-shims.sh
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
@@ -141,3 +201,20 @@ target/debug/bx-cli trace /tmp/bx-test.jsonl
# 4. Repository Markdown link & hygiene check
python3 scripts/audit/docs_hygiene.py
```
---
## 9. AI Agent Efficiency & Resource Management
These rules apply to every coding agent, whatever its model, vendor or plan. Saving resources never justifies skipping necessary verification, fabricating or assuming results, weakening a security, legal or provenance safeguard, or bypassing independent review. Where this section and Sections 4–8 appear to conflict, Sections 4–8 win.
- **Spend in proportion:** Keep token consumption, API usage, reasoning effort and compute cost as low as correctness allows.
- **Reuse what is still valid:** Reuse conversation context, repository knowledge, review findings and verification evidence. Evidence is valid only for the revision and environment it was recorded on; re-run whatever a later change could affect.
- **Read narrowly:** Inspect relevant files and incremental diffs instead of rescanning the repository. Batch independent tool calls and GitHub API requests where practical.
- **Delegate sparingly:** Avoid unnecessary subagents, duplicate investigations and overlapping responsibilities. Independent review (Section 5) is not duplicate work.
- **Reasoning effort:** Default to low for routine tasks and for helper subagents; raise it only when technical complexity justifies it or the user asks.
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and eligible (Section 7), instead of stopping at intermediate reports. This grants no permission beyond Section 7.
- **Escalate real uncertainty:** Raise genuine doubt about ABI compatibility, memory safety, concurrency, security, GPU synchronization, licensing or architecture with a maintainer rather than guessing.
+260 -13
View File
@@ -9,23 +9,241 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Fixed
- Fixed `bx-cli stop` failing on an idle environment, leaving its session marker in place: `wineserver -k` exits 1 when no server is running.
- `bx-cli run` again configures the shim overrides from `build-shims/bin` when `--shims` is not given, as `main` does.
- `bx-cli run --log` now prints the trace summary to stderr when the run ends, leaving the JSON record alone on stdout (#408).
- `bx-cli run` and `bench` now refuse a CrossOver build they have not been run against unless `--allow-untested-crossover` is given, and records carry `crossover_build_tested`. The notices record the contributor work carried from #405.
- Fixed `bx-cli run --bottle` losing DLL overrides, including those set for `--shims`: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll`. A requested `--backend` is also passed with `--env`, so a backend saved in the bottle's settings no longer replaces it. First found by jelly013 on #425.
- Fixed unattended crash handling in new test bottles: `create-test-bottle.py` now turns off Wine's crash dialog, which otherwise waits for a click until the run times out (observed: timeout at 240 s with the dialog, 2.8 s without).
- The acceptance suite now soaks Direct3D 12 as well as the Direct3D 11 control. One D3D11 soak stalled on a GPU event query after 9,183 frames; three reruns passed and the cause is unknown.
### 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.
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
- `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
- Added `docs/maintainer-testing.md` (build, acceptance, expected graphics, known limitations, cleanup) and a CI syntax check for the hybrid scripts.
- Strengthened the hybrid acceptance suite (#407): every injected rendering fault must now fail the specific gate it targets, the crash control allows for slow `winedbg` start-up, the suite includes the swapchain lifetime probe and the Shader Model 6 readback check (reported `NOT-RUN` without DXC, never as a pass), and a window hidden on another macOS Space is reported as such. `bx-cli doctor` again reports the recommended memory profile, D3DMetal presence and the shim cross-compiler.
- Recorded two local findings on Apple M4 with CrossOver 26.3, neither independently reproduced: under D3DMetal a new D3D12 swapchain starts with two references and survives the application's release, while the same binary on the `vkd3d` path starts with one and is freed; on the `vkd3d` path frames after about 437 each spend 2000 ms inside `Present`, and teardown then hangs.
- The migrated #405 work includes Adeeb Rahman's D3D11 compute-buffer readback workload (`ce9c10a`) and Bartosz Szczepański's GPU wired-memory fields in host receipts and run records (`0427465`).
- Moved #405's supervised runtime onto the six-track layout (#407): `bx-cli run`, `doctor`, `bench`, `stop` and the evidence commands now share one engine in `launcher/crates/bx-runtime`, replacing the unsupervised launch path. It adds timeout, stall, memory and output limits, a per-environment session lock with explicit recovery, cleanup limited to the selected environment, and JSON run records; `probe`, `shader` and `trace` are unchanged. `bx-cli run` now requires `--bottle` or `--prefix` (there is no shared `/tmp` default). The D3D11 and D3D12 workloads moved to `tests/conformance/`. Verified locally only; no independent reproduction.
- 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`:
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
- **The default APU heap** is 64 MB.
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
- **Samplers and page pools.**
- **Pipelines** through the shader gate.
- **Opt-in null rendering** (`BX_NULL_RENDER=1`): pipelines that cannot be built become null pipelines, and their draws and dispatches are skipped and logged.
- **Fences** at GPU addresses and GPU value writes.
- **`PresentX`** onto a DXGI swapchain.
- **Console page mappings:** `CopyPageMappingsX`, `CopyPageMappingsBatchX` and `ClearPageMappingsX`.
- **The full 1,384-byte Xbox command-list area.**
- **Opt-in dumps of presented frames** (`BX_PRESENT_DUMP`).
`test_d3d12_xbox_layout` checks the page mappings and the command-list area.
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
- `d3d12_xs.dll` gives titles Xbox-layout D3D12 objects ([ADR 0009](docs/adr/0009-xbox-layout-d3d12-objects.md)). A title built against the Xbox Series D3D12 header calls through function tables whose order differs from PC D3D12. `ID3D12Device` matches only up to slot 43, and `ID3D12Device11` has 139 slots. So before, every call past those slots reached the wrong PC method, and on a project-authorized target build the first such call jumped to address 0.
- **Objects and tables:** `BxXboxObject` (`shims/d3d12_xs/xbox_facade.{h,cpp}`) has the Xbox object layout and sets `m_OutOfLineFlags`. Its Xbox-order table forwards to the PC proxies. `shims/d3d12_xs/tools/gen_xbox_tables.py` generates the tables (`xbox_tables_generated.cpp`) from the Xbox header, used under Microsoft's authorization, and the toolchain's `<d3d12.h>`. It takes only slot order, names, IIDs and parameter types, and the header is not committed.
- **Slots:** a slot with an equivalent PC signature forwards with the PC types, unwrapping interface parameters and wrapping created objects. Every other slot logs `BX_VTABLE_STUB_LOG`.
- **Coverage:** the device chain up to `ID3D12Device11`, plus resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues. Command lists are not covered yet.
- **`CreateCommandQueueX`:** maps the Xbox queue description onto PC `CreateCommandQueue`.
- **Layout choice:** titles set `Version` in the device parameter block and get the Xbox layout. BetterXen's PC-layout fixtures pass a zeroed block and keep the PC proxy. The choice is logged as `xbox_layout`.
- **Phase 2:**
- **Command lists:** `ID3D12GraphicsCommandList8`, created through `CreateCommandListX` or `CreateCommandList`. Their zeroed put-buffer fields force the five inline fast paths through the table.
- **Embedded interface pointers:** `ResourceBarrier` and `CopyTextureRegion` unwrap the interface pointers inside their structures.
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` are emulated by a host timer (`frame_pacing.cpp`).
- **Generator fixes:** CRLF lines, a table-boundary overrun that hid `ID3D12GraphicsCommandList1`, nested SAL, and `FLOAT`.
- **Resources at title-chosen addresses:** `CreatePlacedResourceX`/`X1` create host shadow resources (`placed_x.cpp`), with buffer contents copied from the title's memory at creation. The resource reports the title's address from `GetGPUVirtualAddress`. Ongoing synchronisation, GPU-to-CPU copies, title-address translation in GPU calls and texture contents are not implemented yet.
- **Test:** `tests/conformance/test_d3d12_xbox_layout/` calls Xbox slots by number, with the slot numbers and offsets written out by hand from the header and the expected values taken from a PC-layout device. It also records a buffer copy through Xbox command objects, runs it on the GPU and reads the result back, and checks frame pacing. It fails against the previous DLL (8 checks against the Phase 1 build).
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
### Fixed
- `XCRDAPI.dll` Xbox DirectStorage fixes:
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
- `xmem.dll` follows the documented signatures of five exports (source: the authorized GDK documentation). Before, a title calling them as documented had its arguments misread: on a project-authorized target build, `XMemAllocatePhysicalPages` failed and the title's check broke into its crash reporter. `XMemAllocatePhysicalPages` accepts `MEM_64K_PAGES` (`MEM_2MB_PAGES | MEM_PHYSICAL`) as 64 KB pages, as Microsoft's public samples pass it; the `MEM_2MB_PAGES` bit alone is `XMEM_2MB_CLUSTERS`, still unimplemented and logged. `test_xmem_physical` adds the samples' shape: a `MEM_64K_PAGES` page mapped into a mappable reservation made with protection `0x2404`.
- **Signatures:** `XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray)`, `XMemFreePhysicalPages(NumberOfPages, PageArray)` (count by value), `XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray)` and `XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)` (parallel arrays, returns `BOOL`). `XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection)` takes five arguments, which supersedes the closed #518.
- **Pages and flags:** physical pages are always 64 KB. The four memory-bandwidth values are accepted. `XMEM_2MB_CLUSTERS` and mapping into `MEM_2MB_PAGES` reservations are not implemented: they log `BX_STUB_LOG` and fail with `ERROR_NOT_SUPPORTED`. Other flag bits fail with `ERROR_INVALID_PARAMETER`.
- **Mapping:** `XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)` reserves a placeholder, and `XMemMapPhysicalPages` maps into it. It replaces pages already mapped there, a NULL page array unmaps, and an unmapped range stays reserved and can be mapped again. Scatter checks every entry before changing any, and a 0 tag unmaps its slot. Mapping outside a mappable reservation is refused. A NULL address remains a BetterXen extension for synthetic fixtures: the shim picks the span, and unmapping it frees it.
- **Title-managed placeholders:**
- `XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)` reserves a placeholder the title splits itself with `VirtualFree(MEM_PRESERVE_PLACEHOLDER)`.
- `MEM_REPLACE_PLACEHOLDER` with `XMEM_MAPPABLE` turns a split part into a mappable range without a new reservation. It is refused unless the part is still a placeholder.
- `XMEM_GRAPHICS_32BIT_ADDRESS` keeps new reservations below 4 GB.
- The `PAGE_GRAPHICS_*` protection bits set a GPU view the host does not have, so mapped views use the low-byte CPU protection.
- Replacing a placeholder with committed memory is not implemented and logs `BX_STUB_LOG`.
- A project-authorized target build lays out its descriptor memory this way.
- **Tests:** `test_xmem_physical` is rewritten against the documented contracts, with constants written out from the documentation, and fails against the previous `xmem.dll`. `test_xmem`, `test_xmem_external_charge`, `test_d3d12_placed`, `test_d3d12_vmem_xbox`, `test_m2_first_frame` and `test_integration_boot` use the documented signatures.
- **Not covered:** `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` still differ from their documented signatures (#642).
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
- `d3d12_xs.dll!D3D12XboxCreateDevice` takes the documented four parameters `(pAdapter, pParameters, riid, ppDevice)`. Before, it took three `(params, riid, ppv)`, so a title calling it as documented had its interface ID treated as the out pointer, and the shim wrote through it. On a project-authorized target build that faulted on a write into read-only data. Source: the authorized GDK documentation of the function and of `D3D12XBOX_CREATE_DEVICE_PARAMETERS`. A NULL parameter block now fails with `E_INVALIDARG`, as documented. A non-NULL adapter is logged and the default host adapter is used, which is an inference, since BetterXen has no adapter objects. Of the parameter block only `Version` is read and logged. All fixtures that create a device pass a zeroed 80-byte parameter block. `test_d3d12_xs` checks the NULL-parameter refusal and that it clears the out pointer.
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
- `bx-cli`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
- `XCRDAPI.dll` completes a multi-request batch from one `Submit()` in queue order into CPU memory, mapped D3D12 upload buffers, and default buffers (a copy on the resource's device when the heap is not CPU-visible). If that copy has been submitted and its GPU completion is not confirmed, the shim keeps the destination and the copy's GPU objects alive and logs a warning, unless the device was removed or the fence already reached the waited value. The request still returns the failure HRESULT. LZ, BCPack, and GDeflate requests finish as `E_NOTIMPL` and log `BX_VTABLE_STUB_LOG`. `DStorageGetFactory` remains the only export (#467).
- M2 Shader Format Gate (#466). `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` classify every stage through `bx_shader_bridge.dll` (#445) and log one `shader_gate` JSONL record per stage: kind, stage, shader model, chunk sizes, `SFI0` feature flags and `PSV0` wave lane range.
- **Decisions:** DXIL and dual containers go to the host as the bridge's prepared copy. ACCC-only containers are refused with `E_NOTIMPL` before the host is called. Legacy DXBC and unclassifiable input pass unchanged. The bridge is loaded only by full path from `d3d12_xs.dll`'s directory. A missing bridge is logged once as `shader_bridge_missing`. Shaders then pass unclassified, but a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it.
- **D3DMetal gaps:** stages needing a wave wider than 32 lanes or 64-bit atomics also log `shader_d3dmetal_gap`, the cases #453 measured as created but not run. The structural check now counts an `ACCC` chunk as a shader chunk, so the gate decides it.
- **Test:** `tests/conformance/test_shader_gate/` runs a real DXC SM 6.6 compute shader through `d3d12_xs` and checks 256/256 output words. It requires `E_NOTIMPL` for an ACCC-only compute and graphics shader, and checks the logged wave64 and typed 64-bit-atomic constraints and every JSONL record. It then reruns itself from a directory without the bridge, which must still run DXIL and refuse ACCC-only. It passed on one Apple M5 Pro in a CrossOver 26.3 D3DMetal bottle. A bare prefix's vkd3d cannot load a DXIL converter, so the DXIL part needs the D3DMetal backend. `scripts/build-shims.sh` stages the bridge it needs (#484).
- **ADR:** [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) proposes Branch D1 for M3, with the evidence; it is pending maintainer acceptance.
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
- name rules, the write and read round trip, and the size limits;
- SCID isolation and enumeration;
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
- 64 threaded and 160 cross-process concurrent submits;
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
- `QueryApiImpl` also serves offline XGameSave and XPackage on the public COM class and interface ids, with slot order from [xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) commit `7090008692569aa6081e30dfdd9de58237741e24` (#468). The ids and slot order come from that documentation; its provenance is recorded in `docs/research/upstream-registry.md` and the component reuse matrix, pending maintainer acceptance. `XPackageMountWithUiAsync` / `XPackageMountWithUiResult` (`IXPackageImpl2` slots 37–38) now mount through the XAsync engine, like `XPackageMount`. `IXError` slot 3 now returns `false`, following the #492 review's observation that the GDK's static library continues only on `false`; that source lists the slot as unknown.
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
Everything else is printed as `OBSERVED:` lines. On one Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from source, D3DMetal 4.0b3), three runs gave the same outcomes, with 4/4 required checks passing each time:
- the `[WaveSize(64)]` pipeline is created but never runs;
- kernels using SM 6.6 64-bit atomics, on a typed UAV or a raw buffer, are created but never run, although the device reports support for them; a plain-store marker beside the atomics shows the skip;
- a 64-try lock cap drops 96–108 of 512 updates.
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
- `bx_runtime_veh.dll` handles illegal-instruction traps for CLZERO, MONITORX, MWAITX, RDPRU, EXTRQ and INSERTQ (#451). The decoder and fixture derive the encodings and expected results from the AMD Architecture Programmer’s Manual [volume 3](https://kib.kiev.ua/x86docs/AMD/AMD64/24594_APM_v3-r3.36.pdf) (24594, rev. 3.36) and [volume 4](https://kib.kiev.ua/x86docs/AMD/AMD64/26568_APM_v4-r3.25.pdf) (26568, rev. 3.25, EXTRQ pp. 139–140 and INSERTQ pp. 154–155).
- CLZERO clears a 64-byte cache line selected by RAX or, with the `67` prefix, EAX. An unwritable target is reported as a write access violation at the line address and the guest can repair the page and retry. One-shot Windows guard-page behavior is outside this emulation.
- MONITORX arms no host monitor. MWAITX yields once, so the EBX timer and ECX extensions have no effect. RDPRU approximates MPERF and APERF with the same timestamp rate and returns zero for unknown selectors. It clears the five flags specified by AMD and chooses zero for CF, whose value the manual leaves open.
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
- **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently.
- **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed.
- **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running.
- **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix.
- **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host.
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
- Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437).
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
- `xgameruntime.dll` exports BetterXen-defined `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, `UninitializeApiImpl`, `QueryApiImpl`, and `XErrorReport` so a static loader can resolve them. No public prototype for those six names was found. The documented `XGameRuntimeInitialize`, `XGameRuntimeUninitialize`, `XGameRuntimeInitializeWithOptions`, and `XGameRuntimeOptions` behavior is what the shared refcount follows. `QueryApiImpl` rejects a missing output or id, clears the output pointer on failure, dispatches the offline families this DLL already implements, and logs any other class through `BX_STUB_LOG` before `E_NOINTERFACE`. `XErrorReport` is `void` and writes only valid UTF-8, replacing an invalid byte with `\u00XX` and truncating on a character boundary. The DLL has 49 exports. This is not an Xbox hardware result (#439).
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
@@ -51,11 +269,19 @@ remains unsupported.
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
### Removed
- Removed the repository-wide provenance, third-party licensing and legal-boundary rules from `AGENTS.md`: §4's per-file license audit and proprietary-component restrictions, §6's "Conditions for target builds" (including lawful acquisition, no leaked or unauthorized builds, no decryption or circumvention, and "If any condition is unknown, do not use the build"), the §6 "Repository & clean-tree boundary" and "Legal boundary" rules, plus the earlier removals of §4's "Provenance first" and §6's "Never obtain or use" bullets. §4 is left as a placeholder pending a replacement policy; the §6 "Authorized compatibility evidence" and §5 honesty rules stay. Nothing in `CONTRIBUTING.md`, `docs/legal.md`, `docs/claims.toml`, the ADRs or the research registry was changed, so those documents still describe the previous policy.
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Updated the roadmap with the startup checkpoint, synthetic first-frame backing contract, and shared-budget correction. M3 and M6 memory work now has explicit eligibility and measurement criteria.
- Recorded the target-workload shader-corpus scan in the roadmap and [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) (2026-11-28). A read-only container scan of an authorized local test workload — structure only, no run, no extraction, not redistributed — found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, and 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable; its packaged shader archive exposes no plaintext `DXBC` and remains unclassified. `dxbc-accc` accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers with `FspxSectionOutOfBounds` because their section tables do not match the clean-room layout. The roadmap keeps D1, treats the upscaler's ACCC-only containers as a concrete D2 candidate gated on runtime submission (first-frame blocker before the first presented frame, M4 upscaling if only upscaling needs them), and records both parser gaps as Track D prerequisites. Build-specific details stay in a local evidence note. Runtime use is unmeasured: the recorded startup run wrote no `shader_gate` records.
- `dxbc-accc` reports an `FSPX` descriptor whose offset lands inside the 16-byte header or the descriptor table as `ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }`, not `FspxSectionOutOfBounds` (#599). The reserved region cannot hold section data under BetterXen's synthetic layout, so such a table does not follow that layout; it is not merely truncated. A section that runs past the payload end is still `FspxSectionOutOfBounds`. Both `inspect_dxbc` and the C ABI's `summarize_dxbc` path classify it the same way. The container is still refused: `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` keep returning `BX_SHADER_ERR_INVALID_BLOB` with output cleared, and the C ABI is unchanged, so the distinction does not yet reach `d3d12_xs` gate telemetry. One existing test case (offset 0 in a one-section table) now expects the new variant. New unit tests cover the reserved-region boundary, the out-of-bounds case, the unchanged C ABI refusal, and 4,096 seeded random `FSPX` tables without a panic. Synthetic bytes only; the `FSPX` layout itself is unchanged and remains synthetic (`CLAIM-XBOX-ISA-ABI`, class U).
- Added a model-agnostic "AI Agent Efficiency & Resource Management" section to `AGENTS.md` (§9), absorbing the earlier subagent reasoning rule: agents reuse valid evidence, read and verify narrowly and avoid redundant work, without weakening required verification, safeguards or independent review.
- Changed contributor and agent rules (`AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md`): agents now pick work in priority order (fix their own open PRs, then take an unclaimed issue, then review others' PRs); lawfully obtained, maintainer-approved target builds may be inspected locally as compatibility evidence where license terms and law permit, with no decryption or circumvention, and leaked or unauthorized material stays excluded; maintainer-directed tasks may cross track directories without a prior issue claim, while active claims, `[ABI]`-first changes and independent review still apply. Policy only; no compatibility claim.
- Corrected `shader-transpiler/crates/dxbc-accc/README.md` (#498): its "Not done here" section listed the export list, the `build-shims.sh` staging and the `d3d12_xs` PSO hook as outstanding, but those shipped (#445, #484, #466). The section now describes each one and credits the issue that delivered it. Documentation only.
- Documented independent Direct3D acceptance results on CrossOver 26.3 and CrossOver Preview 27, including D3D12 swapchain retention and Wine presentation stalls (#450).
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
@@ -85,6 +311,24 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
- `bx-cli`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
@@ -96,6 +340,9 @@ remains unsupported.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
- `bx-cli run` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers; each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
- `d3dmetal-harness` runner tests no longer give a freshly written script only 300–500 ms to start (#479); both use a 2 s deadline. The kill test now also checks that the probe ran until the deadline and that its process is gone, which catches a timeout path that neither kills nor waits for the probe. It passes the PID-file path as a script argument so temporary directory names containing apostrophes work. Test-only change. Slow script start-up as the cause of the earlier failures is inferred, not measured. `output_complete` is not asserted for the killed probe, because a child spawned by a parallel test may inherit its pipe.
- `bx-cli run` no longer blocks when `--log` names something other than a regular file (#502). The trace-log reads added for #461 opened the path and read it to the end, which waits forever on a FIFO nobody writes to; the log is now opened without waiting and only a regular file is summarized (anything else gets no summary). Also added the missing test for the file-identity half of the replaced-log check (a different file that begins with the old log's bytes), which a reviewer found untested, and documented that Ctrl-Z typed between supervised phases takes effect when the next phase starts. Covered by 2 new unit tests; three deliberate breakages each failed a test. Not run under CrossOver.
### Added
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
+13 -4
View File
@@ -8,7 +8,7 @@ The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
@@ -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, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
- 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.
- 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).
@@ -49,4 +49,13 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
git commit -s -m "Describe the change"
```
## Review and Merging
- A PR needs at least one current approval, passing required checks and resolved blocking conversations. Any later push that changes the PR dismisses earlier approvals.
- You do not merge your own PR. A maintainer other than the original author merges it.
- Please leave **Allow edits by maintainers** enabled on fork PRs (GitHub does not offer it for organization-owned forks). Maintainers may then resolve conflicts and push fixes to your branch, and may still merge it.
- A maintainer may re-approve after their own routine fix (conflicts, changelog, minor docs). Substantive changes need approval from someone who did not write them.
The full rule, including what GitHub does not enforce, is in [AGENTS.md](AGENTS.md) §7, "Merge eligibility".
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
Generated
+1 -8
View File
@@ -7,22 +7,15 @@ name = "bx-cli"
version = "0.2.0"
dependencies = [
"bx-probe",
"bx-runtime",
"bx-telemetry",
"dxbc-accc",
"libc",
]
[[package]]
name = "bx-probe"
version = "0.2.0"
[[package]]
name = "bx-runtime"
version = "0.2.0"
dependencies = [
"libc",
]
[[package]]
name = "bx-telemetry"
version = "0.2.0"
-1
View File
@@ -3,7 +3,6 @@ members = [
"launcher/crates/bx-cli",
"launcher/crates/bx-probe",
"launcher/crates/bx-telemetry",
"launcher/crates/bx-runtime",
"shader-transpiler/crates/d3dmetal-harness",
"shader-transpiler/crates/dxbc-accc",
]
+26 -24
View File
@@ -9,13 +9,13 @@
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: D3DMetal 3.0](https://img.shields.io/badge/graphics-D3DMetal%203.0%20%2F%20Metal-8957e5)
![Stack: Rust + C++20 PE32+](https://img.shields.io/badge/stack-Rust%20%2B%20C%2B%2B20%20PE32%2B-dea584)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M0)-d29922)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M2)-0969da)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
</div>
> [!IMPORTANT]
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
@@ -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.
---
@@ -33,9 +33,9 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
```mermaid
flowchart LR
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
M2["M2: First Frame &\nShader Gate"]:::planned
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
M3["M3: Shaders &\nTexture Tiling"]:::planned
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
M5["M5: Audio, Saves\n& Stability"]:::planned
@@ -50,16 +50,16 @@ flowchart LR
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
| Track | Focus | Visual Status | Live Issues |
| --- | --- | --- | --- |
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
@@ -67,9 +67,9 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
| Milestone | Scope | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Merged (`#406`)** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
@@ -129,10 +129,10 @@ The repository is organized into disjoint track directories around a single froz
| Directory | Track | Stack | Contents |
| --- | --- | --- | --- |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
@@ -165,8 +165,9 @@ cargo build -p bx-cli
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
target/debug/bx-cli doctor
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
# bx_shader_bridge.dll with cargo, and build the conformance binaries
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
scripts/build-shims.sh
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
@@ -185,8 +186,7 @@ python3 scripts/audit/docs_hygiene.py
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture. Needs `--bottle` or `--prefix`; supervised with timeout, stall, memory and output limits and writes a JSON record |
| `bx-cli stop (--bottle B \| --prefix P)` | Recovers an environment after a supervisor was force-killed |
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
---
@@ -209,9 +209,11 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
- **Not yet implemented (M1–M6):**
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
+61 -15
View File
@@ -1,24 +1,14 @@
# Third-party notices
BetterXen's own source is `GPL-3.0-or-later`. The active launcher uses `libc` 0.2.191 (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX signals and file locks, under its MIT option. Preserve the Rust Project Developers notice and permission text. Private build bundles include the unmodified locked libc source and notices.
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `GPL-3.0-or-later` source with **one external crates.io dependency**: `libc`, used only by `bx-cli`.
The memory guard and stall/memory-settle concepts in `launcher/crates/bx-runtime` are inherited from BetterXen #405: attributed Rust reimplementations of contributor-owned supervision concepts from skakwy/victory-mac at `22b3f8e45a59`, GPL-3.0, used with the author's permission as recorded in the [donor per-component audit](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/upstream-integration-audit.md). No game-facing implementation is copied. The excluded `victory-shader` compiler is not imported.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. The crate is licensed `MIT OR Apache-2.0`; its notice and permission text (`LICENSE-MIT` in the 0.2.191 crate) are reproduced under [libc MIT license text](#libc-mit-license-text) below.
Original conformance workloads are built with external llvm-mingw 20261117 (archive SHA-256 `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`). Its wrappers are ISC; LLVM and MinGW compiler/runtime components carry separate terms. Compiler binaries are not bundled. Windows workload bundles preserve the unmodified LLVM/MinGW notices for linked runtime support. Microsoft DXC v1.9.2609 is an external, checksum-pinned Windows guest tool; its executable and DLLs are never bundled. Details: [selected source review](docs/research/maintainer-upstream-review.md).
## Vendored source files
## BetterXen contributor work carried from #405
These are contributions to BetterXen under `GPL-3.0-or-later`, not third-party code. They were moved onto the six-track layout, so their original commits are not in the new history. The sign-offs recorded in the original commits are:
```text
ce9c10a Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
0427465 Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
```
| Contributor | Original commit | Carried to |
| Files | Origin | License |
| --- | --- | --- |
| Adeeb Rahman | [`ce9c10a`](https://github.com/MacosPorters/betterxen/commit/ce9c10a3ab4e2c476bf8ab568688089e1edbd19e) | `tests/conformance/optional/d3d11-compute/` (D3D11 compute-buffer readback workload) |
| Bartosz Szczepański | [`0427465`](https://github.com/MacosPorters/betterxen/commit/042746554c808dafe48b76b765efd872545429bd) | `launcher/crates/bx-runtime/src/host.rs` and `run.rs` (GPU wired-memory fields in receipts and run records) |
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
## External Host Tools & Runtime Dependencies (Never Bundled)
@@ -29,3 +19,59 @@ ce9c10a Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
## libc MIT license text
```text
Copyright (c) The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
```
## DirectStorage headers MIT license text
```text
Copyright (c) Microsoft Corporation.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+1 -1
View File
@@ -7,4 +7,4 @@ This directory holds the **only shared interface boundary** across BetterXen's s
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files. One entry is not under `shims/`: `bx_shader_bridge.def` is the export list of `bx_shader_bridge.dll`, the x86-64 Windows build of `shader-transpiler/crates/dxbc-accc` (#445). `scripts/build-shims.sh` links it into that build and verifies it with the shims (#484).
+5
View File
@@ -0,0 +1,5 @@
LIBRARY bx_shader_bridge.dll
EXPORTS
bx_shader_inspect
bx_shader_prepare_for_d3dmetal
bx_shader_free_buffer
+6
View File
@@ -43,3 +43,9 @@ EXPORTS
XGameUiShowTextEntryAsync
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
XNetworkingQuerySecurityInformationForUrlAsync
InitializeApiImpl
InitializeApiImplEx
InitializeApiImplEx2
UninitializeApiImpl
QueryApiImpl
XErrorReport
+2
View File
@@ -15,3 +15,5 @@ EXPORTS
XMemVirtualQuery
bx_xmem_query_region
bx_xmem_get_internal_stats
bx_xmem_try_charge_external
bx_xmem_release_charge_external
+16 -1
View File
@@ -33,9 +33,24 @@ typedef struct bx_xmem_stats {
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
* committed_virtual_bytes includes bytes admitted through
* bx_xmem_try_charge_external(), so committed + physical is everything the
* cap counts and peak_committed_bytes never exceeds what was reported. */
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
/* Admit `bytes` against the combined title cap, counting every owner.
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
* bookkeeping could not be refreshed (logged as external_charge). On success the
* caller owns the charge and must release it exactly once with
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
int bx_xmem_try_charge_external(uint64_t bytes);
/* Release a charge previously admitted by bx_xmem_try_charge_external().
* Releasing more than is outstanding is refused: the counter is left
* unchanged and an external_charge error is logged. */
void bx_xmem_release_charge_external(uint64_t bytes);
#ifdef __cplusplus
}
#endif
+12 -5
View File
@@ -3,32 +3,39 @@
## Getting Started & Architecture
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
- [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) — 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/`).
- [Synthetic Conformance Suite](../tests/conformance/README.md) — Auto-discovered PE32+ conformance binaries.
- [Maintainer Testing Guide](maintainer-testing.md) — Build, acceptance, expected graphics, known limitations and cleanup for the hybrid runtime.
- [Changelog](../CHANGELOG.md) — Unreleased and historical changes.
## Architecture Decision Records
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
## Research, Testing & Licensing
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [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.
- [Runtime Integration Source Review](research/maintainer-upstream-review.md) and its [reference revisions](research/maintainer-reference-heads.json) — Upstream source inspected for the supervised runtime; nothing adopted.
- [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.
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
- [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.
+1 -1
View File
@@ -26,7 +26,7 @@ BetterXen provides integration, configuration, environment management, diagnosti
## Verified implementation capabilities
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md` at tag `native-first-final`, the archive ADR 0006 makes canonical; the file is retired from `main`.
## Planning consequence
@@ -0,0 +1,45 @@
# ADR 0007: API-set win32_bridge shims are not reached under CrossOver
Status: **Accepted** (2026-11-26, issue #437). Independently verified on CrossOver 26.0 and CrossOver 26.3 on Apple Silicon.
## Context
`shims/win32_bridge/` builds six DLLs named after Windows API sets:
`api-ms-win-core-psm-appnotify-l1-1-0`, `api-ms-win-core-psm-appnotify-l1-1-1` and four `ext-ms-win-rtcore-ntuser-*` forwarders to `user32.dll`. A guest that imports those names statically is expected to load the BetterXen files placed next to the EXE. #437 reports that under CrossOver 26.3 it does not: Wine answers the names itself, even with `WINEDLLOVERRIDES=<name>=n,b` and the shim files in the EXE's directory.
## Evidence
`tests/conformance/test_apiset_resolution` imports one export from each of the six DLLs through the PE import directory, then reports for every name the module that owns the name and the module the loader bound the import address table slot to.
Run on an Apple M-series Mac, macOS 27.2.1, Rosetta 2, **CrossOver 26.0 (`26.0.0.39794`)**, bare prefix, with the override list from `bx-cli` (`SHIM_DLL_OVERRIDES`) and `build-shims/bin` as the EXE directory:
| Import name | Served by | Module that owns the name | Module the import is bound to |
| --- | --- | --- | --- |
| `api-ms-win-core-psm-appnotify-l1-1-0` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `api-ms-win-core-psm-appnotify-l1-1-1` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
`WINEDEBUG=+loaddll` shows `Loaded` records for `user32.dll` and `twinapi.appcore.dll` (both builtin) and none for any of the six shim files. `--expect shim` fails 0/6, so the fixture does distinguish the two outcomes.
This behaviour was independently reproduced on **CrossOver 26.3** on Apple Silicon (`bx-cli run` with the shim directory and direct loader runs with `WINEDEBUG=+loaddll`), yielding the exact same 6/6 host resolution (`twinapi.appcore.dll` and `user32.dll`, both builtin, with no `Loaded` records for the six shim files) and `--expect shim` exiting 1. The internal Wine mechanism is not claimed here; this records observed loader behaviour.
## Decision
Rely on Wine's built-ins. Under CrossOver the six API-set shims are not part of the supported path: the host answers window and message calls through `user32.dll` and PSM registration through `twinapi.appcore.dll`.
- The six DLLs stay in the tree, built and export-checked, and are still exercised by explicit full-path loads (#431).
- No attempt is made to make them win name resolution. That would depend on undocumented Wine API-set behaviour (#350) and, within this issue's scope, on patching or redistributing CrossOver or Wine components, which is out of scope.
- Offline PSM behaviour that a title needs must live somewhere a static import actually reaches. This ADR does not choose that place.
## Consequences
- `test_apiset_resolution` records the current behaviour (`--expect host`) and fails when it changes. If a CrossOver build starts loading the shims, run it with `--expect shim` and revisit this ADR.
- `test_integration_boot` continues to report `shim_backing` as pending for these six names under CrossOver.
- Documentation describes the bridges as Windows-only stubs that CrossOver does not load for static imports.
## Not claimed
Nothing here shows Xbox title compatibility, behaviour on Xbox hardware, or behaviour on CrossOver builds outside 26.0 and 26.3. Evidence class: local Apple Silicon runs.
+78
View File
@@ -0,0 +1,78 @@
# ADR 0008: M2 Shader Format Gate — Branch D1 (DXIL normalization) for M3
Status: **Proposed** (2026-11-26, issue #466). The choice for M3 is the maintainers' to accept. The evidence below is from local Apple Silicon runs by the implementer and has not been independently reproduced.
## Context
The roadmap's M2 gate asks which shader path M3 builds:
- **Branch D1, DXIL normalization:** shaders reach D3DMetal as DXIL, and BetterXen rewrites only what D3DMetal cannot run.
- **Branch D2, `ACCC`/`FSPX` translation:** console-compiled RDNA 2 code in `ACCC` chunks is translated to DXIL or MSL.
The gate needs a classifier that guest pipeline creation actually reaches, plus measurements of what D3DMetal does with each form.
## What M2 built
- **Bridge (#445):** `bx_shader_bridge.dll` is the x86-64 Windows build of `dxbc-accc`, so guest code can call the inspector.
- **Gate (#466):** `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` pass every stage through `bx_shader_inspect`. One `shader_gate` JSONL record per stage gives:
- the container kind, stage, shader model and chunk sizes;
- the `SFI0` feature flags (`D3D_SHADER_FEATURE_*` values from DirectX-Headers `d3dcommon.h`);
- the `PSV0` wave lane range.
- **Decisions:**
- **DXIL and dual containers:** go to the host as the bridge's prepared copy (`bx_shader_prepare_for_d3dmetal`).
- **ACCC-only containers:** are refused with `E_NOTIMPL` before the host device is called.
- **Legacy DXBC and unclassifiable input:** pass unchanged.
- **A missing bridge:** is logged once (`shader_bridge_missing`). Shaders then pass unclassified, except that a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it. The bridge is loaded only by full path from `d3d12_xs.dll`'s own directory.
- **Known D3DMetal gaps:** a stage that needs a wave wider than 32 lanes, or 64-bit atomics, also gets a `shader_d3dmetal_gap` record.
`tests/conformance/test_shader_gate` exercises all of this.
## Evidence
| Observation | Source | Host and class |
| --- | --- | --- |
| A real DXC 1.9.2609 SM 6.6 compute shader (`fill_cs66`) creates a PSO through `d3d12_xs`, runs, and all 256 output words match the CPU reference. | `test_shader_gate` | Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 (`26.3.0.39832`) bottle with `CX_GRAPHICS_BACKEND=d3dmetal`; class A, this host only |
| The same shader, run outside Wine through `d3dmetal-native` against CrossOver's D3DMetal 3.0, matches 256/256. | [d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) (#417) | Same host; class A |
| An ACCC-only container is refused with `E_NOTIMPL` for compute and graphics, no host object is created, and the device stays usable. | `test_shader_gate` | Same bottle; class A |
| In a bare CrossOver 26.3 prefix (vkd3d), SM 6.6 DXIL PSOs fail with `E_FAIL`. vkd3d reports `Cannot load DXIL conversion library`. | `test_shader_gate`, same host | Class A; DXIL needs the D3DMetal backend under CrossOver |
| `[WaveSize(64)]` kernels and kernels with SM 6.6 64-bit atomics are created but never run on D3DMetal. | [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints) (#453) | Apple M3 Pro, Wine 11.0 source build, D3DMetal 4.0b3; class A for that host |
| DXC records `[WaveSize(64)]` as `PSV0` lanes 64/64, and 64-bit atomics on typed resources as `SFI0` `0x400000`. 64-bit atomics on raw buffers set only `INT64_OPS` (`0x8000`), the same as other 64-bit integer use. | The #453 blobs, read by the gate and by a script | Class A |
| Public sources do not establish a console-native shader container layout. BetterXen's `FSPX` is a clean-room synthetic layout, not a description of a console compiler's format. | `CLAIM-XBOX-ISA-ABI` (class U) in [claims.toml](../claims.toml); `shader-transpiler/crates/dxbc-accc/src/fspx.rs` | Source review |
| A serialized console pipeline path exists for Series X\|S, with no public version-independent format. | `CLAIM-XBOX-ACO-SAMPLE` (class D) | Source review |
| A read-only structural scan of an authorized local test workload (2026-11-28) found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable, and no plaintext `DXBC` in its packaged shader archive. | Static container scan on this host, re-run through `dxbc-accc`; private evidence note, workload not redistributed | This host; structure only, runtime use unmeasured |
Runtime gate telemetry still covers only synthetic programs; no target-workload run has reached pipeline creation, so what a run submits remains unmeasured. One static measurement now exists (2026-11-28): a read-only container scan of an authorized local test workload, re-run through `dxbc-accc`, with the counts in the table above. The scan measures what shipped components contain, not what any run submits, and the workload is not redistributed. Wherever the gate runs, its `shader_gate` records count it.
## Decision
Branch **D1** is proposed for M3:
1. **Pass DXIL through the gate to D3DMetal.** This is the only path with measured, end-to-end execution evidence.
2. **Spend M3 shader work on the two measured gaps,** within the [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints):
- lower `WaveSize(64)` programs to 32-lane code;
- lower SM 6.6 64-bit atomics to 32-bit operations or bounded lock emulation.
The gate's `shader_d3dmetal_gap` records show which pipelines need this.
3. **Keep refusing ACCC-only containers** with `E_NOTIMPL` and a structured log.
Branch **D2** is deferred. It needs a documented, lawfully available description of console-compiled containers and their RDNA 2 code, and none exists (`CLAIM-XBOX-ISA-ABI`). A translator built against the synthetic `FSPX` layout would prove nothing about real inputs.
Revisit this ADR in any of these cases:
- an authorized public source for that format appears;
- gate telemetry shows a required pipeline-creation path refusing an ACCC-only container at runtime — a static scan already established that the target workload's upscaler component embeds 29, so the open question is submission, not existence;
- D3DMetal starts running the gap cases.
## Consequences
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
- **Not covered by the gate yet:**
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
- **`NOBC` programs:** the classifier validates the `DXIL` program header's sizes but not the LLVM bitcode signature, so a container whose bitcode payload is the four-byte placeholder `NOBC` still classifies as executable DXIL and is prepared for the host unchanged. The target workload's main executable embeds 10 such containers (nine pixel, one vertex, SM 6.6). They carry no bitcode, so D1 cannot run them as-is; their signature and validation chunks are intact.
- **Wave size:** the gate logs constraints but changes no shader. A pipeline that D3DMetal creates but does not run still behaves that way.
## Not claimed
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs, one local static container scan of an authorized test workload, and public-source review. The scan counts containers embedded in shipped components on this host; it does not establish what any run submits, and it documents no console-compiled format layout beyond the stated mismatch.
@@ -0,0 +1,59 @@
# ADR 0009: Xbox-layout D3D12 objects in d3d12_xs
Status: **Proposed** (2026-11-28). Phase 1 is implemented with this ADR; the maintainers decide whether the direction stands. The evidence is from local Apple Silicon runs by the implementer and has not been independently reproduced.
## Context
`d3d12_xs.dll` handed titles PC D3D12 objects: C++ proxies (`proxy.h`, `proxy_generated.cpp`) whose vtables follow the PC `<d3d12.h>` order. A title built against the Xbox Series D3D12 header (`d3d12_xs.h`, part of the GDK material Microsoft authorized the project to use) calls through each object's **function table**, and that order is different:
| Interface | Xbox slots | PC slots | Orders agree up to |
| --- | --- | --- | --- |
| `ID3D12Device` | 83 | 44 | slot 43. Xbox then adds 39 methods (`CreatePlacedResourceX`, `CreateCommandQueueX`, ...) before `ID3D12Device1`. |
| `ID3D12Device11` (chain) | 139 | — | `ID3D12Device11` is the interface a project-authorized target build asks for. |
| `ID3D12GraphicsCommandList` | 107 | 60 | slot 27 |
| `ID3D12CommandQueue` | 38 | 19 | slot 13 |
So every call past those slots reached the wrong PC method. On the target build, the first call on the device after `QueryInterface(ID3D12Device11)` jumped to address 0.
From the same header:
- **Base layout:** every object starts with the table pointer, a 32-bit flags word and `m_RefCount`, 16 bytes in all.
- **`ID3D12Device` fields:** a 64-bit null constant-buffer address at +16 and a 64-byte union at +24. The union's first byte, `m_OutOfLineFlags`, makes the two inline device helpers (`CopyDescriptorsSimple`, `CreateConstantBufferView`) call out through the table when it is non-zero. That holds unless a title is compiled with `D3DCOMPILE_NO_DEBUG`, in which case they write descriptors inline.
- **Command lists:** they add a put buffer and CPU state. Of their 76 inline methods, 71 call the table. The other five write command packets directly when the next write fits below `m_Putter`'s limits, and call the table otherwise.
- **IIDs:** the interface IDs of shared interfaces are the PC ones (`ID3D12Device` `189819f1-…`, `ID3D12Resource` `696442be-…`).
## Decision
1. **Xbox-layout objects:** titles get `BxXboxObject`s (`xbox_facade.h`). They have the Xbox object layout, with `m_OutOfLineFlags` set, and an Xbox-order function table. Each object hosts a PC object, normally one of the existing proxies, so their logging, shader gate, heap hooks and wrapping stay in force.
2. **Generated tables:** `tools/gen_xbox_tables.py` reads the Xbox header locally and the toolchain's `<d3d12.h>`, and writes `xbox_tables_generated.cpp`. It takes only slot order, names, IIDs and parameter types from the Xbox header. The header is never committed.
- **Forwarders:** a slot whose Xbox and PC signatures are equivalent gets a typed forwarder written with the PC types. That includes the free-function versus member struct-return difference, so the compiler produces the right calling convention. Interface pointers passed in are unwrapped, and `(REFIID, void**)` results are wrapped.
- **Stubs:** every other slot is a `BX_VTABLE_STUB_LOG` stub.
- **Hand-written slots:** Xbox-only methods are implemented in `xbox_facade.cpp` as titles need them.
3. **Who gets which layout:** titles set `Version` in the `D3D12XBOX_CREATE_DEVICE_PARAMETERS` block they pass to `D3D12XboxCreateDevice`, and the documentation requires it. Those calls get the Xbox layout. BetterXen's synthetic fixtures are PC-layout clients built against `<d3d12.h>`, pass a zeroed block, and keep the PC proxy. The log records which layout was chosen (`xbox_layout`).
4. **Command lists (Phase 2):** command lists get an Xbox object whose zeroed put-buffer pointers fail every inline room check, so every call reaches the table.
## Consequences
- **Phase 1 (this change):**
- The device chain up to `ID3D12Device11` is covered: 139 slots, 75 forwarded, 4 shared or hand-written, 60 stubs.
- So are the objects it creates: resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues.
- `CreateCommandQueueX` maps the Xbox queue description onto PC `CreateCommandQueue`. The engine and queue indices are logged and not used.
- On the target build, the title now creates its device and four compute queues, and stops at `CreateCommandListX`, which is Phase 2.
- **Phase 2:**
- **Command lists:** `ID3D12GraphicsCommandList8`, 150 slots: 75 forwarded, 6 shared or hand-written, 69 stubs. They are created through `CreateCommandListX` and the PC `CreateCommandList`, and their Xbox field area is zeroed, so the five inline fast paths call through the table.
- **Interface pointers inside structures:** `ResourceBarrier` and `CopyTextureRegion` unwrap them before the host call. The Xbox `ResourceBarrier` returns 0 actions.
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` (`frame_pacing.cpp`) are emulated from the recorded interval by a host timer. It signals the origin, vblank and flip events and their ancillary handles, and gives out frame-pipeline tokens as documented.
- **Generator fixes:** CRLF lines in parts of the header, a table definition whose end the boundary pattern ran past (it hid `ID3D12GraphicsCommandList1`), SAL annotations with nested parentheses, and `FLOAT`/`float`.
- **Resources at title-chosen addresses** (`placed_x.cpp`), translation by copy:
- `CreatePlacedResourceX` and `CreatePlacedResourceX1` create a host shadow resource. A buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's memory at creation; a texture gets a committed texture whose contents are not filled, which is logged.
- The resource reports the title's address from `GetGPUVirtualAddress`.
- Not yet done: keeping shadows in step with later CPU writes (planned: page-protection dirty tracking, copying at submit), copying GPU writes back, and translating title addresses in GPU calls.
- **On the target build:** the title creates 581 command lists, sets a 30 Hz interval and schedules its origin and flip events. It then lays out its own descriptor memory with `xmem` placeholders (#643) and creates a 174 MB buffer at a title-chosen address through `CreatePlacedResourceX1`, now served by a shadow.
- **Where it stops:** the title creates a descriptor heap and requires `GetCPUDescriptorHandleForHeapStart` to equal an address in its own descriptor memory. D3DMetal returns an opaque handle.
- **What that needs:** BetterXen-owned descriptor heaps whose handles are addresses, translated to host descriptors when used. That is the descriptor-heap item under Consequences.
- **Fixtures:** the existing fixtures are unaffected, since they use the PC layout. `tests/conformance/test_d3d12_xbox_layout` calls Xbox slots by number, with the expected results taken from a PC-layout device. It fails against the previous `d3d12_xs.dll`.
- **What the fixture can and cannot show:** its slot numbers and object offsets are written by hand, but from the same header the generator reads. It shows that the generator and the fixture agree. It cannot show that either read the header correctly; only an independent re-derivation from the header, or a title running further, can.
- **On a host without the forwarded interface** (vkd3d stops at `ID3D12Device9`): the Xbox-layout device is refused with `E_NOINTERFACE` and logged. The fixture verifies the refusal and skips (exit 77). `bx_xbox_wrap` refuses the same way for every wrapped family, so a title never gets a PC object where it expects an Xbox one.
- **Frame pacing:** the emulated frame interval follows host `Sleep` and is not synchronised to the display. The pacing thread is detached and never exits, which is safe only while `d3d12_xs.dll` stays loaded for the life of the process.
- **Descriptor heaps:** a title compiled with `D3DCOMPILE_NO_DEBUG` writes console-format descriptors straight into descriptor-heap memory and computes handles with Xbox descriptor sizes. Supporting that needs BetterXen-owned descriptor heaps translated at bind time, which is not part of this ADR.
- **Identity:** QueryInterface on an Xbox object for another wrapped family returns that family's Xbox object over the same host. A host reached through another path, such as `GetDevice` returning the raw host device, may get a second Xbox object.
- **Replacing the PC proxy:** this ADR supersedes the PC proxy for titles. Whether the PC proxy is eventually removed in favour of fixtures that use the Xbox layout is left open.
+2 -2
View File
@@ -9,7 +9,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
@@ -25,7 +25,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
## Milestones (M0 → M6)
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 16 shim DLLs load cleanly; auto-logging COM proxy captures startup call traces.
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
+36
View File
@@ -1,4 +1,30 @@
# Source review is distinct from a Xenora test run.
#
# Evidence classes (derived from existing usage; claim classes are unchanged):
# A — Executed measurement on a named Apple Silicon host, with an independent
# CPU/reference expectation. Valid only for the named host/software versions;
# implementer-run unless independently reproduced. Never Xbox verification.
# B — Source-derived semantics from a public vendor specification, scoped to the
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
# exercised by synthetic tests, but does not establish console applicability.
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
# without console execution. Establishes only what the reviewed source states.
# E — Public tool/format documentation or observed behavior of a public
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
# Documentation review and execution are distinct; the claim's test field
# records which one applies.
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
# about the evidence reviewed, not proof that no authorized source exists.
#
# Use B for semantics from a specification, D for a claim about what a public
# document or sample says, and E for a claim about a tool or its format support.
# The current registry does not assign class C.
#
# These are the repository's evidence classes. AGENTS.md §5 refers to this
# file and does not define a second vocabulary; the longer VERIFIED /
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
# present in the in-tree AGENTS.md, so no mapping is invented here.
schema_version = 1
[[claim]]
@@ -242,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.
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
-8
View File
@@ -2,14 +2,6 @@
The workspace is GPL-3.0-or-later. The following is the lead's preliminary compatibility inventory. The independent license audit is pending.
## Active hybrid launcher
The migrated `bx-cli` uses only `libc` 0.2.191 as an external Rust dependency (revision `ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`, MIT selected). Its MIT notice was read at the locked source and is compatible with GPL-3.0-or-later; source and notices are retained in private bundles. Rust 1.100.0, llvm-mingw 20261117 and optional Microsoft DXC v1.9.2609 are external build tools. Their compiler/runtime notices remain applicable to compiled output and are preserved as described in [third-party notices](../THIRD_PARTY_NOTICES.md).
The native-first dependency inventory and redistribution discussion below are historical, preserved for the retired code at `native-first-final`. Those objc2/native graphics packages are not dependencies of the active hybrid launcher.
## Historical native-first inventory
| Component | Version and upstream revision | License used | Scope |
|---|---|---|---|
| objc2 | 0.6.5, `d7d2fa23ceaa5e6096c923b081040e5d81b3b9df` | MIT | Runtime bindings |
-185
View File
@@ -1,185 +0,0 @@
# Maintainer testing guide
How to build and independently test the supervised hybrid runtime and its Direct3D
workloads (issue #407). The workloads are original Windows programs. Passing them shows
narrow Windows API behaviour under CrossOver on one Mac. It says nothing about Xbox
software, game compatibility or performance, and no maintainer has reproduced these
results yet.
The D3D11 and D3D12 workloads are Track F acceptance inputs for the launcher. They are not a
second graphics pipeline and do not exercise the `d3d12_xs` shim.
`bx-cli` has been run only against CrossOver 26.3 (26.3.0.39832). On any other build `run` and
`bench` refuse to start unless given `--allow-untested-crossover`, and `doctor` reports
`crossover_build_tested: false`. `stop` is never refused.
## What has been run
On commit `7451f0f2ae27b19313015d1ee529b69a755ef12f`, from an existing checkout rebuilt with
`build-maintainer.sh`, on one Apple M4 with CrossOver 26.3, by the author's coding agent.
This is not independent verification.
| Check | Result |
| --- | --- |
| fmt, clippy, tests | clean; 109 passed, 0 failed, 1 ignored (opt-in live D3DMetal test) |
| Shim build | 16 DLLs, 102 exports |
| `test_*.exe` fixtures, through `--bottle` and `--prefix` | passed, except `test_veh_unhandled.exe`, which crashes on purpose |
| Full acceptance suite | exit 2: 50 `ok`, 2 `KNOWN`, 0 `FAIL`, 0 `NOT-RUN` |
| On-screen capture checks | passed |
The two `KNOWN` lines are the D3D12 swapchain retention below. A clean-clone run and a
private-bundle run were last done on earlier source, before `main` was merged.
`main` at `02b8924` (`xmem` physical pages) was merged afterwards. The Rust checks, shim
build and all fixtures, now including `test_xmem_physical.exe`, were rerun with the same
results; the full acceptance suite was not.
After merging `main` at `bfa80de` (`bx-cli trace` reporting), the Rust checks (113 passed, 0
failed, 1 ignored), shim build and the shim export, CLWB and crash fixtures with their traces
were rerun.
## Requirements
- Apple Silicon Mac. Developed on an M4 with 24 GB and macOS 27; nothing else was tried.
- CrossOver 26.3 installed from CodeWeavers, and Rosetta 2. Neither is bundled.
- Xcode command line tools, `rustup`, Python 3.12 or newer.
- For the shim superbuild: `brew install mingw-w64 cmake`.
- At least 50% free memory (`memory_pressure -Q`) for the whole run. The runner refuses to
start below that; close browsers and other large applications first.
- For the on-screen and keyboard checks: a desktop Space in front (not a full-screen app),
an unlocked display, and Screen Recording and Accessibility permission for the terminal.
Do not type while the keyboard check runs.
## Build
From a fresh clone of the branch under test:
```sh
TC=$(scripts/hybrid/install-dependencies.sh) # pinned llvm-mingw and Rust 1.100.0
DXC=$(python3 scripts/hybrid/install-dxc.py) # pinned Microsoft DXC, for Shader Model 6
export RUSTUP_TOOLCHAIN=1.100.0-aarch64-apple-darwin
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
scripts/build-shims.sh # 16 shim DLLs, 102 exports
scripts/hybrid/build-maintainer.sh "$TC" # arm64 bx-cli and workloads
BX=$PWD/artifacts/maintainer/bin/bx-cli
```
Both installers download over the network, check a pinned SHA-256 and refuse to overwrite
an existing installation.
## Run
Use a new bottle that nothing else uses. Stopping a run stops everything in its bottle.
```sh
python3 scripts/hybrid/create-test-bottle.py "$BX" betterxen-maintainer-test
"$BX" doctor --bottle betterxen-maintainer-test
```
Shim fixtures (an explicit Wine prefix, separate from the bottle):
```sh
for t in test_veh_clwb test_shim_exports; do
"$BX" run --prefix "$PWD/artifacts/m0-prefix" --shims build-shims/bin \
--log "$PWD/artifacts/m0-shim.jsonl" --exe build-shims/bin/$t.exe
done
"$BX" trace artifacts/m0-shim.jsonl # expect "clwb VEH traps : at least 4 (sampled)", ADX 0
```
Full acceptance (Direct3D 12 and 11 workloads, negative controls, lifecycle, soak):
```sh
BETTERXEN_DXC_DIR="$DXC" scripts/hybrid/accept-integrated.sh "$TC" betterxen-maintainer-test
```
Each line is `ok`, `FAIL`, `KNOWN` or `NOT-RUN`. Records, logs and `summary.json` are
written under `artifacts/acceptance/<timestamp>/`.
| Exit status | Meaning |
| --- | --- |
| 0 | Every check ran and passed |
| 1 | At least one check failed |
| 2 | No failures, but the known D3D12 retention was seen or a check did not run |
On CrossOver 26.3 with D3DMetal, 2 is the best result available today.
## See the graphics
```sh
"$BX" run --bottle betterxen-maintainer-test -- \
"$PWD/artifacts/maintainer/workloads/d3d12-integrated.exe" --frames 128 --hold-ms 15000
```
A small window titled "BetterXen D3D12 workload" appears on a black background:
- a 16-row purple band across the top (the frame number, encoded as a colour);
- an upper-left square split into green, blue (top) and red, white (bottom);
- a lower-right square split into cyan, magenta (top) and yellow, grey (bottom),
overlapping the first and drawn in front of it.
The command then reports `failed_exit_1` with only the `shutdown` gate failed. That is the
known issue below, not a broken build. Any other failed gate is a new problem.
## Package (optional)
From a clean committed checkout, after `build-maintainer.sh`:
```sh
scripts/hybrid/package-maintainer.sh
```
It writes `artifacts/packages/betterxen-maintainer-<commit>.tar.gz` and its SHA-256. The
bundle contains `bx-cli`, the original workloads, source and licence notices. On another
Mac: check the SHA-256, unpack, and run `./test.sh NEW_BOTTLE_NAME` (set
`BETTERXEN_DXC_DIR` to include Shader Model 6). The binaries are not signed or notarized.
## Known limitations
- **API-set bridge shims (#437).** Under CrossOver, statically imported `api-ms-win-*` and
`ext-ms-win-*` names are answered by Wine, not by the `win32_bridge` shims.
- **Bottle settings.** `[EnvironmentVariables]` in a bottle apply over variables given with
`--env`; only `--backend` and DLL overrides are protected from this.
- **Intermittent D3D11 control stall.** One 20,000-frame soak stopped after 9,183 frames
because a GPU event query did not complete within 10 s. Three reruns passed. The cause is
unknown. The two D3D12 soaks of the same length did not show it.
- **Keyboard negative control.** It failed once inside a full run and passed twice on its
own. The cause of that one failure was not captured.
- **D3D12 swapchain retention (D3DMetal).** A new swapchain starts with two references and
survives the application's release, with no application GPU work. The same binary on the
`vkd3d` path starts with one and is freed. Observed on one Mac; the cause inside D3DMetal
is unknown and BetterXen has no mitigation. Programs that recreate swapchains will grow.
- **D3D12 on the `wined3d`/`dxvk` settings (`vkd3d`).** After about 437 frames every
`Present` takes 2000 ms and teardown hangs. A 2000 ms wait in public Wine DXGI source is
a likely explanation, not a confirmed one. Use the default D3DMetal path for D3D12.
- The earlier two-hour D3D12 run presented 844,497 frames with no mismatch in the verified
frames, but failed the shutdown gate. It used a pre-migration build, so it does not
certify this one.
- Double-precision shader operations are not exercised.
- Pixel checks read back what was handed to `Present`. Only the window-capture checks
observe the macOS compositor.
## Security limits
A bottle or prefix is not a sandbox. A Windows program started this way can read and write
your files and use the network. `bx-cli` passes only a short list of environment variables
(`--inherit-env` opts out), supervises time, output and memory, and stops the selected
environment. Run only programs you trust.
## Troubleshooting
| Symptom | Action |
| --- | --- |
| `refused_to_start_low_memory` | Free memory and rerun; do not run other heavy work alongside |
| `bottle has an active BetterXen runner` | Stop that runner with Ctrl-C or SIGTERM |
| `bottle has an unfinished session` | `bx-cli stop --bottle NAME` (or `--prefix PATH`) |
| `the window exists but is not on the active Space` | Bring a desktop to the front and rerun |
| `NOT-RUN Shader Model 6` | Install DXC and set `BETTERXEN_DXC_DIR` |
| Crash control reports `timed_out` | Wine's crash dialog is waiting for a click. Create the bottle with `create-test-bottle.py`, which turns it off |
## Clean up
Stop any run with `bx-cli stop --bottle NAME`, then delete the test bottle from CrossOver.
Build output lives in `artifacts/`, `target/` and `build-shims/` inside the checkout;
installers use `~/Library/Caches/BetterXen/`.
+200
View File
@@ -0,0 +1,200 @@
# Working Method: Run, Fix, Pull Request
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
BetterXen is built by collaborators who each have the project-authorized target build and 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?*
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
What the first target-build runs taught us:
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
## The stages
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
## Where the state lives
| 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.
### Why a blocker gets a pull request and not an 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.
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.** `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
run → signature → draft pull request (the claim) → evidence → smallest fix + test → runs before and after → ready → someone else reviews and merges
```
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
Five parts and nothing else:
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
2. **Contract:** what the console does, and which source says so (ranks below).
3. **Fix:** what changed.
4. **Test:** the conformance test, and that it fails without the fix.
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
### Review
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
- a change under `abi/`;
- a new or changed translator instruction class;
- a contract from source rank 4 or 5;
- anything touching the sandbox, security or licensing.
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
## Run protocol
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
- **Build:** current `main`, or `main` plus exactly the one branch under test.
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
**The run report** is generated, not written. Per run:
- outcome: frames presented, clean timeout, early exit with its status, or hang;
- the start-up path taken;
- every unimplemented call reached, counted;
- every fault inside a BetterXen module;
- 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 pull requests and handoff issues are titled with.
## Sources of truth
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
| Rank | Source | Notes |
| --- | --- | --- |
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
## Evidence and references
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
## Finding blockers once the game runs
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
**How a problem is recognised,** from most to least reliable without a person:
| Signal | Catches | Needs a person |
| --- | --- | --- |
| Crash, hang, early exit | Stability | No |
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
| Frame compared with the last good capture of the same route | Regressions | No |
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
| 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 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.
## What people do
People are needed for exactly four things, each marked `needs-human`:
1. confirming a stage change after a gate passes;
2. deciding a decision gate (for example the graphics back end);
3. licence, provenance and legal questions;
4. changing these rules.
Everything else is the queue.
## The first handoffs
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.
+4
View File
@@ -20,5 +20,9 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
+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.
+175
View File
@@ -0,0 +1,175 @@
# D3DMetal and Apple GPU limits for a shader translator
Constraints that a translator emitting shaders for D3DMetal on Apple Silicon has to
handle (#453). Writing the translator is out of scope.
The note has two parts:
- [Measured constraints](#measured-constraints) come from
`tests/conformance/test_d3dmetal_gpu_limits`, an original synthetic D3D12 compute
fixture checked against values computed on the CPU. These are the only items the
roadmap links to. They are a local Apple Silicon run by the implementer, class A for
the stated host only, not independently reproduced.
- [Unverified reports](#unverified-reports-not-evidence) are observations a contributor
posted on #453 from local builds of another project running a commercial title. They are
**not evidence** under [AGENTS.md](../../AGENTS.md) §5–6 and must not steer the plan
until a synthetic workload reproduces them. They are kept only as leads for writing such
workloads.
Nothing here is an Xbox hardware result, and nothing generalizes beyond the D3DMetal
version named.
## Measured constraints
### `WaveSize(64)` is created but not run
`wave.control` (no `WaveSize`) and `wave.wavesize64` (`[WaveSize(64)]`, SM 6.6) record,
for each thread, the wave width, its lane index and the dispatch index of its wave's first
lane.
The control passes the check D3D12 actually guarantees: every thread reports the same
width, and within each wave the lane indices are a permutation of `0..W-1`. No particular
thread-to-lane order is assumed. On D3DMetal 4.0b3:
- the device reports `WaveLaneCountMin = WaveLaneCountMax = 32`;
- the control runs at width 32;
- the wave64 pipeline is **created without error but never runs**: its output buffer keeps
the sentinel.
So a translator cannot rely on pipeline creation failing. A program written for a 64-lane
wave has to be emitted as 32-lane code, with its two halves made to agree wherever the
original wave acted as one.
### Kernels using SM 6.6 64-bit atomics are created but not run
`atomic64.image` runs a 64-bit `InterlockedAdd` (low halves carrying into the high half)
and an `InterlockedMax` (decided by the high half) on a `RWTexture2D<uint64_t>` over
`DXGI_FORMAT_R32G32_UINT`. `atomic64.buffer` runs the same operations on a raw buffer. Each
kernel also writes a plain 64-bit marker next to its atomics, which shows whether the kernel
ran at all. On D3DMetal 4.0b3:
- The device reports `AtomicInt64OnTypedResourceSupported` and
`AtomicInt64OnDescriptorHeapResourceSupported` as supported, and both pipelines are
created without error.
- Neither kernel runs. The atomic results and the markers all read back as their initial
zeros, on the texture and on the raw buffer alike.
- A throwaway variant with the atomics removed but the markers kept wrote 8/8 markers.
That shows the readback path is sound and the skip comes from the atomics.
So these kernels are silently skipped, on raw buffers as well as images. This is
consistent with d3dmetal-native's `d3d12-atomic64-test` reading back zeros in the
[d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) evaluation
on D3DMetal 3.0. A translator has to lower 64-bit atomics to 32-bit operations.
### Lock-based emulation needs a sufficient retry cap and both fences
`lock64.cap64` and `lock64.cap1024` emulate both operations with a per-texel lock word,
with 32 contending threads per texel and a bounded number of tries:
1. take the lock with `InterlockedCompareExchange` 0→1;
2. `DeviceMemoryBarrier()` (**acquire**: the data reads are ordered after taking the lock;
`globallycoherent` gives visibility, not ordering);
3. update the two 32-bit halves;
4. `DeviceMemoryBarrier()` (**release**);
5. free the lock with `InterlockedExchange`.
A thread that runs out of tries counts a drop instead of spinning on. The 1024-try run is
required to drop nothing and to match the CPU reference exactly. The 64-try run is
reported. On D3DMetal 4.0b3, in three runs each:
- **1024 tries:** nothing dropped, 16/16 values exact, about 15,000–18,000 tries in all.
- **64 tries:** 96–108 of 512 updates dropped.
So a low cap trades a hang for silently lost updates. With 32 contending threads, 64 tries
is already too low.
The loop shape matters. The critical section sits **inside** the retry loop, so a lane
that wins finishes it in the same iteration, and no lane waits for another lane to leave a
loop. The fixture does not run the classic shape (`while (!acquire()) {}` followed by the
critical section). There, the winning lane can be parked at the loop's reconvergence point
behind the lanes still spinning, and on a GPU without independent forward progress for
each thread that could hang the queue. Apple's shader converter prints `Warning:
Undefined: Shader might rely on forward progress/persistent thread` even for the safe
shape.
## Fixture results
A local run by the implementer on 2026-11-26. Class A for this host only; not
independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
| | |
| --- | --- |
| Host | Apple M3 Pro, macOS 27.2.1 (26B131), Rosetta 2 |
| Wine | CodeWeavers Wine 11.0 built from CodeWeavers' published source; CrossOver itself was not installed |
| D3DMetal | 4.0b3 from Apple's Game Porting Toolkit (x86_64; SHA-256 of the binary starts with `b16aab78127d`), user-supplied |
| Shaders | DXC 1.9.2609 via `shaders/compile.sh`; the same DXC reproduces the d3dmetal-harness `fill_cs66` container byte for byte (SHA-256 `7df11b63…`) |
| Command | `ROSETTA_ADVERTISE_AVX=1 WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" wine build-shims/bin/test_d3dmetal_gpu_limits.exe` in a fresh prefix |
| Runs | 3, identical outcomes apart from the 64-try drop counts; exit 0, `SUMMARY: 4 required checks, 0 failed` each time |
| Check | Outcome |
| --- | --- |
| `device.shader_model` | 6.6 |
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
| `wave.wavesize64` | created but not run (output still sentinel) |
| `atomic64.reported` | typed and descriptor-heap 64-bit atomics reported as supported |
| `atomic64.buffer` | not run: marker 0/8, atomic values 16/16 still zero |
| `atomic64.image` | not run: marker 0/8, atomic values 16/16 still zero |
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
(D3DMetal 3.0) by another contributor.
## Unverified reports (not evidence)
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
host. None of this is a BetterXen measurement, no code or shader from that project is
used, and none of it may be cited by the roadmap or a milestone gate. Each item names the
synthetic workload that would turn it into evidence.
- **Splitting wave64 programs.** Operations that need care when the two halves must agree:
- wave reductions;
- first-lane and indexed lane reads;
- the 64-bit lane mask read as data;
- cross-half permutes;
- scalar values spilled into vector lanes;
- group barriers, which are only safe where both halves provably reach them.
The reporter found a uniformity analysis of the program's values, with barriers placed
only after uniform branches, made most such programs translate exactly. Where agreement
cannot be proven and each half runs as its own wave, a group sync that not every lane
reaches must become a memory fence without the group wait. *Workload needed:* SM 6.6
wave64-style kernels with each of these patterns, checked half by half.
- **Helper lanes in a spin lock.** In a pixel shader, helper lanes must not take part in
such a lock: their atomics have no effect, so they never win and spin to the cap. This
was reported as a hard queue hang with no macOS GPU timeout logged. A cap of 2^16 was
reported to hang while 2^10 did not; whether the cap or the helper lanes caused it was not
separated. *Workload needed:* a pixel shader with a lock-protected 64-bit update across
triangle edges.
- **Mesh output size.** Metal refuses mesh pipelines whose per-vertex outputs exceed 32,768
bytes, counting the aligned layout (distances, position, then outputs in register order,
each aligned to its own size). A refused pipeline submitted anyway was reported to hang
the queue under Wine. *Workload needed:* mesh shaders whose output size crosses 32 KiB
only once alignment is counted.
- **Apple shader compiler crash.** `MTLCompilerService` was reported to crash in register
allocation on mesh pipelines whose pixel shader writes several render targets. The
reported cause was output stores merged before all their values are defined, and the
reported fix was emitting each output row's stores after its values. *Workload needed:* a
mesh and pixel pair with several render targets and late-computed outputs.
- **No zero-copy heaps.** D3DMetal 4.0b3 was reported to answer
`ID3D12Device3::OpenExistingHeapFromAddress` with "Not implemented". *Workload needed:*
a fixture that calls it on a page-aligned allocation.
## Regenerating the shaders
`tests/conformance/test_d3dmetal_gpu_limits/shaders/compile.sh` regenerates the committed
headers with Microsoft's DXC release v1.9.2609 (`dxc_2026_09_29.zip`, SHA-256
`ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1`, the same package the
d3dmetal-harness records), running `bin/x64/dxc.exe` under a Wine loader.
@@ -0,0 +1,88 @@
# D3D12 swapchain references under D3DMetal
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. See the independent Apple M2 Pro run below.
| | D3DMetal | Wine `vkd3d` path |
| --- | --- | --- |
| References on the swapchain right after creation | 2 | 1 |
| Count returned by the application's final `Release` | 1 | 0 |
| Swapchains still referenced after 12 create/release cycles | 12 | 0 |
The same program was used for both, and it submitted no GPU work of its own. Under D3DMetal
each retained swapchain also kept a device reference. The cause inside D3DMetal is unknown. A
program that recreates swapchains (for example on resize) should be expected to grow until this
is explained.
The probe is
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
on the branch of #425; it is not part of this branch. Tracked in #450.
## Independent run on Apple M2 Pro
On 2026-11-26, an Apple M2 Pro (16 GiB, macOS 27.3 build 26C5035r) reproduced
the swapchain retention in CrossOver 26.3.0.39832 with D3DMetal 3.0. The
same x86-64 probe under Rosetta 2 released all swapchains in CrossOver
Preview 27.0.0.41303. Each CrossOver build used a fresh Windows 11
64-bit bottle. The Direct3D 12 workload loaded the `apple_gptk` D3D12
and DXGI modules in both builds. The bundled framework in the Preview
build's `apple_gptk` directory reports version 4.0b3.
| Swapchain lifetime probe | Initial reference count | Application release returned | Witnesses retained |
| --- | ---: | ---: | ---: |
| 26.3 D3DMetal | 2 | 1 | 12 of 12 |
| 26.3 Wine D3D12 | 1 | 0 | 0 of 12 |
| Preview D3DMetal | 1 | 0 | 0 of 12 |
| Preview Wine D3D12 | 1 | 0 | 0 of 12 |
Destroying the window before releasing the swapchain and calling
`ResizeBuffers` before teardown each left 3 of 3 witnesses retained on
26.3 D3DMetal. Explicitly detaching the witness released the probe's
private data, while the swapchain's release still returned 1. The
deliberately retained witness control failed as expected. An extra
application-side `Release` would drop a reference the application
does not own.
The separate D3D12 integrated workload presented 600 frames and verified
eight readbacks with zero mismatches on both D3DMetal builds. It failed
only the shutdown gate on 26.3, where the final device release returned
2. Preview passed shutdown with a final device release of 0. These runs
used the direct host D3D12 path without BetterXen's D3D12 shim. The
comparison establishes behavior for these two CrossOver builds on this
host. The underlying ownership change is unknown.
Build the probe from the pinned source linked above with
`x86_64-w64-mingw32-clang -std=c11 -O2 -Wall -Wextra -Werror lifetime.c -o d3d12-lifetime.exe -ld3d12 -ldxgi -ldxguid -luser32`
(LLVM-MinGW 20261117 in this run). Run in a clean bottle using
`ROSETTA_ADVERTISE_AVX=1 CX_GRAPHICS_BACKEND=d3dmetal wine --bottle <bottle> <absolute-path-to-exe> --cycles 12`
and repeat with `CX_GRAPHICS_BACKEND=wined3d`. The two witness controls
use `--cycles 3 --detach-witness` with and without `--retain-app-reference`.
## Related Direct3D acceptance failures
The [integrated D3D12 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_integrated/integrated12.c)
also reproduced the presentation slowdown on the Wine D3D12 path on
26.3. With `CX_GRAPHICS_BACKEND=wined3d` and a 600-frame target, the
workload logged approximately 2,000 ms inside `Present` on frames
12–38, then exited 3 after a 10-second GPU completion wait failed. The
previous M4 report saw the slowdown around frame 437. This run exited
before reaching normal teardown. Preview completed the same 600-frame
workload on the Wine path with eight verified readbacks, no mismatches
and clean shutdown. A 600-frame repeat on 26.3 passed with `--vsync`
enabled. A subsequent 600-frame repeat also passed with the flag off,
so the slowdown remains intermittent and the successful vsync run
does not establish a workaround.
The [integrated D3D11 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d11_integrated/integrated.c)
completed the 20,000-frame soak on 26.3 with 46 verified readbacks,
zero mismatches and a clean shutdown. The intermittent GPU event
stall did not recur in this run. Preview also completed all 20,000
frames and all 46 readbacks, then failed the shutdown gate with one
device reference remaining. A separate 600-frame Preview run
reproduced that shutdown result.
The 26.3 keyboard check delivered five macOS events to the workload and
reached the expected offset (16, 32). The negative control delivered
two Up events and reached (0, -32), which the input gate rejected as
expected. These were isolated runs, so they do not reproduce the
intermittent failure observed inside the full acceptance suite.
@@ -1,196 +0,0 @@
{
"evidence_class": "D",
"observed_date_local": "2026-11-25",
"scope": "Public repository accessibility/head metadata only; authenticated private repository metadata remains in ignored local evidence. Source review scope is separate.",
"repositories": [
{
"repo": "MacosPorters/VIctory-macOS",
"url": "https://github.com/MacosPorters/VIctory-macOS",
"branch": "main",
"head": "d6fc0620f53a5c9073b9d08d0910c8d6aa5d0bdf",
"license": "GPL-3.0",
"archived": false,
"private": false
},
{
"repo": "pragyaangaur/VIctory-macOS",
"url": "https://github.com/pragyaangaur/VIctory-macOS",
"branch": "main",
"head": "b6dd0b184277fc307b93a4cc90d23dca9f05e7b3",
"license": "GPL-3.0",
"archived": false,
"private": false
},
{
"repo": "utmapp/d3dmetal-native",
"url": "https://github.com/utmapp/d3dmetal-native",
"branch": "main",
"head": "af1ee1710711fadff41dead87960d0f1336c1047",
"license": "MIT",
"archived": false,
"private": false
},
{
"repo": "ProhorovIlja/NativeX-Runtime",
"url": "https://github.com/ProhorovIlja/NativeX-Runtime",
"branch": "main",
"head": "b3087ce0ab191227dc9e7af37cab97a0b097bb98",
"license": "MIT",
"archived": false,
"private": false
},
{
"repo": "wine-mirror/wine",
"url": "https://github.com/wine-mirror/wine",
"branch": "master",
"head": "274fcfa9691bf3b7f24c0833ad33e9d57c3df65f",
"license": "NOASSERTION",
"archived": false,
"private": false
},
{
"repo": "doitsujin/dxvk",
"url": "https://github.com/doitsujin/dxvk",
"branch": "master",
"head": "6e25a5e7af5a05e5729e7abc5bf1184df9242e2a",
"license": "Zlib",
"archived": false,
"private": false
},
{
"repo": "HansKristian-Work/vkd3d-proton",
"url": "https://github.com/HansKristian-Work/vkd3d-proton",
"branch": "master",
"head": "71cae091b06571e51446cf2a937f0b04c237c04d",
"license": "LGPL-2.1",
"archived": false,
"private": false
},
{
"repo": "3Shain/dxmt",
"url": "https://github.com/3Shain/dxmt",
"branch": "main",
"head": "faa73e4a0686e432ce5d3bb99a02b5363d76885c",
"license": "NOASSERTION",
"archived": false,
"private": false
},
{
"repo": "KhronosGroup/MoltenVK",
"url": "https://github.com/KhronosGroup/MoltenVK",
"branch": "main",
"head": "5189f8de86ec365860f63bf1da736815cfaea5cd",
"license": "Apache-2.0",
"archived": false,
"private": false
},
{
"repo": "llvm/llvm-project",
"url": "https://github.com/llvm/llvm-project",
"branch": "main",
"head": "0cae57720c3ca7cb09b5ba48d199f1ba04e3aae2",
"license": "NOASSERTION",
"archived": false,
"private": false
},
{
"repo": "mstorsjo/llvm-mingw",
"url": "https://github.com/mstorsjo/llvm-mingw",
"branch": "master",
"head": "903f4cf7faa24e30c8e0c4615f8ce61a0f3d80f8",
"license": "NOASSERTION",
"archived": false,
"private": false
},
{
"repo": "microsoft/DirectXShaderCompiler",
"url": "https://github.com/microsoft/DirectXShaderCompiler",
"branch": "main",
"head": "2600ae89a6153302421b13b4db7d3bd1bd0d9385",
"license": "NOASSERTION",
"archived": false,
"private": false
},
{
"repo": "microsoft/DirectX-Graphics-Samples",
"url": "https://github.com/microsoft/DirectX-Graphics-Samples",
"branch": "master",
"head": "68a2b1e97f71642924e74c7757ca21756ad221b5",
"license": "MIT",
"archived": false,
"private": false
},
{
"repo": "microsoft/DirectX-Headers",
"url": "https://github.com/microsoft/DirectX-Headers",
"branch": "main",
"head": "61c7718954ec73dbdd43c723240fe1a0452a3724",
"license": "MIT",
"archived": false,
"private": false
},
{
"repo": "microsoft/DirectXTex",
"url": "https://github.com/microsoft/DirectXTex",
"branch": "main",
"head": "a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379",
"license": "MIT",
"archived": false,
"private": false
},
{
"repo": "KhronosGroup/SPIRV-Cross",
"url": "https://github.com/KhronosGroup/SPIRV-Cross",
"branch": "main",
"head": "57e4efcc84112abcd426dc5ec248b5339bee04f2",
"license": "Apache-2.0",
"archived": false,
"private": false
},
{
"repo": "gfx-rs/wgpu",
"url": "https://github.com/gfx-rs/wgpu",
"branch": "trunk",
"head": "60cef2be828e03ba54e2e1598001b4625c0c2163",
"license": "Apache-2.0",
"archived": false,
"private": false
},
{
"repo": "LIEF-project/LIEF",
"url": "https://github.com/lief-project/LIEF",
"branch": "main",
"head": "2a6fdbc5a3af9b7ac797514ca38b1175c78f3fcf",
"license": "Apache-2.0",
"archived": false,
"private": false
},
{
"repo": "FEX-Emu/FEX",
"url": "https://github.com/FEX-Emu/FEX",
"branch": "main",
"head": "3ee25399232a6431c77c6314c437ea523ec29d0c",
"license": "MIT",
"archived": false,
"private": false
},
{
"repo": "apitrace/apitrace",
"url": "https://github.com/apitrace/apitrace",
"branch": "master",
"head": "28bb3aba57f3f9df4932867496308f4fc0a2b423",
"license": "MIT",
"archived": false,
"private": false
},
{
"repo": "apple/game-porting-toolkit",
"url": "https://github.com/apple/game-porting-toolkit",
"branch": "main",
"head": "4f42344c90be22112f46becc3fb9687f423f2f88",
"license": "Apache-2.0",
"archived": false,
"private": false
}
]
}
@@ -1,39 +0,0 @@
# Runtime integration source review
This continues the existing [donor audit ledger](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/audit-ledger.tsv), [donor reference assessment](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/reference-projects-2026-11-25.md) and [donor integration audit](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/hybrid-runtime-audit-2026-11-25.md). It does not recertify their execution results. Source review is evidence class D; newly run workloads must have separate execution records. No reference-project implementation was added to BetterXen source. A private bundle includes unmodified source/notices for the already selected libc dependency.
## Components affecting demonstrated blockers
| Component and exact revision | Source actually inspected | Finding and integration decision |
| --- | --- | --- |
| Wine `274fcfa9691bf3b7f24c0833ad33e9d57c3df65f` | `dlls/dxgi/swapchain.c`: D3D12 `Present`, worker presentation, destruction and release functions; LGPL-2.1-or-later header and `COPYING.LIB` | `d3d12_swapchain_present` waits up to 2000 ms on the frame-latency semaphore. The worker releases it after successful Vulkan presentation. This is a testable explanation for two-second frames, not proof of the installed CrossOver failure. Destruction joins the worker, destroys graphics resources and releases the command queue, device and factory. Do not replace CrossOver with this moving upstream head. |
| VKD3D-Proton `71cae091b06571e51446cf2a937f0b04c237c04d` | `libs/vkd3d/swapchain.c`: frame-latency wait/signal sites; `COPYING` | Separate internal and application latency events. LGPL-2.1-or-later. This is not proof CrossOver ships this implementation: its official source list names Vkd3d. No integration or performance claim. |
| DXMT `faa73e4a0686e432ce5d3bb99a02b5363d76885c` | `src/d3d12/d3d12_swapchain.cpp`: constructor/destructor and latency sites; `LICENSE` | Current source contains D3D12 development code despite older D3D11-only descriptions. Presence is not backend availability in installed CrossOver 26.3. LGPL-2.1-or-later, CodeWeavers attribution. Do not silently substitute an untested build. |
| NativeX Runtime `b3087ce0ab191227dc9e7af37cab97a0b097bb98` | Entire `fixtures/native_win_dxgi_multiframe.cpp` and `src/native_upload_arena.cpp`; tiled-resource fixture through its GPU copy/readback path; `LICENSE`, `docs/PUBLIC_SCOPE.md` | MIT at repository root; fixture says original synthetic Win32/WARP work. Multiframe fixture uses explicit pacing and fences, releases per-frame resources before resizing, and disclaims physical-GPU/pixel verification. Upload arena bounds allocations and recycles only completed fence ranges. Windows/WARP assumptions and project-local timing/upload headers prevent treating these as turnkey Mac tests. Historical title-specific planning is disclosed; independent origin is not certified by a licence label. Source-level comparison only; nothing adopted or executed. |
| d3dmetal-native `af1ee1710711fadff41dead87960d0f1336c1047` | Prior source/build record reused; no repeat build | See [donor evaluation](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/d3dmetal-native-evaluation.md), including exact dependencies and unverified framework rights. An x86-64 native graphics host does not replace Wine's Windows runtime and does not satisfy BetterXen's ARM64 host rule. No framework extraction, patching or new execution. |
Primary source links: [Wine swapchain](https://github.com/wine-mirror/wine/blob/274fcfa9691bf3b7f24c0833ad33e9d57c3df65f/dlls/dxgi/swapchain.c), [VKD3D-Proton](https://github.com/HansKristian-Work/vkd3d-proton/blob/71cae091b06571e51446cf2a937f0b04c237c04d/libs/vkd3d/swapchain.c), [DXMT](https://github.com/3Shain/dxmt/blob/faa73e4a0686e432ce5d3bb99a02b5363d76885c/src/d3d12/d3d12_swapchain.cpp), [NativeX fixture](https://github.com/ProhorovIlja/NativeX-Runtime/blob/b3087ce0ab191227dc9e7af37cab97a0b097bb98/fixtures/native_win_dxgi_multiframe.cpp).
## Shader decision and legitimate compiler path
The runtime consumes ordinary Windows shaders through CrossOver. `launcher/crates/bx-runtime` has no dependency on the console shader import. #394's compiler therefore solves no demonstrated requirement of this execution path. The complete per-file [independent #399 review](https://github.com/MacosPorters/betterxen/issues/399) and [donor decision proposal](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/shader-import-decision.md) identify unresolved origin and explicit project-policy exclusions. This candidate excludes #394 and the dependent #395 runner. Passing compiler tests cannot resolve those exclusions; no replacement console compiler is required.
Only the seven original `tests/conformance/test_d3d12_wave/` files from BetterXen commit `d8c7a398492c483599f02766ebf5707f38dc6128` are retained. The C runner has bounded inputs and releases successful-run resources; the build adds the missing GUID library. Numeric acceptance compares GPU words with independent arithmetic constants and checks a one-bit wrong expectation. Unsupported double precision is not counted as a pass.
Microsoft DXC is an external open-source **Windows guest build tool**, not a BetterXen x86-64 host executable. The selected release is [v1.9.2609](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609), asset `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` (verified against GitHub release metadata). Its LLVM/MIT/Microsoft notices stay with the external installation. No compiler DLL or executable is packaged. Original HLSL and its compiled output are separate from the excluded console compiler. The installer must verify the archive before use.
The external llvm-mingw pin remains release `20261117`, SHA-256 `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`, LLVM commit `5b10d2d74929eae78912771222c9855af97496f4`. Its wrappers are ISC; compiler, builtins, headers and runtime carry their own notices. The universal compiler is run natively on ARM64 and is not distributed. Build notices include the unmodified LLVM and MinGW runtime terms. Rust Windows COFF timestamps are explicitly disabled; source paths are remapped. The original independent #364 build review remains separate from this task.
## Provenance restrictions and permission scope
The reachable heads for skakwy/victory-mac and MacosPorters/victory-mac-new remain identical at `3ecbb8f96956513df71343ad9de41aa48b0b8008`. MacosPorters/VIctory-macOS is `d6fc0620f53a5c9073b9d08d0910c8d6aa5d0bdf`; pragyaangaur/VIctory-macOS is `b6dd0b184277fc307b93a4cc90d23dca9f05e7b3`. Existing inventories and permission records are reused. Contributor permission covers only independently owned contributions; it does not clear other contributors' lines or underlying third-party material. No broader permission document was established by this task.
The current engineering rules require a recorded per-file provenance and licence audit before taking any code or tooling from leaked-build derivatives, and exclude game-, asset- and decryption-specific code. Contributor permission covers only contributions the contributor owns. This candidate takes no additional source from those projects; the inherited Rust memory guard is an attributed conceptual reimplementation from #405, with the original per-component review preserved in its donor audit. The current Track D shader-format gate remains separate from the excluded #394 import. No policy amendment is needed for the current Windows shader probes.
## Accessibility check and limits
All 23 requested GitHub repositories were reachable during this task; public heads are saved in the [accessibility snapshot](maintainer-reference-heads.json), with authenticated private metadata kept in ignored local evidence. The existing 84-entry PortWatch inventory was not repeated. Except for the source files identified above, those checks are metadata only, not implementation review. LLVM, llvm-mingw, DXC, DirectX-Headers, DirectXTex, DirectX-Graphics-Samples, SPIRV-Cross, wgpu, LIEF, FEX and apitrace remain available references; none supplies a demonstrated missing loader, translator or backend for this candidate merely by being available.
The [CodeWeavers source page](https://www.codeweavers.com/crossover/source) publishes `crossover-sources-26.3.0.tar.gz`. This task downloads that official archive for targeted source comparison; downloading is not a rebuilt or validated replacement runtime. CodeWeavers' [graphics documentation](https://support.codeweavers.com/advanced-settings-in-crossover-mac?kb_language=en_US) separates D3DMetal's D3D11/12 support from DXVK's D3D10/11 role. A `dxvk` or `wined3d` selection must not be labelled proof of the active D3D12 implementation.
Apple's [Metal command execution documentation](https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/Cmd-Submiss/Cmd-Submiss.html) distinguishes submission, completion and presentation. Accordingly, an application fence and matching readback do not establish that pixels reached the compositor; screen capture remains a separate check. None of this establishes Xbox execution, commercial-game compatibility or performance.
+94
View File
@@ -84,3 +84,97 @@ Identification is not execution. `xenora shaders coverage` reports forms
discovered in metadata against forms the semantic decoder accepts
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
per form remains in `docs/status.toml`.
## 64 KiB swizzle (`SW_64KB_S`) — public sources (#505)
`xg_xs.dll` implements `SW_64KB_S` tile addressing for `TEXTURE2D`, one array
slice and one mip, over the element sizes the RB+ tables specify: 32-bpp RGBA8
(4-byte elements) and the BC family — BC1/BC4 with 8-byte blocks and
BC2/3/5/6H/7 with 16-byte blocks, where one "texel" element is a 4x4 block and
`elemLog2 = log2(block_bytes)`. At 32 bpp the two public sources below agree
bit-for-bit, which is why this is the mode implemented first; the 8- and 16-byte
rows come from AddrLib alone.
**Microsoft, `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE`** (public, no NDA):
<https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout>.
The page gives the 32-bpp masks `xBytesMask = 0xAA8F` and `yMask = 0x5570`,
combined with `_pdep_u32`. It states that tail-mip packing is **adapter-specific**,
which is why only the single-mip case is implemented. It has no `D` or `R` variant.
**AMD AddrLib (MIT)** — the authoritative public implementation, in both
[Mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib)
and [AMD PAL](https://github.com/GPUOpen-Drivers/pal/tree/dev/src/core/imported/addrlib)
(`SPDX-License-Identifier: MIT`, AMD copyright; PAL `LICENSE.txt` is MIT):
- `src/amd/addrlib/inc/addrtypes.h` — `AddrSwizzleMode`: `ADDR_SW_64KB_S` = 9,
`_D` = 10, `_R` = 11 (Reserved on GFX10).
- `src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h` — `GFX10_SW_64K_S_PATINFO`
and `GFX10_SW_64K_S_RBPLUS_PATINFO`, plus the `GFX10_SW_PATTERN_NIBBLE01/2/3/4`
tables. The RB+ variant is used because `gfx1030` is Navi2x.
- `src/amd/addrlib/src/gfx10/gfx10addrlib.h` — `GetSwizzlePatternFromPatternInfo`,
`IsInMipTail`.
- `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp` — `GetSwizzlePatternInfo`,
`HwlComputeSurfaceAddrFromCoordTiled`, `ComputeSurfaceAddrFromCoordMacroTiled`.
- `src/amd/addrlib/src/core/addrlib2.cpp` — `ComputeThinBlockDimension`,
`Block256_2d`.
There is **no** standalone GPUOpen `addrlib` repository (404). The public
[RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf)
only names a 5-bit "SW mode" field in the T# descriptor (bits 120:116) and does
not define the patterns.
### S versus D versus R
- **S and D are not interchangeable.** At 32 bpp RB+, D uses nibble01 index 39
(`[0,0,X0,X1,Y0,Y1,X2,Y2]`) while S uses index 2
(`[0,0,X0,X1,Y0,Y1,Y2,X2]`) — address bits 6 and 7 swapped.
- **`SW_64KB_R` has no public GFX10 form.** Mesa's `SwizzleModeTable` marks
`ADDR_SW_64KB_R` (enum 11) as Reserved; the render-target mode is
`ADDR_SW_64KB_R_X`, whose pipe/packer XOR depends on the console
`GB_ADDR_CONFIG`, which is not public.
### Xbox `XG` tile modes are NDA
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
interface have been retired: `xg_xs.dll` now follows the documented XG contract
titles call, with values from the authorized GDK documentation recorded as derived
facts in `shims/xg_xs/xg_xbox.cpp`.
### Element sizes and the derived masks
For a 64 KiB tile the intra-tile byte offset of element (x, y) is
`pdep(x, x_mask) | pdep(y, y_mask)`, where x and y are **block** indices (one
4x4 block for BC, one texel for 32 bpp). The masks were expanded by hand from
`GFX10_SW_PATTERN_NIBBLE01/2/3` at the patinfo indices
`GFX10_SW_64K_S_RBPLUS_PATINFO` selects for each `elemLog2`:
| block bytes | formats | `elemLog2` | x mask | y mask | tile (blocks) |
| --- | --- | --- | --- | --- | --- |
| 4 | R8G8B8A8_* | 2 | `0xAA8C` | `0x5570` | 128 x 128 |
| 8 | BC1, BC4 | 3 | `0xAAC8` | `0x5530` | 128 x 64 |
| 16 | BC2, BC3, BC5, BC6H, BC7 | 4 | `0xAAC0` | `0x5530` | 64 x 64 |
At 32 bpp the x mask `0xAA8C` is Microsoft's public `xBytesMask` `0xAA8F` with
the two intra-texel byte bits cleared (`0xAA8F & ~0x3`), and the y mask matches
`0x5570` exactly. The 8- and 16-byte rows have no D3D12 page to cross-check
against; they are AddrLib-only, which is stated in the PR risks. All three rows
were checked to be bijections over their 64 KiB tile (16384 / 8192 / 4096
distinct offsets, each block-aligned and inside the tile).
### Verification
The three masks above were expanded and their bijectivity checked against an
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
back from the shim:
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
the offsets are a bijection of aligned slots inside the 64 KiB tile;
- it checks that the 16 texels of a BC block share one byte offset.
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
Xbox-hardware claim.
+17
View File
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
## Built and run for M1-D2 (#417)
@@ -25,6 +26,22 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
| directx-native | [osy/directx-native](https://github.com/osy/directx-native) | `7258be1c56cdbf1e55c56b1bc4a866169c8ca0da` (pinned by d3dmetal-native's `subprojects/directx-native.wrap`) | Apache-2.0: repository `LICENSE`, plus `SPDX-License-Identifier: Apache-2.0` in 22 of its 25 files | Build dependency of d3dmetal-native, statically linked into the dylib; nothing is copied into BetterXen | Supplies the shared-resource and embedder headers that `d3dmetal_native.h` includes. Apache-2.0 is compatible with GPL-3.0, not GPL-2.0. |
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The package ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
## Interface facts for XGameSave and XPackage (#468, #492)
Facts only, no text or code copied. **Pending maintainer provenance acceptance** under AGENTS.md §4.
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| xgameruntime-docs | [xodus-gaming/xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) | `7090008692569aa6081e30dfdd9de58237741e24` | Repository `LICENSE` is the unmodified GNU GPL version 3 text. No project copyright holder is named, nothing states "only" or "or later", and the documentation files checked (`README.md`, `COM/XErrorImpl/IXErrorImpl.md`, `COM/XPackageImpl/IXPackageImpl.md`, `IXPackageImpl2.md`, `XErrorReport.md`) carry no licence or copyright header. | Source of the interface facts behind the public `QueryApiImpl` entries in `shims/xgameruntime/com_dispatch.cpp`: class and interface ids, interface inheritance, and vtable slot order for `IXGameSaveImpl`–`IXGameSaveImpl3` and `IXPackageImpl`–`IXPackageImpl4`. | Its README says the information "was found using black box reverse engineering" following Wine's clean-room guidelines. It states no use of Microsoft binaries, leaked material or the GDK EULA either way, and the COM notes say the listing is incomplete. It lists `IXErrorImpl` slot 3 only as unknown. BetterXen's answer for that slot (return `false`) instead follows an interop observation in the #492 review (2026-11-26), not this repository. Function signatures come from Microsoft Learn. |
## Vendored for the public PC DirectStorage interfaces (#483)
Checked on 2026-11-26 by reading the package files, not just its metadata. Not legal advice. Details and file hashes: [`shims/xcrdapi/dstorage/README.md`](../../shims/xcrdapi/dstorage/README.md).
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| DirectStorage SDK headers | NuGet [`Microsoft.Direct3D.DirectStorage`](https://www.nuget.org/packages/Microsoft.Direct3D.DirectStorage/1.4.0) | `1.4.0`, package SHA-256 `0838e7f71b14acfbd1ac7ecc5e943f6c95e4f4e679e8a67f8ff6e7c102414321` | `native/include/dstorage.h` and `dstorageerr.h` each carry `Copyright (c) Microsoft Corporation` / `Licensed under the MIT license`; the package's `LICENSE-CODE.txt` is the MIT text. The package as a whole is under the proprietary *Microsoft DirectStorage SDK* terms, whose distributables are only `dstorage.dll` and `dstoragecore.dll`. | The two headers are vendored unmodified in `shims/xcrdapi/dstorage/` for the public `IDStorage*` interfaces in `XCRDAPI.dll` and `test_xcrdapi`. No DLL or other package file is used or redistributed. | The headers are not in the MIT `microsoft/DirectStorage` repository; they ship only in this package. Microsoft Learn documents the same API but gives neither IIDs nor vtable order. The Xbox `IDStorage*X` interfaces (`dstorage_xs.h`) ship only in the GDK with Xbox Extensions, "only available to licensed partners", so they are excluded. |
## Additional candidates found by search (not reviewed)
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
+91 -13
View File
@@ -1,6 +1,6 @@
# BetterXen Roadmap
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
## Direction
@@ -9,7 +9,8 @@ BetterXen builds a modular **Xbox Series (`Scarlett`) compatibility layer for Ap
```text
BetterXen (in-tree):
launcher/ (ARM64 CLI, probe, telemetry) + abi/ (frozen contracts)
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs)
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs
+ the Rust-built bx_shader_bridge.dll)
shader-transpiler/ (DXBC / DXIL / ACCC / FSPX classifier & RDNA 2 pipeline)
|
External Foundation (user-installed, never bundled):
@@ -18,34 +19,111 @@ External Foundation (user-installed, never bundled):
Apple Silicon: ARM64, Metal, unified memory
```
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
---
## Completed Research Inputs (Carried Forward)
## Research Inputs
- **Licensing & redistribution boundaries:** [docs/research/crossover-licensing.md](research/crossover-licensing.md) and [docs/licenses.md](licenses.md) (#354). CrossOver, D3DMetal, and Rosetta 2 stay strictly external and unbundled.
- **Primary-source verification & upstream registry:** [docs/research/primary-source-verification-2026-11-25.md](research/primary-source-verification-2026-11-25.md), [docs/research/upstream-registry.md](research/upstream-registry.md), and [docs/research/component-reuse-matrix.md](research/component-reuse-matrix.md).
- **Hybrid measurement protocol:** [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) (#353).
- **Buffer ownership on CrossOver 26.3.0.39832 and D3DMetal 3.0 (#473).** On the tested M4 (24 GiB) and M5 (16 GiB), the two existing-memory heap imports returned `E_NOTIMPL`. A D3D12-owned persistent buffer mapping supported fence-separated CPU/GPU access and ordered virtual aliasing (BASE-2, BASE-4, A-8). The actual CPU address could miss 64 KiB alignment (A-6). Inside the timed small-copy window, no serialized copy cost as much as the explicit full copy to READBACK. The other workstream accepted 13 of 29 register entries within stated scopes, mostly through same-source reruns. #473 remains open. Physical page identity, hidden copies, workload memory savings and speedups remain open. [Report 001](https://github.com/MacosPorters/betterxen/blob/0aaa81ab81309d64432d97d3005284c8b13cd285/docs/research/publications/001-unified-memory/technical-findings.md) · [Evidence register](https://github.com/MacosPorters/betterxen/blob/f8810a48af384d13c594b9fba954200bfdb944f1/docs/research/d3dmetal-zero-copy/allocation-profiling/consolidation-draft/evidence-register.md) · [Review corrections](https://github.com/MacosPorters/betterxen/discussions/493)
- **Target-workload shader corpus (static scan, 2026-11-28).** A read-only container scan of an authorized local test workload measured what its shipped components embed — structure only, no run, no extraction, and the workload is not redistributed. Its `XboxBvhBuilder` component carries **52 DXIL compute containers, all Shader Model 6.5, with valid LLVM bitcode**; its AMD FidelityFX upscaler component carries **29 ACCC-only containers** whose payloads start with `FSPX`, none with a `DXIL` chunk; its main executable carries **10 DXIL containers (nine pixel, one vertex, Shader Model 6.6) whose `DXIL` chunks hold four-byte `NOBC` payloads** — valid program headers, no executable bitcode. Its packaged shader archive exposes no plaintext `DXBC` signatures and remains unclassified. BetterXen's classifier accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers because their section tables do not match the clean-room `FSPX` layout (`FspxSectionOutOfBounds` at the time of the scan; that cause is `FspxLayoutMismatch` since #599, not re-measured). Runtime use is unmeasured: the recorded startup run stopped before pipeline creation and wrote no `shader_gate` records. [ADR 0008](adr/0008-m2-shader-format-gate.md)
---
## Milestones (M0 → M6)
## Foundation and stages
| Milestone | Objective | Exit Gate | Status |
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
### Foundation (history)
| Milestone | What it established | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
### The stages
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
| Stage | The target build… | Exit gate | Status |
| --- | --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **In validation (PR #406)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime`, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, and combined synthetic integration boot fixture | All 13 Wave 1 conformance binaries pass under CrossOver + Rosetta 2; combined `integration_boot.exe` initializes every subsystem cleanly | **Next (Wave 1 ready)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, and `dxbc-accc` shader inspection to establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)** | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | Planned |
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
### Boot
**Known work, all found by running the target build:**
| Blocker | Effect | State |
| --- | --- | --- |
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
**Not needed for the gate:** audio output, correct pictures, performance.
### Picture
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
2. **The translator.** Vendor a pinned copy of the authorized upstream GFX10-to-DXIL translator into `shader-transpiler/` (per-file licence check, upstream registry and reuse matrix entries, ADR 0008 amendment), and expose it through `bx_shader_bridge.dll`. BetterXen owns its copy and fixes it.
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
### Menus to Playable — known work and unknowns
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
| Stage | Known work | Main unknown |
| --- | --- | --- |
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
### Decision gates
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
| Gate | When | Question | If the answer is no |
| --- | --- | --- | --- |
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
### What counts as progress
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
1. remove a blocker of the current stage (shown by the run report before and after);
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
4. retire a risk at a decision gate.
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
---
## How Progress Is Reported
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
-5
View File
@@ -7,11 +7,6 @@ It adds no runner and reports no new Windows or GPU execution results.
## Implementation checkpoint
Current runner: the same commands are `bx-cli` subcommands (`receipt`, `run`, `bench`,
`stop`, `frames`) and the workloads are under `tests/conformance/`; see
[maintainer testing](../maintainer-testing.md). The text below records the protocol as
first written against the earlier candidate and is kept for its provenance.
The commands below refer to [PR #384](https://github.com/MacosPorters/betterxen/pull/384),
reviewed at commit `566272082a74d8b45fcec37edd00f4f6703df3ab` on 2026-11-25.
Its `betterxen-hybrid` command, build script and Windows workloads are not on
+137
View File
@@ -0,0 +1,137 @@
# Target-Build Bring-Up: Development Cycle and Review
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
## Authorization is recorded, not assumed
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
- the build;
- the evidence class: target-build observation, or authorized SDK documentation;
- the maintainer who approved it;
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
- **The note's ID goes into every PR and every review** that relies on that evidence.
## Roles
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
- **Author.** Turns one finding into one single-track PR.
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
## Cycle
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
2. **Record the evidence privately,** under an evidence note ID.
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
6. **Review independently** (see "What a reviewer does").
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
### Bring-up checkpoints
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
1. **Starts:** reaches its first graphics device.
2. **Presents:** presents its first frame, whatever it contains.
3. **Frame loop:** keeps presenting for a recorded duration.
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
5. **Interactive:** reaches a menu that accepts input.
Each PR states which checkpoint it affects, and the measured result before and after.
## PR description template
```text
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
Source: "authorized SDK documentation" and/or "target-build observation";
never quote header or documentation text, never name the title or build
Authorization: authorization note ID
Evidence: evidence note ID(s)
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
Test: the conformance test that asserts the contract, and how its expected
values were derived independently of the implementation
Checkpoint: the checkpoint this affects, with the measured result before and after
```
## What a reviewer does
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
## Offline-run procedure
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
```sh
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
BOTTLE=<bottle name>
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
# serve the title outside it.
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
&& echo REACHABLE || echo BLOCKED
# 3. Run the title inside the same profile. Every process it starts, including the new
# wineserver, inherits the sandbox.
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 \
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
```
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
## Diagnostics
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
| Switch | Where | Effect |
| --- | --- | --- |
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
Their output can contain title addresses and file names, so it goes only into the private evidence store.
## Evidence
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
## What never enters the repository
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
- SDK header or documentation text;
- the title's name or file names;
- identifiers derived from the title or build: its hashes, addresses or raw logs;
- decompiled code or disassembly;
- screenshots of the title;
- personal paths.
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
+2 -1
View File
@@ -13,7 +13,8 @@ path = "src/main.rs"
bx-probe = { path = "../bx-probe" }
bx-telemetry = { path = "../bx-telemetry" }
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
bx-runtime = { path = "../bx-runtime" }
# POSIX signals and process groups for `run` supervision.
libc = "=0.2.191"
[lints]
workspace = true
+548
View File
@@ -0,0 +1,548 @@
//! Xbox title drive letters, linked in the prefix's `dosdevices` before launch.
//!
//! The project-authorized target title we traced reads its package from `G:` and writes
//! temporary files such as crash logs to `T:`. That is an observation of one title at startup;
//! that `G:` is the package root and `T:` temporary storage for Xbox titles in general is an
//! inference. A Wine prefix has neither drive, so that title's first `G:\...` open fails with
//! `STATUS_OBJECT_PATH_NOT_FOUND`. `bx-cli run` links `g:` to the executable's directory and
//! `t:` to `drive_c/bx_temp`.
//!
//! As with system32 staging (#474), a drive letter the prefix already uses is not ours. A
//! `.bx-drives` manifest in `dosdevices` records each link this tool made, and only a link that
//! is listed and still points where it was pointed is replaced. Any other mapping to a
//! different target is reported and left unchanged.
use std::collections::BTreeMap;
use std::fs;
use std::io::{self, Write};
use std::os::fd::AsRawFd;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::{OpenOptionsExt, symlink};
use std::path::{Path, PathBuf};
const MANIFEST: &str = ".bx-drives";
const LOCK_FILE: &str = ".bx-drive-mapping.lock";
/// The prefix-relative target of `t:`, in the form Wine itself uses for `c:`.
pub const TEMP_TARGET: &str = "../drive_c/bx_temp";
#[derive(Debug)]
pub struct DriveMappingLock {
_file: fs::File,
}
/// Holds the prefix's drive mappings stable until the returned lock is dropped.
pub fn lock_drive_mappings(prefix: &Path) -> Result<DriveMappingLock, String> {
fs::create_dir_all(prefix).map_err(|e| {
format!(
"cannot prepare prefix {} for drive lock: {e}",
prefix.display()
)
})?;
let prefix = fs::canonicalize(prefix).map_err(|e| {
format!(
"cannot resolve prefix {} for drive lock: {e}",
prefix.display()
)
})?;
let path = prefix.join(LOCK_FILE);
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.custom_flags(libc::O_NOFOLLOW)
.open(&path)
.map_err(|e| format!("cannot open drive lock {}: {e}", path.display()))?;
loop {
// The open file descriptor stays alive in DriveMappingLock for the full launch.
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if result == 0 {
return Ok(DriveMappingLock { _file: file });
}
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted {
continue;
}
if error.kind() == io::ErrorKind::WouldBlock {
return Err(format!(
"another bx-cli run is active for prefix {}; refusing to launch with shared Xbox drive mappings",
prefix.display()
));
}
return Err(format!("cannot lock {}: {error}", path.display()));
}
}
#[derive(Debug)]
pub enum Mapping {
Created(char, PathBuf),
/// A link this tool made earlier, pointed at a new target.
Retargeted(char, PathBuf),
Unchanged(char, PathBuf),
/// A mapping this tool did not make, to a different target; left as it is.
Foreign {
letter: char,
existing: String,
wanted: PathBuf,
},
}
impl Mapping {
pub fn describe(&self) -> String {
match self {
Mapping::Created(l, t) => {
format!("mapped {}: to {}", l.to_ascii_uppercase(), t.display())
}
Mapping::Retargeted(l, t) => {
format!(
"remapped own {}: to {}",
l.to_ascii_uppercase(),
t.display()
)
}
Mapping::Unchanged(l, t) => {
format!(
"{}: already maps to {}",
l.to_ascii_uppercase(),
t.display()
)
}
Mapping::Foreign {
letter,
existing,
wanted,
} => format!(
"warning: {}: already maps to {existing}, not {}; left unchanged, so the guest \
may not find its files there",
letter.to_ascii_uppercase(),
wanted.display()
),
}
}
}
fn read_manifest(dosdevices: &Path) -> Result<BTreeMap<char, PathBuf>, String> {
let path = dosdevices.join(MANIFEST);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
};
let mut owned = BTreeMap::new();
for line in text.lines().filter(|l| !l.is_empty()) {
let mut chars = line.chars();
match (chars.next(), chars.next()) {
(Some(letter), Some('\t')) if letter.is_ascii_lowercase() => {
let encoded = chars.as_str();
let target = match encoded.strip_prefix('@') {
Some(hex) => decode_path(hex)
.ok_or_else(|| format!("malformed path in {}: {line:?}", path.display()))?,
None => PathBuf::from(encoded),
};
owned.insert(letter, target);
}
_ => return Err(format!("malformed line in {}: {line:?}", path.display())),
}
}
Ok(owned)
}
fn write_manifest(dosdevices: &Path, owned: &BTreeMap<char, PathBuf>) -> Result<(), String> {
let path = dosdevices.join(MANIFEST);
let mut text = String::new();
for (letter, target) in owned {
text.push_str(&format!("{letter}\t@{}\n", encode_path(target)));
}
// Written to a temporary file and renamed over the manifest, like `relink`, so an
// interrupted write can never leave a truncated manifest that later runs refuse to parse.
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)
.map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
let written = file.write_all(text.as_bytes()).and_then(|()| {
drop(file);
fs::rename(&tmp, &path)
});
if written.is_err() {
let _ = fs::remove_file(&tmp);
}
written.map_err(|e| format!("cannot write {}: {e}", path.display()))
}
fn encode_path(path: &Path) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let bytes = path.as_os_str().as_bytes();
let mut encoded = String::with_capacity(bytes.len() * 2);
for &byte in bytes {
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
encoded
}
fn decode_path(hex: &str) -> Option<PathBuf> {
fn nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
let bytes = hex.as_bytes();
if bytes.len() % 2 != 0 {
return None;
}
let mut decoded = Vec::with_capacity(bytes.len() / 2);
for pair in bytes.chunks_exact(2) {
decoded.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
}
Some(PathBuf::from(std::ffi::OsString::from_vec(decoded)))
}
/// Points `link` at `target`, replacing what is there through a rename so the link never
/// disappears in between.
fn relink(dosdevices: &Path, link: &Path, target: &Path) -> io::Result<()> {
let tmp = dosdevices.join(format!(".bx-drive-tmp.{}", std::process::id()));
let _ = fs::remove_file(&tmp);
symlink(target, &tmp)?;
let result = fs::rename(&tmp, link);
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result
}
/// Links `g:` to `package_dir` and `t:` to [`TEMP_TARGET`] in `prefix`'s `dosdevices`.
pub fn map_xbox_drives(prefix: &Path, package_dir: &Path) -> Result<Vec<Mapping>, String> {
let dosdevices = prefix.join("dosdevices");
if !dosdevices.is_dir() {
return Err(format!(
"{} does not exist (start the prefix once so Wine creates it)",
dosdevices.display()
));
}
let temp_dir = prefix.join("drive_c/bx_temp");
fs::create_dir_all(&temp_dir)
.map_err(|e| format!("cannot create {}: {e}", temp_dir.display()))?;
let mut owned = read_manifest(&dosdevices)?;
let mut mappings = Vec::new();
for (letter, target) in [
('g', package_dir.to_path_buf()),
('t', PathBuf::from(TEMP_TARGET)),
] {
let link = dosdevices.join(format!("{letter}:"));
let current = match fs::symlink_metadata(&link) {
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(format!("cannot inspect {}: {e}", link.display())),
Ok(meta) if meta.file_type().is_symlink() => Some(
fs::read_link(&link).map_err(|e| format!("cannot read {}: {e}", link.display()))?,
),
Ok(_) => {
mappings.push(Mapping::Foreign {
letter,
existing: format!("a non-link entry {}", link.display()),
wanted: target,
});
continue;
}
};
let mapping = match current {
None => {
owned.insert(letter, target.clone());
write_manifest(&dosdevices, &owned)?;
relink(&dosdevices, &link, &target)
.map_err(|e| format!("cannot create {}: {e}", link.display()))?;
Mapping::Created(letter, target.clone())
}
Some(current) if current == target => Mapping::Unchanged(letter, target.clone()),
Some(current) if owned.get(&letter) == Some(&current) => {
owned.insert(letter, target.clone());
write_manifest(&dosdevices, &owned)?;
if let Err(error) = relink(&dosdevices, &link, &target) {
owned.insert(letter, current);
let restore = write_manifest(&dosdevices, &owned);
let detail = restore
.err()
.map(|e| format!("; also could not restore the drive manifest: {e}"))
.unwrap_or_default();
return Err(format!(
"cannot replace {}: {error}{detail}",
link.display()
));
}
Mapping::Retargeted(letter, target.clone())
}
Some(current) => {
mappings.push(Mapping::Foreign {
letter,
existing: current.display().to_string(),
wanted: target,
});
continue;
}
};
mappings.push(mapping);
}
Ok(mappings)
}
#[cfg(test)]
mod tests {
use super::*;
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let p = std::env::temp_dir().join(format!(
"bx-drives-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&p);
fs::create_dir_all(p.join("prefix/dosdevices")).unwrap();
fs::create_dir_all(p.join("game")).unwrap();
TempDir(p)
}
fn prefix(&self) -> PathBuf {
self.0.join("prefix")
}
fn game(&self) -> PathBuf {
self.0.join("game")
}
fn link(&self, letter: char) -> PathBuf {
self.0.join(format!("prefix/dosdevices/{letter}:"))
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn missing_drives_are_created_and_resolve() {
let t = TempDir::new("create");
fs::write(t.game().join("package.bin"), b"pkg").unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(
mappings[..],
[Mapping::Created('g', _), Mapping::Created('t', _)]
));
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
assert_eq!(
fs::read_link(t.link('t')).unwrap(),
PathBuf::from(TEMP_TARGET)
);
// Both links resolve the way Wine resolves them, from inside dosdevices.
assert_eq!(fs::read(t.link('g').join("package.bin")).unwrap(), b"pkg");
assert!(t.link('t').is_dir());
}
#[test]
fn a_second_run_changes_nothing() {
let t = TempDir::new("rerun");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(
mappings[..],
[Mapping::Unchanged('g', _), Mapping::Unchanged('t', _)]
));
}
#[test]
fn an_own_link_follows_a_new_package_directory() {
let t = TempDir::new("retarget");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(mappings[0], Mapping::Retargeted('g', _)));
assert_eq!(fs::read_link(t.link('g')).unwrap(), other);
}
#[test]
fn a_foreign_mapping_is_reported_and_kept() {
let t = TempDir::new("foreign");
let elsewhere = t.0.join("elsewhere");
symlink(&elsewhere, t.link('g')).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
assert!(mappings[0].describe().starts_with("warning: G:"));
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
// A link this tool did not record is never treated as its own on a later run.
let again = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&again[0], Mapping::Foreign { letter: 'g', .. }));
}
#[test]
fn an_own_link_changed_by_someone_else_becomes_foreign() {
let t = TempDir::new("changed");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
fs::remove_file(t.link('g')).unwrap();
let elsewhere = t.0.join("elsewhere");
symlink(&elsewhere, t.link('g')).unwrap();
let other = t.0.join("other-game");
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
}
#[test]
fn a_non_link_entry_is_never_touched() {
let t = TempDir::new("nonlink");
fs::create_dir_all(t.link('t')).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&mappings[1], Mapping::Foreign { letter: 't', .. }));
assert!(t.link('t').is_dir() && !fs::symlink_metadata(t.link('t')).unwrap().is_symlink());
}
#[test]
fn a_prefix_without_dosdevices_is_an_error() {
let t = TempDir::new("nodos");
fs::remove_dir_all(t.prefix().join("dosdevices")).unwrap();
let e = map_xbox_drives(&t.prefix(), &t.game()).unwrap_err();
assert!(e.contains("dosdevices"), "{e}");
}
#[test]
fn a_malformed_manifest_is_an_error_not_an_ownership_claim() {
let t = TempDir::new("badmanifest");
fs::write(t.prefix().join("dosdevices").join(MANIFEST), "g /x\n").unwrap();
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
}
#[test]
fn a_failed_manifest_write_leaves_no_unrecorded_link() {
let t = TempDir::new("orphan");
// A directory where the manifest's temporary file goes makes the write fail.
let tmp = t
.prefix()
.join("dosdevices")
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
fs::create_dir(&tmp).unwrap();
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
assert!(
fs::symlink_metadata(t.link('g')).is_err(),
"g: must not be created before ownership is recorded"
);
fs::remove_dir(&tmp).unwrap();
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
}
#[test]
fn an_interrupted_manifest_write_keeps_the_previous_manifest() {
let t = TempDir::new("atomic");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let manifest = t.prefix().join("dosdevices").join(MANIFEST);
let before = fs::read(&manifest).unwrap();
// Fail the next write after the new contents would have been produced: the old
// manifest must survive whole, never truncated or half written.
let tmp = t
.prefix()
.join("dosdevices")
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
fs::create_dir(&tmp).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
assert_eq!(
fs::read(&manifest).unwrap(),
before,
"previous manifest kept intact"
);
fs::remove_dir(&tmp).unwrap();
// The intact manifest still proves ownership, so the retry re-points g:.
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
assert!(
fs::read_dir(t.prefix().join("dosdevices"))
.unwrap()
.all(|e| !e.unwrap().file_name().to_string_lossy().contains(".tmp."))
);
}
#[test]
fn manifest_temp_does_not_follow_an_existing_symlink() {
let t = TempDir::new("manifest-symlink");
let dosdevices = t.prefix().join("dosdevices");
let target = t.0.join("outside-manifest");
fs::write(&target, b"unchanged").unwrap();
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
symlink(&target, &tmp).unwrap();
assert!(write_manifest(&dosdevices, &BTreeMap::new()).is_err());
assert_eq!(fs::read(&target).unwrap(), b"unchanged");
assert_eq!(fs::read_link(&tmp).unwrap(), target);
}
#[test]
fn a_failed_retarget_restores_the_previous_manifest_and_link() {
let t = TempDir::new("retarget-failure");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let temp_link = t
.prefix()
.join("dosdevices")
.join(format!(".bx-drive-tmp.{}", std::process::id()));
fs::create_dir(&temp_link).unwrap();
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
t.game()
);
}
#[test]
fn a_prefix_lock_rejects_another_launcher_until_released() {
let t = TempDir::new("lock");
let lock = lock_drive_mappings(&t.prefix()).unwrap();
let error = lock_drive_mappings(&t.prefix()).unwrap_err();
assert!(error.contains("another bx-cli run"), "{error}");
drop(lock);
assert!(lock_drive_mappings(&t.prefix()).is_ok());
}
#[test]
fn a_non_utf8_target_round_trips_through_the_manifest() {
let t = TempDir::new("non-utf8");
let mut game_bytes = t.0.as_os_str().as_bytes().to_vec();
game_bytes.extend_from_slice(b"/game-\xff");
let game = PathBuf::from(std::ffi::OsString::from_vec(game_bytes));
let owned = BTreeMap::from([('g', game.clone())]);
write_manifest(&t.prefix().join("dosdevices"), &owned).unwrap();
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
game
);
}
#[test]
fn a_legacy_plain_text_target_still_reads() {
let t = TempDir::new("legacy-manifest");
let legacy_target = t.0.join("old-game");
fs::write(
t.prefix().join("dosdevices").join(MANIFEST),
format!("g\t{}\n", legacy_target.display()),
)
.unwrap();
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
legacy_target
);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+492
View File
@@ -0,0 +1,492 @@
//! Supervision for `bx-cli run` (#408): the launcher gets its own process group, and a timeout
//! or signal stops that group and then the environment's `wineserver`.
//!
//! The `wineserver` is stopped only after a timeout or signal, never after a normal exit,
//! because it ends every program in that bottle or prefix, not only this run's.
use std::io::IsTerminal;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use std::time::{Duration, Instant};
const POLL: Duration = Duration::from_millis(50);
/// How long the launcher group has to exit after SIGTERM before SIGKILL.
const GRACE: Duration = Duration::from_secs(5);
const SERVER_WAIT: Duration = Duration::from_secs(15);
/// Signals that stop the run: the guest group is terminated and the environment cleaned up.
/// SIGQUIT (Ctrl-\) is included so it cannot kill `bx-cli` and leave the guest running (#461).
const STOP_SIGNALS: [libc::c_int; 4] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];
static SIGNAL: AtomicI32 = AtomicI32::new(0);
static SUSPEND: AtomicBool = AtomicBool::new(false);
/// Total time this process has spent suspended inside [`supervise`], in nanoseconds.
static SUSPENDED_NANOS: AtomicU64 = AtomicU64::new(0);
extern "C" fn note_signal(signal: libc::c_int) {
SIGNAL.store(signal, Ordering::SeqCst);
}
extern "C" fn note_suspend(_signal: libc::c_int) {
SUSPEND.store(true, Ordering::SeqCst);
}
/// Installs `handler` for `signal` unless the disposition this process inherited is `SIG_IGN`.
/// Returns whether the handler was installed.
///
/// A signal the caller chose to ignore (`nohup`, or a `&` job of a non-interactive shell) stays
/// ignored, so it cannot stop the run or the bottle (#461).
fn install_unless_ignored(signal: libc::c_int, handler: extern "C" fn(libc::c_int)) -> bool {
// SAFETY: `current` is a valid, writable sigaction; a null new action only queries. The
// handlers passed here only store to an atomic, which is async-signal-safe.
unsafe {
let mut current: libc::sigaction = std::mem::zeroed();
if libc::sigaction(signal, std::ptr::null(), &mut current) == 0
&& current.sa_sigaction == libc::SIG_IGN
{
return false;
}
libc::signal(signal, handler as libc::sighandler_t) != libc::SIG_ERR
}
}
/// Records SIGINT, SIGTERM, SIGHUP and SIGQUIT instead of dying, so the run can be cleaned up,
/// and records SIGTSTP (Ctrl-Z) so the guest group can be suspended together with `bx-cli`.
/// Signals that were inherited as ignored are left ignored.
///
/// SIGTSTP is only acted on inside [`supervise`]. A Ctrl-Z typed while nothing is being
/// supervised (for example while shims are copied) has no visible effect until the next
/// supervised phase starts, which is then suspended at once.
pub fn install_signal_handlers() {
for signal in STOP_SIGNALS {
install_unless_ignored(signal, note_signal);
}
install_unless_ignored(libc::SIGTSTP, note_suspend);
}
pub fn received_signal() -> i32 {
SIGNAL.load(Ordering::SeqCst)
}
/// Total time spent suspended (Ctrl-Z until continued) across every [`supervise`] call so far.
///
/// A caller that budgets one `--timeout` over several supervised phases subtracts this from its
/// own wall-clock measurement, so a pause during an earlier phase is not charged to a later one.
pub fn suspended_time() -> Duration {
Duration::from_nanos(SUSPENDED_NANOS.load(Ordering::SeqCst))
}
/// True once per SIGTSTP received since the last call.
fn take_suspend_request() -> bool {
SUSPEND.swap(false, Ordering::SeqCst)
}
/// Stops this process the way the terminal's Ctrl-Z would; returns when it is continued.
fn suspend_self(_guest: libc::pid_t) {
// SAFETY: raise takes no pointers. SIGSTOP cannot be caught, so this stops the process.
unsafe {
libc::raise(libc::SIGSTOP);
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Stop {
TimedOut,
Signalled(i32),
}
#[derive(Debug)]
pub enum Outcome {
Exited(ExitStatus),
Stopped(Stop),
}
impl Outcome {
/// The guest's own numeric exit code (so a conformance fixture's documented exit-77 skip
/// stays distinguishable from a failure, #565), 124 for a timeout (as `timeout(1)`),
/// 128 + N for a signal.
pub fn exit_code(&self) -> u8 {
match self {
// Unix guest codes are already 0-255; a signalled guest has no code, which is a
// failure. `code.max(1)` at the call sites still turns a failed cleanup into 1.
Outcome::Exited(status) => status.code().map_or(1, |code| code.clamp(0, 255) as u8),
Outcome::Stopped(Stop::TimedOut) => 124,
Outcome::Stopped(Stop::Signalled(signal)) => 128u8.saturating_add(*signal as u8),
}
}
}
fn signal_group(child: &Child, signal: libc::c_int) {
// SAFETY: kill takes no pointers. The child leads its own group and has not been reaped,
// so the group id cannot have been reused.
unsafe {
libc::kill(-(child.id() as libc::pid_t), signal);
}
}
fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if Instant::now() >= deadline {
return Ok(None);
}
std::thread::sleep(POLL);
}
}
/// Runs `command` in a new process group until it exits, `timeout` passes, or `signal`
/// returns non-zero. On a stop the whole group is terminated before this returns.
///
/// The guest is not in the terminal's foreground group, so Ctrl-Z reaches only `bx-cli`. It is
/// passed on: the guest group gets SIGTSTP, `bx-cli` stops itself, and when `bx-cli` is continued
/// the guest group gets SIGCONT. Time spent suspended does not count against `timeout`.
pub fn supervise(
command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
) -> std::io::Result<Outcome> {
supervise_with(command, timeout, signal, take_suspend_request, suspend_self)
}
/// [`supervise`] with the suspend request and the self-stop injected, so tests can exercise the
/// job-control path without stopping the test process. `suspend` is called with the guest
/// group's id after that group was sent SIGTSTP and returns when the launcher may continue.
fn supervise_with(
mut command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
suspend_requested: impl Fn() -> bool,
mut suspend: impl FnMut(libc::pid_t),
) -> std::io::Result<Outcome> {
// A background process group is stopped by SIGTTIN if it reads the terminal, so a terminal
// is replaced by end-of-file. Piped and redirected input is passed through.
if std::io::stdin().is_terminal() {
command.stdin(Stdio::null());
}
let mut child = command.process_group(0).spawn()?;
let started = Instant::now();
let mut suspended = Duration::ZERO;
let stop = loop {
if let Some(status) = child.try_wait()? {
return Ok(Outcome::Exited(status));
}
let received = signal();
if received != 0 {
break Stop::Signalled(received);
}
if suspend_requested() {
let paused = Instant::now();
signal_group(&child, libc::SIGTSTP);
suspend(child.id() as libc::pid_t);
signal_group(&child, libc::SIGCONT);
let pause = paused.elapsed();
suspended += pause;
SUSPENDED_NANOS.fetch_add(
u64::try_from(pause.as_nanos()).unwrap_or(u64::MAX),
Ordering::SeqCst,
);
continue;
}
if timeout.is_some_and(|limit| started.elapsed().saturating_sub(suspended) >= limit) {
break Stop::TimedOut;
}
std::thread::sleep(POLL);
};
signal_group(&child, libc::SIGTERM);
// Wait without reaping first, so SIGKILL still reaches members that outlive the leader.
std::thread::sleep(POLL);
let deadline = Instant::now() + GRACE;
while Instant::now() < deadline && group_leader_running(&child) {
std::thread::sleep(POLL);
}
signal_group(&child, libc::SIGKILL);
wait_until(&mut child, Instant::now() + GRACE)?;
Ok(Outcome::Stopped(stop))
}
/// True while the leader has not exited; does not reap it.
fn group_leader_running(child: &Child) -> bool {
// SAFETY: `info` is a valid, writable siginfo_t and WNOWAIT leaves the child unreaped.
unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
libc::waitid(
libc::P_PID,
child.id() as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
) == 0
&& info.si_pid() == 0
}
}
/// `wineserver -k` then `-w` for the environment at `prefix`.
///
/// `-k` exits 1 when no server is running (observed on CrossOver 26.3), so 1 is accepted
/// there; `-w` must still succeed, which a surviving server prevents.
///
/// Each `wineserver` runs in its own process group with no terminal input, so a second Ctrl-C
/// typed while cleanup is running reaches only `bx-cli` (which records it) and cannot kill the
/// cleanup itself (#461).
pub fn stop_server(
wineserver: &Path,
prefix: &Path,
environment: &[(String, String)],
) -> Result<(), String> {
for (flag, idle_code) in [("-k", Some(1)), ("-w", None)] {
let mut child = Command::new(wineserver)
.arg(flag)
.env_clear()
.envs(environment.iter().map(|(k, v)| (k, v)))
.env("WINEPREFIX", prefix)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0)
.spawn()
.map_err(|e| format!("cannot start wineserver {flag}: {e}"))?;
match wait_until(&mut child, Instant::now() + SERVER_WAIT) {
Ok(Some(status)) if status.success() => {}
Ok(Some(status)) if idle_code.is_some() && status.code() == idle_code => {}
other => {
let _ = child.kill();
let _ = child.wait();
return Err(format!("wineserver {flag} did not succeed: {other:?}"));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
fn shell(script: &str) -> Command {
let mut command = Command::new("/bin/sh");
command.args(["-c", script]);
command
}
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("bx-cli-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn classifies_exit_timeout_and_signal() {
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
assert_eq!(ok.exit_code(), 0);
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
assert_eq!(failed.exit_code(), 7);
// A conformance fixture's documented skip must stay distinguishable from a failure
// through `bx-cli run` (#565); the old `!status.success()` collapsed it to 1.
let skipped = supervise(shell("exit 77"), Some(Duration::from_secs(10)), || 0).unwrap();
assert_eq!(skipped.exit_code(), 77);
let slow = supervise(shell("sleep 30"), Some(Duration::from_millis(200)), || 0).unwrap();
assert!(matches!(slow, Outcome::Stopped(Stop::TimedOut)));
assert_eq!(slow.exit_code(), 124);
let interrupted = supervise(shell("sleep 30"), None, || libc::SIGTERM).unwrap();
assert_eq!(interrupted.exit_code(), 128 + libc::SIGTERM as u8);
}
#[test]
fn a_timeout_stops_children_that_ignore_sigterm() {
let dir = scratch("group");
let pid_file = dir.join("child.pid");
let script = format!(
"(trap '' TERM; exec sleep 30) & echo $! > '{}'; wait",
pid_file.display()
);
supervise(shell(&script), Some(Duration::from_millis(500)), || 0).unwrap();
let pid: libc::pid_t = std::fs::read_to_string(&pid_file)
.unwrap()
.trim()
.parse()
.unwrap();
let gone = (0..100).any(|_| {
std::thread::sleep(POLL);
// SAFETY: signal 0 only checks whether the process exists.
unsafe { libc::kill(pid, 0) != 0 }
});
assert!(gone, "grandchild {pid} survived the timeout");
std::fs::remove_dir_all(dir).unwrap();
}
/// Signal dispositions and the recorded signal are process-wide: tests that touch them run
/// one at a time and use signals no other test raises.
static SIGNAL_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn set_disposition(signal: libc::c_int, action: libc::sighandler_t) {
// SAFETY: SIG_DFL and SIG_IGN are valid dispositions for these signals.
unsafe {
libc::signal(signal, action);
}
}
fn disposition(signal: libc::c_int) -> libc::sighandler_t {
// SAFETY: a null new action only queries; `current` is valid and writable.
unsafe {
let mut current: libc::sigaction = std::mem::zeroed();
assert_eq!(libc::sigaction(signal, std::ptr::null(), &mut current), 0);
current.sa_sigaction
}
}
fn raise(signal: libc::c_int) {
// SAFETY: raise takes no pointers.
unsafe {
libc::raise(signal);
}
}
#[test]
fn an_inherited_ignored_signal_stays_ignored() {
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
// As under nohup: the signal arrives already ignored.
set_disposition(libc::SIGUSR2, libc::SIG_IGN);
SIGNAL.store(0, Ordering::SeqCst);
assert!(!install_unless_ignored(libc::SIGUSR2, note_signal));
assert_eq!(disposition(libc::SIGUSR2), libc::SIG_IGN);
raise(libc::SIGUSR2);
assert_eq!(
received_signal(),
0,
"an ignored signal must not stop the run"
);
// Control: the same signal with the default disposition is recorded.
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
assert!(install_unless_ignored(libc::SIGUSR2, note_signal));
raise(libc::SIGUSR2);
assert_eq!(received_signal(), libc::SIGUSR2);
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
SIGNAL.store(0, Ordering::SeqCst);
}
#[test]
fn sigquit_is_recorded_and_stops_the_guest_group() {
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
assert!(STOP_SIGNALS.contains(&libc::SIGQUIT));
let before = disposition(libc::SIGQUIT);
set_disposition(libc::SIGQUIT, libc::SIG_DFL);
SIGNAL.store(0, Ordering::SeqCst);
assert!(install_unless_ignored(libc::SIGQUIT, note_signal));
// Without the handler this would kill the test process, as it killed bx-cli.
raise(libc::SIGQUIT);
assert_eq!(received_signal(), libc::SIGQUIT);
set_disposition(libc::SIGQUIT, before);
SIGNAL.store(0, Ordering::SeqCst);
let stopped = supervise(shell("sleep 30"), None, || libc::SIGQUIT).unwrap();
assert!(matches!(
stopped,
Outcome::Stopped(Stop::Signalled(libc::SIGQUIT))
));
assert_eq!(stopped.exit_code(), 128 + libc::SIGQUIT as u8);
}
/// True once `pid` is reported stopped; leaves the status in place.
fn is_stopped(pid: libc::pid_t) -> bool {
(0..100).any(|_| {
// SAFETY: `info` is valid and writable; WNOWAIT leaves the child's state in place.
let stopped = unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WSTOPPED | libc::WNOHANG | libc::WNOWAIT,
) == 0
&& info.si_pid() == pid
};
if !stopped {
std::thread::sleep(POLL);
}
stopped
})
}
#[test]
fn a_suspend_request_stops_and_resumes_the_guest_without_using_up_the_timeout() {
let requested = std::cell::Cell::new(false);
let guest_was_stopped = std::cell::Cell::new(false);
let suspended_before = suspended_time();
let outcome = supervise_with(
shell("sleep 0.4; exit 0"),
// Shorter than the suspension below: only running time may count.
Some(Duration::from_millis(1500)),
|| 0,
|| !requested.replace(true),
|guest| {
guest_was_stopped.set(is_stopped(guest));
std::thread::sleep(Duration::from_millis(2000));
},
)
.unwrap();
assert!(guest_was_stopped.get(), "the guest group was not stopped");
// The pause is also reported to callers that budget a timeout across several phases.
let reported = suspended_time() - suspended_before;
assert!(reported >= Duration::from_millis(2000), "{reported:?}");
match outcome {
Outcome::Exited(status) => assert!(status.success(), "{status}"),
other => panic!("the resumed guest should have finished on its own: {other:?}"),
}
}
#[test]
fn cleanup_runs_outside_the_callers_process_group() {
let dir = scratch("cleanup-group");
let server = dir.join("wineserver");
let seen = dir.join("pgid");
std::fs::write(
&server,
format!(
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
seen.display()
),
)
.unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_server(&server, &dir, &[]).unwrap();
// SAFETY: getpgrp takes no arguments and cannot fail.
let ours = unsafe { libc::getpgrp() };
let groups: Vec<libc::pid_t> = std::fs::read_to_string(&seen)
.unwrap()
.lines()
.map(|line| line.trim().parse().unwrap())
.collect();
assert_eq!(groups.len(), 2, "-k and -w should both have run");
for group in groups {
// A terminal signal goes to the foreground group, which these are not part of.
assert_ne!(group, ours, "cleanup shares the caller's process group");
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn an_idle_server_is_accepted_only_when_the_wait_succeeds() {
let dir = scratch("server");
for (name, kill, wait, ok) in [
("running", 0, 0, true),
("idle", 1, 0, true),
("stuck", 1, 1, false),
("broken", 2, 0, false),
] {
let server = dir.join(name);
std::fs::write(
&server,
format!("#!/bin/sh\n[ \"$1\" = -k ] && exit {kill}\nexit {wait}\n"),
)
.unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(stop_server(&server, &dir, &[]).is_ok(), ok, "{name}");
}
std::fs::remove_dir_all(dir).unwrap();
}
}
+43
View File
@@ -0,0 +1,43 @@
//! Runs the built `bx-cli` binary to check what `main` prints and returns for the
//! usage paths (#532). The unit tests cover `Dispatch::classify`; these cover the
//! mapping from that classification to the real exit code and output stream.
use std::process::Command;
fn run(args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_bx-cli"))
.args(args)
.env_clear()
.output()
.expect("bx-cli must start")
}
#[test]
fn help_prints_usage_on_stdout_and_succeeds() {
for flag in ["--help", "-h", "help"] {
let out = run(&[flag]);
assert!(out.status.success(), "{flag}: {:?}", out.status);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("bx-cli run --exe"),
"{flag}: usage on stdout: {stdout}"
);
assert!(out.stderr.is_empty(), "{flag}: nothing on stderr");
}
}
#[test]
fn a_bare_invocation_is_a_usage_error_on_stderr() {
let out = run(&[]);
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "nothing on stdout");
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
}
#[test]
fn an_unknown_subcommand_is_a_usage_error_on_stderr() {
let out = run(&["frobnicate"]);
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "nothing on stdout");
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
}
+349 -11
View File
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
}
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeSummary {
pub image_base: u64,
pub size_of_image: u32,
@@ -128,12 +128,21 @@ struct Section {
}
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
}
/// Map an RVA to a file offset and report how many raw bytes remain in that
/// section from the mapped offset. The bound lets callers walk a table without
/// leaving the section that contains it.
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
for s in sections {
let span = s.vsize.max(s.raw_size);
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
let delta = rva - s.vaddr;
if delta < s.raw_size {
return Some((s.raw_ptr + delta) as usize);
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
return Some((off, remaining));
}
}
}
@@ -167,8 +176,36 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
let mut sections = Vec::with_capacity(section_count as usize);
// The import data directory is entry index 1, an 8-byte RVA/size pair at
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
// validated while the optional header is read: a short optional header must
// not let the read fall through into the section table.
const IMPORT_DIR_INDEX: u32 = 1;
const IMPORT_DIR_OFF: usize = 112 + 8;
let mut import_dir: Option<(u32, u32)> = None;
if num_rvas > IMPORT_DIR_INDEX {
let entry = bytes
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
if IMPORT_DIR_OFF + 8 > opt_size {
return Err(ProbeError::NotPe32Plus(
"import directory outside SizeOfOptionalHeader",
));
}
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
import_dir = Some((rva, size));
}
let sec_base = opt + opt_size;
let section_table_size = (section_count as usize)
.checked_mul(40)
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
bytes
.get(sec_base..sec_base + section_table_size)
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
let mut sections = Vec::with_capacity(section_count as usize);
for i in 0..section_count as usize {
let so = sec_base + i * 40;
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
@@ -184,16 +221,22 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
}
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
if num_rvas > 1 {
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
if let Some((imp_rva, imp_size)) = import_dir {
if imp_rva != 0
&& let Some(mut desc_off) = rva_to_off(&sections, imp_rva)
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(&sections, imp_rva)
{
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) {
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
// declared directory Size and the section's raw bytes, whichever
// ends first, so descriptors past the directory are not reported.
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
while desc_bytes_left >= 20 {
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) else {
break;
};
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
break;
}
@@ -225,6 +268,7 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
imports.entry(dll).or_default().extend(syms);
}
desc_off += 20;
desc_bytes_left -= 20;
}
}
}
@@ -242,6 +286,129 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
mod tests {
use super::*;
const PE_OFF: usize = 0x80;
const COFF: usize = PE_OFF + 4;
const OPT: usize = COFF + 20;
const OPT_SIZE: usize = 0xF0;
const SEC: usize = OPT + OPT_SIZE;
const SECTION_RVA: u32 = 0x1000;
const RAW_PTR: u32 = 0x200;
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
}
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
}
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
}
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
put_u32(bytes, base + 8, raw_size);
put_u32(bytes, base + 12, rva);
put_u32(bytes, base + 16, raw_size);
put_u32(bytes, base + 20, raw_ptr);
}
fn minimal_pe32_plus() -> Vec<u8> {
let mut bytes = vec![0u8; 0x400];
bytes[0..2].copy_from_slice(b"MZ");
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
put_u16(&mut bytes, COFF, 0x8664);
put_u16(&mut bytes, COFF + 2, 1);
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
put_u16(&mut bytes, OPT, 0x020B);
put_u32(&mut bytes, OPT + 16, 0x1234);
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
put_u32(&mut bytes, OPT + 56, 0x2000);
put_u32(&mut bytes, OPT + 108, 16);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
bytes
}
fn two_import_pe32_plus() -> Vec<u8> {
let mut bytes = minimal_pe32_plus();
let import_rva = SECTION_RVA;
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
// Two descriptors followed by the required all-zero terminator.
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
put_u64(
&mut bytes,
RAW_PTR as usize + 0x80,
u64::from(SECTION_RVA + 0x60),
);
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
bytes
}
/// Two sections: an import-descriptor section holding exactly two
/// descriptors and no terminator, and a data section for names and thunks.
/// Ellipsis bytes just past the descriptor section spell a third valid
/// descriptor, so an unbounded walk reports a DLL that is not imported.
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
const DATA_PTR: u32 = 0x300;
let mut bytes = minimal_pe32_plus();
put_u16(&mut bytes, COFF + 2, 2);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
// Declare the directory to cover the whole descriptor section, so the
// section bound (not the Size) is what this fixture exercises.
put_u32(&mut bytes, OPT + 112 + 12, 40);
for (base, dll_rva, thunk_rva) in [
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
] {
put_u32(&mut bytes, base, thunk_rva);
put_u32(&mut bytes, base + 12, dll_rva);
put_u32(&mut bytes, base + 16, thunk_rva);
}
// A third, entirely valid descriptor just past the section boundary.
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
for (delta, name) in [
(0x00, &b"ONE.DLL\0"[..]),
(0x20, &b"TWO.DLL\0"[..]),
(0x40, &b"THREE.DLL\0"[..]),
] {
let off = DATA_PTR as usize + delta;
bytes[off..off + name.len()].copy_from_slice(name);
}
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
let off = DATA_PTR as usize + delta;
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
put_u64(&mut bytes, off + 8, 0);
}
bytes
}
#[test]
fn classifies_tracks_accurately() {
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
@@ -263,4 +430,175 @@ mod tests {
);
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
}
#[test]
fn parses_minimal_pe32_plus_without_imports() {
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
assert_eq!(summary.entry_point_rva, 0x1234);
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
assert_eq!(summary.size_of_image, 0x2000);
assert_eq!(summary.section_count, 1);
assert!(summary.imports.is_empty());
}
#[test]
fn parses_named_and_ordinal_imports_from_two_dlls() {
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
#[test]
fn rejects_truncation_at_every_header_boundary() {
let image = minimal_pe32_plus();
for len in 0..=0x100 {
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
}
}
#[test]
fn rejects_section_rva_mapping_that_would_wrap_u32() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
put_u32(&mut image, SEC + 20, u32::MAX);
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
assert!(result.is_ok(), "raw pointer addition panicked");
assert!(result.unwrap().unwrap().imports.is_empty());
}
#[test]
fn rejects_section_count_larger_than_file() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, COFF + 2, u16::MAX);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated section table")
);
}
#[test]
fn rejects_pe32_magic() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, OPT, 0x010B);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
);
}
#[test]
fn import_directory_outside_all_sections_is_safe() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, 0x8000);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
#[test]
fn rejects_truncated_import_directory() {
let mut image = minimal_pe32_plus();
// An empty section table that fits, an optional header long enough to
// declare the import entry, and a file cut after two of the entry's
// RVA bytes.
put_u16(&mut image, COFF + 2, 0);
put_u16(&mut image, COFF + 16, 0xE0);
image.truncate(OPT + 112 + 8 + 2);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated import directory")
);
}
#[test]
fn bounds_unterminated_import_descriptor_walk() {
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
/// past the end of the optional header, so its 8 bytes would otherwise be
/// read from the section table. The entry index is still within
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
#[test]
fn rejects_import_directory_outside_short_optional_header() {
let mut image = two_import_pe32_plus();
// Import entry spans optional-header offsets 120..128; declare the
// optional header to end at 120, inside the entry.
put_u16(&mut image, COFF + 16, 120);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// One byte short of the full 8-byte entry is still out of range.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 127);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// Exactly 128 bytes covers the whole entry, so the import directory is
// read normally. The section table now starts at OPT + 128, so write it
// there for this size.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 128);
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.contains_key("ALPHA.DLL"));
assert!(summary.imports.contains_key("BETA.DLL"));
}
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
/// import entry (index 1) must not be probed even though its bytes are
/// present and inside SizeOfOptionalHeader.
#[test]
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
let mut image = two_import_pe32_plus();
put_u32(&mut image, OPT + 108, 1);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
/// (b) The declared import directory Size is shorter than the containing
/// section, so descriptors past the declared size must not be reported even
/// though they are valid and inside the section's raw bytes.
#[test]
fn bounds_import_descriptor_walk_by_declared_directory_size() {
// Size 40 covers exactly the two real descriptors; the third valid
// descriptor at +40 lies outside the directory but inside the section.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 40);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
assert!(!summary.imports.contains_key("THREE.DLL"));
// Size 20 reports only the first descriptor.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 20);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
// A size that is not a multiple of 20 stops before the next descriptor
// would exceed the directory.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 39);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
}
}
-13
View File
@@ -1,13 +0,0 @@
[package]
name = "bx-runtime"
description = "Shared CrossOver launch supervision, environment checks and run evidence"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
libc = "=0.2.191"
[lints]
workspace = true
-7
View File
@@ -1,7 +0,0 @@
# Shared hybrid runtime
`bx-cli` is the executable. This library supplies its single supervised execution path for named CrossOver bottles and explicit Wine prefixes, environment preflight, PE validation, process/session lifecycle, memory and output limits, and JSON run evidence. `bx-cli probe`, `shader` and `trace` retain the original #406 classifiers and telemetry aggregator.
The implementation is migrated from BetterXen #405 (`b42133a`) and the maintainer draft preserved at `2645c42`, with #406 (`30e551a`, merged as `f2c42ba`) prefix/shim/profile/log contracts integrated. Original attribution remains in each source file; no retired native crate is a dependency and no alternate runner binary is built.
CrossOver, Rosetta 2 and graphics backends remain external. A dedicated Wine environment is required for safe cleanup: stopping one run stops that environment's server. Session locking coordinates BetterXen launchers; it does not prevent CrossOver's UI or another launcher from using the same environment. A bottle is not a security sandbox.
-928
View File
@@ -1,928 +0,0 @@
//! Command-line interface of the hybrid tooling.
use crate::session::BottleSession;
use crate::{crossover, frames, host, json::Json, memory, pe, preflight, run, toolchain};
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::atomic::{AtomicBool, Ordering};
const USAGE: &str = "usage: bx-cli <command>
host host receipt (JSON)
crossover [--app P] CrossOver installs and documented preferences (JSON)
toolchain Windows cross-compilers found on PATH (JSON)
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
run CMD; refuse to start / stop it when free memory is low
doctor [--bottle B] [--min-start-free N]
check that a run could start here (JSON); non-zero exit if not
inspect <file.exe> identify a Windows executable: machine, subsystem, imports (JSON)
run (--bottle B | --prefix P) [--exe FILE] [--shims DIR (default build-shims/bin)] [--profile lockhart|anaconda] [--log FILE] [--backend d3dmetal|dxmt|dxvk|wined3d] [--timeout S] [--stall-timeout S]
[--settle-bound S] [--expect TEXT] [--require-gates a,b,c] [--out DIR]
[--min-start-free N] [--min-free N] [--allow-untested-crossover] -- EXE [ARGS...]
run a Windows program through CrossOver; write a JSON record
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
run the program per backend N times; summarise frame times
stop (--bottle B | --prefix P) recover a dedicated environment; SIGTERM an active runner first
receipt host + crossover + toolchain in one JSON document
run and bench also accept: --env NAME=VALUE (repeatable), --inherit-env true, --keep-output true.
The child otherwise receives only a short allowlist of host variables. A bottle is not a sandbox.";
/// Set by the signal handler; every run polls it.
static INTERRUPTED: AtomicBool = AtomicBool::new(false);
extern "C" fn on_signal(_: libc::c_int) {
// Storing to an atomic is async-signal-safe.
INTERRUPTED.store(true, Ordering::SeqCst);
}
fn install_signal_handlers() {
let handler = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
// SAFETY: `on_signal` has the required signature and only touches an atomic.
unsafe { libc::signal(signal, handler) };
}
}
fn crossover_json(app: Option<PathBuf>) -> Json {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let cands = match app {
Some(p) => vec![p],
None => crossover::candidate_paths(&home),
};
let installs = crossover::discover(&cands);
Json::obj(vec![
("installed", Json::Bool(!installs.is_empty())),
(
"installs",
Json::Arr(installs.iter().map(|i| i.to_json()).collect()),
),
(
"bottle_dir_preference",
Json::opt_str(crossover::preference("BottleDir")),
),
(
"managed_bottle_dirs_preference",
Json::opt_str(crossover::preference("ManagedBottleDirs")),
),
(
"searched",
Json::Arr(
cands
.iter()
.map(|p| Json::str(p.display().to_string()))
.collect(),
),
),
(
"note",
Json::str(
"Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).",
),
),
])
}
fn toolchain_json() -> Json {
let path = std::env::var("PATH").unwrap_or_default();
Json::Arr(
toolchain::probe(&path)
.iter()
.map(|c| c.to_json())
.collect(),
)
}
fn guard(args: &[String]) -> ExitCode {
let mut limits = memory::Limits {
min_start_free: 70,
min_free: 20,
poll: std::time::Duration::from_secs(1),
grace: std::time::Duration::from_secs(10),
};
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args.get(i + 1).and_then(|v| v.parse::<u8>().ok());
match (args[i].as_str(), v) {
("--min-start-free", Some(v)) => limits.min_start_free = v,
("--min-free", Some(v)) => limits.min_free = v,
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
}
i += 2;
}
let Some(cmd) = args.get(i + 1) else {
eprintln!("{USAGE}");
return ExitCode::from(2);
};
match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) {
memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS,
memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8),
other => {
eprintln!("guard: {other:?}");
ExitCode::from(3)
}
}
}
struct RunArgs {
allow_untested: bool,
cfg: run::RunConfig,
backends: Vec<String>,
repeat: u32,
out: Option<PathBuf>,
/// What the program file is, recorded with every run.
executable: Json,
}
// Environment contract preserved from #406; frozen C headers remain unchanged.
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
api-ms-win-core-psm-appnotify-l1-1-0,api-ms-win-core-psm-appnotify-l1-1-1,\
ext-ms-win-rtcore-ntuser-message-l1-1-0,ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0,\
ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0=n,b";
fn unix_to_wine_z_path(path: &std::path::Path) -> String {
format!("Z:{}", path.to_string_lossy().replace('/', "\\"))
}
/// #406's launch contract: shim overrides and `WINEPATH` are always configured, from
/// `build-shims/bin` unless `--shims` names another directory. An explicit `--shims` wins over
/// `--env`; the default does not replace a value the caller passed with `--env`.
fn shim_environment(
explicit: Option<&std::path::Path>,
user: &[(String, String)],
) -> Result<Vec<(String, String)>, String> {
let dir = match explicit {
Some(path) => {
let path = std::fs::canonicalize(path)
.map_err(|e| format!("cannot open shims {}: {e}", path.display()))?;
if !path.is_dir() {
return Err("--shims must name a directory".into());
}
path
}
None => std::fs::canonicalize(DEFAULT_SHIMS).unwrap_or_else(|_| DEFAULT_SHIMS.into()),
};
Ok([
("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES.to_string()),
("WINEPATH", unix_to_wine_z_path(&dir)),
]
.into_iter()
.filter(|(name, _)| explicit.is_some() || !user.iter().any(|(k, _)| k == name))
.map(|(name, value)| (name.to_string(), value))
.collect())
}
const DEFAULT_SHIMS: &str = "build-shims/bin";
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let (mut bottle, mut prefix, mut exe, mut shims, mut log) = (None, None, None, None, None);
let mut profile = "lockhart".to_string();
let mut backend = None;
let mut backends = Vec::new();
let mut repeat = 1u32;
let mut timeout = 300u64;
let mut stall = None;
let mut settle = 60u64;
let mut expect = None;
let mut require_gates = Vec::new();
let mut out = None;
let (mut min_start, mut min_free) = (50u8, 15u8);
let (mut inherit_env, mut keep_output) = (false, false);
let mut allow_untested = false;
let mut env = Vec::new();
let mut i = 0;
while i < args.len() && args[i] != "--" {
let key = args[i].as_str();
if matches!(
key,
"--inherit-env" | "--keep-output" | "--allow-untested-crossover"
) {
let value = args
.get(i + 1)
.filter(|v| matches!(v.as_str(), "true" | "false"));
let enabled = value
.map_or(Ok(true), |v| v.parse::<bool>())
.map_err(|_| "invalid boolean")?;
match key {
"--inherit-env" => inherit_env = enabled,
"--keep-output" => keep_output = enabled,
_ => allow_untested = enabled,
}
i += if value.is_some() { 2 } else { 1 };
continue;
}
let v = args
.get(i + 1)
.ok_or_else(|| format!("{key} needs a value"))?
.clone();
match key {
"--bottle" => bottle = Some(v),
"--prefix" => prefix = Some(PathBuf::from(v)),
"--exe" => exe = Some(v),
"--shims" => shims = Some(PathBuf::from(v)),
"--profile" => profile = v,
"--log" => log = Some(PathBuf::from(v)),
"--backend" => backend = Some(v),
"--backends" => backends = v.split(',').map(String::from).collect(),
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
"--expect" => expect = Some(v),
"--env" => {
let (name, value) = v.split_once('=').ok_or("--env needs NAME=VALUE")?;
if !valid_environment_name(name) || value.contains('\0') {
return Err("--env needs NAME=VALUE".into());
}
if [
"HOME",
"USER",
"LOGNAME",
"WINEPREFIX",
"WINESERVER",
"WINELOADER",
"WINEDLLPATH",
"CX_BOTTLE",
"CX_BOTTLE_PATH",
"CX_ROOT",
]
.contains(&name)
{
return Err(format!(
"{name} controls launcher identity or bottle selection and cannot be overridden"
));
}
if name.starts_with("CX_GRAPHICS_BACKEND") {
return Err("select the backend with --backend, not --env".into());
}
if name.starts_with("DYLD_") {
return Err("DYLD_ variables are not passed to the launcher".into());
}
env.push((name.to_string(), value.to_string()));
}
"--require-gates" => require_gates = v.split(',').map(String::from).collect(),
"--out" => out = Some(PathBuf::from(v)),
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
"--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?,
o => return Err(format!("unknown option {o}")),
}
i += 2;
}
let (program, guest_args) = if let Some(exe) = exe {
(
exe,
if args.get(i).map(String::as_str) == Some("--") {
args[i + 1..].to_vec()
} else {
vec![]
},
)
} else {
(
args.get(i + 1)
.ok_or("use --exe FILE or -- FILE [ARGS...]")?
.clone(),
args[i + 2..].to_vec(),
)
};
if bottle.is_some() && prefix.is_some() {
return Err("choose --bottle or --prefix, not both".into());
}
if bottle.is_none() && prefix.is_none() {
return Err("--bottle or --prefix is required; use a dedicated test environment".into());
}
let bottle = bottle.unwrap_or_default();
if prefix.is_none() && !preflight::valid_bottle_name(&bottle) {
return Err(format!("invalid bottle name {bottle:?}"));
}
if !matches!(profile.as_str(), "lockhart" | "anaconda") {
return Err("profile must be lockhart or anaconda".into());
}
if min_start > 100 || min_free > 100 {
return Err("memory percentages must be 0..100".into());
}
if let Some(unknown) = backend
.iter()
.chain(backends.iter().filter(|b| *b != "default"))
.find(|b| !run::BACKENDS.contains(&b.as_str()))
{
return Err(format!(
"unknown backend {unknown:?}; use one of {}",
run::BACKENDS.join(", ")
));
}
if program.starts_with('-') {
return Err("the program path must not start with '-' (write ./name.exe)".into());
}
let executable = identify(std::path::Path::new(&program))?;
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let installs = crossover::discover(&crossover::candidate_paths(&home));
let install = installs.first().ok_or("no CrossOver installation found")?;
let mut wine = run::wine_path(&install.path);
let prefix = if let Some(path) = prefix {
std::fs::create_dir_all(&path)
.map_err(|e| format!("cannot create prefix {}: {e}", path.display()))?;
wine.set_file_name("wineloader");
Some(std::fs::canonicalize(path).map_err(|e| e.to_string())?)
} else {
if !run::bottle_prefix(&bottle).join("drive_c").is_dir() {
return Err(format!("bottle {bottle:?} not found"));
}
None
};
if !wine.is_file() {
return Err(format!(
"{} not found in this CrossOver build",
wine.display()
));
}
env.push(("ROSETTA_ADVERTISE_AVX".into(), "1".into()));
env.push(("BX_PROFILE".into(), profile));
let shim_env = shim_environment(shims.as_deref(), &env)?;
env.extend(shim_env);
if let Some(path) = log {
let path = if path.is_absolute() {
path
} else {
std::env::current_dir()
.map_err(|e| e.to_string())?
.join(path)
};
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
env.push(("BX_LOG_FILE".into(), unix_to_wine_z_path(&path)));
}
Ok(RunArgs {
allow_untested,
cfg: run::RunConfig {
wine,
bottle,
prefix,
backend,
program,
args: guest_args,
timeout: std::time::Duration::from_secs(timeout),
limits: memory::Limits {
min_start_free: min_start,
min_free,
poll: std::time::Duration::from_millis(250),
grace: std::time::Duration::from_secs(10),
},
expect,
work_dir: out
.clone()
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs")),
stall_timeout: stall.map(std::time::Duration::from_secs),
settle_bound: std::time::Duration::from_secs(settle),
read_free: memory::free_percentage,
require_gates,
max_output: 64 << 20,
inherit_env,
env,
keep_output,
interrupted: &INTERRUPTED,
},
backends,
repeat,
out,
executable,
})
}
/// Refuse anything that is not a launchable Windows program, and describe what is.
fn identify(path: &std::path::Path) -> Result<Json, String> {
let image = pe::inspect(path)?;
image
.check_launchable()
.map_err(|e| format!("{}: {e}", path.display()))?;
let sha256 = crate::cmdutil::run(
"/usr/bin/shasum",
&["-a", "256", &path.display().to_string()],
)
.and_then(|o| o.split_whitespace().next().map(String::from));
Ok(Json::obj(vec![
("path", Json::str(path.display().to_string())),
("sha256", Json::opt_str(sha256)),
("image", image.to_json()),
]))
}
fn with_executable(mut record: Json, executable: &Json) -> Json {
if let Json::Obj(fields) = &mut record {
fields.push(("executable".into(), executable.clone()));
}
record
}
fn doctor(args: &[String]) -> ExitCode {
let (mut bottle, mut prefix, mut min_start) = (None, None, 50u8);
let mut it = args.iter();
while let Some(a) = it.next() {
match (a.as_str(), it.next()) {
("--bottle", Some(v)) => bottle = Some(v.clone()),
("--prefix", Some(v)) => prefix = Some(PathBuf::from(v)),
("--min-start-free", Some(v)) if v.parse::<u8>().is_ok() => {
min_start = v.parse().unwrap_or(min_start)
}
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
}
}
if bottle.is_some() && prefix.is_some() {
eprintln!("choose --bottle or --prefix");
return ExitCode::from(2);
}
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let install = crossover::discover(&crossover::candidate_paths(&home))
.into_iter()
.next();
let wine = install.as_ref().map(|i| run::wine_path(&i.path));
let mut facts = preflight::gather(
bottle.as_deref(),
wine.as_deref()
.map(|w| (crossover_build().unwrap_or_else(|| "unknown".into()), w)),
min_start,
);
if let Some(path) = prefix {
facts.bottle = Some(("prefix".into(), path));
}
let checks = preflight::evaluate(&facts);
let mut report = preflight::to_json(&checks);
if let Json::Obj(fields) = &mut report {
fields.push(("host_info".into(), host_info(install.as_ref())));
}
print!("{}", report.render());
if checks.iter().all(|c| c.ok) {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
/// Reported, never gating: running a prebuilt program needs none of these. Preserves what
/// #406's `doctor` showed (memory profile, D3DMetal presence, the shim cross-compiler).
fn host_info(install: Option<&crossover::Install>) -> Json {
let memory_gib = host::collect().memory_bytes.map(|b| b >> 30);
let d3dmetal = install.map(|i| {
i.path
.join("Contents/SharedSupport/CrossOver/lib64/apple_gptk/external/D3DMetal.framework")
.exists()
});
let mingw = std::env::var_os("PATH").and_then(|path| {
std::env::split_paths(&path)
.map(|dir| dir.join("x86_64-w64-mingw32-g++"))
.find(|candidate| candidate.is_file())
});
Json::obj(vec![
(
"memory_gib",
memory_gib.map_or(Json::Null, |g| Json::Num(g as f64)),
),
(
"recommended_profile",
Json::opt_str(memory_gib.map(|g| recommended_profile(g).to_string())),
),
(
"crossover_build_tested",
install.map_or(Json::Null, |_| {
Json::Bool(run::tested_crossover_build(crossover_build().as_deref()))
}),
),
(
"d3dmetal_framework_present",
d3dmetal.map_or(Json::Null, Json::Bool),
),
(
"shim_cross_compiler",
Json::opt_str(mingw.map(|p| p.display().to_string())),
),
])
}
fn recommended_profile(memory_gib: u64) -> &'static str {
if memory_gib >= 32 {
"anaconda"
} else {
"lockhart"
}
}
fn crossover_build() -> Option<String> {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
crossover::discover(&crossover::candidate_paths(&home))
.first()
.and_then(|i| {
Some(format!(
"{} ({})",
i.short_version.clone()?,
i.build_version.clone()?
))
})
}
/// The launcher options are observed behaviour of specific builds, so an unlisted build is
/// refused unless the caller opts in. `stop` is not gated: recovery must always work.
fn check_build(build: Option<&str>, allow_untested: bool) -> Result<(), String> {
if run::tested_crossover_build(build) {
return Ok(());
}
let message = format!(
"CrossOver {} has not been tested with this launcher (tested: {})",
build.unwrap_or("of unknown version"),
run::TESTED_CROSSOVER_BUILDS.join(", ")
);
if allow_untested {
eprintln!("warning: {message}");
Ok(())
} else {
Err(format!(
"{message}; pass --allow-untested-crossover to run anyway"
))
}
}
fn save(dir: &std::path::Path, kind: &str, j: &Json) -> Result<(), String> {
crate::records::save(dir, kind, j)
.map(|path| eprintln!("report saved: {}", path.display()))
.map_err(|error| format!("cannot save {kind} report in {}: {error}", dir.display()))
}
fn finish_report(passed: bool, out: Option<&std::path::Path>, kind: &str, j: &Json) -> ExitCode {
print!("{}", j.render());
if let Some(dir) = out
&& let Err(error) = save(dir, kind, j)
{
eprintln!("{error}");
return ExitCode::from(1);
}
if passed {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn run_cmd(args: &[String]) -> ExitCode {
if args == ["--help"] {
eprintln!("{USAGE}");
return ExitCode::SUCCESS;
}
let a = match parse_run_args(args) {
Ok(a) => a,
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let build = crossover_build();
if let Err(e) = check_build(build.as_deref(), a.allow_untested) {
eprintln!("{e}");
return ExitCode::from(2);
}
let mut session = match BottleSession::acquire(&a.cfg.prefix_path(), false) {
Ok(s) => s,
Err(e) => {
eprintln!("{e}");
return ExitCode::from(1);
}
};
let mut r = run::execute(&a.cfg, build);
if r.class != run::Class::CleanupFailed
&& let Err(e) = session.complete()
{
eprintln!("cannot finish bottle session: {e}");
r.class = run::Class::CleanupFailed;
if let Json::Obj(fields) = &mut r.json {
fields.retain(|(name, _)| name != "classification");
fields.push(("classification".into(), Json::str("cleanup_failed")));
fields.push(("session_error".into(), Json::str(e)));
}
}
if r.class != run::Class::Passed {
eprintln!("run: {}", r.class.name());
for g in r.gates.iter().filter(|g| !g.passed) {
eprintln!(" gate {} failed: {}", g.name, g.detail);
}
if let Some(e) = &r.error {
eprintln!(" {e}");
}
}
finish_report(
r.class == run::Class::Passed,
a.out.as_deref(),
"run",
&with_executable(r.json, &a.executable),
)
}
fn bench_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) if !a.backends.is_empty() => a,
Ok(_) => {
eprintln!("bench needs --backends\n{USAGE}");
return ExitCode::from(2);
}
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let build = crossover_build();
if let Err(e) = check_build(build.as_deref(), a.allow_untested) {
eprintln!("{e}");
return ExitCode::from(2);
}
let mut session = match BottleSession::acquire(&a.cfg.prefix_path(), false) {
Ok(s) => s,
Err(e) => {
eprintln!("{e}");
return ExitCode::from(1);
}
};
let mut per_backend = Vec::new();
let mut all_ok = true;
let mut cleanup_failed = false;
for b in &a.backends {
let mut runs = Vec::new();
for _ in 0..a.repeat {
if INTERRUPTED.load(Ordering::SeqCst) || cleanup_failed {
all_ok = false;
break;
}
let mut cfg = a.cfg.clone();
cfg.backend = if b == "default" {
None
} else {
Some(b.clone())
};
let r = run::execute(&cfg, build.clone());
cleanup_failed |= r.class == run::Class::CleanupFailed;
all_ok &= r.class == run::Class::Passed;
runs.push(with_executable(r.json, &a.executable));
}
per_backend.push(Json::obj(vec![
("backend", Json::str(b.clone())),
("runs", Json::Arr(runs)),
]));
}
let doc = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-bench/0")),
("repeat", Json::Num(a.repeat as f64)),
("host", host::collect().to_json()),
("results", Json::Arr(per_backend)),
]);
if !cleanup_failed && let Err(e) = session.complete() {
eprintln!("cannot finish bottle session: {e}");
all_ok = false;
}
finish_report(all_ok, a.out.as_deref(), "bench", &doc)
}
fn stop(args: &[String]) -> ExitCode {
let [flag, target] = args else {
eprintln!("{USAGE}");
return ExitCode::from(2);
};
let prefix = match flag.as_str() {
"--bottle" if preflight::valid_bottle_name(target) => run::bottle_prefix(target),
"--prefix" => PathBuf::from(target),
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
};
if !prefix.join("drive_c").is_dir() {
eprintln!("initialized environment not found at {}", prefix.display());
return ExitCode::from(1);
}
let prefix = match std::fs::canonicalize(&prefix) {
Ok(path) => path,
Err(error) => {
eprintln!("cannot resolve prefix {}: {error}", prefix.display());
return ExitCode::from(1);
}
};
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let Some(install) = crossover::discover(&crossover::candidate_paths(&home))
.into_iter()
.next()
else {
eprintln!("no CrossOver installation found");
return ExitCode::from(1);
};
let mut session = match BottleSession::acquire(&prefix, true) {
Ok(s) => s,
Err(e) => {
eprintln!("{e}");
return ExitCode::from(1);
}
};
if let Err(e) =
run::stop_prefix(&run::wine_path(&install.path), &prefix).and_then(|()| session.complete())
{
eprintln!("{e}");
return ExitCode::from(1);
}
println!(
"{}",
Json::obj(vec![
("schema", Json::str("betterxen-hybrid-stop/0")),
("prefix", Json::str(prefix.display().to_string())),
("stopped", Json::Bool(true))
])
.render()
);
ExitCode::SUCCESS
}
fn valid_environment_name(name: &str) -> bool {
let mut chars = name.chars();
chars
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
#[cfg(test)]
mod foundation_contract_tests {
use super::*;
#[test]
fn profile_recommendation_matches_the_foundation_threshold() {
assert_eq!(recommended_profile(16), "lockhart");
assert_eq!(recommended_profile(24), "lockhart");
assert_eq!(recommended_profile(32), "anaconda");
}
#[test]
fn untested_crossover_builds_are_refused_unless_allowed() {
assert!(check_build(Some("26.3 (26.3.0.39832)"), false).is_ok());
for build in [Some("26.2 (26.2.0.39821)"), None] {
let refused = check_build(build, false).unwrap_err();
assert!(refused.contains("--allow-untested-crossover"));
assert!(check_build(build, true).is_ok());
}
}
#[test]
fn shims_are_configured_by_default_without_replacing_env_values() {
let names =
|env: Vec<(String, String)>| env.into_iter().map(|(k, _)| k).collect::<Vec<_>>();
let default = shim_environment(None, &[]).unwrap();
assert!(
default[1].1.ends_with("build-shims\\bin"),
"{}",
default[1].1
);
assert_eq!(names(default), ["WINEDLLOVERRIDES", "WINEPATH"]);
let user = [("WINEDLLOVERRIDES".to_string(), "xmem=".to_string())];
assert_eq!(names(shim_environment(None, &user).unwrap()), ["WINEPATH"]);
let dir = std::env::temp_dir();
assert_eq!(
names(shim_environment(Some(&dir), &user).unwrap()),
["WINEDLLOVERRIDES", "WINEPATH"]
);
assert!(shim_environment(Some(std::path::Path::new("/nonexistent")), &[]).is_err());
}
#[test]
fn converts_unix_path_to_wine_z_drive() {
assert_eq!(
unix_to_wine_z_path(std::path::Path::new("/tmp/bx-test.jsonl")),
"Z:\\tmp\\bx-test.jsonl"
);
}
}
/// Entry point for the runtime subcommands of `bx-cli`. `args` excludes the program name; a
/// leading `hybrid` word (the #405 spelling) is accepted and ignored.
pub fn run_cli(args: &[String]) -> ExitCode {
// The standalone maintainer bundle accepts the same `hybrid ...` argument vector as
// the full CLI. Both enter this implementation; no wrapper or native research runtime
// needs to be distributed for the acceptance tools.
let args = if args.first().map(String::as_str) == Some("hybrid") {
&args[1..]
} else {
args
};
let rest = args.get(1..).unwrap_or_default();
match args.first().map(String::as_str) {
Some("run") => {
install_signal_handlers();
return run_cmd(rest);
}
Some("bench") => {
install_signal_handlers();
return bench_cmd(rest);
}
Some("doctor") => return doctor(rest),
Some("guard") => return guard(rest),
Some("stop") => return stop(rest),
_ => {}
}
let result: Result<Json, String> = match args.first().map(String::as_str) {
Some("host") => Ok(host::collect().to_json()),
Some("inspect") => match args.get(1) {
None => Err("inspect needs a file".into()),
Some(f) => pe::inspect(std::path::Path::new(f)).map(|i| i.to_json()),
},
Some("crossover") => {
let app = match args.get(1).map(String::as_str) {
Some("--app") => args.get(2).map(PathBuf::from),
_ => None,
};
Ok(crossover_json(app))
}
Some("toolchain") => Ok(toolchain_json()),
Some("frames") => match args.get(1) {
None => Err("frames needs a file".into()),
Some(f) => std::fs::read_to_string(f)
.map_err(|e| format!("{f}: {e}"))
.and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string()))
.and_then(|v| frames::analyze(&v).map_err(|e| e.to_string()))
.map(|s| s.to_json()),
},
Some("receipt") => Ok(Json::obj(vec![
("schema", Json::str("betterxen-hybrid-receipt/0")),
("host", host::collect().to_json()),
("crossover", crossover_json(None)),
("windows_cross_compilers", toolchain_json()),
])),
_ => Err(USAGE.into()),
};
match result {
Ok(j) => {
print!("{}", j.render());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("{e}");
ExitCode::from(2)
}
}
}
#[cfg(test)]
mod report_tests {
use super::*;
fn args(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
// These fail before CrossOver discovery, so they run on hosts without CrossOver.
#[test]
fn bad_backend_bottle_or_program_is_refused_before_launch() {
let err = |a: &[&str]| parse_run_args(&args(a)).err().unwrap();
assert!(
err(&["--bottle", "b", "--backend", "dmxt", "--", "x.exe"]).contains("unknown backend")
);
assert!(
err(&["--bottle", "b", "--backends", "default,typo", "--", "x.exe"])
.contains("unknown backend")
);
assert!(err(&["--bottle", "../b", "--", "x.exe"]).contains("invalid bottle"));
assert!(err(&["--bottle", "b", "--", "/nonexistent/x.exe"]).contains("/nonexistent/x.exe"));
assert!(err(&["--bottle", "b", "--", "/bin/sh"]).contains("not a PE"));
assert!(err(&["--bottle", "b", "--", "--help"]).contains("must not start with"));
}
#[test]
fn requested_evidence_failure_overrides_a_passing_workload() {
let path = std::env::temp_dir().join(format!(
"bx-report-invalid-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(&path, "keep this file").unwrap();
for kind in ["run", "bench"] {
assert_eq!(
finish_report(true, Some(&path), kind, &Json::Null),
ExitCode::from(1)
);
}
assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep this file");
std::fs::remove_file(path).unwrap();
}
#[test]
fn stdout_only_reporting_preserves_workload_status() {
assert_eq!(
finish_report(true, None, "run", &Json::Null),
ExitCode::SUCCESS
);
assert_eq!(
finish_report(false, None, "bench", &Json::Null),
ExitCode::from(1)
);
}
}
-13
View File
@@ -1,13 +0,0 @@
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
//! never a guessed value.
use std::process::Command;
pub fn run(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
if !out.status.success() {
return None;
}
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
Some(s)
}
-162
View File
@@ -1,162 +0,0 @@
//! Discover installed CrossOver bundles and read standard bundle metadata.
//!
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
//! interface (#350). The graphics backend of a bottle is deliberately not read.
use crate::cmdutil::run;
use crate::json::Json;
use std::path::{Path, PathBuf};
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
#[derive(Debug, Clone, PartialEq)]
pub struct Install {
pub path: PathBuf,
pub bundle_id: Option<String>,
pub short_version: Option<String>,
pub build_version: Option<String>,
pub executable_archs: Option<Vec<String>>,
pub minimum_macos: Option<String>,
}
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
let mut v = vec![
PathBuf::from("/Applications/CrossOver.app"),
home.join("Applications/CrossOver.app"),
];
if let Some(found) = run(
"/usr/bin/mdfind",
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
) {
for line in found.lines().filter(|l| !l.is_empty()) {
let p = PathBuf::from(line);
if !v.contains(&p) {
v.push(p);
}
}
}
v
}
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
candidates.iter().filter_map(|p| inspect(p)).collect()
}
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
pub fn inspect(app: &Path) -> Option<Install> {
let plist = app.join("Contents/Info.plist");
if !plist.is_file() {
return None;
}
let json = run(
"/usr/bin/plutil",
&["-convert", "json", "-o", "-", plist.to_str()?],
)?;
let exe = crate::host_string(&json, "CFBundleExecutable");
let archs = exe.and_then(|e| {
let p = app.join("Contents/MacOS").join(e);
run("/usr/bin/lipo", &["-archs", p.to_str()?])
.map(|s| s.split_whitespace().map(String::from).collect())
});
Some(Install {
path: app.to_path_buf(),
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
build_version: crate::host_string(&json, "CFBundleVersion"),
executable_archs: archs,
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
})
}
/// A documented CrossOver preference, or None when unset or unreadable.
pub fn preference(key: &str) -> Option<String> {
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
}
impl Install {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("path", Json::str(self.path.display().to_string())),
("bundle_id", Json::opt_str(self.bundle_id.clone())),
("short_version", Json::opt_str(self.short_version.clone())),
("build_version", Json::opt_str(self.build_version.clone())),
(
"executable_archs",
self.executable_archs.as_ref().map_or(Json::Null, |a| {
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
}),
),
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
(
"bundle_id_is_codeweavers_crossover",
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
// A synthetic bundle written by the test: it proves the metadata path, not that
// any real CrossOver build has this layout.
fn fake_bundle(dir: &Path) -> PathBuf {
let app = dir.join("CrossOver.app");
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
fs::write(
app.join("Contents/Info.plist"),
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>CrossOver</string>
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
<key>CFBundleShortVersionString</key><string>99.1.2</string>
<key>CFBundleVersion</key><string>12345</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
</dict></plist>"#,
)
.unwrap();
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
app
}
#[test]
fn reads_bundle_metadata() {
if !cfg!(target_os = "macos") {
return;
}
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp).unwrap();
let app = fake_bundle(&tmp);
let i = inspect(&app).expect("inspect");
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
assert_eq!(i.build_version.as_deref(), Some("12345"));
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
assert!(
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
"{:?}",
i.executable_archs
);
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
fs::remove_dir_all(&tmp).unwrap();
}
#[test]
fn missing_or_plistless_bundle_is_none() {
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
assert!(inspect(&tmp.join("X.app")).is_none());
assert!(inspect(&tmp.join("Nope.app")).is_none());
fs::remove_dir_all(&tmp).unwrap();
}
}
-192
View File
@@ -1,192 +0,0 @@
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
//!
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
//! percentile interval. These definitions are fixed here so reports are comparable; other
//! tools define lows differently (for example as the mean of the worst 1 %).
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct FrameStats {
pub frames: usize,
pub total_ms: f64,
pub mean_ms: f64,
pub avg_fps: f64,
pub min_ms: f64,
pub max_ms: f64,
pub p50_ms: f64,
pub p95_ms: f64,
pub p99_ms: f64,
pub p999_ms: f64,
pub low_1pct_fps: f64,
pub low_01pct_fps: f64,
/// Frames longer than twice the median interval.
pub stutters: usize,
}
#[derive(Debug, PartialEq)]
pub enum FrameError {
Empty,
Invalid { index: usize, value: f64 },
Parse { line: usize, text: String },
}
impl std::fmt::Display for FrameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FrameError::Empty => write!(f, "no frame intervals"),
FrameError::Invalid { index, value } => {
write!(
f,
"frame {index}: interval {value} is not a positive finite number of milliseconds"
)
}
FrameError::Parse { line, text } => {
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
}
}
}
}
impl std::error::Error for FrameError {}
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
let n = sorted.len();
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
sorted[rank.min(n) - 1]
}
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
if intervals_ms.is_empty() {
return Err(FrameError::Empty);
}
for (index, &value) in intervals_ms.iter().enumerate() {
if !value.is_finite() || value <= 0.0 {
return Err(FrameError::Invalid { index, value });
}
}
let mut sorted = intervals_ms.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
let total: f64 = intervals_ms.iter().sum();
let n = sorted.len();
let p50 = nearest_rank(&sorted, 50.0);
let p99 = nearest_rank(&sorted, 99.0);
let p999 = nearest_rank(&sorted, 99.9);
Ok(FrameStats {
frames: n,
total_ms: total,
mean_ms: total / n as f64,
avg_fps: n as f64 / (total / 1000.0),
min_ms: sorted[0],
max_ms: sorted[n - 1],
p50_ms: p50,
p95_ms: nearest_rank(&sorted, 95.0),
p99_ms: p99,
p999_ms: p999,
low_1pct_fps: 1000.0 / p99,
low_01pct_fps: 1000.0 / p999,
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
})
}
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
let mut out = Vec::new();
for (i, line) in text.lines().enumerate() {
let t = line.trim();
if t.is_empty() || t.starts_with('#') {
continue;
}
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
line: i + 1,
text: t.to_string(),
})?;
out.push(v);
}
Ok(out)
}
impl FrameStats {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("frames", Json::Num(self.frames as f64)),
("total_ms", Json::Num(self.total_ms)),
("mean_ms", Json::Num(self.mean_ms)),
("avg_fps", Json::Num(self.avg_fps)),
("min_ms", Json::Num(self.min_ms)),
("max_ms", Json::Num(self.max_ms)),
("p50_ms", Json::Num(self.p50_ms)),
("p95_ms", Json::Num(self.p95_ms)),
("p99_ms", Json::Num(self.p99_ms)),
("p999_ms", Json::Num(self.p999_ms)),
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
("percentile_method", Json::str("nearest-rank")),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
// Expected values below are worked out by hand, not produced by analyze().
#[test]
fn known_answer_ten_frames() {
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
let s = analyze(&v).unwrap();
assert_eq!(s.frames, 10);
assert_eq!(s.total_ms, 200.0);
assert_eq!(s.mean_ms, 20.0);
assert_eq!(s.avg_fps, 50.0);
assert_eq!(s.p50_ms, 10.0); // rank 5
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
assert_eq!(s.p99_ms, 100.0);
assert_eq!(s.low_1pct_fps, 10.0);
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
}
#[test]
fn stutter_threshold_is_strict() {
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
assert_eq!(s.stutters, 1);
}
#[test]
fn one_frame_per_second() {
let s = analyze(&[1000.0, 1000.0]).unwrap();
assert_eq!(s.avg_fps, 1.0);
}
#[test]
fn rejects_bad_input() {
assert_eq!(analyze(&[]), Err(FrameError::Empty));
assert!(matches!(
analyze(&[1.0, 0.0]),
Err(FrameError::Invalid { index: 1, .. })
));
assert!(matches!(
analyze(&[f64::NAN]),
Err(FrameError::Invalid { .. })
));
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
}
#[test]
fn parses_text() {
assert_eq!(
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
vec![16.5, 8.0]
);
assert_eq!(
parse_intervals("1\nabc\n"),
Err(FrameError::Parse {
line: 2,
text: "abc".into()
})
);
}
}
-228
View File
@@ -1,228 +0,0 @@
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
//!
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
use crate::cmdutil::run;
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct HostReceipt {
pub macos_version: Option<String>,
pub macos_build: Option<String>,
pub chip: Option<String>,
pub apple_silicon: Option<bool>,
pub memory_bytes: Option<u64>,
pub logical_cpus: Option<u32>,
pub performance_cores: Option<u32>,
pub efficiency_cores: Option<u32>,
/// True only if an x86_64 slice of a system binary actually executed.
pub rosetta_executes_x86_64: Option<bool>,
pub gpu_name: Option<String>,
pub gpu_cores: Option<String>,
pub metal_support: Option<String>,
pub gpu_wired: GpuWired,
pub host_arch_of_this_binary: &'static str,
}
fn sysctl(name: &str) -> Option<String> {
run("/usr/sbin/sysctl", &["-n", name])
}
/// GPU wired-memory sysctls (issue #386), recorded as the raw integers `sysctl -n` prints.
///
/// Read only: nothing in BetterXen writes these keys. `None` means the key is absent (the
/// command failed) or its output is not an unsigned integer. A value of 0 was observed on an
/// M4 and an M5; Apple does not document what 0 means in anything reviewed for #386, so it is
/// reported as observed and never interpreted (for example as "system default" or "no limit").
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GpuWired {
/// `iogpu.wired_limit_mb`.
pub limit_mb: Option<u64>,
/// `iogpu.wired_lwm_mb`.
pub lwm_mb: Option<u64>,
}
pub const GPU_WIRED_SOURCE: &str = "sysctl -n iogpu.wired_limit_mb, iogpu.wired_lwm_mb (read-only; raw values, meaning of 0 undocumented)";
/// Read the GPU wired-memory keys through `read`, which returns a key's trimmed output or
/// `None` when the key cannot be read. Injected so tests do not depend on this Mac.
pub fn gpu_wired_with(read: impl Fn(&str) -> Option<String>) -> GpuWired {
let num = |key: &str| read(key).and_then(|v| v.trim().parse::<u64>().ok());
GpuWired {
limit_mb: num("iogpu.wired_limit_mb"),
lwm_mb: num("iogpu.wired_lwm_mb"),
}
}
pub fn gpu_wired() -> GpuWired {
gpu_wired_with(sysctl)
}
impl GpuWired {
/// The record fields shared by the host receipt and every run record.
pub fn json_fields(&self) -> Vec<(&'static str, Json)> {
let n = |v: Option<u64>| v.map_or(Json::Null, |x| Json::Num(x as f64));
vec![
("gpu_wired_limit_mb", n(self.limit_mb)),
("gpu_wired_lwm_mb", n(self.lwm_mb)),
("gpu_wired_source", Json::str(GPU_WIRED_SOURCE)),
]
}
}
pub fn collect() -> HostReceipt {
let gpu = run(
"/usr/sbin/system_profiler",
&["SPDisplaysDataType", "-json"],
)
.and_then(|j| parse_gpu(&j));
HostReceipt {
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
macos_build: sysctl("kern.osversion"),
chip: sysctl("machdep.cpu.brand_string"),
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
// now; it does not distinguish "not installed" from "disabled".
rosetta_executes_x86_64: Some(
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
),
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
gpu_wired: gpu_wired(),
host_arch_of_this_binary: std::env::consts::ARCH,
}
}
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
let model = string_value(json, "sppci_model")?;
Some((
model,
string_value(json, "sppci_cores"),
string_value(json, "spdisplays_mtlgpufamilysupport"),
))
}
fn string_value(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('"')?;
let end = rest.find('"')?;
Some(rest[..end].to_string())
}
impl HostReceipt {
pub fn to_json(&self) -> Json {
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
let mut fields = vec![
("macos_version", Json::opt_str(self.macos_version.clone())),
("macos_build", Json::opt_str(self.macos_build.clone())),
("chip", Json::opt_str(self.chip.clone())),
(
"apple_silicon",
self.apple_silicon.map_or(Json::Null, Json::Bool),
),
(
"memory_bytes",
self.memory_bytes
.map_or(Json::Null, |x| Json::Num(x as f64)),
),
("logical_cpus", n(self.logical_cpus)),
("performance_cores", n(self.performance_cores)),
("efficiency_cores", n(self.efficiency_cores)),
(
"rosetta_executes_x86_64",
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
),
("gpu_name", Json::opt_str(self.gpu_name.clone())),
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
("metal_support", Json::opt_str(self.metal_support.clone())),
];
fields.extend(self.gpu_wired.json_fields());
fields.push((
"receipt_binary_arch",
Json::str(self.host_arch_of_this_binary),
));
Json::obj(fields)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_gpu_fixture() {
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
let g = parse_gpu(j).unwrap();
assert_eq!(g.0, "Apple M4");
assert_eq!(g.1.as_deref(), Some("10"));
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
}
#[test]
fn missing_gpu_is_none() {
assert!(parse_gpu("{}").is_none());
}
fn reader<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
move |key| {
pairs
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| v.to_string())
}
}
#[test]
fn gpu_wired_values_are_reported_raw() {
let w = gpu_wired_with(reader(&[
("iogpu.wired_limit_mb", "24576"),
("iogpu.wired_lwm_mb", "0"),
]));
assert_eq!(w.limit_mb, Some(24576));
// 0 is a value like any other, not "absent".
assert_eq!(w.lwm_mb, Some(0));
}
#[test]
fn missing_or_unparsable_gpu_wired_keys_are_null() {
let w = gpu_wired_with(reader(&[("iogpu.wired_limit_mb", "unlimited")]));
assert_eq!(w, GpuWired::default());
let j = Json::obj(w.json_fields()).render();
assert!(j.contains("\"gpu_wired_limit_mb\": null"), "{j}");
assert!(j.contains("\"gpu_wired_lwm_mb\": null"), "{j}");
assert!(j.contains("\"gpu_wired_source\": \"sysctl -n"), "{j}");
}
#[test]
fn receipt_carries_gpu_wired_fields() {
let mut r = collect();
r.gpu_wired = GpuWired {
limit_mb: Some(0),
lwm_mb: None,
};
let j = r.to_json().render();
assert!(j.contains("\"gpu_wired_limit_mb\": 0"), "{j}");
assert!(j.contains("\"gpu_wired_lwm_mb\": null"), "{j}");
}
#[test]
fn collect_runs_on_this_host() {
let r = collect();
if cfg!(target_os = "macos") {
assert!(r.macos_version.is_some());
assert!(r.memory_bytes.unwrap() > 0);
}
assert!(r.to_json().render().contains("receipt_binary_arch"));
}
}
-114
View File
@@ -1,114 +0,0 @@
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
pub fn str(s: impl Into<String>) -> Json {
Json::Str(s.into())
}
pub fn opt_str(s: Option<String>) -> Json {
s.map_or(Json::Null, Json::Str)
}
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
pub fn render(&self) -> String {
let mut out = String::new();
self.write(&mut out, 0);
out.push('\n');
out
}
fn write(&self, out: &mut String, depth: usize) {
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) if n.is_finite() => {
if n.fract() == 0.0 && n.abs() < 1e15 {
out.push_str(&format!("{}", *n as i64));
} else {
out.push_str(&format!("{n}"));
}
}
// JSON has no NaN or infinity; refuse to invent a number.
Json::Num(_) => out.push_str("null"),
Json::Str(s) => escape(s, out),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
pad(out, depth + 1);
item.write(out, depth + 1);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push(']');
}
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (k, v)) in fields.iter().enumerate() {
pad(out, depth + 1);
escape(k, out);
out.push_str(": ");
v.write(out, depth + 1);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push('}');
}
}
}
}
fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_and_nests() {
let j = Json::obj(vec![
("a", Json::str("q\"\\\n\u{1}")),
(
"b",
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
),
("c", Json::Num(f64::NAN)),
]);
let r = j.render();
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
assert!(r.contains("0.5"));
assert!(r.contains(r#""c": null"#));
}
}
-38
View File
@@ -1,38 +0,0 @@
//! BetterXen hybrid tooling: environment checks, executable identification, supervised
//! launches and measurement around an externally installed CrossOver. Nothing here claims
//! game or console compatibility.
pub mod cli;
pub mod cmdutil;
pub mod crossover;
pub mod frames;
pub mod host;
pub mod json;
pub mod memory;
pub mod pe;
pub mod preflight;
pub mod records;
pub mod run;
pub mod session;
pub mod toolchain;
/// Value of a top-level string key in flat JSON produced by `plutil -convert json`.
pub fn host_string(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..]
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
-210
View File
@@ -1,210 +0,0 @@
//! Memory-pressure supervision of a child process.
//!
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
//! the author's permission): do not start a workload when little memory is free, and stop it
//! when system-wide free memory falls below a limit, because GPU memory is wired under
//! unified memory and a runaway workload can take the whole Mac down. This version is
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
//! stopped. It supervises any command; it contains nothing game-specific.
//!
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
//! stable interface, so an unreadable value is an error, never "assume enough memory".
use crate::cmdutil::run;
use std::process::{Child, Command};
use std::time::{Duration, Instant};
pub fn parse_free_percentage(output: &str) -> Option<u8> {
let line = output
.lines()
.find(|l| l.contains("System-wide memory free percentage"))?;
let digits: String = line
.split(':')
.nth(1)?
.trim()
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let v: u8 = digits.parse().ok()?;
(v <= 100).then_some(v)
}
pub fn free_percentage() -> Option<u8> {
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Limits {
/// Refuse to start below this percent free.
pub min_start_free: u8,
/// Stop the child when free memory drops below this percent.
pub min_free: u8,
pub poll: Duration,
/// Time between SIGTERM and SIGKILL.
pub grace: Duration,
}
#[derive(Debug, PartialEq)]
pub enum Outcome {
/// The child ran to completion; `None` means it ended by a signal.
Exited(Option<i32>),
RefusedToStart {
free: u8,
need: u8,
},
StoppedLowMemory {
free: u8,
limit: u8,
},
/// Memory could not be read, so no guarantee can be given.
MemoryUnreadable,
SpawnFailed(String),
}
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
let _ = Command::new("/bin/kill")
.args(["-TERM", &child.id().to_string()])
.status();
let t0 = Instant::now();
while t0.elapsed() < grace {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
}
/// Run `program` under `limits`, reading memory through `read_free`.
pub fn supervise(
program: &str,
args: &[String],
limits: Limits,
read_free: &mut dyn FnMut() -> Option<u8>,
) -> Outcome {
match read_free() {
None => return Outcome::MemoryUnreadable,
Some(free) if free < limits.min_start_free => {
return Outcome::RefusedToStart {
free,
need: limits.min_start_free,
};
}
Some(_) => {}
}
let mut child = match Command::new(program).args(args).spawn() {
Ok(c) => c,
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
};
loop {
match child.try_wait() {
Ok(Some(status)) => return Outcome::Exited(status.code()),
Ok(None) => {}
Err(e) => return Outcome::SpawnFailed(e.to_string()),
}
match read_free() {
None => {
terminate(&mut child, limits.grace);
return Outcome::MemoryUnreadable;
}
Some(free) if free < limits.min_free => {
terminate(&mut child, limits.grace);
return Outcome::StoppedLowMemory {
free,
limit: limits.min_free,
};
}
Some(_) => {}
}
std::thread::sleep(limits.poll);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> Limits {
Limits {
min_start_free: 50,
min_free: 20,
poll: Duration::from_millis(20),
grace: Duration::from_millis(500),
}
}
#[test]
fn parses_memory_pressure_output() {
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
assert_eq!(parse_free_percentage(real), Some(71));
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 100%"),
Some(100)
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 101%"),
None
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: x"),
None
);
assert_eq!(parse_free_percentage("nothing"), None);
}
#[test]
fn refuses_to_start_when_low() {
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
}
#[test]
fn unreadable_memory_is_an_error() {
assert_eq!(
supervise("/usr/bin/true", &[], limits(), &mut || None),
Outcome::MemoryUnreadable
);
}
#[test]
fn child_exit_code_is_reported() {
let out = supervise(
"/bin/sh",
&["-c".into(), "exit 7".into()],
limits(),
&mut || Some(90),
);
assert_eq!(out, Outcome::Exited(Some(7)));
}
#[test]
fn stops_child_when_memory_drops() {
let mut calls = 0;
let t0 = Instant::now();
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
calls += 1;
Some(if calls < 4 { 90 } else { 10 })
});
assert_eq!(
out,
Outcome::StoppedLowMemory {
free: 10,
limit: 20
}
);
assert!(
t0.elapsed() < Duration::from_secs(10),
"child was not stopped promptly"
);
}
#[test]
fn real_reading_is_available_on_macos() {
if cfg!(target_os = "macos") {
assert!(free_percentage().is_some());
}
}
}
-311
View File
@@ -1,311 +0,0 @@
//! Identify a Windows executable before it is handed to CrossOver.
//!
//! Reads only the headers and the import directory names of a PE/COFF image, following
//! Microsoft's published "PE Format" specification. The file is untrusted input: every
//! offset is checked, counts are capped, and nothing is executed. This answers "is this a
//! launchable x86 Windows program, and which DLLs does it import"; it does not prove that
//! the program will run.
use crate::json::Json;
/// Largest file this will read. Larger programs are refused rather than partly checked.
pub const MAX_BYTES: u64 = 1 << 30;
const MAX_SECTIONS: usize = 96;
const MAX_IMPORTS: usize = 512;
const MAX_NAME: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Machine {
X86_64,
I386,
Arm64,
Other(u16),
}
impl Machine {
pub fn name(self) -> String {
match self {
Machine::X86_64 => "x86_64".into(),
Machine::I386 => "i386".into(),
Machine::Arm64 => "arm64".into(),
Machine::Other(m) => format!("unknown_0x{m:04x}"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
pub machine: Machine,
pub pe32_plus: bool,
pub subsystem: u16,
pub is_dll: bool,
/// Imported DLL names, lower-cased, from the (non-delayed) import directory.
pub imports: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
NotPe(&'static str),
Truncated(&'static str),
Unsupported(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::NotPe(why) => write!(f, "not a PE executable: {why}"),
Error::Truncated(what) => write!(f, "truncated or inconsistent PE: {what}"),
Error::Unsupported(why) => write!(f, "unsupported executable: {why}"),
}
}
}
fn bytes<'a>(d: &'a [u8], at: usize, n: usize, what: &'static str) -> Result<&'a [u8], Error> {
at.checked_add(n)
.and_then(|end| d.get(at..end))
.ok_or(Error::Truncated(what))
}
fn u16_at(d: &[u8], at: usize, what: &'static str) -> Result<u16, Error> {
let b = bytes(d, at, 2, what)?;
Ok(u16::from_le_bytes([b[0], b[1]]))
}
fn u32_at(d: &[u8], at: usize, what: &'static str) -> Result<u32, Error> {
let b = bytes(d, at, 4, what)?;
Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
struct Section {
va: u32,
size: u32,
file: u32,
}
fn file_offset(sections: &[Section], rva: u32) -> Option<usize> {
sections.iter().find_map(|s| {
let into = rva.checked_sub(s.va)?;
(into < s.size).then(|| s.file.checked_add(into).map(|v| v as usize))?
})
}
pub fn parse(d: &[u8]) -> Result<Image, Error> {
if bytes(d, 0, 2, "DOS magic").map_err(|_| Error::NotPe("file too small"))? != b"MZ" {
return Err(Error::NotPe("missing MZ magic"));
}
let pe = u32_at(d, 0x3c, "e_lfanew")? as usize;
if bytes(d, pe, 4, "PE signature")? != b"PE\0\0" {
return Err(Error::NotPe("missing PE signature"));
}
let coff = pe.checked_add(4).ok_or(Error::Truncated("COFF header"))?;
let machine = match u16_at(d, coff, "machine")? {
0x8664 => Machine::X86_64,
0x014c => Machine::I386,
0xaa64 => Machine::Arm64,
m => Machine::Other(m),
};
let section_count = u16_at(d, coff + 2, "section count")? as usize;
let optional_size = u16_at(d, coff + 16, "optional header size")? as usize;
let characteristics = u16_at(d, coff + 18, "characteristics")?;
if characteristics & 0x0002 == 0 {
return Err(Error::NotPe("not marked as an executable image"));
}
if section_count > MAX_SECTIONS {
return Err(Error::Truncated("implausible section count"));
}
let opt = coff + 20;
let optional = bytes(d, opt, optional_size, "optional header")?;
let (pe32_plus, count_at, dirs_at) = match u16_at(optional, 0, "optional magic")? {
0x20b => (true, 108, 112),
0x10b => (false, 92, 96),
_ => return Err(Error::NotPe("unknown optional header magic")),
};
let subsystem = u16_at(optional, 68, "subsystem")?;
let mut sections = Vec::with_capacity(section_count);
let table = opt + optional_size;
for i in 0..section_count {
let at = table + i * 40;
sections.push(Section {
va: u32_at(d, at + 12, "section address")?,
size: u32_at(d, at + 16, "section raw size")?,
file: u32_at(d, at + 20, "section raw pointer")?,
});
}
let mut imports = Vec::new();
let directories = u32_at(optional, count_at, "directory count")?;
let import_rva = if directories >= 2 {
u32_at(optional, dirs_at + 8, "import directory")?
} else {
0
};
if import_rva != 0 {
let start = file_offset(&sections, import_rva)
.ok_or(Error::Truncated("import directory outside sections"))?;
let mut terminated = false;
for i in 0..=MAX_IMPORTS {
let entry = bytes(d, start + i * 20, 20, "import descriptor")?;
if entry.iter().all(|b| *b == 0) {
terminated = true;
break;
}
let name_rva = u32_at(entry, 12, "import name")?;
let at = file_offset(&sections, name_rva)
.ok_or(Error::Truncated("import name outside sections"))?;
let rest = d.get(at..).ok_or(Error::Truncated("import name"))?;
let len = rest
.iter()
.take(MAX_NAME)
.position(|b| *b == 0)
.ok_or(Error::Truncated("unterminated import name"))?;
imports.push(String::from_utf8_lossy(&rest[..len]).to_ascii_lowercase());
}
if !terminated {
return Err(Error::Truncated("import directory has no terminator"));
}
}
Ok(Image {
machine,
pe32_plus,
subsystem,
is_dll: characteristics & 0x2000 != 0,
imports,
})
}
impl Image {
/// Refuse what is known not to launch. ARM64 programs were observed to be rejected by
/// CrossOver 26.3 on macOS ("cannot execute").
pub fn check_launchable(&self) -> Result<(), Error> {
if self.is_dll {
return Err(Error::Unsupported(
"the file is a DLL, not a program".into(),
));
}
if !matches!(self.machine, Machine::X86_64 | Machine::I386) {
return Err(Error::Unsupported(format!(
"machine {} (CrossOver on macOS runs x86 and x86_64 Windows programs)",
self.machine.name()
)));
}
// 2 = Windows GUI, 3 = Windows console.
if !matches!(self.subsystem, 2 | 3) {
return Err(Error::Unsupported(format!("subsystem {}", self.subsystem)));
}
Ok(())
}
pub fn to_json(&self) -> Json {
Json::obj(vec![
("machine", Json::str(self.machine.name())),
("pe32_plus", Json::Bool(self.pe32_plus)),
("subsystem", Json::Num(self.subsystem as f64)),
(
"imports",
Json::Arr(self.imports.iter().map(|s| Json::str(s.clone())).collect()),
),
])
}
}
/// Read and identify a program file, refusing anything that is not a regular file of a
/// plausible size.
pub fn inspect(path: &std::path::Path) -> Result<Image, String> {
let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
if !meta.is_file() {
return Err(format!("{}: not a regular file", path.display()));
}
if meta.len() > MAX_BYTES {
return Err(format!("{}: larger than {MAX_BYTES} bytes", path.display()));
}
let data = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
parse(&data).map_err(|e| format!("{}: {e}", path.display()))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
fn put16(d: &mut [u8], at: usize, v: u16) {
d[at..at + 2].copy_from_slice(&v.to_le_bytes());
}
fn put32(d: &mut [u8], at: usize, v: u32) {
d[at..at + 4].copy_from_slice(&v.to_le_bytes());
}
/// A minimal image written field by field from the PE Format specification: one section
/// at RVA 0x1000 holding one import descriptor and its name.
pub(crate) fn synthetic(machine: u16, characteristics: u16) -> Vec<u8> {
let mut d = vec![0u8; 0x400];
d[0..2].copy_from_slice(b"MZ");
put32(&mut d, 0x3c, 0x40);
d[0x40..0x44].copy_from_slice(b"PE\0\0");
put16(&mut d, 0x44, machine);
put16(&mut d, 0x46, 1); // one section
put16(&mut d, 0x54, 240); // PE32+ optional header with 16 directories
put16(&mut d, 0x56, characteristics);
let opt = 0x58;
put16(&mut d, opt, 0x20b);
put16(&mut d, opt + 68, 3);
put32(&mut d, opt + 108, 16);
put32(&mut d, opt + 120, 0x1000); // directory 1: imports
let section = opt + 240;
put32(&mut d, section + 12, 0x1000);
put32(&mut d, section + 16, 0x100);
put32(&mut d, section + 20, 0x200);
put32(&mut d, 0x200 + 12, 0x1080); // name of descriptor 0
d[0x280..0x28a].copy_from_slice(b"D3D11.dll\0");
d
}
#[test]
fn reads_machine_subsystem_and_imports() {
let i = parse(&synthetic(0x8664, 0x0022)).unwrap();
assert_eq!(i.machine, Machine::X86_64);
assert!(i.pe32_plus);
assert_eq!(i.subsystem, 3);
assert_eq!(i.imports, ["d3d11.dll"]);
assert_eq!(i.check_launchable(), Ok(()));
}
#[test]
fn refuses_arm64_dlls_and_unknown_machines() {
let arm = parse(&synthetic(0xaa64, 0x0022)).unwrap();
assert!(matches!(arm.check_launchable(), Err(Error::Unsupported(_))));
let dll = parse(&synthetic(0x8664, 0x2022)).unwrap();
assert!(matches!(dll.check_launchable(), Err(Error::Unsupported(_))));
let other = parse(&synthetic(0x1f0, 0x0022)).unwrap();
assert!(other.check_launchable().is_err());
}
#[test]
fn non_pe_input_is_an_error() {
assert!(matches!(parse(b""), Err(Error::NotPe(_))));
assert!(matches!(parse(b"#!/bin/sh\n"), Err(Error::NotPe(_))));
let mut d = synthetic(0x8664, 0x0022);
d[0x40] = b'X';
assert!(matches!(parse(&d), Err(Error::NotPe(_))));
assert!(parse(&synthetic(0x8664, 0)).is_err());
}
#[test]
fn hostile_offsets_and_truncation_never_panic() {
let good = synthetic(0x8664, 0x0022);
for n in 0..good.len() {
let _ = parse(&good[..n]);
}
// Every aligned word replaced by extreme values: must return, never panic.
for at in (0..good.len() - 4).step_by(2) {
for v in [u32::MAX, 0x7fff_ffff, 0x1000] {
let mut d = good.clone();
put32(&mut d, at, v);
let _ = parse(&d);
}
}
let mut far = good.clone();
put32(&mut far, 0x58 + 120, 0xdead_0000);
assert!(matches!(parse(&far), Err(Error::Truncated(_))));
}
}
-197
View File
@@ -1,197 +0,0 @@
//! Read-only environment checks before a run (`bx-cli doctor`).
//!
//! Each check is something observed on this host. A pass means the pieces the runner needs
//! are present; it does not mean any program will run.
use crate::json::Json;
use std::path::Path;
#[derive(Debug, Clone, PartialEq)]
pub struct Check {
pub name: &'static str,
pub ok: bool,
pub detail: String,
}
#[derive(Debug, Clone)]
pub struct Facts {
pub host_arch: &'static str,
/// None when no CrossOver bundle was found.
pub crossover: Option<(String, std::path::PathBuf)>,
pub rosetta_runs_x86_64: bool,
pub bottle: Option<(String, std::path::PathBuf)>,
pub free_percent: Option<u8>,
pub min_start_free: u8,
}
pub fn evaluate(f: &Facts) -> Vec<Check> {
let mut out = vec![Check {
name: "host_arm64",
ok: f.host_arch == "aarch64",
detail: f.host_arch.to_string(),
}];
match &f.crossover {
None => out.push(Check {
name: "crossover_installed",
ok: false,
detail: "no CrossOver bundle found; install it from CodeWeavers".into(),
}),
Some((version, wine)) => {
out.push(Check {
name: "crossover_installed",
ok: true,
detail: version.clone(),
});
for (name, path) in [
("wine_launcher", wine.clone()),
("wineserver", wine.with_file_name("wineserver")),
] {
out.push(Check {
name,
ok: path.is_file(),
detail: path.display().to_string(),
});
}
}
}
out.push(Check {
name: "rosetta",
ok: f.rosetta_runs_x86_64,
detail: "whether an x86_64 binary executes (CrossOver 26.3's Wine is x86_64-only)".into(),
});
if let Some((name, dir)) = &f.bottle {
out.push(Check {
name: "bottle",
ok: valid_bottle_name(name) && dir.join("drive_c").is_dir(),
detail: dir.display().to_string(),
});
if dir.join("drive_c").is_dir() {
let marker = dir.join(".betterxen-session");
let clean = match std::fs::symlink_metadata(&marker) {
Ok(meta) => meta.is_file() && !meta.file_type().is_symlink() && meta.len() == 0,
Err(e) => e.kind() == std::io::ErrorKind::NotFound,
};
out.push(Check {
name: "bottle_session",
ok: clean,
detail: if clean { "no unfinished BetterXen session".into() } else {
"active, unfinished or invalid session marker; SIGTERM an active runner, or use `bx-cli stop` for abandoned sessions".into()
},
});
}
}
out.push(match f.free_percent {
Some(p) => Check {
name: "free_memory",
ok: p >= f.min_start_free,
detail: format!("{p}% free, {}% required", f.min_start_free),
},
None => Check {
name: "free_memory",
ok: false,
detail: "could not be read".into(),
},
});
out
}
/// A bottle name becomes a path component and a command argument, so it must be neither a
/// path nor something the launcher could read as an option.
pub fn valid_bottle_name(name: &str) -> bool {
!name.is_empty()
&& !name.starts_with('-')
&& !name.contains(['/', '\\'])
&& !name.chars().any(char::is_control)
&& name != "."
&& name != ".."
}
pub fn rosetta_runs_x86_64() -> bool {
crate::cmdutil::run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some()
}
pub fn gather(bottle: Option<&str>, wine: Option<(String, &Path)>, min_start_free: u8) -> Facts {
Facts {
host_arch: std::env::consts::ARCH,
crossover: wine.map(|(v, p)| (v, p.to_path_buf())),
rosetta_runs_x86_64: rosetta_runs_x86_64(),
bottle: bottle.map(|b| (b.to_string(), crate::run::bottle_prefix(b))),
free_percent: crate::memory::free_percentage(),
min_start_free,
}
}
pub fn to_json(checks: &[Check]) -> Json {
Json::obj(vec![
("schema", Json::str("betterxen-hybrid-doctor/0")),
("ready", Json::Bool(checks.iter().all(|c| c.ok))),
(
"checks",
Json::Arr(
checks
.iter()
.map(|c| {
Json::obj(vec![
("name", Json::str(c.name)),
("ok", Json::Bool(c.ok)),
("detail", Json::str(c.detail.clone())),
])
})
.collect(),
),
),
])
}
#[cfg(test)]
mod tests {
use super::*;
fn failing(checks: &[Check]) -> Vec<&str> {
checks.iter().filter(|c| !c.ok).map(|c| c.name).collect()
}
#[test]
fn missing_pieces_are_named() {
let f = Facts {
host_arch: "aarch64",
crossover: None,
rosetta_runs_x86_64: false,
bottle: Some(("nope".into(), "/nonexistent/nope".into())),
free_percent: Some(10),
min_start_free: 50,
};
assert_eq!(
failing(&evaluate(&f)),
["crossover_installed", "rosetta", "bottle", "free_memory"]
);
}
#[test]
fn complete_synthetic_environment_passes() {
let dir = std::env::temp_dir().join(format!("bx-preflight-{}", std::process::id()));
std::fs::create_dir_all(dir.join("bottle/drive_c")).unwrap();
std::fs::write(dir.join("wine"), "").unwrap();
std::fs::write(dir.join("wineserver"), "").unwrap();
let f = Facts {
host_arch: "aarch64",
crossover: Some(("1.0".into(), dir.join("wine"))),
rosetta_runs_x86_64: true,
bottle: Some(("bottle".into(), dir.join("bottle"))),
free_percent: Some(80),
min_start_free: 50,
};
assert!(failing(&evaluate(&f)).is_empty());
std::fs::write(dir.join("bottle/.betterxen-session"), "pid=123").unwrap();
assert_eq!(failing(&evaluate(&f)), ["bottle_session"]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn bottle_names_that_are_paths_or_options_are_invalid() {
for bad in ["", "..", ".", "a/b", "a\\b", "a\nb", "--bottle"] {
assert!(!valid_bottle_name(bad), "{bad}");
}
assert!(valid_bottle_name("betterxen-test"));
}
}
-142
View File
@@ -1,142 +0,0 @@
//! Exclusive report creation: previous evidence is never replaced.
use crate::json::Json;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
/// Save a run or benchmark report under a unique name, reporting all I/O errors.
pub fn save(dir: &Path, kind: &str, report: &Json) -> io::Result<PathBuf> {
if !matches!(kind, "run" | "bench") {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"unknown report kind",
));
}
std::fs::create_dir_all(dir)?;
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(io::Error::other)?
.as_nanos();
let bytes = report.render();
loop {
let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
let path = dir.join(format!(
"{kind}-{nanos}-{}-{sequence}.json",
std::process::id()
));
match write_new(&path, bytes.as_bytes(), |file, bytes| file.write_all(bytes)) {
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
Ok(()) => return Ok(path),
}
}
}
fn write_new(
path: &Path,
bytes: &[u8],
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
) -> io::Result<()> {
let mut file = OpenOptions::new().write(true).create_new(true).open(path)?;
if let Err(error) = write(&mut file, bytes).and_then(|()| file.sync_all()) {
drop(file);
// Remove only the incomplete file this call exclusively created.
return match std::fs::remove_file(path) {
Ok(()) => Err(error),
Err(cleanup) => Err(io::Error::new(
error.kind(),
format!(
"{error}; cannot remove incomplete report {}: {cleanup}",
path.display()
),
)),
};
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn directory() -> PathBuf {
let id = SEQUENCE.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("bx-records-{}-{id}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn repeated_run_and_bench_reports_preserve_prior_evidence() {
let dir = directory();
std::fs::write(dir.join("bench.json"), "previous evidence").unwrap();
let first = save(&dir, "run", &Json::str("first")).unwrap();
let second = save(&dir, "run", &Json::str("second")).unwrap();
let bench1 = save(&dir, "bench", &Json::str("bench one")).unwrap();
let bench2 = save(&dir, "bench", &Json::str("bench two")).unwrap();
assert_ne!(first, second);
assert_ne!(bench1, bench2);
assert_eq!(
std::fs::read_to_string(first).unwrap(),
Json::str("first").render()
);
assert_eq!(
std::fs::read_to_string(second).unwrap(),
Json::str("second").render()
);
assert_eq!(
std::fs::read_to_string(bench1).unwrap(),
Json::str("bench one").render()
);
assert_eq!(
std::fs::read_to_string(bench2).unwrap(),
Json::str("bench two").render()
);
assert_eq!(
std::fs::read_to_string(dir.join("bench.json")).unwrap(),
"previous evidence"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn existing_destination_is_never_truncated() {
let dir = directory();
let path = dir.join("record.json");
std::fs::write(&path, "original").unwrap();
let error =
write_new(&path, b"replacement", |file, bytes| file.write_all(bytes)).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "original");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn invalid_directory_is_an_error() {
let dir = directory();
let path = dir.join("not-a-directory");
std::fs::write(&path, "original").unwrap();
assert!(save(&path, "run", &Json::Null).is_err());
assert_eq!(std::fs::read_to_string(path).unwrap(), "original");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn partial_write_failure_is_reported_and_incomplete_file_removed() {
let dir = directory();
let path = dir.join("record.json");
let error = write_new(&path, b"a complete report", |file, _| {
file.write_all(b"partial")?;
Err(io::Error::other("injected write failure"))
})
.unwrap_err();
assert!(error.to_string().contains("injected write failure"));
assert!(!path.exists());
std::fs::remove_dir_all(dir).unwrap();
}
}
File diff suppressed because it is too large. Load diff
-128
View File
@@ -1,128 +0,0 @@
//! Coordinate BetterXen runners for one bottle. This does not lock out CrossOver's UI or
//! other launchers: maintainers must dedicate the bottle to BetterXen tests.
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::fd::AsRawFd;
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
use std::path::Path;
pub struct BottleSession {
file: File,
}
impl BottleSession {
pub fn acquire(prefix: &Path, recovery: bool) -> Result<Self, String> {
let path = prefix.join(".betterxen-session");
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
let metadata = file.metadata().map_err(|e| e.to_string())?;
// SAFETY: geteuid takes no pointers and has no memory preconditions.
let uid = unsafe { libc::geteuid() };
if !metadata.is_file() || metadata.nlink() != 1 || metadata.uid() != uid {
return Err(format!(
"{} must be a regular, singly linked file owned by the current user",
path.display()
));
}
// SAFETY: the descriptor remains owned by `file`; flock changes no Rust memory.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
return Err(
"bottle has an active BetterXen runner; stop that runner with SIGTERM first".into(),
);
}
let mut previous = String::new();
Read::by_ref(&mut file)
.take(4096)
.read_to_string(&mut previous)
.map_err(|e| e.to_string())?;
if !recovery && !previous.is_empty() {
return Err(format!(
"bottle has an unfinished session ({previous:?}); run `bx-cli stop --bottle B` (or `--prefix P`) before another run"
));
}
file.set_len(0).map_err(|e| e.to_string())?;
file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
writeln!(file, "pid={} recovery={recovery}", std::process::id())
.map_err(|e| e.to_string())?;
file.sync_all().map_err(|e| e.to_string())?;
Ok(Self { file })
}
/// Clear only after supervision or explicit bottle recovery completed successfully.
pub fn complete(&mut self) -> Result<(), String> {
self.file
.set_len(0)
.and_then(|()| self.file.sync_all())
.map_err(|e| e.to_string())?;
Ok(())
}
}
// The kernel releases the lock on close, including SIGKILL. Without `complete`, the
// nonempty marker survives so a new runner cannot hide a surviving guest.
impl Drop for BottleSession {
fn drop(&mut self) {
// A concurrent fork briefly inherits the open file description until exec closes
// its CLOEXEC descriptor. Explicit unlock prevents that transient child reference
// from keeping a completed parent session locked after this object is dropped.
// SAFETY: the descriptor is still owned and open; flock changes no Rust memory.
unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn active_and_abandoned_sessions_require_distinct_recovery() {
let dir = std::env::temp_dir().join(format!("bx-session-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let first = BottleSession::acquire(&dir, false).unwrap();
assert!(BottleSession::acquire(&dir, false).is_err());
assert!(BottleSession::acquire(&dir, true).is_err());
drop(first); // models a supervisor disappearing without completing cleanup
assert!(BottleSession::acquire(&dir, false).is_err());
BottleSession::acquire(&dir, true)
.unwrap()
.complete()
.unwrap();
BottleSession::acquire(&dir, false)
.unwrap()
.complete()
.unwrap();
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_marker_symlink_does_not_truncate_its_target() {
let dir = std::env::temp_dir().join(format!("bx-session-link-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let target = dir.join("valuable");
std::fs::write(&target, "preserve me").unwrap();
std::os::unix::fs::symlink(&target, dir.join(".betterxen-session")).unwrap();
assert!(BottleSession::acquire(&dir, true).is_err());
assert_eq!(std::fs::read_to_string(target).unwrap(), "preserve me");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_hardlinked_marker_is_never_truncated_during_recovery() {
let dir = std::env::temp_dir().join(format!("bx-session-hardlink-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let target = dir.join("valuable");
std::fs::write(&target, "preserve me").unwrap();
std::fs::hard_link(&target, dir.join(".betterxen-session")).unwrap();
assert!(BottleSession::acquire(&dir, true).is_err());
assert_eq!(std::fs::read_to_string(target).unwrap(), "preserve me");
std::fs::remove_dir_all(dir).unwrap();
}
}
@@ -1,82 +0,0 @@
//! Probe Windows cross-compilers for original test programs (issue #364).
//!
//! Reports what is installed and what each compiler targets; it does not install anything.
use crate::cmdutil::run;
use crate::json::Json;
/// (name, kind). Order is the discovery order only, not a preference.
pub const CANDIDATES: &[&str] = &[
"aarch64-w64-mingw32-clang",
"x86_64-w64-mingw32-clang",
"x86_64-w64-mingw32-gcc",
"i686-w64-mingw32-gcc",
];
#[derive(Debug, Clone, PartialEq)]
pub struct Compiler {
pub name: String,
pub path: String,
pub version_line: Option<String>,
pub target_machine: Option<String>,
}
pub fn probe(search_path: &str) -> Vec<Compiler> {
CANDIDATES
.iter()
.filter_map(|name| {
let path = search_path
.split(':')
.map(|d| std::path::Path::new(d).join(name))
.find(|p| p.is_file())?;
let p = path.to_str()?.to_string();
Some(Compiler {
name: name.to_string(),
version_line: run(&p, &["--version"])
.and_then(|s| s.lines().next().map(String::from)),
target_machine: run(&p, &["-dumpmachine"]),
path: p,
})
})
.collect()
}
impl Compiler {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("name", Json::str(self.name.clone())),
("path", Json::str(self.path.clone())),
("version", Json::opt_str(self.version_line.clone())),
("target_machine", Json::opt_str(self.target_machine.clone())),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_path_finds_nothing() {
assert!(probe("").is_empty());
assert!(probe("/nonexistent-dir").is_empty());
}
#[test]
fn finds_a_stub_compiler_and_reports_its_output() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let f = dir.join("x86_64-w64-mingw32-gcc");
std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap();
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
let found = probe(dir.to_str().unwrap());
assert_eq!(found.len(), 1);
assert_eq!(
found[0].target_machine.as_deref(),
Some("x86_64-w64-mingw32")
);
assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+749 -5
View File
@@ -13,10 +13,168 @@ pub struct TraceSummary {
pub clwb_events: usize,
/// Highest cumulative counter in the sampled CLWB records, if available.
pub clwb_trap_lower_bound: Option<u64>,
/// Sampled `<kind>_trapped` records for the other AMD-only instructions the
/// VEH emulates (`clzero`, `monitorx`, `mwaitx`, `rdpru`, `extrq`, `insertq`).
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).
pub shader_gate: ShaderGateSummary,
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
pub shader_gaps: Vec<ShaderGap>,
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
pub shader_gap_groups: Vec<ShaderGapGroup>,
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
/// they are grouped under `unknown`. Counted here so the group counts reconcile
/// with [`TraceSummary::shader_gaps`].
pub shader_gaps_missing_identity: usize,
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
/// value for one). Counted here rather than dropped or assumed.
pub shader_gaps_missing_constraints: usize,
/// `shader_bridge_missing` messages, in log order.
pub shader_bridge_missing: Vec<String>,
}
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapGroup {
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
/// `unknown`).
pub pso: Option<String>,
/// The emitted `stage=` value, or `None` when the record carried none.
pub stage: Option<String>,
/// How many gap records this `(pso, stage)` pair covers.
pub count: usize,
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
/// first-seen order. Two pipelines of the same kind and stage can need different
/// wave widths or atomic features, so a group keeps each constraint set rather than
/// reporting only the first and losing the rest.
pub variants: Vec<ShaderGapVariant>,
}
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapVariant {
pub wave_lanes_min: Option<String>,
pub atomic64_flags: Option<String>,
/// How many records in the group carried exactly these constraints.
pub count: usize,
}
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
/// their emitted string so unknown values are counted rather than dropped.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGateSummary {
pub total: usize,
/// Gate records whose `detail` could not be parsed as `key=value` pairs.
pub unparsed: usize,
/// Parsed gate records that carry no `decision` field, so they appear in no
/// `decisions` bucket. Counted here so the decision counts can be
/// reconciled against `total` (#497 review). `kind` is legitimately absent
/// on unclassified records and is not counted here.
pub missing_decision: usize,
pub decisions: BTreeMap<String, usize>,
pub kinds: BTreeMap<String, usize>,
pub stages: BTreeMap<String, usize>,
/// Individual gate records, in log order.
pub records: Vec<ShaderGateRecord>,
}
/// One `shader_gate` record. Fields absent from the emitted `detail` (for
/// example on unclassified records) are `None`; `atomic64` may be `Some("")`.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGateRecord {
pub pso: Option<String>,
pub stage: Option<String>,
pub decision: Option<String>,
pub hr: Option<String>,
pub kind: Option<String>,
pub shader_stage: Option<String>,
pub sm: Option<String>,
pub bytes: Option<String>,
pub dxil: Option<String>,
pub accc: Option<String>,
pub sfi0: Option<String>,
pub wave_ops: Option<String>,
pub int64_ops: Option<String>,
pub atomic64: Option<String>,
pub wave_lanes: Option<String>,
}
/// One `shader_d3dmetal_gap` record.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGap {
pub pso: Option<String>,
pub stage: Option<String>,
pub wave_lanes_min: Option<String>,
pub atomic64_flags: Option<String>,
}
/// Tokenize a `detail` string of space-separated `key=value` pairs.
///
/// Only the `shader_d3dmetal_gap` record appends free text after its pairs
/// (`... atomic64_flags=0x400000: D3DMetal ...`), so `stop_at_free_text`
/// selects how a token without `=` is treated:
///
/// - `true` (gap records): the token ends the key=value section.
/// - `false` (`shader_gate` records): a stray token is skipped and parsing
/// continues, so one unexpected word cannot silently drop every later
/// field (#497 review).
///
/// Values never contain spaces, so `atomic64=` followed by a space yields an
/// empty value.
/// Splits a log detail string into `key=value` pairs.
///
/// `stop_at_free_text` exists for records that end with prose after their
/// fields (`shader_d3dmetal_gap` ends in a sentence), where the first token
/// without `=` marks the end of the structured part.
///
/// For `shader_gate` the whole string is structured, so a token without `=`
/// is skipped rather than treated as the end. Stopping there would silently
/// drop every later field while the record still counted as parsed: with
/// `atomic64=typed, raw, wave_lanes=64-64`, a `break` loses `wave_lanes`,
/// whereas a `continue` keeps it. The emitter writes no spaces inside a value
/// today, so this is robustness against a future value containing one, not a
/// fix for current output.
fn parse_key_values(detail: &str, stop_at_free_text: bool) -> Vec<(&str, &str)> {
let mut pairs = Vec::new();
for token in detail.split_ascii_whitespace() {
match token.split_once('=') {
Some((key, value)) if !key.is_empty() => pairs.push((key, value)),
_ if stop_at_free_text => break,
_ => continue,
}
}
pairs
}
/// Sampled trap records of one instruction kind.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TrapCount {
pub events: usize,
/// Highest cumulative counter in the sampled records, if available.
pub lower_bound: Option<u64>,
}
const AMD_TRAP_EVENTS: [(&str, &str); 6] = [
("clzero_trapped", "clzero"),
("monitorx_trapped", "monitorx"),
("mwaitx_trapped", "mwaitx"),
("rdpru_trapped", "rdpru"),
("extrq_trapped", "extrq"),
("insertq_trapped", "insertq"),
];
fn sampled_counter(detail: &str) -> Option<u64> {
detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok())
}
#[derive(Debug, PartialEq, Eq)]
@@ -27,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();
@@ -35,6 +217,124 @@ fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
Some(&rest[..end])
}
fn get_field<'a>(pairs: &[(&'a str, &'a str)], key: &str) -> Option<String> {
pairs
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| (*v).to_owned())
}
fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
let gate = &mut summary.shader_gate;
gate.total += 1;
let pairs = parse_key_values(detail, false);
if pairs.is_empty() {
gate.unparsed += 1;
return;
}
let record = ShaderGateRecord {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
decision: get_field(&pairs, "decision"),
hr: get_field(&pairs, "hr"),
kind: get_field(&pairs, "kind"),
shader_stage: get_field(&pairs, "shader_stage"),
sm: get_field(&pairs, "sm"),
bytes: get_field(&pairs, "bytes"),
dxil: get_field(&pairs, "dxil"),
accc: get_field(&pairs, "accc"),
sfi0: get_field(&pairs, "sfi0"),
wave_ops: get_field(&pairs, "wave_ops"),
int64_ops: get_field(&pairs, "int64_ops"),
atomic64: get_field(&pairs, "atomic64"),
wave_lanes: get_field(&pairs, "wave_lanes"),
};
match &record.decision {
Some(decision) => *gate.decisions.entry(decision.clone()).or_insert(0) += 1,
None => gate.missing_decision += 1,
}
if let Some(kind) = &record.kind {
*gate.kinds.entry(kind.clone()).or_insert(0) += 1;
}
if let Some(stage) = &record.stage {
*gate.stages.entry(stage.clone()).or_insert(0) += 1;
}
gate.records.push(record);
}
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
/// always writes a value, so an empty one means the record is malformed, not that the
/// pipeline is named "".
fn non_empty(value: Option<String>) -> Option<String> {
value.filter(|v| !v.is_empty())
}
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
///
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
let pso = non_empty(gap.pso.clone());
let stage = non_empty(gap.stage.clone());
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
if pso.is_none() || stage.is_none() {
groups.shader_gaps_missing_identity += 1;
}
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
groups.shader_gaps_missing_constraints += 1;
}
// The group list is small (one entry per affected pipeline stage), so a linear scan
// keeps first-seen order without a second index to keep in sync.
let group_index = match groups
.shader_gap_groups
.iter()
.position(|g| g.pso == pso && g.stage == stage)
{
Some(index) => index,
None => {
groups.shader_gap_groups.push(ShaderGapGroup {
pso,
stage,
count: 0,
variants: Vec::new(),
});
groups.shader_gap_groups.len() - 1
}
};
let group = &mut groups.shader_gap_groups[group_index];
group.count += 1;
match group
.variants
.iter()
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
{
Some(index) => group.variants[index].count += 1,
None => group.variants.push(ShaderGapVariant {
wave_lanes_min,
atomic64_flags,
count: 1,
}),
}
}
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
let pairs = parse_key_values(detail, true);
// The emitter appends `: D3DMetal creates such pipelines ...` directly
// after the flags value, so strip the trailing colon.
let atomic64_flags = get_field(&pairs, "atomic64_flags")
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
let gap = ShaderGap {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
atomic64_flags,
};
record_shader_gap_group(summary, &gap);
summary.shader_gaps.push(gap);
}
pub fn summarize_jsonl(input: &str) -> TraceSummary {
let mut summary = TraceSummary::default();
for line in input.lines() {
@@ -48,11 +348,19 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
match event {
"clwb_trapped" => {
summary.clwb_events += 1;
let sample = detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok());
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
summary.clwb_trap_lower_bound =
summary.clwb_trap_lower_bound.max(sampled_counter(detail));
}
_ if AMD_TRAP_EVENTS.iter().any(|(e, _)| *e == event) => {
let name = AMD_TRAP_EVENTS.iter().find(|(e, _)| *e == event).unwrap().1;
let entry = summary.amd_traps.entry(name.to_string()).or_default();
entry.events += 1;
entry.lower_bound = entry.lower_bound.max(sampled_counter(detail));
}
"shader_gate" => record_shader_gate(&mut summary, detail),
"shader_d3dmetal_gap" => record_shader_gap(&mut summary, detail),
"shader_bridge_missing" => {
summary.shader_bridge_missing.push(detail.to_owned());
}
"adx_illegal_instruction" => summary.adx_errors += 1,
"unhandled_exception" => {
@@ -63,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
@@ -139,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#"
@@ -165,4 +517,396 @@ mod tests {
]
);
}
#[test]
fn counts_amd_only_traps_per_kind() {
let summary = summarize_jsonl(
r#"{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=1"}
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=2"}
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=4"}
{"event":"extrq_trapped","detail":"rip=0x2000 len=5 total_traps=1"}
{"event":"rdpru_trapped","detail":"rip=0x3000 len=3"}"#,
);
assert_eq!(
summary.amd_traps["clzero"],
TrapCount {
events: 3,
lower_bound: Some(4)
}
);
assert_eq!(
summary.amd_traps["extrq"],
TrapCount {
events: 1,
lower_bound: Some(1)
}
);
assert_eq!(
summary.amd_traps["rdpru"],
TrapCount {
events: 1,
lower_bound: None
}
);
assert!(!summary.amd_traps.contains_key("mwaitx"));
assert_eq!(summary.clwb_events, 0);
}
#[test]
fn summarizes_full_pass_dxil_gate_record() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.unparsed, 0);
assert_eq!(summary.shader_gate.decisions["pass_dxil"], 1);
assert_eq!(summary.shader_gate.kinds["dxil"], 1);
assert_eq!(summary.shader_gate.stages["CS"], 1);
assert_eq!(summary.shader_gate.records.len(), 1);
let r = &summary.shader_gate.records[0];
assert_eq!(r.pso.as_deref(), Some("compute"));
assert_eq!(r.stage.as_deref(), Some("CS"));
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
assert_eq!(r.hr.as_deref(), Some("0x00000000"));
assert_eq!(r.kind.as_deref(), Some("dxil"));
assert_eq!(r.shader_stage.as_deref(), Some("5"));
assert_eq!(r.sm.as_deref(), Some("6.6"));
assert_eq!(r.bytes.as_deref(), Some("1234"));
assert_eq!(r.dxil.as_deref(), Some("800"));
assert_eq!(r.accc.as_deref(), Some("0"));
assert_eq!(r.sfi0.as_deref(), Some("0x4000"));
assert_eq!(r.wave_ops.as_deref(), Some("1"));
assert_eq!(r.int64_ops.as_deref(), Some("0"));
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
}
#[test]
fn summarizes_reject_accc_only_gate_record() {
let log = r#"{"ts_ms":12,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_gate","detail":"pso=graphics stage=VS decision=reject_accc_only hr=0x80004001 kind=accc_only shader_stage=0 sm=6.0 bytes=2048 dxil=0 accc=512 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=none"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.decisions["reject_accc_only"], 1);
assert_eq!(summary.shader_gate.kinds["accc_only"], 1);
assert_eq!(summary.shader_gate.stages["VS"], 1);
let r = &summary.shader_gate.records[0];
assert_eq!(r.hr.as_deref(), Some("0x80004001"));
assert_eq!(r.sm.as_deref(), Some("6.0"));
assert_eq!(r.accc.as_deref(), Some("512"));
assert_eq!(r.atomic64.as_deref(), Some(""));
assert_eq!(r.wave_lanes.as_deref(), Some("none"));
}
#[test]
fn summarizes_unclassified_gate_record_without_kind() {
let log = r#"{"ts_ms":14,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_unclassified hr=0x00000000 bytes=4096"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.decisions["pass_unclassified"], 1);
assert_eq!(summary.shader_gate.stages["CS"], 1);
assert!(summary.shader_gate.kinds.is_empty());
let r = &summary.shader_gate.records[0];
assert_eq!(r.bytes.as_deref(), Some("4096"));
assert_eq!(r.kind, None);
assert_eq!(r.sm, None);
assert_eq!(r.dxil, None);
assert_eq!(r.atomic64, None);
assert_eq!(r.wave_lanes, None);
}
#[test]
fn summarizes_d3dmetal_gap_with_free_text_suffix() {
let log = r#"{"ts_ms":16,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gaps.len(), 1);
let gap = &summary.shader_gaps[0];
assert_eq!(gap.pso.as_deref(), Some("compute"));
assert_eq!(gap.stage.as_deref(), Some("CS"));
assert_eq!(gap.wave_lanes_min.as_deref(), Some("64"));
assert_eq!(gap.atomic64_flags.as_deref(), Some("0x400000"));
}
#[test]
fn collects_shader_bridge_missing_messages() {
let log = r#"{"ts_ms":18,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_bridge_missing","detail":"bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, ACCC-only refused"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_bridge_missing.len(), 1);
assert!(summary.shader_bridge_missing[0].contains("not found beside d3d12_xs.dll"));
}
#[test]
fn malformed_shader_gate_detail_is_counted_not_dropped() {
for detail in ["", "garbage", "=value", " "] {
let log = format!(
"{{\"ts_ms\":20,\"tid\":1,\"level\":\"INFO\",\"sub\":\"d3d12_xs\",\"event\":\"shader_gate\",\"detail\":\"{detail}\"}}"
);
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gate.total, 1, "detail={detail:?}");
assert_eq!(summary.shader_gate.unparsed, 1, "detail={detail:?}");
assert!(summary.shader_gate.records.is_empty(), "detail={detail:?}");
}
}
#[test]
fn empty_atomic64_value_is_preserved() {
let log = r#"{"ts_ms":22,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=100 dxil=64 accc=0 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=0-4294967295"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.atomic64.as_deref(), Some(""));
assert_eq!(r.wave_lanes.as_deref(), Some("0-4294967295"));
}
#[test]
fn a_stray_token_does_not_drop_later_gate_fields() {
// #497 review point 1: one value containing a space must not turn every
// later field into None.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil atomic64=typed, raw wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
assert_eq!(summary.shader_gate.unparsed, 0);
}
#[test]
fn two_atomic64_flags_are_parsed() {
// #497 review point 1: the emitter concatenates flags with no separator,
// but two flags must round-trip if they ever are spaced.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil kind=dxil atomic64=typed, groupshared, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
}
#[test]
fn a_gate_record_without_a_decision_is_counted_as_missing() {
// #497 review point 2: decision counts must reconcile against total.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.missing_decision, 1);
assert_eq!(summary.shader_gate.unparsed, 0);
assert!(summary.shader_gate.decisions.is_empty());
assert_eq!(summary.shader_gate.stages["CS"], 1);
}
#[test]
fn decision_buckets_plus_missing_reconcile_with_total() {
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil bytes=1"}
{"event":"shader_gate","detail":"pso=compute stage=CS"}
{"event":"shader_gate","detail":"garbage"}"#;
let summary = summarize_jsonl(log);
let gate = &summary.shader_gate;
let bucketed: usize = gate.decisions.values().sum();
assert_eq!(gate.total, 3);
assert_eq!(gate.unparsed, 1);
assert_eq!(gate.missing_decision, 1);
assert_eq!(bucketed + gate.unparsed + gate.missing_decision, gate.total);
}
#[test]
fn unknown_decisions_and_kinds_are_counted() {
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=some_future_decision hr=0x00000000 kind=some_future_kind bytes=1"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.decisions["some_future_decision"], 1);
assert_eq!(summary.shader_gate.kinds["some_future_kind"], 1);
}
/// A stray token must not end the structured part of a `shader_gate`
/// record: if it did, every later field would silently become `None`
/// while the record still counted as parsed.
#[test]
fn a_record_without_a_decision_is_counted_as_missing() {
let mut summary = TraceSummary::default();
record_shader_gate(&mut summary, "pso=graphics stage=pixel");
let gate = &summary.shader_gate;
assert_eq!(gate.total, 1);
assert_eq!(gate.unparsed, 0);
assert_eq!(gate.missing_decision, 1);
assert!(gate.decisions.is_empty());
}
/// The free-text path is the opposite: `shader_d3dmetal_gap` ends in a
/// sentence, so the first token without `=` ends the structured part.
#[test]
fn free_text_ends_the_structured_part_of_a_gap_record() {
let pairs = parse_key_values("pso=graphics stage=pixel and then some prose", true);
assert_eq!(pairs.len(), 2);
assert_eq!(pairs[1], ("stage", "pixel"));
}
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
/// with its own wave width and 64-bit-atomic flags.
#[test]
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
// Same pso, different stages: grouping on pso alone would collapse these, so the
// test discriminates the (pso, stage) key rather than only the pso.
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
assert_eq!(summary.shader_gap_groups.len(), 3);
let first = &summary.shader_gap_groups[0];
assert_eq!(first.pso.as_deref(), Some("graphics"));
assert_eq!(first.stage.as_deref(), Some("VS"));
assert_eq!(first.count, 1);
assert_eq!(
first.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 1,
}]
);
let second = &summary.shader_gap_groups[1];
assert_eq!(second.pso.as_deref(), Some("compute"));
assert_eq!(second.stage.as_deref(), Some("CS"));
assert_eq!(second.count, 1);
// A second stage of the *same* pso stays its own group, which is what separates a
// (pso, stage) key from a pso-only key.
let third = &summary.shader_gap_groups[2];
assert_eq!(third.pso.as_deref(), Some("graphics"));
assert_eq!(third.stage.as_deref(), Some("PS"));
assert_eq!(third.count, 1);
}
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
/// identical records are not adjacent.
#[test]
fn groups_identical_gaps_together() {
let record = r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let log = format!("{record}\n{other}\n{record}\n");
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gap_groups.len(), 2);
let compute = &summary.shader_gap_groups[0];
assert_eq!(compute.stage.as_deref(), Some("CS"));
assert_eq!(compute.count, 2);
assert_eq!(
compute.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 2,
}]
);
assert_eq!(summary.shader_gap_groups[1].count, 1);
// Every record is in exactly one group.
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
assert_eq!(grouped, summary.shader_gaps.len());
}
/// #590: one pipeline kind and stage can need different wave widths or atomic
/// features, so a group keeps every distinct constraint set, not only the first.
#[test]
fn one_group_keeps_each_distinct_constraint_set() {
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gap_groups.len(), 1);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 3);
assert_eq!(
group.variants,
[
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 2,
},
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 1,
},
]
);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
/// #590: a gap record with a missing or empty field must not panic. It is grouped
/// under `unknown` and counted, never dropped or guessed.
#[test]
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
for (detail, missing_identity, missing_constraints) in [
("", 1, 1),
("garbage", 1, 1),
("pso=compute", 1, 1),
("stage=CS", 1, 1),
(
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
1,
0,
),
("pso=compute stage=CS", 0, 1),
(
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
0,
1,
),
] {
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
assert_eq!(
summary.shader_gap_groups.len(),
1,
"detail={detail:?} lost its record"
);
assert_eq!(
summary.shader_gaps_missing_identity, missing_identity,
"detail={detail:?}"
);
assert_eq!(
summary.shader_gaps_missing_constraints, missing_constraints,
"detail={detail:?}"
);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 1, "detail={detail:?}");
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
assert_eq!(recorded, 1, "detail={detail:?}");
}
}
/// #590: the fields a malformed record does carry are still reported.
#[test]
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
let log =
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
let summary = summarize_jsonl(log);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.pso.as_deref(), Some("compute"));
assert_eq!(group.stage.as_deref(), Some("CS"));
assert_eq!(
group.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: None,
count: 1,
}]
);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 1);
}
/// #590: a run with no gap records produces no groups and no missing-field counts, so
/// the trace renders as it did before the grouping existed.
#[test]
fn a_run_with_no_gaps_has_no_groups() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert!(summary.shader_gaps.is_empty());
assert!(summary.shader_gap_groups.is_empty());
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
}
-5
View File
@@ -1,5 +0,0 @@
[toolchain]
channel = "1.100.0"
profile = "minimal"
components = ["rustfmt", "clippy"]
targets = ["aarch64-apple-darwin"]
+117 -21
View File
@@ -4,11 +4,15 @@
Checks only tracked files:
1. no merge-conflict markers in tracked text files;
2. every relative Markdown link points at a tracked file or directory;
3. every workflow file under .github/workflows parses as YAML.
3. every fragment (``#heading``) in a Markdown link resolves to a real
heading in the target Markdown file, including in-page ``](#foo)``
links validated against the same file's headings;
4. every workflow file under .github/workflows parses as YAML.
External URLs and in-page anchors are not fetched or validated, so the result
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
when PyYAML is missing.
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
fetched or validated, so the result does not depend on the network.
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
not skip, when PyYAML is missing.
"""
import re
import subprocess
@@ -17,9 +21,16 @@ from pathlib import Path, PurePosixPath
from urllib.parse import unquote
ROOT = Path(__file__).resolve().parents[2]
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
MARKER = re.compile(r"^(<{7}( |$)|\|{7}( |$)|={7}$|>{7}( |$))")
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
FENCE = re.compile(r"^\s*(```|~~~)")
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
# GitHub slugs the rendered heading, so an inline link contributes only its
# text: ``## See [ADR](x.md)`` slugs as ``see-adr``, not ``see-adrxmd``.
# Link syntax inside a code span stays literal, so those spans are set aside
# before substituting and put back afterwards.
INLINE_LINK = re.compile(r"(?<!\!)\[([^\]]*)\]\([^)]*\)")
CODE_SPAN = re.compile(r"(`+)(.+?)\1")
def tracked():
@@ -35,6 +46,63 @@ def text(path):
return data.decode("utf-8", "replace")
def _slug(text):
"""GitHub-style slug: lowercase, strip non-alnum/-/_/space, spaces -> -."""
text = text.lower()
text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE)
return text.replace(" ", "-")
def _heading_text(text):
"""Rendered text of a heading: link text in, code spans left literal."""
spans = []
def stash(match):
spans.append(match.group(0))
return "\x00%d\x00" % (len(spans) - 1)
stashed = CODE_SPAN.sub(stash, text)
substituted = INLINE_LINK.sub(r"\1", stashed)
for index, span in enumerate(spans):
substituted = substituted.replace("\x00%d\x00" % index, span)
return substituted
def markdown_slugs(body):
"""Return the set of GitHub-style heading slugs in a Markdown document.
Duplicate headings get ``-1``, ``-2``, ... suffixes. Headings inside
fenced code blocks are ignored.
"""
slugs = set()
seen = {}
in_fence = False
for line in body.splitlines():
if FENCE.match(line):
in_fence = not in_fence
continue
if in_fence:
continue
m = HEADING.match(line)
if not m:
continue
base = _slug(_heading_text(m.group(2)))
if not base:
continue
# Advance the numeric suffix until we find a slug that has not
# already been emitted. Counting only identical bases is not
# enough: a literal heading such as ``Foo-1`` may already own
# ``foo-1``, so the next ``Foo`` must become ``foo-2``.
count = seen.get(base, 0)
slug = base if count == 0 else f"{base}-{count}"
while slug in slugs:
count += 1
slug = f"{base}-{count}"
seen[base] = count + 1
slugs.add(slug)
return slugs
def check_markers(files, problems):
for path in files:
if path.endswith((".patch", ".diff")):
@@ -47,9 +115,30 @@ def check_markers(files, problems):
problems.append(f"{path}:{number}: merge conflict marker")
def _resolve_link(path, target):
"""Resolve a relative link target to a repo-root-relative POSIX path."""
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
return "/".join(parts)
def check_links(files, problems):
known = set(files)
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
slug_cache = {}
def slugs_for(md_path):
if md_path not in slug_cache:
slug_cache[md_path] = markdown_slugs(text(md_path) or "")
return slug_cache[md_path]
for path in files:
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
continue
@@ -61,24 +150,31 @@ def check_links(files, problems):
if in_fence:
continue
line = re.sub(r"`[^`]*`", "", line)
for target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
for raw_target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|//)", raw_target, re.I):
continue
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
if not target:
if raw_target == "#":
continue
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
norm = "/".join(parts)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
fragment = ""
if "#" in raw_target:
fragment = unquote(raw_target.split("#", 1)[1])
target = unquote(raw_target.split("#", 1)[0].split("?", 1)[0])
if not target and not fragment:
continue
if target:
norm = _resolve_link(path, target)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
continue
else:
norm = path
if fragment and norm.endswith(".md") and norm in known:
if fragment not in slugs_for(norm):
shown = raw_target
problems.append(
f"{path}:{number}: broken fragment '#{fragment}' "
f"in link '{shown}' (heading not found)"
)
def check_workflows(files, problems, require_yaml):
+296
View File
@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
Run with:
python3 -m unittest scripts/audit/test_docs_hygiene.py
"""
import importlib.util
import sys
import unittest
from pathlib import Path
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
docs_hygiene = importlib.util.module_from_spec(_spec)
sys.modules["docs_hygiene"] = docs_hygiene
_spec.loader.exec_module(docs_hygiene)
class SlugTests(unittest.TestCase):
def test_basic_slug(self):
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
self.assertIn("hello-world", slugs)
def test_strips_punctuation(self):
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
self.assertIn("whats-new-2024", slugs)
def test_keeps_underscore_and_hyphen(self):
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
self.assertIn("foo_bar-baz", slugs)
def test_duplicate_headings(self):
body = "# Setup\n\n# Setup\n\n# Setup\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("setup", slugs)
self.assertIn("setup-1", slugs)
self.assertIn("setup-2", slugs)
def test_suffix_skips_literal_heading_slug(self):
# Regression: counting identical bases alone lets a generated
# suffix collide with a literal heading slug, so the third `Foo`
# also became `foo-1` and a link to the wrong heading validated.
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_suffix_skips_multiple_literal_heading_slugs(self):
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
def test_three_identical_headings(self):
body = "# Foo\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_literal_slug_before_duplicates(self):
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
def test_heading_link_contributes_only_its_text(self):
# GitHub slugs the rendered heading, where the link's URL is gone.
# Slugging the raw source appended the URL and made the first real
# link to the anchor look broken.
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
self.assertEqual(slugs, {"setup-guide-notes"})
def test_heading_link_matches_github_for_the_readme_heading(self):
# The exact heading at README.md:53; GitHub renders
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
def test_heading_link_duplicate_still_gets_a_suffix(self):
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
def test_heading_link_inside_a_code_span_stays_literal(self):
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
# the slug. Substituting links first made this `code-x-span`.
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
self.assertEqual(slugs, {"code-xy-span"})
def test_heading_mixes_a_code_span_and_a_link(self):
# Only the real link loses its URL; the code span keeps its text.
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
self.assertEqual(slugs, {"see-a-and-b"})
def test_heading_double_backtick_code_span(self):
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
# the inner single-backtick run closes the outer span early, so the
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
# observed GitHub anchor keeps this honest rather than assuming the
# "obvious" answer.
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
def test_heading_image_is_not_treated_as_a_link(self):
# An image contributes its alt text through GitHub's rendering, but
# the `(?<!\!)` guard must keep this path unchanged for now.
slugs = docs_hygiene.markdown_slugs("## ![img](a.png) caption\n")
self.assertEqual(len(slugs), 1)
def test_fenced_code_block_ignored(self):
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("real-heading", slugs)
self.assertNotIn("not-a-heading", slugs)
def test_tilde_fence_ignored(self):
body = "~~~\n# Not A Heading\n~~~\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertNotIn("not-a-heading", slugs)
def test_atx_levels(self):
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
slugs = docs_hygiene.markdown_slugs(body)
for s in ("one", "two", "three", "four", "five", "six"):
self.assertIn(s, slugs)
class CheckLinksTests(unittest.TestCase):
"""Exercise check_links with a synthetic in-memory file set."""
def _run(self, files):
"""files: dict mapping repo-relative path -> Markdown body."""
problems = []
original_text = docs_hygiene.text
def fake_text(path):
return files.get(path)
docs_hygiene.text = fake_text
try:
docs_hygiene.check_links(list(files), problems)
finally:
docs_hygiene.text = original_text
return problems
def test_existing_heading_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(problems, [])
def test_in_page_anchor_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
})
self.assertEqual(problems, [])
def test_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "[link](b.md#no-such-heading)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#no-such-heading", problems[0])
self.assertIn("heading not found", problems[0])
def test_in_page_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#this-heading-does-not-exist", problems[0])
def test_duplicate_heading_addressable(self):
problems = self._run({
"docs/a.md": "[link](b.md#setup-1)\n",
"docs/b.md": "# Setup\n\n# Setup\n",
})
self.assertEqual(problems, [])
def test_fenced_heading_not_a_slug(self):
problems = self._run({
"docs/a.md": "[link](b.md#not-a-heading)\n",
"docs/b.md": "```\n# Not A Heading\n```\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#not-a-heading", problems[0])
def test_external_url_with_fragment_not_checked(self):
problems = self._run({
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
})
self.assertEqual(problems, [])
def test_mailto_not_checked(self):
problems = self._run({
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
})
self.assertEqual(problems, [])
def test_protocol_relative_not_checked(self):
problems = self._run({
"docs/a.md": "[link](//example.com/page#frag)\n",
})
self.assertEqual(problems, [])
def test_bare_hash_skipped(self):
problems = self._run({
"docs/a.md": "[link](#)\n",
})
self.assertEqual(problems, [])
def test_missing_file_still_reported(self):
problems = self._run({
"docs/a.md": "[link](nonexistent.md#foo)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("broken relative link", problems[0])
def test_fragment_on_non_markdown_not_checked(self):
problems = self._run({
"docs/a.md": "[link](image.png#foo)\n",
"docs/image.png": None,
})
# image.png is binary (text returns None) but it exists in the
# file list, so the link itself resolves; fragment is not checked.
self.assertEqual(problems, [])
class MarkerTests(unittest.TestCase):
"""The conflict-marker check must catch all four markers, including the diff3 one."""
def _markers(self, text):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "f.md").write_text(text, encoding="utf-8")
previous = docs_hygiene.ROOT
docs_hygiene.ROOT = root
try:
problems = []
docs_hygiene.check_markers({"f.md": text}, problems)
return problems
finally:
docs_hygiene.ROOT = previous
def test_every_marker_kind_is_reported(self):
for line in ["<<<<<<< HEAD", "||||||| merged common ancestors", "=======", ">>>>>>> topic"]:
problems = self._markers(line + "\n")
self.assertEqual(len(problems), 1, f"{line!r} was not reported: {problems}")
self.assertIn("f.md:1", problems[0])
def test_diff3_base_marker_is_reported(self):
base = self._markers("||||||| merged common ancestors\n")
self.assertEqual(len(base), 1, "the diff3 base marker must be reported")
self.assertIn("conflict marker", base[0])
def test_a_diff3_block_reports_all_four_lines(self):
block = "<<<<<<< HEAD\na\n||||||| merged common ancestors\nb\n=======\nc\n>>>>>>> topic\n"
problems = self._markers(block)
self.assertEqual(len(problems), 4, problems)
def test_ordinary_content_is_not_a_marker(self):
for text in ["| a | b |\n", "||||||\n", "======\n", "prose with | pipes\n", "---\n"]:
self.assertEqual(self._markers(text), [], f"{text!r} was wrongly reported")
class WorkflowTests(unittest.TestCase):
"""check_workflows must reject unparseable YAML."""
def _check(self, text):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / ".github" / "workflows").mkdir(parents=True)
(root / ".github" / "workflows" / "a.yml").write_text(text, encoding="utf-8")
previous = docs_hygiene.ROOT
docs_hygiene.ROOT = root
try:
problems = []
docs_hygiene.check_workflows({".github/workflows/a.yml": text}, problems, require_yaml=True)
return problems
finally:
docs_hygiene.ROOT = previous
def test_parses_a_valid_workflow(self):
self.assertEqual(self._check("on: push\njobs:\n b:\n runs-on: ubuntu-latest\n"), [])
def test_reports_invalid_yaml(self):
problems = self._check("on: [push\n")
self.assertEqual(len(problems), 1, problems)
self.assertIn("a.yml", problems[0])
if __name__ == "__main__":
unittest.main()
+31
View File
@@ -18,6 +18,37 @@ cmake -S "$ROOT_DIR/shims" -B "$BUILD_DIR" \
cmake --build "$BUILD_DIR" --parallel "$JOBS"
# bx_shader_bridge.dll (#445, #484): shader-transpiler/crates/dxbc-accc built for x86-64
# Windows guests, linked with abi/defs/bx_shader_bridge.def so its export list and internal
# name are the frozen ones. The verifier below then checks it like every other shim.
# Cargo and rustc are resolved through rustup when present (a cargo earlier on PATH may have
# no Windows std), and the build always goes to <repo>/target so no stale DLL is staged.
BRIDGE_TARGET=x86_64-pc-windows-gnu
if command -v rustup >/dev/null 2>&1; then
BRIDGE_CARGO="$(cd "$ROOT_DIR" && rustup which cargo)"
BRIDGE_RUSTC="$(cd "$ROOT_DIR" && rustup which rustc)"
else
BRIDGE_CARGO="$(command -v cargo || true)"
BRIDGE_RUSTC="$(command -v rustc || true)"
fi
if [ -z "$BRIDGE_CARGO" ] || [ -z "$BRIDGE_RUSTC" ]; then
echo "error: cargo/rustc not found; bx_shader_bridge.dll needs the Rust toolchain" >&2
exit 1
fi
BRIDGE_LIBDIR="$("$BRIDGE_RUSTC" --print target-libdir --target "$BRIDGE_TARGET" 2>/dev/null || true)"
if [ -z "$BRIDGE_LIBDIR" ] || ! ls "$BRIDGE_LIBDIR"/libstd-*.rlib >/dev/null 2>&1; then
echo "error: $("$BRIDGE_RUSTC" --version) has no std for $BRIDGE_TARGET, needed for bx_shader_bridge.dll" >&2
echo "error: install it with: rustup target add $BRIDGE_TARGET" >&2
exit 1
fi
echo "=== Building bx_shader_bridge.dll with $("$BRIDGE_RUSTC" --version) ==="
RUSTC="$BRIDGE_RUSTC" CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
"$BRIDGE_CARGO" rustc --locked --release -j "$JOBS" --manifest-path "$ROOT_DIR/Cargo.toml" \
-p dxbc-accc --lib --crate-type cdylib --target "$BRIDGE_TARGET" --target-dir "$ROOT_DIR/target" \
-- -C link-arg="$ROOT_DIR/abi/defs/bx_shader_bridge.def"
mkdir -p "$BUILD_DIR/bin"
cp "$ROOT_DIR/target/$BRIDGE_TARGET/release/dxbc_accc.dll" "$BUILD_DIR/bin/bx_shader_bridge.dll"
echo "=== Verifying built PE32+ DLL Export Directories against abi/defs/*.def ==="
python3 - "$ROOT_DIR/abi/defs" "$BUILD_DIR/bin" <<'PY'
import os
-260
View File
@@ -1,260 +0,0 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Run the integrated-workload acceptance sequence through `betterxen hybrid` on this Mac.
# Every line printed is "ok <check>" or "FAIL <check>"; the exit status is non-zero if any
# check failed. Raw JSON records and logs are kept under the output directory.
#
# scripts/hybrid/accept-integrated.sh <llvm-mingw-dir> <bottle> [soak-frames] [repeats]
#
# Exit 0: every check ran and passed. 1: a check failed. 2: the only deviations are the known
# D3DMetal swapchain retention and/or checks reported NOT-RUN. NOT-RUN is never a pass.
# Shader Model 6 needs Microsoft's DXC (scripts/hybrid/install-dxc.py); point
# BETTERXEN_DXC_DIR at its bin/x64 directory.
# Needs CrossOver, an existing win11_64 bottle, Rust 1.100.0, the pinned llvm-mingw
# (https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md), and for the on-screen check a GUI session with the
# Screen Recording and Accessibility permissions (the latter for the keyboard check, which
# brings the test window to the front: do not type while it runs). Opens small windows; do not
# run on a busy machine or alongside anything else using the same bottle.
set -u
TC=${1:?usage: $0 <llvm-mingw-dir> <bottle> [soak-frames] [repeats]}
BOTTLE=${2:?name an existing bottle}
SOAK=${3:-20000}
REPEATS=${4:-5}
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
export RUSTUP_TOOLCHAIN=${RUSTUP_TOOLCHAIN:-1.100.0-aarch64-apple-darwin}
mkdir -p "$ROOT/artifacts/acceptance" || exit 1
OUT=$(mktemp -d "$ROOT/artifacts/acceptance/$(date -u +%Y%m%dT%H%M%SZ)-XXXXXX") || exit 1
failed=0
known=0
not_run=0
ok() { echo "ok $1"; }
bad() { echo "FAIL $1"; failed=1; }
if [ -z "${BETTERXEN_RUNNER:-}" ]; then
(cd "$ROOT" && cargo build --locked --release -p bx-cli) >"$OUT/build-runner.log" 2>&1 ||
{ bad "build runner"; exit 1; }
fi
if [ -n "${BETTERXEN_WORKLOAD_DIR:-}" ]; then
mkdir -p "$OUT/bin" || exit 1
for name in d3d11-integrated d3d12-integrated d3d12-lifetime d3d12-wave-probe; do
cp "$BETTERXEN_WORKLOAD_DIR/$name.exe" "$OUT/bin/" || exit 1
done
else
"$ROOT/tests/conformance/test_d3d11_integrated/build.sh" "$TC" "$OUT/bin" >"$OUT/build-workload.log" 2>&1 ||
{ bad "build workload"; exit 1; }
"$ROOT/tests/conformance/test_d3d12_integrated/build.sh" "$TC" "$OUT/bin" >"$OUT/build-workload12.log" 2>&1 ||
{ bad "build D3D12 workload"; exit 1; }
for probe in lifetime wave; do
"$ROOT/tests/conformance/test_d3d12_$probe/build.sh" "$TC" "$OUT/bin" >"$OUT/build-$probe.log" 2>&1 ||
{ bad "build D3D12 $probe probe"; exit 1; }
done
fi
BX=${BETTERXEN_RUNNER:-"${CARGO_TARGET_DIR:-$ROOT/target}/release/bx-cli"}
HYBRID=${BETTERXEN_HYBRID_RUNNER:-"$(dirname "$BX")/bx-cli"}
EXE12="$OUT/bin/d3d12-integrated.exe"
EXE="$OUT/bin/d3d11-integrated.exe"
# Unique executable names separate lifecycle observations from other bottles. Names are
# never used as kill authority by the runner.
RUN_ID=$(basename "$OUT")
mv "$EXE" "$OUT/bin/d3d11-$RUN_ID.exe" || exit 1
mv "$EXE12" "$OUT/bin/d3d12-$RUN_ID.exe" || exit 1
EXE="$OUT/bin/d3d11-$RUN_ID.exe"
EXE12="$OUT/bin/d3d12-$RUN_ID.exe"
if [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null)" = "$ROOT" ]; then
git -C "$ROOT" rev-parse HEAD >"$OUT/commit.txt"
git -C "$ROOT" status --porcelain >>"$OUT/commit.txt"
elif [ -n "${BETTERXEN_SOURCE_COMMIT:-}" ]; then
printf '%s\nprebuilt bundle; source archive SHA-256 verified by test.sh\n' "$BETTERXEN_SOURCE_COMMIT" >"$OUT/commit.txt"
else
bad "source commit unavailable; use a Git checkout or the verified bundle test.sh"
exit 1
fi
"$BX" hybrid receipt >"$OUT/receipt.json" 2>&1
if "$BX" hybrid doctor --bottle "$BOTTLE" >"$OUT/doctor.json" 2>&1; then ok "A environment"; else
bad "A environment (see doctor.json)"; exit 1; fi
if "$BX" hybrid inspect "$EXE" >"$OUT/inspect.json" 2>&1; then ok "B executable identified"; else bad "B inspect"; fi
GATES=runtime.threads,runtime.memory,runtime.exceptions,runtime.time,runtime.files,graphics.init,shader.compile,frame.first,frame.continuous,resources.churn,input,memory.bounded,shutdown
# run <name> <expected-classification> [runner options...] -- [workload args...]
run() {
name=$1; want=$2; shift 2
opts=""
while [ $# -gt 0 ] && [ "$1" != -- ]; do opts="$opts $1"; shift; done
shift
# shellcheck disable=SC2086 # options are fixed words from this script
"$BX" hybrid run --bottle "$BOTTLE" --expect "PASS integrated" --keep-output true --out "$OUT/raw" $opts -- "$EXE" "$@" \
>"$OUT/$name.json" 2>"$OUT/$name.log"
got=$(sed -n 's/^ "classification": "\(.*\)",$/\1/p' "$OUT/$name.json")
case "$got" in
$want) ok "$name ($got)" ;;
*) bad "$name: expected $want, got ${got:-no record}" ;;
esac
}
run C-F-G-H-full passed --require-gates "$GATES" --timeout 180 --stall-timeout 60 -- --frames 600
run BC1-full passed --require-gates "$GATES,textures.bc1" --timeout 180 -- --frames 128 --bc1
run BC1-negative failed_exit_1 --timeout 120 -- --frames 128 --bc1 --fault bc1
# a negative control counts only if the gate the fault targets is the one that failed
intended() {
case "$1" in
input) echo input ;;
stale) echo frame.continuous ;;
bc1) echo textures.bc1 ;;
*) echo "frame.first frame.continuous" ;;
esac
}
detects() {
# shellcheck disable=SC2046 # gate names are fixed words
if python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/$1.json" $(intended "$2") >"$OUT/$1.gates.log" 2>&1;
then ok "$1 failed its intended gate ($(cat "$OUT/$1.gates.log"))"
else bad "$1: $(cat "$OUT/$1.gates.log")"; fi
}
detects BC1-negative bc1
for scene in C-F-G-H-full BC1-full; do
if python3 "$ROOT/scripts/hybrid/check-image-digest.py" "$OUT/$scene.json" >"$OUT/oracle-$scene.log" 2>&1;
then ok "independent image oracle $scene"; else bad "independent image oracle $scene (see log)"; fi
done
for fault in color blank stale input depth; do
run "negative-$fault" failed_exit_1 --timeout 120 -- --frames 128 --fault "$fault"
detects "negative-$fault" "$fault"
done
# With Wine's crash dialog on, winedbg waits for a click and this times out;
# scripts/hybrid/create-test-bottle.py turns it off in new test bottles.
run negative-crash 'failed_exit_*' --timeout 240 -- --frames 128 --fault crash
run recovery-after-crash passed --require-gates "$GATES" --timeout 120 -- --frames 128
run negative-hang stalled --timeout 90 --stall-timeout 15 -- --frames 128 --fault hang
if pgrep -f "$(basename "$EXE")" >/dev/null; then bad "hung workload still running after stop";
else ok "hung workload removed"; fi
run recovery-after-hang passed --require-gates "$GATES" --timeout 120 -- --frames 128
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE" \
--keep "$OUT/window.png" >"$OUT/window.log" 2>&1; then ok "F on-screen frame"; else
bad "F on-screen frame: $(cat "$OUT/window.log")"; fi
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE" \
--fault depth >"$OUT/window-negative.log" 2>&1; then bad "on-screen check accepted a wrong image";
else
if grep -q 'samples differ' "$OUT/window-negative.log"; then ok "on-screen negative control";
else bad "on-screen negative control did not reach comparison"; fi
fi
i=1
while [ "$i" -le "$REPEATS" ]; do
run "I-repeat-$i" passed --require-gates "$GATES" --timeout 180 -- --frames 600
i=$((i + 1))
done
# Direct3D 12. Under D3DMetal (CrossOver 26.3) a destroyed D3D12 swapchain leaves a device
# reference, so the `shutdown` gate fails. That is reported as KNOWN only when it is the sole
# failing gate; any other failure is a failure.
d12_summary() {
python3 - "$1" <<'PY'
import json, re, sys
j = json.load(open(sys.argv[1]))
failed = sorted(g["name"] for g in j["gates"] if not g["passed"])
digest = "".join(re.findall(r"digest=([0-9a-f]+)", " ".join(g["detail"] for g in j["gates"])))
backend = j["backend_detected"].split(" ")[0]
print(j["classification"], backend, ",".join(failed) or "-", digest or "-")
PY
}
digest11=$(sed -n 's/.*digest=\([0-9a-f]*\).*/\1/p' "$OUT/C-F-G-H-full.json" | head -1)
BX_SECRET_PROBE=1 "$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 180 --stall-timeout 60 -- "$EXE12" \
--expect-absent-env BX_SECRET_PROBE >"$OUT/d3d12-full.json" 2>"$OUT/d3d12-full.log"
read -r class backend failed12 digest12 <<EOT
$(d12_summary "$OUT/d3d12-full.json")
EOT
case "$class:$backend:$failed12" in
passed:*:-) ok "D3D12 all gates (backend $backend)" ;;
failed_exit_1:d3dmetal:shutdown)
ok "D3D12 all gates but shutdown"
known=1
echo "KNOWN D3D12 shutdown: D3DMetal retains a device reference per swapchain" ;;
*) bad "D3D12: $class backend=$backend failed=$failed12" ;;
esac
if [ -n "$digest11" ] && [ "$digest11" = "$digest12" ]; then ok "D3D11 and D3D12 pixel digests equal ($digest12)";
else bad "pixel digests differ: d3d11=$digest11 d3d12=$digest12"; fi
if python3 "$ROOT/scripts/hybrid/check-image-digest.py" "$OUT/d3d12-full.json" >"$OUT/oracle-d3d12.log" 2>&1;
then ok "independent image oracle D3D12"; else bad "independent image oracle D3D12 (see log)"; fi
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE12" \
--keep "$OUT/window12.png" >"$OUT/window12.log" 2>&1; then ok "D3D12 on-screen frame";
else bad "D3D12 on-screen frame: $(cat "$OUT/window12.log")"; fi
for api in d3d11 d3d12; do
case "$api" in d3d11) first_exe=$EXE ;; d3d12) first_exe=$EXE12 ;; esac
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$first_exe" \
--first-frame --keep "$OUT/first-$api.png" >"$OUT/first-$api.log" 2>&1;
then ok "$api first frame on screen"; else bad "$api first frame on screen (see log)"; fi
done
for fault in color blank stale input depth upload; do
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 90 -- "$EXE12" --frames 128 --fault "$fault" \
>"$OUT/d3d12-negative-$fault.json" 2>/dev/null
detects "d3d12-negative-$fault" "$fault"
done
# Minimal swapchain lifetime probe: no application GPU work. The detach control must pass
# and the deliberately retained reference must be caught, or the witness proves nothing.
LIFE="$OUT/bin/d3d12-lifetime.exe"
lifetime() {
name=$1
shift
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 90 -- "$LIFE" "$@" \
>"$OUT/$name.json" 2>"$OUT/$name.log"
}
if lifetime lifetime-detach-control --detach-witness; then ok "lifetime witness detaches";
else bad "lifetime detach control (see lifetime-detach-control.log)"; fi
lifetime lifetime-retained-negative --detach-witness --retain-app-reference
if python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/lifetime-retained-negative.json" resources.private-data-detach >/dev/null 2>&1;
then ok "lifetime witness catches a retained reference"; else bad "lifetime retained-reference control"; fi
if lifetime lifetime-swapchain; then ok "D3D12 swapchain released"
elif grep -q 'adapter=AMD Compatibility Mode' "$OUT/lifetime-swapchain.json" &&
python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/lifetime-swapchain.json" resources.swapchain-release >/dev/null 2>&1; then
known=1
echo "KNOWN D3D12 swapchain retention under D3DMetal (minimal probe)"
else bad "lifetime probe (see lifetime-swapchain.log)"; fi
DXC=${BETTERXEN_DXC_DIR:-$ROOT/artifacts/dependencies/dxc-v1.9.2609/bin/x64}
if [ -f "$DXC/dxc.exe" ]; then
if python3 "$ROOT/scripts/hybrid/accept-sm6.py" "$BX" "$BOTTLE" "$OUT/bin/d3d12-wave-probe.exe" "$DXC" "$OUT/sm6" \
>"$OUT/sm6.log" 2>&1; then ok "Shader Model 6 GPU readback"; else bad "Shader Model 6: $(tail -1 "$OUT/sm6.log")"; fi
else
not_run=1
echo "NOT-RUN Shader Model 6: no dxc.exe at $DXC"
fi
if python3 "$ROOT/tests/conformance/test_d3d12_integrated/send_keys.py" "$BX" "$BOTTLE" "$EXE12" >"$OUT/keys.log" 2>&1;
then ok "H macOS keyboard events"; else bad "H keyboard: $(tail -1 "$OUT/keys.log")"; fi
if python3 "$ROOT/tests/conformance/test_d3d12_integrated/send_keys.py" "$BX" "$BOTTLE" "$EXE12" --keys up,up \
--expect fail >"$OUT/keys-negative.log" 2>&1; then ok "keyboard negative control";
else bad "keyboard negative control"; fi
if python3 "$ROOT/scripts/hybrid/accept-lifecycle.py" "$BX" "$BOTTLE" "$EXE" >"$OUT/lifecycle.log" 2>&1;
then ok "lifecycle: signals, kill and stop, repeated launch"; else
bad "lifecycle (see lifecycle.log)"; grep FAIL "$OUT/lifecycle.log"; fi
# Direct3D 12 is the primary target, so it is soaked first; Direct3D 11 stays as the control.
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 1800 --stall-timeout 60 -- "$EXE12" \
--frames "$SOAK" --verify-every 500 >"$OUT/I-soak-d3d12.json" 2>"$OUT/I-soak-d3d12.log"
read -r class backend failed12 digest12 <<EOT
$(d12_summary "$OUT/I-soak-d3d12.json")
EOT
case "$class:$backend:$failed12" in
passed:*:-) ok "I-soak D3D12 ($SOAK frames)" ;;
failed_exit_1:d3dmetal:shutdown)
known=1
ok "I-soak D3D12 all gates but the known shutdown ($SOAK frames)" ;;
*) bad "I-soak D3D12: $class backend=$backend failed=$failed12" ;;
esac
run I-soak-d3d11 passed --require-gates "$GATES" --timeout 1800 --stall-timeout 60 -- --frames "$SOAK" --verify-every 500
echo "records: $OUT"
python3 - "$OUT" "$failed" "$known" "$not_run" <<'PY'
import json, pathlib, sys
path = pathlib.Path(sys.argv[1])
failed, known, not_run = map(int, sys.argv[2:])
(path / "summary.json").write_text(json.dumps({
"schema": "betterxen-integrated-acceptance/0",
"unexpected_failures": bool(failed), "known_d3d12_swapchain_retention": bool(known),
"checks_not_run": bool(not_run), "all_checks_passed": not (failed or known or not_run),
}, indent=2) + "\n")
PY
[ "$failed" -eq 0 ] || exit 1
[ "$known" -eq 0 ] && [ "$not_run" -eq 0 ] || exit 2
exit 0
-131
View File
@@ -1,131 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Process lifecycle checks for the hybrid runner against an installed CrossOver.
Uses the Direct3D 11 workload: `--fault hang` makes a program that never exits, and a normal
run shows recovery. Prints "ok"/"FAIL" per check and exits non-zero on any failure. Do not
run anything else in the same bottle meanwhile: stopping a run stops the whole bottle.
usage: accept-lifecycle.py RUNNER BOTTLE D3D11_EXE [--launches N]
"""
import argparse
import json
import os
import signal
import subprocess
import sys
import tempfile
import time
failed = False
def check(ok, what):
global failed
failed |= not ok
print(("ok " if ok else "FAIL ") + what, flush=True)
def workload_pids(exe_name):
out = subprocess.run(["/bin/ps", "-axo", "pid=,command="], capture_output=True, text=True).stdout
pids = []
for line in out.splitlines():
pid, _, command = line.strip().partition(" ")
command = command.strip()
# the Windows program appears with a drive-letter command line
if command[1:3] == ":\\" and exe_name.lower() in command.lower():
pids.append(int(pid))
return pids
def wait_for(predicate, seconds):
end = time.time() + seconds
while time.time() < end:
if predicate():
return True
time.sleep(0.2)
return False
def main():
p = argparse.ArgumentParser()
p.add_argument("runner")
p.add_argument("bottle")
p.add_argument("exe")
p.add_argument("--launches", type=int, default=20)
a = p.parse_args()
name = os.path.basename(a.exe)
base = [a.runner, "hybrid", "run", "--bottle", a.bottle, "--timeout", "120"]
if workload_pids(name):
print(f"FAIL precondition: {name} is already running")
return 1
def start(extra, out):
return subprocess.Popen(base + ["--", a.exe] + extra, stdout=out, stderr=subprocess.DEVNULL,
start_new_session=True)
def healthy(label):
with tempfile.TemporaryFile("w+") as out:
run = start(["--frames", "64"], out)
code = run.wait(timeout=150)
check(code == 0, f"{label}: next run passes")
check(not workload_pids(name), f"{label}: nothing left running")
for sig, to_group in ((signal.SIGINT, True), (signal.SIGTERM, False), (signal.SIGHUP, False)):
label = sig.name + (" to the process group" if to_group else "")
with tempfile.TemporaryFile("w+") as out:
run = start(["--frames", "64", "--fault", "hang"], out)
if not wait_for(lambda: workload_pids(name), 60):
check(False, f"{label}: workload never started")
run.kill()
continue
time.sleep(2)
began = time.time()
(os.killpg if to_group else os.kill)(run.pid, sig)
try:
code = run.wait(timeout=40)
except subprocess.TimeoutExpired:
run.kill()
check(False, f"{label}: supervisor did not exit")
continue
out.seek(0)
try:
record = json.load(out)
except json.JSONDecodeError:
record = {}
check(code == 1 and record.get("classification") == "interrupted",
f"{label}: classified {record.get('classification')} in {time.time() - began:.1f}s")
check(wait_for(lambda: not workload_pids(name), 10), f"{label}: workload stopped")
healthy(label)
with tempfile.TemporaryFile("w+") as out:
run = start(["--frames", "64", "--fault", "hang"], out)
started = wait_for(lambda: workload_pids(name), 60)
time.sleep(2)
run.kill()
run.wait()
# SIGKILL cannot be handled: the program is expected to survive until `stop`.
check(started and bool(workload_pids(name)), "SIGKILL: program survives, as documented")
subprocess.run([a.runner, "hybrid", "stop", "--bottle", a.bottle], timeout=60)
check(wait_for(lambda: not workload_pids(name), 15), "SIGKILL: `hybrid stop` removes it")
healthy("after stop")
passed = 0
for launch in range(a.launches):
with tempfile.TemporaryFile("w+") as out:
code = start(["--frames", "64"], out).wait(timeout=150)
passed += code == 0
if code:
out.seek(0)
try:
reason = json.load(out).get("classification")
except json.JSONDecodeError:
reason = "no record"
print(f" launch {launch + 1}: {reason}", flush=True)
check(passed == a.launches, f"repeated launch: {passed} of {a.launches} passed")
check(not workload_pids(name), "repeated launch: nothing left running")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
-102
View File
@@ -1,102 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Compile original HLSL with external DXC, then verify actual Shader Model 6 GPU readback.
RUNNER BOTTLE PROBE_EXE DXC_BIN_DIR OUTPUT_DIR
The dedicated test bottle must have Z: mapped to / (CrossOver's observed default).
Expected float bit patterns below are derived from arithmetic, not the compiler or GPU.
"""
import json
from pathlib import Path
import re
import subprocess
import sys
def windows(path):
return "Z:" + str(Path(path).resolve()).replace("/", "\\")
def main():
runner, bottle, probe, dxc, output = sys.argv[1:]
root = Path(__file__).resolve().parents[2]
output = Path(output).resolve()
output.mkdir(parents=True, exist_ok=False)
dxc = Path(dxc).resolve() / "dxc.exe"
base = [str(Path(runner).resolve()), "hybrid", "run", "--bottle", bottle,
"--backend", "d3dmetal", "--timeout", "120", "--keep-output", "true", "--out", str(output / "raw")]
def run(name, command):
result = subprocess.run(base + ["--"] + command, capture_output=True, text=True, timeout=180)
(output / (name + ".json")).write_text(result.stdout)
(output / (name + ".log")).write_text(result.stderr)
if result.returncode:
raise RuntimeError(f"{name} failed; see {output}")
record = json.loads(result.stdout)
# Read the complete supervised stdout; a successful exit alone proves no result.
return Path(record["stdout_path"]).read_text(errors="replace")
caps = run("caps", [probe, "caps"])
match = re.search(r"options1: hr=0x0+ wave_ops=1 wave_lane_count_min=(\d+) wave_lane_count_max=(\d+)", caps)
if not match:
raise RuntimeError("wave capability query did not succeed; SM6 acceptance unavailable")
expectations = {"add_f32_4": [0x40000000, 0] * 4, "sum_f32_4": [0x40A00000] * 4}
results = {}
for name, words in [("lanes4", 4), ("add_f32_4", 8), ("sum_f32_4", 4)]:
shader = output / (name + ".dxil")
run("compile-" + name, [str(dxc), "-T", "cs_6_6", "-E", "main", "-Fo", windows(shader),
windows(root / "tests/conformance/test_d3d12_wave/hlsl" / (name + ".hlsl"))])
disassembly = run("dxil-" + name, [str(dxc), "-dumpbin", windows(shader)])
operations = {
"lanes4": [r"\bcall\b[^\n]*@dx\.op\.waveGetLaneIndex", r"\bcall\b[^\n]*@dx\.op\.waveGetLaneCount"],
"sum_f32_4": [r"\bcall\b[^\n]*@dx\.op\.waveActiveOp\.f32"],
"add_f32_4": [r"\bfadd\b"],
}
if any(not re.search(pattern, disassembly) for pattern in operations[name]):
raise RuntimeError(f"{name}: compiled DXIL does not contain the operation being tested")
text = run(name, [probe, "run", windows(shader), "1", str(words)])
pairs = [(int(i), int(v, 16)) for i, v in re.findall(r"^out (\d+) 0x([0-9a-fA-F]+)$", text, re.M)]
if [i for i, _ in pairs] != list(range(words)):
raise RuntimeError(f"{name}: missing, duplicate or unexpected readback words")
actual = [v for _, v in pairs]
dispatch = re.search(r"dispatch_caps wave_ops=1 min=(\d+) max=(\d+)", text)
if not dispatch:
raise RuntimeError(f"{name}: no wave capabilities for the dispatch device")
minimum, maximum = map(int, dispatch.groups())
if name == "lanes4":
width = actual[0] >> 8
def valid_lanes(values):
widths = {v >> 8 for v in values}
lanes = {v & 255 for v in values}
return (len(widths) == 1 and minimum <= width <= maximum and 4 <= width <= 128
and not width & (width - 1) and len(lanes) == 4 and max(lanes) < width)
if not valid_lanes(actual):
raise RuntimeError(f"invalid or duplicate lane IDs or wave width: {actual}")
wrong = actual.copy()
wrong[0] ^= 0x80000000
if valid_lanes(wrong):
raise RuntimeError("lane invariant negative control failed")
results[name] = {"actual": actual, "expected_properties": "one supported wave width; four distinct lane IDs below width", "negative_mismatches": 1}
print("PASS SM6 lanes4: independent lane invariants and one-bit negative control")
continue
else:
expected = expectations[name]
mismatches = sum(a != b for a, b in zip(actual, expected))
if mismatches:
raise RuntimeError(f"{name}: {mismatches} incorrect GPU words: {actual}")
# The deliberately wrong expectation must detect exactly one mismatch in this readback.
wrong = expected.copy()
wrong[0] ^= 1
if sum(a != b for a, b in zip(actual, wrong)) != 1:
raise RuntimeError(f"{name}: negative control failed")
results[name] = {"actual": actual, "expected": expected, "negative_mismatches": 1}
print(f"PASS SM6 {name}: {words} exact GPU words, one-bit negative control detected")
(output / "summary.json").write_text(json.dumps({"schema": "betterxen-sm6/0", "passed": True, "results": results}, indent=2) + "\n")
print("Unsupported double precision is not exercised or counted as passing.")
if __name__ == "__main__":
try:
main()
except (ValueError, OSError, RuntimeError, subprocess.SubprocessError, KeyError) as error:
sys.exit(f"FAIL SM6: {error}")
-44
View File
@@ -1,44 +0,0 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Produce a native runner and original redistributable workloads without starting CrossOver.
set -eu
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
TC=${1:?usage: build-maintainer.sh LLVM_MINGW_DIR}
TC=$(CDPATH='' cd -- "$TC" && pwd)
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-2}
export RUSTUP_TOOLCHAIN=1.100.0-aarch64-apple-darwin
OUT="$ROOT/artifacts/maintainer"
mkdir -p "$OUT/bin" "$OUT/workloads" "$OUT/logs"
cd "$ROOT"
cargo build --locked --release --target aarch64-apple-darwin -p bx-cli \
>"$OUT/logs/build.log" 2>&1 || { cat "$OUT/logs/build.log" >&2; exit 1; }
for exe in bx-cli; do
cp "${CARGO_TARGET_DIR:-$ROOT/target}/aarch64-apple-darwin/release/$exe" "$OUT/bin/$exe"
file "$OUT/bin/$exe"
[ "$(lipo -archs "$OUT/bin/$exe")" = arm64 ] || { echo "unexpected host architecture" >&2; exit 1; }
otool -L "$OUT/bin/$exe" >"$OUT/logs/$exe-linkage.txt"
python3 - "$OUT/logs/$exe-linkage.txt" <<'PY'
from pathlib import Path
import sys
libraries = [line.strip().split(' (', 1)[0] for line in Path(sys.argv[1]).read_text().splitlines()[1:]]
if not libraries or any(not lib.startswith(('/usr/lib/', '/System/Library/')) for lib in libraries):
sys.exit(f'non-system or missing host linkage: {libraries}')
PY
done
scripts/hybrid/build-windows-workloads.sh "$TC" >"$OUT/logs/build-workloads.log" 2>&1 ||
{ cat "$OUT/logs/build-workloads.log" >&2; exit 1; }
for exe in selfcheck-c selfcheck-rust d3d11-clear d3d11-frameloop; do
cp "artifacts/hybrid-workloads/x86_64/$exe.exe" "$OUT/workloads/"
done
for api in d3d11 d3d12; do
"tests/conformance/test_${api}_integrated/build.sh" "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
done
tests/conformance/test_d3d12_lifetime/build.sh "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
tests/conformance/test_d3d12_wave/build.sh "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
python3 scripts/hybrid/collect-build-notices.py "$TC" "$OUT/licenses"
git rev-parse HEAD >"$OUT/commit.txt"
git status --porcelain >"$OUT/source-status.txt"
"$OUT/bin/bx-cli" hybrid receipt >"$OUT/receipt.json"
(cd "$OUT" && shasum -a 256 bin/* workloads/*.exe > SHA256SUMS)
echo "Build and checksums: $OUT"
-54
View File
@@ -1,54 +0,0 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build BetterXen's original Windows workloads (issue #364) with a pinned cross toolchain and
# write the results to artifacts/hybrid-workloads/<arch>/. Nothing is executed; the script ends
# by printing `file` and the PE machine type of every output so a build that produced the wrong
# architecture fails here.
#
# scripts/hybrid/build-windows-workloads.sh <llvm-mingw-dir>
#
# <llvm-mingw-dir> is an unpacked llvm-mingw release (https://github.com/mstorsjo/llvm-mingw;
# wrappers/scripts ISC, compiler and runtime under their component licences);
# see https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md for the pinned
# release and checksum. Rust workloads use the x86_64-pc-windows-gnullvm and
# aarch64-pc-windows-gnullvm targets (rustup target add ...) linked with that toolchain.
set -eu
TC=$(CDPATH='' cd -- "${1:?usage: $0 <llvm-mingw-dir>}" && pwd)
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
OUT="$ROOT/artifacts/hybrid-workloads"
RUSTC_TC=${RUSTUP_TOOLCHAIN_FOR_WORKLOADS:-1.100.0}
[ -x "$TC/bin/x86_64-w64-mingw32-clang" ] || { echo "no llvm-mingw at $TC" >&2; exit 1; }
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
for arch in x86_64; do
d="$OUT/$arch"; mkdir -p "$d"
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$d/selfcheck-c.exe" "$ROOT/tests/conformance/test_runtime_c/selfcheck.c"
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$d/d3d11-clear.exe" "$ROOT/tests/conformance/test_d3d11_clear/d3d11_clear.c" -ld3d11 -ldxgi
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
-o "$d/d3d11-frameloop.exe" "$ROOT/tests/conformance/test_d3d11_frameloop/frameloop.c" -ld3d11 -ldxgi -ldxguid -ld3dcompiler -lm
env_arch=$(echo "$arch" | tr a-z A-Z)
(
export PATH="$TC/bin:$PATH"
export "CARGO_TARGET_${env_arch}_PC_WINDOWS_GNULLVM_LINKER=$TC/bin/$arch-w64-mingw32-clang"
export CARGO_ENCODED_RUSTFLAGS
CARGO_ENCODED_RUSTFLAGS=$(printf '%s\037%s\037%s' '-C' 'link-arg=-Wl,--no-insert-timestamp' "--remap-path-prefix=$ROOT=/betterxen")
cd "$ROOT/tests/conformance/support/win-selfcheck-rust"
CARGO_TARGET_DIR="$OUT/rust-target" rustup run "$RUSTC_TC" cargo build --locked --release --target "$arch-pc-windows-gnullvm" -q
)
cp "$OUT/rust-target/$arch-pc-windows-gnullvm/release/win-selfcheck-rust.exe" "$d/selfcheck-rust.exe"
done
fail=0
for f in "$OUT"/x86_64/*.exe; do
want=$(basename "$(dirname "$f")")
desc=$(file -b "$f")
case "$want:$desc" in
x86_64:*"PE32+"*"x86-64"*) ok=ok ;;
aarch64:*"PE32+"*"Aarch64"*|aarch64:*"PE32+"*"ARM64"*) ok=ok ;;
*) ok=WRONG; fail=1 ;;
esac
echo "$ok $f: $desc"
done
exit $fail
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""A negative control counts only when the injected fault failed the gate it targets.
check-failed-gates.py RECORD.json GATE [GATE...]
Passes when the record is a non-zero workload exit and every named gate was reported
and failed. A crash, a missing gate or an unrelated failure is not a detection.
"""
import json
from pathlib import Path
import sys
def main():
path, *wanted = sys.argv[1:]
if not wanted:
raise ValueError("name at least one gate")
record = json.loads(Path(path).read_text())
if record["classification"] != "failed_exit_1":
raise ValueError(f"expected failed_exit_1, got {record['classification']}")
reported = {gate["name"]: gate["passed"] for gate in record["gates"]}
for name in wanted:
if name not in reported:
raise ValueError(f"gate {name} was never reported")
if reported[name]:
raise ValueError(f"gate {name} passed despite the injected fault")
failed = sorted(name for name, passed in reported.items() if not passed)
print(",".join(failed))
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyError) as error:
sys.exit(f"FAIL negative control: {error}")
-76
View File
@@ -1,76 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Independent image oracle for the fixed scripted D3D11/D3D12 scene.
Build images by painting whole rectangles, independently of the workloads' pixel
functions and GPU shaders. The fixed protocol is: far A at (32,32), near B at
(96,96), 128-square quads with four 64-square colours; five 16-pixel key moves;
rotate RGB to BRG; overwrite the top 16 rows with the frame number. Hash only the
specified verification frames, in row-major RGBA order. No renderer or C oracle
is called. The legacy digest seed is intentionally preserved (it differs from
the standard FNV offset basis).
"""
import json
from pathlib import Path
import re
import sys
PALETTES = (((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)),
((255, 255, 0), (0, 255, 255), (255, 0, 255), (128, 128, 128)))
POSITIONS = ((96, 96), (112, 96), (128, 96), (128, 112), (112, 112), (112, 128))
def image(frame, interval):
pixels = bytearray(b"\x00\x00\x00\xff" * (256 * 256))
def rectangle(x, y, width, height, rgba):
row = bytes(rgba) * width
for line in range(y, y + height):
start = (line * 256 + x) * 4
pixels[start:start + width * 4] = row
# Painter's order is analytically equivalent to the scene's depth test.
steps = min(frame // interval, 5)
for palette, (x, y) in zip(PALETTES, ((32, 32), POSITIONS[steps])):
for quadrant, (r, g, b) in enumerate(palette):
rectangle(x + (quadrant % 2) * 64, y + (quadrant // 2) * 64, 64, 64, (b, r, g, 255))
marker = (frame + 1) & 65535
rectangle(0, 0, 256, 16, (marker & 255, marker >> 8, 77, 255))
return pixels
def expected_digest(frames, verify_every):
interval = frames // 8
selected = set(range(0, frames, verify_every)) | {0, frames - 1}
selected.update(k * interval + 1 for k in range(1, 6) if k * interval + 1 < frames)
digest = 1469598103934665603
for frame in sorted(selected):
for byte in image(frame, interval):
digest = ((digest ^ byte) * 1099511628211) & 0xffffffffffffffff
return f"{digest:016x}", len(selected)
def main():
record = json.loads(Path(sys.argv[1]).read_text())
args = record["args"]
if any(flag in args for flag in ["--fault", "--duration-s", "--external-input", "--interactive"]):
raise ValueError("oracle accepts only the fixed scripted scene, without injected faults")
frames = int(args[args.index("--frames") + 1]) if "--frames" in args else 600
verify = int(args[args.index("--verify-every") + 1]) if "--verify-every" in args else 30
if frames < 64 or verify < 1:
raise ValueError("invalid verification schedule")
gate = next(g for g in record["gates"] if g["name"] == "frame.continuous")
if not gate["passed"]:
raise ValueError("continuous rendering gate did not pass")
observed = re.search(r"verified=(\d+) mismatched=0 digest=([0-9a-f]{16})", gate["detail"])
expected, count = expected_digest(frames, verify)
if not observed or observed.groups() != (str(count), expected):
raise ValueError(f"independent digest mismatch: expected {count} verified frames, digest={expected}; {gate['detail']}")
print(f"PASS independent image oracle: {count} frames digest={expected}")
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyError, StopIteration) as error:
sys.exit(f"FAIL independent image oracle: {error}")
-13
View File
@@ -1,13 +0,0 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
set -eu
TC=${1:?usage: check-toolchain.sh LLVM_MINGW_DIR}
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
PIN=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["llvm_commit"])' "$ROOT/scripts/hybrid/toolchain.json")
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
for name in clang ld.lld; do
[ -x "$TC/bin/$name" ] || { echo "missing $TC/bin/$name" >&2; exit 1; }
lipo "$TC/bin/$name" -verify_arch arm64
done
"$TC/bin/x86_64-w64-mingw32-clang" --version | grep -F "$PIN" >/dev/null
echo "verified ARM64-capable llvm-mingw compiler at $PIN" >&2
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Preserve unmodified notices for the standalone hybrid runner and Windows runtime."""
import json
from pathlib import Path
import shutil
import subprocess
import sys
root = Path(__file__).resolve().parents[2]
toolchain, output = map(lambda p: Path(p).resolve(), sys.argv[1:])
output.mkdir(parents=True, exist_ok=True)
meta = json.loads(subprocess.check_output(["cargo", "metadata", "--locked", "--format-version", "1"], cwd=root))
libc = [p for p in meta["packages"] if p["name"] == "libc"]
if len(libc) != 1:
sys.exit("expected exactly one locked libc dependency")
package = libc[0]
source = Path(package["manifest_path"]).parent
shutil.copytree(source, output / "libc-source", dirs_exist_ok=True)
notices = [source / "LICENSE-MIT", source / "LICENSE-APACHE"]
for path in notices:
shutil.copy2(path, output / ("libc-" + path.name))
shutil.copy2(toolchain / "LICENSE.TXT", output / "llvm-mingw-LICENSE.TXT")
for path in (toolchain / "x86_64-w64-mingw32/share/mingw32").glob("COPYING*"):
shutil.copy2(path, output / ("mingw-" + path.name))
sysroot = Path(subprocess.check_output(["rustc", "--print", "sysroot"], text=True).strip())
docs = sysroot / "share/doc/rust"
for name in ["COPYRIGHT.html", "COPYRIGHT-library.html"]:
shutil.copy2(docs / name, output / ("rust-" + name))
shutil.copytree(docs / "licenses", output / "rust-licenses", dirs_exist_ok=True)
manifest = {"schema": "betterxen-build-notices/0", "rust": "1.100.0", "libc": {
"version": package["version"], "license": package["license"], "source": package["source"]},
"llvm_mingw": json.loads((root / "scripts/hybrid/toolchain.json").read_text()),
"scope": "Standalone bx-cli plus original Windows workloads; no native research CLI or external proprietary components"}
(output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
-38
View File
@@ -1,38 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Create a new dedicated test bottle, refusing to reuse an existing directory.
This uses CrossOver's observed cxbottle interface, not a vendor-supported automation API.
The new bottle also has Wine's crash dialog turned off: with it on, a crashing program
waits for a click and an unattended run only ends at its timeout.
RUNNER BOTTLE
"""
import json
from pathlib import Path
import re
import subprocess
import sys
import tempfile
runner, name = sys.argv[1:]
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name):
sys.exit("use a simple new bottle name with letters, digits, dots, dashes or underscores")
facts = json.loads(subprocess.check_output([runner, "crossover"], text=True))
if not facts["installs"]:
sys.exit("install CrossOver from CodeWeavers first")
app = Path(facts["installs"][0]["path"])
base = Path(facts.get("bottle_dir_preference") or "~/Library/Application Support/CrossOver/Bottles").expanduser()
prefix = base / name
if prefix.exists() or prefix.is_symlink():
sys.exit(f"refusing to reuse {prefix}; choose a fresh dedicated name")
subprocess.run([str(app / "Contents/SharedSupport/CrossOver/bin/cxbottle"), "--bottle", name,
"--create", "--template", "win11_64"], check=True, timeout=180, stdout=sys.stderr)
if not (prefix / "drive_c").is_dir():
sys.exit(f"CrossOver did not create the expected bottle at {prefix}")
with tempfile.TemporaryDirectory() as records:
subprocess.run([str(Path(runner).resolve()), "run", "--bottle", name, "--timeout", "180", "--out", records, "--",
str(prefix / "drive_c/windows/system32/reg.exe"), "add", r"HKCU\Software\Wine\WineDbg",
"/v", "ShowCrashDialog", "/t", "REG_DWORD", "/d", "0", "/f"],
check=True, timeout=300, stdout=sys.stderr)
print(json.dumps({"schema": "betterxen-test-bottle/0", "bottle": name, "prefix": str(prefix), "created": True, "crash_dialog": False}))
-14
View File
@@ -1,14 +0,0 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Install only open-source build dependencies. CrossOver and Apple tools remain external.
set -eu
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
command -v python3 >/dev/null
command -v rustup >/dev/null || { echo "install native rustup from https://rustup.rs first" >&2; exit 1; }
xcrun --find clang >/dev/null
TC=$(python3 "$ROOT/scripts/hybrid/install-toolchain.py" "${1:-$HOME/Library/Caches/BetterXen/toolchains}")
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
rustup toolchain install 1.100.0 --profile minimal --component rustfmt --component clippy \
--target aarch64-apple-darwin --target x86_64-pc-windows-gnullvm >&2
printf '%s\n' "$TC"
-55
View File
@@ -1,55 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Install Microsoft's checksum-pinned open-source Windows DXC as an external guest tool."""
import hashlib
from pathlib import Path
import subprocess
import shutil
import stat
import sys
import zipfile
URL = "https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2609/dxc_2026_09_29.zip"
SHA256 = "ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1"
def install(destination):
destination = destination.expanduser().resolve()
archive = destination / "dxc_2026_09_29.zip"
destination.mkdir(parents=True, exist_ok=True)
if any(p != archive for p in destination.iterdir()):
raise RuntimeError(f"{destination} already contains extracted files; choose a fresh installation directory")
if not archive.exists():
subprocess.run(["/usr/bin/curl", "--fail", "--location", "--retry", "3", "--connect-timeout", "30",
URL, "-o", str(archive)], check=True)
with archive.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != SHA256:
raise RuntimeError(f"DXC checksum mismatch: {digest}, expected {SHA256}")
with zipfile.ZipFile(archive) as bundle:
entries = []
for member in bundle.infolist():
# Microsoft's Windows zip uses backslashes; normalize before checking containment.
name = member.filename.replace("\\", "/")
if Path(name).is_absolute() or ".." in Path(name).parts or ":" in name or stat.S_ISLNK(member.external_attr >> 16):
raise RuntimeError(f"invalid archive path {member.filename}")
entries.append((member, name))
for member, name in entries:
path = destination / name
if name.endswith("/"):
path.mkdir(parents=True, exist_ok=True)
else:
path.parent.mkdir(parents=True, exist_ok=True)
with bundle.open(member) as source, path.open("xb") as target:
shutil.copyfileobj(source, target)
compiler = destination / "bin/x64/dxc.exe"
if not compiler.is_file():
raise RuntimeError("pinned archive lacks bin/x64/dxc.exe")
print(compiler.parent)
if __name__ == "__main__":
try:
install(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "Library/Caches/BetterXen/dxc-v1.9.2609")
except (OSError, RuntimeError, zipfile.BadZipFile, subprocess.CalledProcessError) as error:
sys.exit(str(error))
-68
View File
@@ -1,68 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Download the pinned external llvm-mingw release; print its installed path on stdout.
Only the checksum-verified archive is extracted. No compiler, workload or proprietary
component is executed. Existing installations are never overwritten.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tarfile
import tempfile
def install(destination):
if not hasattr(tarfile, "data_filter"):
raise RuntimeError("Python with tarfile.data_filter is required (Python 3.12 or newer)")
pin = json.loads(Path(__file__).with_name("toolchain.json").read_text())
destination = destination.expanduser().resolve()
destination.mkdir(parents=True, exist_ok=True)
archive = destination / pin["asset"]
if not archive.exists():
print(f'Downloading {pin["url"]}', file=sys.stderr)
with tempfile.NamedTemporaryFile(dir=destination, delete=False) as out:
temporary = Path(out.name)
try:
out.close()
subprocess.run(["/usr/bin/curl", "--fail", "--location", "--retry", "3",
"--connect-timeout", "30", "--output", str(temporary), pin["url"]], check=True)
verify(temporary, pin["sha256"])
# Publish without overwriting an archive installed by a concurrent invocation.
os.link(temporary, archive)
finally:
temporary.unlink(missing_ok=True)
verify(archive, pin["sha256"])
installed = destination / pin["asset"].removesuffix(".tar.xz")
if installed.exists():
raise RuntimeError(f"{installed} already exists; choose a fresh destination to avoid using a modified toolchain")
with tempfile.TemporaryDirectory(prefix=".llvm-mingw-", dir=destination) as staging:
with tarfile.open(archive, "r:xz") as bundle:
# The pinned archive is trusted; also reject names escaping its single root.
for member in bundle.getmembers():
parts = Path(member.name).parts
if not parts or parts[0] != installed.name or ".." in parts or Path(member.name).is_absolute():
raise RuntimeError(f"unexpected archive path: {member.name}")
bundle.extractall(staging, filter="data")
os.rename(Path(staging) / installed.name, installed)
print(f'Verified SHA-256 {pin["sha256"]}', file=sys.stderr)
return installed
def verify(path, expected):
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
if digest.hexdigest() != expected:
raise RuntimeError(f"checksum mismatch for {path}: got {digest.hexdigest()}, expected {expected}")
if __name__ == "__main__":
try:
print(install(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "Library/Caches/BetterXen/toolchains"))
except (OSError, RuntimeError, tarfile.TarError, subprocess.CalledProcessError) as error:
sys.exit(str(error))
-36
View File
@@ -1,36 +0,0 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Private maintainer test bundle: original source, ARM64 runners and original Windows probes.
set -eu
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
cd "$ROOT"
[ -z "$(git status --porcelain)" ] || { echo "package requires a clean committed checkout" >&2; exit 1; }
COMMIT=$(git rev-parse HEAD)
OUT="$ROOT/artifacts/maintainer"
[ "$(cat "$OUT/commit.txt")" = "$COMMIT" ] && [ ! -s "$OUT/source-status.txt" ] ||
{ echo "rebuild from this clean commit before packaging" >&2; exit 1; }
(cd "$OUT" && shasum -a 256 -c SHA256SUMS)
mkdir -p "$ROOT/artifacts/packages"
STAGE=$(mktemp -d "$ROOT/artifacts/packages/staging-XXXXXX")
trap 'rm -rf "$STAGE"' EXIT HUP INT TERM
NAME="betterxen-maintainer-$COMMIT"
[ ! -e "$ROOT/artifacts/packages/$NAME.tar.gz" ] || { echo "artifact already exists; preserving it" >&2; exit 1; }
mkdir "$STAGE/$NAME"
mkdir "$STAGE/$NAME/bin"
# bx-cli's only external dependency is libc (docs/licenses.md); CrossOver, Apple components,
# compilers and DXC are never copied into the bundle.
cp "$OUT/bin/bx-cli" "$STAGE/$NAME/bin/"
mkdir "$STAGE/$NAME/workloads"
for exe in selfcheck-c selfcheck-rust d3d11-clear d3d11-frameloop d3d11-integrated d3d12-integrated d3d12-lifetime d3d12-wave-probe; do
cp "$OUT/workloads/$exe.exe" "$STAGE/$NAME/workloads/"
done
cp -R "$OUT/commit.txt" "$OUT/licenses" "$STAGE/$NAME/"
(cd "$STAGE/$NAME" && shasum -a 256 bin/* workloads/*.exe > SHA256SUMS)
cp LICENSE THIRD_PARTY_NOTICES.md docs/maintainer-testing.md "$STAGE/$NAME/"
cp scripts/hybrid/test-bundle.sh "$STAGE/$NAME/test.sh"
chmod +x "$STAGE/$NAME/test.sh"
git archive --format=tar.gz --prefix=betterxen-source/ -o "$STAGE/$NAME/source.tar.gz" "$COMMIT"
(cd "$STAGE/$NAME" && shasum -a 256 source.tar.gz > SOURCE-SHA256SUMS)
tar -czf "$ROOT/artifacts/packages/$NAME.tar.gz" -C "$STAGE" "$NAME"
(cd "$ROOT/artifacts/packages" && shasum -a 256 "$NAME.tar.gz" > "$NAME.tar.gz.sha256")
echo "$ROOT/artifacts/packages/$NAME.tar.gz"
-24
View File
@@ -1,24 +0,0 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Installed as test.sh at the root of a private maintainer bundle. No Rust or cross-compiler
# is needed: both runners and original workload binaries were built from the recorded commit.
set -eu
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
BOTTLE=${1:?usage: ./test.sh NEW_DEDICATED_BOTTLE_NAME}
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
cd "$ROOT"
/usr/bin/shasum -a 256 -c SHA256SUMS
/usr/bin/shasum -a 256 -c SOURCE-SHA256SUMS
BUNDLE_TEST=$(mktemp -d "$ROOT/test-XXXXXX")
tar -xzf "$ROOT/source.tar.gz" -C "$BUNDLE_TEST"
SOURCE="$BUNDLE_TEST/betterxen-source"
BX="$ROOT/bin/bx-cli"
python3 "$SOURCE/scripts/hybrid/create-test-bottle.py" "$BX" "$BOTTLE" >"$BUNDLE_TEST/bottle.json"
"$BX" hybrid doctor --bottle "$BOTTLE" >"$BUNDLE_TEST/doctor.json"
echo "Testing commit $(cat "$ROOT/commit.txt"); diagnostics under $BUNDLE_TEST"
export BETTERXEN_RUNNER="$BX"
export BETTERXEN_HYBRID_RUNNER="$BX"
export BETTERXEN_WORKLOAD_DIR="$ROOT/workloads"
export BETTERXEN_SOURCE_COMMIT
BETTERXEN_SOURCE_COMMIT=$(cat "$ROOT/commit.txt")
exec "$SOURCE/scripts/hybrid/accept-integrated.sh" unused "$BOTTLE"
-8
View File
@@ -1,8 +0,0 @@
{
"release": "20261117",
"asset": "llvm-mingw-20261117-ucrt-macos-universal.tar.xz",
"url": "https://github.com/mstorsjo/llvm-mingw/releases/download/20261117/llvm-mingw-20261117-ucrt-macos-universal.tar.xz",
"sha256": "98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa",
"llvm_commit": "5b10d2d74929eae78912771222c9855af97496f4",
"rust": "1.100.0"
}
+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);
}
@@ -185,6 +185,9 @@ pub enum Verdict {
DeviceRemoved { reason: u32 },
/// The GPU did not signal completion in time.
TimedOut { detail: String },
/// The device reported a highest shader model below the 6.6 the harness kernel
/// requires. The field was parsed and printed before, but never judged (#567).
UnsupportedShaderModel { reported: u8 },
/// Every word still holds the sentinel: the kernel never wrote.
KernelDidNotRun,
/// The kernel wrote, but some words differ from the expected values.
@@ -224,6 +227,12 @@ impl fmt::Display for Verdict {
)
}
Self::TimedOut { detail } => write!(f, "FAIL: GPU timeout ({detail})"),
Self::UnsupportedShaderModel { reported } => write!(
f,
"FAIL: highest shader model {}.{} is below the 6.6 the harness kernel requires",
reported >> 4,
reported & 0xf
),
Self::KernelDidNotRun => write!(
f,
"FAIL: all {WORDS} words still hold the sentinel 0x{SENTINEL:08x}; the kernel did not write"
@@ -272,6 +281,14 @@ pub fn judge(report: &ProbeReport) -> Verdict {
let incomplete = |reason: &str| Verdict::Incomplete {
reason: reason.to_owned(),
};
// Every kernel the harness runs is SM 6.6. A device that reports less, or a
// report with no shader_model record, must not pass on a matching readback
// alone (#567). The live Rust test asserted this; the standalone verdict did not.
match report.shader_model {
Some(sm) if sm < 0x66 => return Verdict::UnsupportedShaderModel { reported: sm },
None => return incomplete("no shader_model record"),
Some(_) => {}
}
match report.dispatch {
None => return incomplete("no dispatch record"),
Some(d) if d != expected_dispatch => {
@@ -341,6 +358,29 @@ mod tests {
assert_eq!(judge(&report), Verdict::Pass);
}
#[test]
fn a_shader_model_below_6_6_fails_even_with_a_matching_readback() {
// The kernel is SM 6.6; the readback matching proves only that something wrote.
for reported in ["0x65", "0x60"] {
let lower = output(&good_words()).replace(
"BXD3DM shader_model 0x66",
&format!("BXD3DM shader_model {reported}"),
);
let report = parse_report(&lower).unwrap();
assert_eq!(
judge(&report),
Verdict::UnsupportedShaderModel {
reported: if reported == "0x65" { 0x65 } else { 0x60 }
}
);
}
// Without the record the harness cannot say the device can run the shader.
let absent = output(&good_words()).replace("BXD3DM shader_model 0x66\n", "");
let report = parse_report(&absent).unwrap();
assert_eq!(report.shader_model, None);
assert!(matches!(judge(&report), Verdict::Incomplete { .. }));
}
#[test]
fn untouched_sentinel_means_the_kernel_did_not_run() {
let report = parse_report(&output(&[SENTINEL; WORDS])).unwrap();
@@ -80,12 +80,14 @@ fn collect(rx: &Receiver<Event>, until: Instant) -> io::Result<(Vec<u8>, Vec<u8>
Ok((stdout, stderr, true))
}
fn wait_until(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
/// `deadline: None` means the requested timeout is not representable on this clock, so the
/// probe is allowed to run without one (#587).
fn wait_until(child: &mut Child, deadline: Option<Instant>) -> io::Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if Instant::now() >= deadline {
if deadline.is_some_and(|at| Instant::now() >= at) {
child.kill()?;
child.wait()?;
return Ok(None);
@@ -112,7 +114,13 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
command.env(key, value);
}
}
let deadline = Instant::now() + timeout;
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow, so a
// huge value would abort the harness with exit 101 instead of one of its verdict codes
// (#586). Saturate at the platform maximum instead: the probe then simply never times out.
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow. When the
// requested timeout is not representable the probe simply has no deadline; representing
// that as `None` avoids inventing a fallback duration that might also not fit (#587).
let deadline = Instant::now().checked_add(timeout);
let mut child = command.spawn()?;
let (tx, rx) = mpsc::channel();
pump(
@@ -126,8 +134,11 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
tx,
);
let status = wait_until(&mut child, deadline)?;
let (stdout, stderr, output_complete) =
collect(&rx, deadline.max(Instant::now() + DRAIN_GRACE))?;
// With no deadline the probe has already exited, so draining still needs a bound.
let drain_until = deadline
.unwrap_or_else(Instant::now)
.max(Instant::now() + DRAIN_GRACE);
let (stdout, stderr, output_complete) = collect(&rx, drain_until)?;
Ok(ProbeRun {
status,
stdout: String::from_utf8_lossy(&stdout).into_owned(),
@@ -161,6 +172,35 @@ mod tests {
}
}
#[test]
fn an_unrepresentable_deadline_leaves_the_probe_without_a_timeout() {
// `checked_add` returns None for a timeout the clock cannot represent; the runner
// must then wait for the probe normally instead of inventing a fallback duration
// that could itself overflow (#587).
let script = Script::new("nodeadline", "sleep 0.2; exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
)
.expect("an unrepresentable deadline must not abort the run");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
assert!(run.output_complete);
}
#[test]
fn an_overflowing_timeout_does_not_panic() {
// u64::MAX seconds overflows `Instant + Duration`; before #586 this panicked.
let script = Script::new("overflow", "exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
);
let run = run.expect("an overflowing timeout must still run the probe, not panic");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
}
#[test]
fn passes_the_framework_and_only_allowlisted_environment() {
let script = Script::new("env", "echo \"args=$*\"; env; echo oops >&2; exit 3");
@@ -186,22 +226,70 @@ mod tests {
assert!(run.output_complete);
}
/// Timeout for the tests below whose stand-in probe has to start and print before the
/// deadline. Starting a freshly written script costs tens of milliseconds here and
/// occasionally far more, so a few hundred milliseconds made these tests fail now and then
/// (#479). They check what happens at the deadline, not how fast a script starts.
const START_MARGIN: Duration = Duration::from_secs(2);
/// Removes the pid file, and kills the recorded process if a failing test left it running.
struct PidFile(PathBuf);
impl Drop for PidFile {
fn drop(&mut self) {
if std::thread::panicking()
&& let Ok(pid) = std::fs::read_to_string(&self.0)
{
let _ = Command::new("/bin/kill").arg(pid.trim()).status();
}
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn kills_a_probe_that_exceeds_the_timeout() {
let script = Script::new("hang", "echo started; exec sleep 30");
let pid_file = PidFile(
std::env::temp_dir().join(format!("bx-harness-probe's-{}.pid", std::process::id())),
);
let _ = std::fs::remove_file(&pid_file.0);
// Pass the path as the value of --framework. The apostrophe tests literal path handling.
// `exec` keeps the pid, so the recorded pid is the process that has to be killed.
let script = Script::new(
"hang",
"echo $$ > \"$2\" || exit 1; echo started; exec sleep 30",
);
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), Duration::from_millis(300)).unwrap();
let run = run_probe(&script.0, &pid_file.0, START_MARGIN).unwrap();
let elapsed = started.elapsed();
assert!(run.status.is_none());
// Output written before the kill is kept.
assert_eq!(run.stdout, "started\n");
assert!(started.elapsed() < Duration::from_secs(10));
// The probe ran until the deadline and no longer: it was killed, not waited for.
assert!(elapsed >= START_MARGIN, "returned early after {elapsed:?}");
assert!(
elapsed < START_MARGIN + DRAIN_GRACE + Duration::from_secs(5),
"returned after {elapsed:?}"
);
// The process is gone. `output_complete` is deliberately not asserted: tests run in
// parallel, and a child spawned by another test at the wrong moment can inherit this
// probe's pipe and hold it open (seen in 2 of 200 runs).
let pid = std::fs::read_to_string(&pid_file.0).unwrap();
let alive = Command::new("/bin/kill")
.args(["-0", pid.trim()])
.stderr(Stdio::null())
.status()
.unwrap()
.success();
assert!(!alive, "probe {} survived the timeout", pid.trim());
}
/// The probe exits at once, but a background descendant inherits stdout and
/// keeps it open well past the timeout.
#[test]
fn a_descendant_holding_the_pipes_cannot_outlast_the_deadline() {
let script = Script::new("orphan", "sleep 5 & echo started");
let timeout = Duration::from_millis(500);
// The descendant has to outlive the bound asserted below by a wide margin.
let script = Script::new("orphan", "sleep 6 & echo started");
let timeout = START_MARGIN;
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), timeout).unwrap();
let elapsed = started.elapsed();
@@ -0,0 +1,73 @@
# dxbc-accc
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
## `FSPX` errors
A malformed `FSPX` table fails inspection with a `ParseError`; it never panics. Two bounds errors are kept apart (#599):
- **`FspxLayoutMismatch`:** a descriptor's offset lands inside the 16-byte header or the descriptor table, the region the synthetic layout reserves. The table does not follow BetterXen's clean-room layout. The error carries the section id, the offset and the table length.
- **`FspxSectionOutOfBounds`:** a section starts after the table but runs past the end of the payload.
Both are still errors. Over the C ABI, both are `BX_SHADER_ERR_INVALID_BLOB`, so a caller of `bx_shader_inspect` cannot tell them apart yet; that would need an `[ABI]` change to `abi/include/bx_shader_bridge.h`.
## Guest access: `bx_shader_bridge.dll` (#445)
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
- **Build:** `cargo build --target x86_64-pc-windows-gnu` turns the crate's `cdylib` into a PE32+ DLL, published as `bx_shader_bridge.dll`. Its Export Address Table holds exactly the three header functions as direct RVAs. It imports only Windows system DLLs that Wine provides, so no MinGW runtime DLL. `guest/build.sh` enforces both. The allowlist is `KERNEL32`, `ntdll`, `bcryptprimitives`, `USERENV`, `WS2_32` and the `api-ms-win-crt-*` / `api-ms-win-core-*` sets.
- **Callers:** a shim loads the bridge at run time with `GetProcAddress`, so a missing bridge is a logged condition, not a load failure of the shim.
- **Full path:** it must load the bridge by **full path from its own directory**. That is `GetModuleFileNameW` of the shim's own module (for example via `GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, ...)`), plus `bx_shader_bridge.dll`, loaded with `LoadLibraryExW(..., LOAD_WITH_ALTERED_SEARCH_PATH)`.
- **Why not the bare name:** a bare `LoadLibraryW(L"bx_shader_bridge.dll")` searches the guest EXE's directory first under the [standard search order](https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order). It can therefore miss a bridge staged next to the shims, or pick up a different copy.
- **Staging:** the bridge is meant to be staged in the same directory as the shims that call it.
- **Why not a host tool over captured logs:** the M2 gate needs the decision at `Create*PipelineState` time inside the guest. That means passing DXIL through and rejecting ACCC-only containers. An offline host tool could count shaders but could not act on them.
### Build and check
```sh
rustup target add x86_64-pc-windows-gnu # once
shader-transpiler/crates/dxbc-accc/guest/build.sh
target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
--exe target/bx-shader-bridge/check_bridge.exe
```
`guest/build.sh` writes `bx_shader_bridge.dll` and `check_bridge.exe` to `target/bx-shader-bridge/`. It always builds into, and copies from, `<repo>/target`, whatever `CARGO_TARGET_DIR` says, so it cannot package a stale DLL. It resolves `cargo` and `rustc` through rustup, checks that this `rustc` has `std` for the Windows target, and prints which `rustc` it used. It fails if the Export Address Table holds anything other than the three entry points as direct RVAs (an ordinal-only entry or a forwarder fails it), or if any import is outside the allowlist above.
[`guest/check_bridge.c`](guest/check_bridge.c) is a C guest program built against the frozen header. It checks the struct layout with `_Static_assert`, loads the DLL by full path from its own directory, and sends nine containers through the DLL:
- a real DXC SM 6.6 compute blob (from [`d3dmetal-harness`](../d3dmetal-harness/README.md));
- synthetic DXIL pixel SM 6.0 with `RTS0`, once as is and once followed by 16 bytes past its declared size;
- `ACCC` with an `FSPX` v1 stage section, and `ACCC` with an `FSPX` v0 stub;
- `DXIL` + `ACCC`;
- legacy `SHEX`;
- two malformed blobs.
The program prints one `BXSHADER` line per container and a count line, and checks:
- **Classification:**
- kind, stage and shader model;
- the declared container size;
- the exact `DXIL` and `ACCC` chunk sizes and the root signature flag, each derived from the program's own chunk-table walk;
- the digest, compared with header bytes 4..20 for every container, the real one included.
- **Prepare:** exactly the declared container is copied, never the trailing bytes. ACCC-only and legacy are `BX_SHADER_ERR_UNSUPPORTED`. Malformed input is `BX_SHADER_ERR_INVALID_BLOB`, with output cleared.
- **Free and argument errors:** freeing returned buffers, and null arguments at the DLL boundary.
Recorded run (one Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 `26.3.0.39832`, both a fresh prefix and a D3DMetal bottle):
```text
BXSHADER counts dxil=3 accc_only=2 dual=1 legacy=1 unknown=0 invalid=2
PASS: check_bridge (9 containers through bx_shader_bridge.dll)
```
This is a synthetic, single-host result. It is not a measurement of any title's shader corpus, and not Xbox hardware.
Each of these faults compiled into the DLL fails the check: `dxil_chunk_size` clamped to 1, `accc_chunk_size` multiplied, the digest zeroed, `has_root_signature` set to 7, and the DXIL and ACCC kind numbers swapped. The last one also fails when it is rebuilt with `CARGO_TARGET_DIR` set elsewhere.
### Related work, owned elsewhere
Three of these pieces around this crate were recorded here as outstanding when this section was written and have since landed. The fourth is the trace summary of the records the shim emits.
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`, #445, #484):** present and in use. Its `LIBRARY` directive is `bx_shader_bridge.dll`, and `scripts/build-shims.sh` passes it to `cargo rustc` as `-C link-arg=…/abi/defs/bx_shader_bridge.def`, so the built DLL's export directory holds exactly the three header entry points and its internal name is `bx_shader_bridge.dll`, not `dxbc_accc.dll`. Cargo still names the built file `dxbc_accc.dll`; the script copies it to `build-shims/bin/bx_shader_bridge.dll`, and the verifier requires the export-directory name to match the `.def`.
- **Staging in `scripts/build-shims.sh` (Track A, #484):** done. The script builds this crate for `x86_64-pc-windows-gnu`, copies the result to `build-shims/bin/bx_shader_bridge.dll`, and verifies its export directory with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. CI's hybrid job installs that target with its pinned toolchain, so `rustup target add x86_64-pc-windows-gnu` is only a one-off step for a local build, and the script stops with that hint when the target's `std` is missing.
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (Track C, #466):** done. `CreateGraphicsPipelineState` and `CreateComputePipelineState` in `shims/d3d12_xs/proxy.cpp` run every stage through `BxShaderGate::admit` (`shims/d3d12_xs/shader_gate.cpp`), which calls `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` and emits `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` records through `bx_log_emit`. The bridge itself still writes its ACCC-only inspection line to the guest's stderr (`bx-shader event=prepare status=unsupported …`), because this crate does not link `bx_log_emit`; the JSONL records come from the shim.
- **Trace summary of those records (`bx-cli trace`, Track A, #496):** the work to parse `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` into `bx-telemetry` and render them in `bx-cli trace` is tracked in #496. This bullet describes the split of responsibility only — it does not depend on that issue's status, and the crate's own behaviour is unaffected either way.
This change does not touch the crate's code or tests; the tests above still describe its own behavior.
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Builds bx_shader_bridge.dll (this crate for x86_64-pc-windows-gnu) and the guest check
# check_bridge.exe into one directory (default: <repo>/target/bx-shader-bridge), then checks
# the DLL: its Export Address Table holds exactly the three bx_shader_bridge.h entry points as
# direct RVAs (no extra named or ordinal-only entries, no forwarders), and every imported DLL
# is a system DLL Wine provides. Run the check under CrossOver afterwards, for example:
# target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
# --exe target/bx-shader-bridge/check_bridge.exe
#
# Needs: rustup with the x86_64-pc-windows-gnu target, x86_64-w64-mingw32-gcc / -objdump
# (mingw-w64), and python3.
set -eu
crate=$(cd "$(dirname "$0")/.." && pwd)
root=$(cd "$crate/../../.." && pwd)
out=${1:-$root/target/bx-shader-bridge}
target=x86_64-pc-windows-gnu
cc=${BX_MINGW_CC:-x86_64-w64-mingw32-gcc}
objdump=${BX_MINGW_OBJDUMP:-x86_64-w64-mingw32-objdump}
# Always build here and copy from here, whatever CARGO_TARGET_DIR or build.target-dir say,
# so a stale DLL left elsewhere can never be packaged.
target_dir=$root/target
for tool in "$cc" "$objdump" python3; do
command -v "$tool" >/dev/null 2>&1 || { echo "build.sh: $tool not found" >&2; exit 1; }
done
# Use one toolchain for both the target check and the build. With rustup, resolve cargo and
# rustc through it (a cargo earlier on PATH, e.g. Homebrew's, has no Windows std).
if command -v rustup >/dev/null 2>&1; then
cargo=$(cd "$root" && rustup which cargo)
rustc=$(cd "$root" && rustup which rustc)
else
cargo=$(command -v cargo) || { echo "build.sh: cargo not found" >&2; exit 1; }
rustc=$(command -v rustc) || { echo "build.sh: rustc not found" >&2; exit 1; }
fi
libdir=$("$rustc" --print target-libdir --target "$target" 2>/dev/null || true)
if [ -z "$libdir" ] || ! ls "$libdir"/libstd-*.rlib >/dev/null 2>&1; then
echo "build.sh: $rustc ($("$rustc" --version)) has no std for $target" >&2
echo "build.sh: install it with: rustup target add $target" >&2
exit 1
fi
echo "build.sh: using $("$rustc" --version) at $rustc"
RUSTC=$rustc CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=$cc \
"$cargo" build --locked --release -p dxbc-accc --target "$target" \
--target-dir "$target_dir" --manifest-path "$root/Cargo.toml"
mkdir -p "$out"
cp "$target_dir/$target/release/dxbc_accc.dll" "$out/bx_shader_bridge.dll"
dll=$out/bx_shader_bridge.dll
# Same reading of `objdump -p` as scripts/build-shims.sh: every populated Export Address Table
# slot must be a direct RVA owned by one of the expected names.
"$objdump" -p "$dll" | python3 -I -c '
import re, sys
expected = {"bx_shader_inspect", "bx_shader_prepare_for_d3dmetal", "bx_shader_free_buffer"}
# The Windows-provided system DLLs a Rust std cdylib imports; anything else is an error.
allowed = {"kernel32.dll", "ntdll.dll", "bcryptprimitives.dll", "userenv.dll", "ws2_32.dll"}
allowed_prefixes = ("api-ms-win-crt-", "api-ms-win-core-")
eat, names, imports, mode = {}, {}, [], None
for line in sys.stdin:
line = line.rstrip("\n")
m = re.match(r"^\s*DLL Name:\s*(\S+)", line)
if m:
imports.append(m.group(1))
if line.startswith("Export Address Table --"):
mode = "eat"; continue
if line.startswith("[Ordinal/Name Pointer] Table --"):
mode = "names"; continue
if not line.strip():
mode = None; continue
if mode == "eat":
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(Export|Forwarder) RVA", line)
if m:
eat[int(m.group(1))] = m.group(2)
elif mode == "names":
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(\S+)", line)
if m:
names[m.group(2)] = int(m.group(1))
errors = []
if set(names) != expected:
errors.append("named exports %s, want %s" % (sorted(names), sorted(expected)))
owned = set(names.values())
for ordinal, kind in sorted(eat.items()):
if ordinal not in owned:
errors.append("export @%d has no name (ordinal-only or stray entry)" % ordinal)
if kind != "Export":
errors.append("export @%d is a forwarder" % ordinal)
for name, ordinal in names.items():
if ordinal not in eat:
errors.append("%s @%d missing from the Export Address Table" % (name, ordinal))
for dll in imports:
low = dll.lower()
if low not in allowed and not low.startswith(allowed_prefixes):
errors.append("unexpected import %s (only Wine-provided system DLLs are allowed)" % dll)
if errors:
sys.exit("build.sh: bx_shader_bridge.dll: " + "; ".join(errors))
print("build.sh: exports %s; imports %s" % (" ".join(sorted(names)), " ".join(imports)))
'
"$cc" -std=c11 -O2 -Wall -Wextra -Werror -static \
-I"$root/abi/include" -I"$crate/../d3dmetal-harness/probe/shaders" \
-o "$out/check_bridge.exe" "$crate/guest/check_bridge.c"
echo "built $dll"
echo "built $out/check_bridge.exe"
@@ -0,0 +1,296 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
*
* Guest-side check for bx_shader_bridge.dll, the x86-64 Windows build of this crate (#445).
*
* Runs as a PE32+ guest under CrossOver/Wine, loads the DLL by full path from its own directory,
* and drives the three entry points from abi/include/bx_shader_bridge.h with synthetic
* containers plus one real DXC SM 6.6 compute blob. It counts the classifications and checks
* them, and the prepare/free behaviour, against expectations written here from the DXBC
* layout and the frozen header, not from the Rust implementation.
*
* Output: "BXSHADER" lines with each blob's classification, one "BXSHADER counts" line, then
* PASS or FAIL. Exit code 0 on success, 1 on a failed check, 2 if the DLL cannot be loaded.
*/
#include <windows.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include "bx_shader_bridge.h"
#include "fill_cs66.h" /* g_fill_cs66: DXC 1.9.2609 output, see d3dmetal-harness */
/* The Rust side asserts the same layout; agreeing here proves both sides read one struct. */
_Static_assert(sizeof(bx_shader_kind_t) == 4, "C enum must be 4 bytes");
_Static_assert(sizeof(bx_shader_inspection_t) == 48, "bx_shader_inspection_t size");
_Static_assert(offsetof(bx_shader_inspection_t, container_size) == 16, "container_size offset");
_Static_assert(offsetof(bx_shader_inspection_t, digest_hash) == 32, "digest_hash offset");
typedef bx_shader_status_t (*inspect_fn)(const uint8_t*, size_t, bx_shader_inspection_t*);
typedef bx_shader_status_t (*prepare_fn)(const uint8_t*, size_t, uint8_t**, size_t*);
typedef void (*free_fn)(uint8_t*, size_t);
static int failures;
#define CHECK(expr) \
do { \
if (!(expr)) { \
fprintf(stderr, "FAIL: check_bridge line %d: %s\n", __LINE__, #expr); \
++failures; \
} \
} while (0)
/* --- Synthetic DXBC containers --- */
static void put32(uint8_t* at, uint32_t value) {
at[0] = (uint8_t)value;
at[1] = (uint8_t)(value >> 8);
at[2] = (uint8_t)(value >> 16);
at[3] = (uint8_t)(value >> 24);
}
typedef struct {
const char* fourcc;
const uint8_t* data;
uint32_t size;
} chunk_t;
/* DXBC layout: "DXBC", 16-byte digest, u32 version 1, u32 total size, u32 chunk count, then
* one u32 offset per chunk; each chunk is fourcc, u32 size, payload. */
static uint32_t build_dxbc(uint8_t* out, size_t cap, const chunk_t* chunks, uint32_t count) {
uint32_t at = 32 + 4 * count;
for (uint32_t i = 0; i < count; ++i) at += 8 + chunks[i].size;
if (at > cap) abort();
memcpy(out, "DXBC", 4);
memset(out + 4, 0x5A, 16);
put32(out + 20, 1);
put32(out + 24, at);
put32(out + 28, count);
uint32_t offset = 32 + 4 * count;
for (uint32_t i = 0; i < count; ++i) {
put32(out + 32 + 4 * i, offset);
memcpy(out + offset, chunks[i].fourcc, 4);
put32(out + offset + 4, chunks[i].size);
memcpy(out + offset + 8, chunks[i].data, chunks[i].size);
offset += 8 + chunks[i].size;
}
return at;
}
/* A 28-byte DxilProgramHeader: program version word (kind << 16 | major << 4 | minor), size
* in dwords (7), "DXIL", DXIL version 1.0, bitcode offset 16, bitcode size 4, 4 bitcode bytes. */
static void dxil_program(uint8_t out[28], uint32_t kind, uint32_t major, uint32_t minor) {
memset(out, 0, 28);
put32(out, kind << 16 | major << 4 | minor);
put32(out + 4, 7);
memcpy(out + 8, "DXIL", 4);
put32(out + 12, 0x0100);
put32(out + 16, 16);
put32(out + 20, 4);
put32(out + 24, 0xDEC011D1u);
}
/* Size of the first chunk named fourcc in a well-formed container, 0 if absent. Written from
* the DXBC layout, independently of the Rust parser. */
static uint32_t get32(const uint8_t* at) {
return (uint32_t)at[0] | (uint32_t)at[1] << 8 | (uint32_t)at[2] << 16 | (uint32_t)at[3] << 24;
}
static int chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
if (len < 32 || memcmp(bytes, "DXBC", 4) != 0) return 0;
const uint32_t count = get32(bytes + 28);
for (uint32_t i = 0; i < count && 36 + 4 * (size_t)i <= len; ++i) {
const uint32_t offset = get32(bytes + 32 + 4 * i);
if (offset + 8 <= len && memcmp(bytes + offset, fourcc, 4) == 0) {
*size = get32(bytes + offset + 4);
return 1;
}
}
return 0;
}
/* --- Cases --- */
typedef struct {
const char* name;
const uint8_t* bytes;
size_t len;
bx_shader_status_t inspect_status;
bx_shader_kind_t kind;
bx_shader_stage_t stage;
uint32_t sm_major, sm_minor;
uint32_t container_size; /* the container's declared size, which may be less than len */
bx_shader_status_t prepare_status;
} case_t;
static const char* kind_name(bx_shader_kind_t kind) {
switch (kind) {
case BX_SHADER_DXBC_DXIL: return "dxil";
case BX_SHADER_DXBC_LEGACY: return "legacy";
case BX_SHADER_DXBC_ACCC: return "accc_only";
case BX_SHADER_DXBC_DUAL: return "dual";
default: return "unknown";
}
}
int main(void) {
/* By full path beside this EXE, as a caller should (see the crate README). */
wchar_t path[MAX_PATH];
const DWORD path_len = GetModuleFileNameW(NULL, path, MAX_PATH);
wchar_t* slash = path_len && path_len < MAX_PATH ? wcsrchr(path, L'\\') : NULL;
if (!slash || (size_t)(slash + 1 - path) + 21 > MAX_PATH) {
fprintf(stderr, "FAIL: check_bridge: executable path too long\n");
return 2;
}
wcscpy(slash + 1, L"bx_shader_bridge.dll");
HMODULE dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!dll) {
fprintf(stderr, "FAIL: check_bridge: bx_shader_bridge.dll not loaded (error %lu)\n", GetLastError());
return 2;
}
inspect_fn inspect = (inspect_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_inspect");
prepare_fn prepare = (prepare_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_prepare_for_d3dmetal");
free_fn release = (free_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_free_buffer");
if (!inspect || !prepare || !release) {
fprintf(stderr, "FAIL: check_bridge: missing export\n");
return 2;
}
uint8_t dxil_cs66[28], dxil_ps60[28];
dxil_program(dxil_cs66, 5, 6, 6); /* DXIL program kind 5 = compute */
dxil_program(dxil_ps60, 0, 6, 0); /* kind 0 = pixel */
const uint8_t rts0[4] = {1, 2, 3, 4};
/* FSPX v1 (BetterXen's synthetic layout): header "FSPX", version 1, 1 section, flags 0;
* descriptor {id 1 (stage config), offset 28, size 12}; body {stage 6 compute, SM 6.0}. */
uint8_t fspx_v1[40] = {0};
memcpy(fspx_v1, "FSPX", 4);
put32(fspx_v1 + 4, 1);
put32(fspx_v1 + 8, 1);
put32(fspx_v1 + 16, 1);
put32(fspx_v1 + 20, 28);
put32(fspx_v1 + 24, 12);
put32(fspx_v1 + 28, BX_STAGE_COMPUTE);
put32(fspx_v1 + 32, 6);
put32(fspx_v1 + 36, 0);
/* FSPX version 0: magic-only stub, no sections. */
uint8_t fspx_v0[16] = {'F', 'S', 'P', 'X'};
/* SM 5.0 compute SHEX token (program type 5 << 16 | 5 << 4 | 0) and a length dword. */
uint8_t shex[8];
put32(shex, 5u << 16 | 5u << 4);
put32(shex + 4, 2);
static uint8_t ps60[256], accc_v1[256], accc_v0[256], dual[256], legacy[256];
const chunk_t ps60_chunks[] = {{"RTS0", rts0, 4}, {"DXIL", dxil_ps60, 28}};
const chunk_t accc_v1_chunks[] = {{"ACCC", fspx_v1, sizeof(fspx_v1)}};
const chunk_t accc_v0_chunks[] = {{"ACCC", fspx_v0, sizeof(fspx_v0)}};
const chunk_t dual_chunks[] = {{"DXIL", dxil_cs66, 28}, {"ACCC", fspx_v0, sizeof(fspx_v0)}};
const chunk_t legacy_chunks[] = {{"SHEX", shex, sizeof(shex)}};
const uint32_t ps60_len = build_dxbc(ps60, sizeof(ps60), ps60_chunks, 2);
const uint32_t accc_v1_len = build_dxbc(accc_v1, sizeof(accc_v1), accc_v1_chunks, 1);
const uint32_t accc_v0_len = build_dxbc(accc_v0, sizeof(accc_v0), accc_v0_chunks, 1);
const uint32_t dual_len = build_dxbc(dual, sizeof(dual), dual_chunks, 2);
const uint32_t legacy_len = build_dxbc(legacy, sizeof(legacy), legacy_chunks, 1);
/* The pixel shader again, followed by 16 bytes that are not part of the container. */
static uint8_t padded[256 + 16];
memcpy(padded, ps60, ps60_len);
memset(padded + ps60_len, 0xEE, 16);
static const uint8_t truncated[20] = {'D', 'X', 'B', 'C'};
static const uint8_t not_dxbc[64] = {'X', 'X', 'X', 'X'};
const case_t cases[] = {
{"dxc_cs_6_6", g_fill_cs66, sizeof(g_fill_cs66), BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_COMPUTE, 6, 6,
sizeof(g_fill_cs66), BX_SHADER_OK},
{"synthetic_ps_6_0", ps60, ps60_len, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
BX_SHADER_OK},
{"trailing_bytes", padded, ps60_len + 16, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
BX_SHADER_OK},
{"accc_fspx_v1", accc_v1, accc_v1_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_COMPUTE, 6, 0, accc_v1_len,
BX_SHADER_ERR_UNSUPPORTED},
{"accc_fspx_v0", accc_v0, accc_v0_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_UNKNOWN, 0, 0, accc_v0_len,
BX_SHADER_ERR_UNSUPPORTED},
{"dual_dxil_accc", dual, dual_len, BX_SHADER_OK, BX_SHADER_DXBC_DUAL, BX_STAGE_COMPUTE, 6, 6, dual_len,
BX_SHADER_OK},
{"legacy_shex_5_0", legacy, legacy_len, BX_SHADER_OK, BX_SHADER_DXBC_LEGACY, BX_STAGE_COMPUTE, 5, 0,
legacy_len, BX_SHADER_ERR_UNSUPPORTED},
{"truncated", truncated, sizeof(truncated), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN,
0, 0, 0, BX_SHADER_ERR_INVALID_BLOB},
{"not_dxbc", not_dxbc, sizeof(not_dxbc), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN, 0,
0, 0, BX_SHADER_ERR_INVALID_BLOB},
};
const size_t count = sizeof(cases) / sizeof(cases[0]);
unsigned tally[5] = {0};
unsigned invalid = 0;
for (size_t i = 0; i < count; ++i) {
const case_t* c = &cases[i];
bx_shader_inspection_t info;
memset(&info, 0xEE, sizeof(info));
const bx_shader_status_t status = inspect(c->bytes, c->len, &info);
printf("BXSHADER %s status=%d kind=%s stage=%d sm=%u.%u container_size=%u dxil=%u accc=%u rts0=%u\n",
c->name, (int)status, kind_name(info.kind), (int)info.stage, info.shader_model_major,
info.shader_model_minor, info.container_size, info.dxil_chunk_size, info.accc_chunk_size,
info.has_root_signature);
CHECK(status == c->inspect_status);
if (status == BX_SHADER_OK) {
if ((unsigned)info.kind < 5) ++tally[info.kind];
CHECK(info.kind == c->kind);
CHECK(info.stage == c->stage);
CHECK(info.shader_model_major == c->sm_major && info.shader_model_minor == c->sm_minor);
CHECK(info.container_size == c->container_size);
/* Exact chunk sizes and the root signature flag, from this file's own chunk walk. */
uint32_t want_dxil = 0, want_accc = 0, rts0_size = 0;
chunk(c->bytes, c->len, "DXIL", &want_dxil);
chunk(c->bytes, c->len, "ACCC", &want_accc);
const uint32_t want_rts0 = (uint32_t)chunk(c->bytes, c->len, "RTS0", &rts0_size);
CHECK(info.dxil_chunk_size == want_dxil);
CHECK(info.accc_chunk_size == want_accc);
CHECK(info.has_root_signature == want_rts0);
CHECK((want_dxil != 0) == (c->kind == BX_SHADER_DXBC_DXIL || c->kind == BX_SHADER_DXBC_DUAL));
CHECK((want_accc != 0) == (c->kind == BX_SHADER_DXBC_ACCC || c->kind == BX_SHADER_DXBC_DUAL));
/* The digest is the container header's bytes 4..20, for every case. */
CHECK(memcmp(info.digest_hash, c->bytes + 4, 16) == 0);
} else {
++invalid;
const bx_shader_inspection_t zero = {0};
CHECK(memcmp(&info, &zero, sizeof(info)) == 0); /* cleared on failure */
}
uint8_t* copy = (uint8_t*)(uintptr_t)1;
size_t copy_len = 1;
const bx_shader_status_t prepared = prepare(c->bytes, c->len, &copy, &copy_len);
CHECK(prepared == c->prepare_status);
if (prepared == BX_SHADER_OK) {
/* Only the declared container is copied, never bytes past it. */
CHECK(copy && copy_len == c->container_size && memcmp(copy, c->bytes, c->container_size) == 0);
release(copy, copy_len);
} else {
CHECK(copy == NULL && copy_len == 0);
}
}
/* Argument checks at the DLL boundary. */
bx_shader_inspection_t info;
CHECK(inspect(g_fill_cs66, sizeof(g_fill_cs66), NULL) == BX_SHADER_ERR_INVALID_BLOB);
CHECK(inspect(NULL, 16, &info) == BX_SHADER_ERR_INVALID_BLOB);
uint8_t* copy = NULL;
CHECK(prepare(g_fill_cs66, sizeof(g_fill_cs66), NULL, NULL) == BX_SHADER_ERR_INVALID_BLOB);
CHECK(prepare(NULL, 16, &copy, &(size_t){0}) == BX_SHADER_ERR_INVALID_BLOB && copy == NULL);
release(NULL, 0);
printf("BXSHADER counts dxil=%u accc_only=%u dual=%u legacy=%u unknown=%u invalid=%u\n",
tally[BX_SHADER_DXBC_DXIL], tally[BX_SHADER_DXBC_ACCC], tally[BX_SHADER_DXBC_DUAL],
tally[BX_SHADER_DXBC_LEGACY], tally[BX_SHADER_UNKNOWN], invalid);
CHECK(tally[BX_SHADER_DXBC_DXIL] == 3 && tally[BX_SHADER_DXBC_ACCC] == 2 && tally[BX_SHADER_DXBC_DUAL] == 1);
CHECK(tally[BX_SHADER_DXBC_LEGACY] == 1 && tally[BX_SHADER_UNKNOWN] == 0 && invalid == 2);
if (failures) {
fprintf(stderr, "FAIL: check_bridge (%d failed checks)\n", failures);
return 1;
}
printf("PASS: check_bridge (%u containers through bx_shader_bridge.dll)\n", (unsigned)count);
return 0;
}
+32 -3
View File
@@ -10,6 +10,13 @@
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
//! count is rejected before any descriptor is compared with another, so
//! inspection stays allocation-free and the pairwise check stays bounded.
//!
//! A descriptor whose offset lands inside the 16-byte header or the
//! descriptor table itself is a layout mismatch, reported apart from a
//! section that runs past the end of the payload. Read through this layout,
//! such a table is not merely truncated or corrupt: its descriptors do not
//! mean `(id, offset, size)` relative to the payload as this module assumes.
//! It is still an error, and the container is still refused.
use super::{ShaderStage, read_u32_le};
@@ -82,9 +89,22 @@ impl FspxInfo {
pub(crate) enum FspxError {
Truncated,
BadVersion(u32),
SectionOutOfBounds { section_id: u32 },
DuplicateSection { section_id: u32 },
Overlap { section_id: u32 },
SectionOutOfBounds {
section_id: u32,
},
/// The descriptor's offset lies inside the header plus descriptor table,
/// the region this layout reserves, so the table does not follow it.
LayoutMismatch {
section_id: u32,
offset: u32,
table_end: u32,
},
DuplicateSection {
section_id: u32,
},
Overlap {
section_id: u32,
},
BadStageConfig,
TooManySections(u32),
}
@@ -217,6 +237,15 @@ fn walk_sections(
) -> Result<(), FspxError> {
for index in 0..header.count {
let (id, offset, size) = descriptor_at(payload, index)?;
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
return Err(FspxError::LayoutMismatch {
section_id: id,
offset,
table_end,
});
}
let end = section_end(offset, size, header.table_end, payload.len())
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
for prev in 0..index {
+685 -56
View File
@@ -9,7 +9,10 @@
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
//! [`ParseError::FspxTooManySections`] before any pairwise comparison.
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
//! descriptor whose offset lands inside the header plus descriptor table is
//! [`ParseError::FspxLayoutMismatch`], kept apart from
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
//! code byte range. The code bytes are not decoded. This layout is synthetic.
@@ -26,13 +29,16 @@
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
//! so preparation does not copy it.
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
//! size and stage metadata but does not classify as executable `DXIL`.
//!
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
//! including when an accompanying `FSPX` table is malformed, and logs only an
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
//! is not implemented.
mod c_abi;
mod fspx;
@@ -94,22 +100,104 @@ pub struct ShaderInspection {
pub chunks: Vec<ChunkInfo>,
}
impl ShaderInspection {
/// Payload of the first chunk tagged `fourcc`, if present and fully
/// inside the container. Returns `None` when absent, when the declared
/// size would run past `container_size` or `container`, or when `offset`
/// points into the DXBC header or chunk-offset table instead of a chunk
/// header.
///
/// `container` must be the same bytes passed to [`inspect_dxbc`]; the
/// inspection only stores chunk metadata, so the original container is
/// required to slice out the payload. `ChunkInfo::offset` is relative to
/// the start of the `DXBC` container and points at the 8-byte chunk
/// header (fourcc + size), so the payload begins at `offset + 8`.
///
/// A zero-size chunk yields `Some(&[])`: the header is present and
/// in-bounds, so an empty payload is a valid result rather than an
/// absence. Callers that require a minimum size must check the returned
/// slice length.
///
/// Only the already-parsed `self.chunks` table is consulted; the raw
/// chunk table is not re-walked. When several chunks share `fourcc`,
/// the first one in table order wins, matching the C++ `find_chunk`.
pub fn chunk_payload<'a>(&self, container: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
let chunk = self.chunks.iter().find(|c| &c.fourcc == fourcc)?;
let table_bytes = u64::try_from(self.chunks.len()).ok()?.checked_mul(4)?;
let table_end = 32u64.checked_add(table_bytes)?;
if u64::from(chunk.offset) < table_end {
return None;
}
let start = u64::from(chunk.offset).checked_add(8)?;
let end = start.checked_add(u64::from(chunk.size))?;
if end > u64::from(self.container_size) {
return None;
}
let start = usize::try_from(start).ok()?;
let end = usize::try_from(end).ok()?;
if end > container.len() {
return None;
}
container.get(start..end)
}
/// True when a chunk header tagged `fourcc` exists, whatever its
/// declared size. Mirrors the C++ `has_chunk_tag`: presence without
/// trusting the size.
pub fn has_chunk_tag(&self, fourcc: &[u8; 4]) -> bool {
self.chunks.iter().any(|c| &c.fourcc == fourcc)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
TooShort,
BadMagic,
UnsupportedVersion(u32),
TruncatedChunkTable,
ChunkOutOfBounds { index: usize },
ChunkOutOfBounds {
index: usize,
},
TruncatedContainer,
FspxTruncated { chunk: usize },
FspxBadVersion { chunk: usize, version: u32 },
FspxSectionOutOfBounds { chunk: usize, section_id: u32 },
FspxDuplicateSection { chunk: usize, section_id: u32 },
FspxSectionOverlap { chunk: usize, section_id: u32 },
FspxBadStageConfig { chunk: usize },
FspxTooManySections { chunk: usize, count: u32 },
BadDxilHeader { chunk: usize },
FspxTruncated {
chunk: usize,
},
FspxBadVersion {
chunk: usize,
version: u32,
},
FspxSectionOutOfBounds {
chunk: usize,
section_id: u32,
},
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
/// table (`table_end` bytes), which the synthetic layout reserves. The
/// table does not follow BetterXen's clean-room layout; it is not reported
/// as an out-of-bounds section. The container is still rejected.
FspxLayoutMismatch {
chunk: usize,
section_id: u32,
offset: u32,
table_end: u32,
},
FspxDuplicateSection {
chunk: usize,
section_id: u32,
},
FspxSectionOverlap {
chunk: usize,
section_id: u32,
},
FspxBadStageConfig {
chunk: usize,
},
FspxTooManySections {
chunk: usize,
count: u32,
},
BadDxilHeader {
chunk: usize,
},
}
impl fmt::Display for ParseError {
@@ -133,6 +221,15 @@ impl fmt::Display for ParseError {
"FSPX section {section_id} out of bounds in chunk {chunk}"
)
}
Self::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
} => write!(
f,
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
),
Self::FspxDuplicateSection { chunk, section_id } => {
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
}
@@ -185,6 +282,16 @@ fn fspx_error(chunk: usize, err: fspx::FspxError) -> ParseError {
fspx::FspxError::SectionOutOfBounds { section_id } => {
ParseError::FspxSectionOutOfBounds { chunk, section_id }
}
fspx::FspxError::LayoutMismatch {
section_id,
offset,
table_end,
} => ParseError::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
},
fspx::FspxError::DuplicateSection { section_id } => {
ParseError::FspxDuplicateSection { chunk, section_id }
}
@@ -209,14 +316,22 @@ fn record_fspx_stage(
}
}
enum DxilProgram {
Executable((ShaderStage, u8, u8)),
HeaderOnly((ShaderStage, u8, u8)),
}
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
///
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
/// and must be at least 16. `BitcodeSize` must be non-zero, and
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
/// bitcode bytes are not decoded.
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
///
/// A bitcode payload beginning with `NOBC` is a header-only container (for
/// example, reflection or signature metadata with bitcode stripped) and is
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
const PROGRAM_PREFIX: u64 = 8;
const BITCODE_HEADER: u64 = 16;
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
@@ -245,7 +360,16 @@ fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
if end > program_bytes {
return Err(());
}
Ok(program_stage(program_version))
let bitcode_start =
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
let stage = program_stage(program_version);
if bitcode.starts_with(b"NOBC") {
Ok(DxilProgram::HeaderOnly(stage))
} else {
Ok(DxilProgram::Executable(stage))
}
}
struct ContainerLimit {
@@ -352,6 +476,37 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
}
}
#[derive(Default)]
struct DxilChunkState {
has_executable: bool,
size: u32,
executable_stage: Option<(ShaderStage, u8, u8)>,
header_only_stage: Option<(ShaderStage, u8, u8)>,
}
impl DxilChunkState {
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
/// header-only placeholders regardless of chunk order.
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
DxilProgram::Executable(stage) => {
self.has_executable = true;
self.size = size;
self.executable_stage = Some(stage);
}
DxilProgram::HeaderOnly(stage) => {
if !self.has_executable {
self.size = size;
}
if self.header_only_stage.is_none() {
self.header_only_stage = Some(stage);
}
}
}
Ok(())
}
}
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
/// keep chunk or section lists.
pub(crate) struct DxbcSummary {
@@ -370,24 +525,16 @@ pub(crate) struct DxbcSummary {
///
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -408,36 +555,40 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
}
Ok(())
})?;
let (stage, shader_model_major, shader_model_minor) = dxil_stage
let (stage, shader_model_major, shader_model_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(DxbcSummary {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major,
shader_model_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
})
}
/// `Ok(Some(container_size))` when the container is structurally valid and
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no `DXIL` chunk.
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no executable `DXIL` chunk.
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
let mut has_dxil = false;
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
if &fourcc == b"DXIL" {
if read_dxil_program(payload).is_err() {
return Err(ParseError::BadDxilHeader { chunk: index });
match read_dxil_program(payload) {
Ok(DxilProgram::Executable(_)) => has_dxil = true,
Ok(DxilProgram::HeaderOnly(_)) => {}
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
}
has_dxil = true;
}
Ok(())
})?;
@@ -457,27 +608,19 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
/// container through.
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
let mut chunks = Vec::new();
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut accc_is_fspx = false;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let mut fspx = None;
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -515,21 +658,22 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
Ok(())
})?;
let (stage, sm_major, sm_minor) =
dxil_stage
.or(legacy_stage)
.or(fspx_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
let (stage, sm_major, sm_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(ShaderInspection {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major: sm_major,
shader_model_minor: sm_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
accc_is_fspx,
fspx,
@@ -868,9 +1012,11 @@ mod tests {
),
(
fspx_header(1, 1, &[(1, 0, 4)], 28),
ParseError::FspxSectionOutOfBounds {
ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 1,
offset: 0,
table_end: 28,
},
),
(
@@ -924,18 +1070,167 @@ mod tests {
#[test]
fn truncated_prefixes_do_not_panic() {
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
nobc_dxil[24..28].copy_from_slice(b"NOBC");
let blobs = [
synthetic_dxil_blob(),
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
vec![0xFF; 64],
];
for blob in blobs {
for len in 0..=blob.len() {
let _ = inspect_dxbc(&blob[..len]);
let _ = summarize_dxbc(&blob[..len]);
let _ = dxil_container_len(&blob[..len]);
}
}
}
/// A two-section table (`table_end` = 16 + 2 * 12 = 40) whose second
/// descriptor's offset is `second_offset`. The first descriptor is a valid
/// 12-byte stage section at 40, and the payload is 64 bytes long.
fn fspx_two_sections(second_offset: u32) -> Vec<u8> {
let mut payload = fspx_header(1, 2, &[(1, 40, 12), (6, second_offset, 4)], 64);
payload[40..44].copy_from_slice(&6u32.to_le_bytes());
payload[44..48].copy_from_slice(&6u32.to_le_bytes());
payload
}
#[test]
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
// Inside the 16-byte header, inside the first descriptor, inside the
// descriptor itself, and the last reserved byte.
for offset in [0u32, 8, 16, 28, 39] {
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
let expected = ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset,
table_end: 40,
};
assert_eq!(
inspect_dxbc(&blob),
Err(expected.clone()),
"offset {offset}"
);
// The C ABI path walks the table through `scan_fspx`, not
// `parse_fspx`, and must classify it the same way.
assert_eq!(
summarize_dxbc(&blob).map(|_| ()),
Err(expected),
"offset {offset}"
);
}
// The first byte after the table is outside the reserved region.
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
assert_eq!(info.kind, ShaderKind::AcccOnly);
assert_eq!(info.stage, ShaderStage::Compute);
assert!(summarize_dxbc(&blob).is_ok());
}
#[test]
fn fspx_layout_mismatch_is_not_out_of_bounds() {
// Past the payload end is still out of bounds, not a layout mismatch.
let mut payload = fspx_two_sections(62);
payload.truncate(64);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let out_of_bounds = ParseError::FspxSectionOutOfBounds {
chunk: 0,
section_id: 6,
};
assert_eq!(inspect_dxbc(&blob), Err(out_of_bounds.clone()));
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(out_of_bounds));
// A reserved offset wins even when the size would also overrun.
let mut payload = fspx_header(1, 1, &[(6, 20, u32::MAX)], 32);
payload.truncate(32);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset: 20,
table_end: 28,
})
);
let message = ParseError::FspxLayoutMismatch {
chunk: 2,
section_id: 6,
offset: 20,
table_end: 28,
}
.to_string();
assert!(message.contains("section 6"), "{message}");
assert!(message.contains("offset 20"), "{message}");
assert!(message.contains("28-byte"), "{message}");
assert!(message.contains("chunk 2"), "{message}");
assert!(!message.contains("out of bounds"), "{message}");
}
#[test]
fn c_abi_still_refuses_fspx_layout_mismatch() {
clear_shader_log();
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]);
let mut c_info = BxShaderInspection {
kind: 99,
..BxShaderInspection::default()
};
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert_eq!(c_info.kind, 0);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn arbitrary_fspx_tables_do_not_panic() {
// Deterministic xorshift so a failure reproduces.
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let mut next = || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for round in 0..4096u32 {
let len = 16 + (next() % 240) as usize;
let mut payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
payload[..4].copy_from_slice(b"FSPX");
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
let count = round % (FSPX_MAX_SECTIONS as u32 + 2);
payload[8..12].copy_from_slice(&count.to_le_bytes());
// Keep some offsets small so the reserved-region branch is hit.
if round % 2 == 0 {
let mut at = 20;
while at + 4 <= len.min(16 + count as usize * 12) {
let small = (next() % 64) as u32;
payload[at..at + 4].copy_from_slice(&small.to_le_bytes());
at += 12;
}
}
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let _ = inspect_dxbc(&blob);
let _ = summarize_dxbc(&blob);
let mut c_info = BxShaderInspection::default();
let _ = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
}
}
#[test]
fn c_abi_inspect_and_passthrough_round_trip() {
clear_shader_log();
@@ -1268,6 +1563,245 @@ mod tests {
assert!(log[0].contains("sm_minor=0"));
}
#[test]
fn nobc_dxil_is_not_classified_as_executable_dxil() {
clear_shader_log();
// Pixel shader (0), SM 6.6, with the four-byte NOBC placeholder instead of LLVM bitcode.
let mut payload = minimal_dxil_program((6u32 << 4) | 6u32);
payload[24..28].copy_from_slice(b"NOBC");
let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &payload)]);
let info = inspect_dxbc(&blob).expect("valid DXBC with NOBC header-only DXIL");
assert_eq!(info.kind, ShaderKind::Unknown);
assert_eq!(info.stage, ShaderStage::Pixel);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6));
assert_eq!(info.dxil_size, 28);
assert!(info.has_root_signature);
let mut c_info = BxShaderInspection::default();
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_OK);
assert_eq!(c_info.kind, 0); // BX_SHADER_UNKNOWN
assert_eq!(c_info.stage, 1); // BX_STAGE_PIXEL
assert_eq!(c_info.shader_model_major, 6);
assert_eq!(c_info.shader_model_minor, 6);
assert_eq!(c_info.dxil_chunk_size, 28);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn nobc_dxil_with_accc_is_classified_as_accc_only_and_rejected() {
clear_shader_log();
let mut dxil = minimal_dxil_program((1u32 << 16) | (6u32 << 4) | 6u32);
dxil[24..28].copy_from_slice(b"NOBC");
let fspx = fspx_compute_stage();
let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil), (b"ACCC", &fspx)]);
let info = inspect_dxbc(&blob).expect("NOBC + ACCC container");
assert_eq!(info.kind, ShaderKind::AcccOnly);
assert_eq!(info.stage, ShaderStage::Compute);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0));
assert_eq!(info.dxil_size, 28);
assert_eq!(info.accc_size, 40);
let mut c_info = BxShaderInspection::default();
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_OK);
assert_eq!(c_info.kind, 3); // BX_SHADER_DXBC_ACCC
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
let log = shader_log_lines();
assert_eq!(log.len(), 1);
assert!(log[0].contains("kind=accc_only(3)"));
}
#[test]
fn nobc_dxil_with_padded_bitcode_is_still_header_only() {
let mut payload = vec![0u8; 32];
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
payload[0..4].copy_from_slice(&prog.to_le_bytes());
payload[4..8].copy_from_slice(&8u32.to_le_bytes());
payload[8..12].copy_from_slice(b"DXIL");
payload[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
payload[16..20].copy_from_slice(&16u32.to_le_bytes());
payload[20..24].copy_from_slice(&8u32.to_le_bytes());
payload[24..28].copy_from_slice(b"NOBC");
let blob = build_synthetic_dxbc(&[(b"DXIL", &payload)]);
let info = inspect_dxbc(&blob).expect("padded NOBC DXIL");
assert_eq!(info.kind, ShaderKind::Unknown);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
}
#[test]
fn mixed_executable_and_nobc_dxil_preserves_executable_metadata() {
let exec = minimal_dxil_program((5u32 << 16) | (6u32 << 4) | 5u32);
let mut nobc = vec![0u8; 32];
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
nobc[0..4].copy_from_slice(&prog.to_le_bytes());
nobc[4..8].copy_from_slice(&8u32.to_le_bytes());
nobc[8..12].copy_from_slice(b"DXIL");
nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
nobc[16..20].copy_from_slice(&16u32.to_le_bytes());
nobc[20..24].copy_from_slice(&8u32.to_le_bytes());
nobc[24..28].copy_from_slice(b"NOBC");
// Executable first, NOBC second: executable stage and size must win.
let blob_exec_first = build_synthetic_dxbc(&[(b"DXIL", &exec), (b"DXIL", &nobc)]);
let info = inspect_dxbc(&blob_exec_first).expect("mixed DXIL");
assert_eq!(info.kind, ShaderKind::Dxil);
assert_eq!(info.stage, ShaderStage::Compute);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 5));
assert_eq!(info.dxil_size, 28);
let mut c_info = BxShaderInspection::default();
assert_eq!(
unsafe {
bx_shader_inspect(blob_exec_first.as_ptr(), blob_exec_first.len(), &mut c_info)
},
BX_SHADER_OK
);
assert_eq!(c_info.kind, 1); // BX_SHADER_DXBC_DXIL
assert_eq!(c_info.stage, 6); // BX_STAGE_COMPUTE
assert_eq!(c_info.dxil_chunk_size, 28);
assert_eq!(
dxil_container_len(&blob_exec_first),
Ok(Some(blob_exec_first.len() as u32))
);
// NOBC first, executable second: executable must still win.
let blob_nobc_first = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"DXIL", &exec)]);
let info2 = inspect_dxbc(&blob_nobc_first).expect("mixed DXIL reversed");
assert_eq!(info2.kind, ShaderKind::Dxil);
assert_eq!(info2.stage, ShaderStage::Compute);
assert_eq!((info2.shader_model_major, info2.shader_model_minor), (6, 5));
assert_eq!(info2.dxil_size, 28);
let summary2 = summarize_dxbc(&blob_nobc_first).expect("mixed DXIL summary");
assert_eq!(summary2.kind, ShaderKind::Dxil);
assert_eq!(summary2.stage, ShaderStage::Compute);
assert_eq!(summary2.dxil_size, 28);
}
#[test]
fn nobc_dxil_with_malformed_fspx_returns_invalid_blob() {
clear_shader_log();
let mut nobc = minimal_dxil_program((6u32 << 4) | 6u32);
nobc[24..28].copy_from_slice(b"NOBC");
let bad_fspx = fspx_header(99, 0, &[], 16);
let blob = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"ACCC", &bad_fspx)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::FspxBadVersion {
chunk: 1,
version: 99,
})
);
assert_eq!(dxil_container_len(&blob), Ok(None));
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn dxil_bitcode_bounds_and_offset_checks() {
let prog = (5u32 << 16) | (6u32 << 4) | 6u32;
// Bitcode shorter than 4 bytes (`NOB`) must not misclassify as `NOBC` or read out of bounds.
let mut short_bitcode = [0u8; 28];
short_bitcode[0..4].copy_from_slice(&prog.to_le_bytes());
short_bitcode[4..8].copy_from_slice(&7u32.to_le_bytes());
short_bitcode[8..12].copy_from_slice(b"DXIL");
short_bitcode[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
short_bitcode[16..20].copy_from_slice(&16u32.to_le_bytes());
short_bitcode[20..24].copy_from_slice(&3u32.to_le_bytes());
short_bitcode[24..27].copy_from_slice(b"NOB");
let blob_short = build_synthetic_dxbc(&[(b"DXIL", &short_bitcode)]);
assert_eq!(
inspect_dxbc(&blob_short).expect("3-byte bitcode").kind,
ShaderKind::Dxil
);
// `NOBC` check follows `BitcodeOffset`, not a fixed offset 24.
let mut shifted_nobc = vec![0u8; 36];
shifted_nobc[0..4].copy_from_slice(&prog.to_le_bytes());
shifted_nobc[4..8].copy_from_slice(&9u32.to_le_bytes());
shifted_nobc[8..12].copy_from_slice(b"DXIL");
shifted_nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
shifted_nobc[16..20].copy_from_slice(&24u32.to_le_bytes());
shifted_nobc[20..24].copy_from_slice(&4u32.to_le_bytes());
shifted_nobc[32..36].copy_from_slice(b"NOBC");
let blob_shifted_nobc = build_synthetic_dxbc(&[(b"DXIL", &shifted_nobc)]);
assert_eq!(
inspect_dxbc(&blob_shifted_nobc).expect("shifted NOBC").kind,
ShaderKind::Unknown
);
assert_eq!(dxil_container_len(&blob_shifted_nobc), Ok(None));
// Bytes before `BitcodeOffset` containing `NOBC` do not make executable bitcode header-only.
let mut shifted_exec = shifted_nobc;
shifted_exec[24..28].copy_from_slice(b"NOBC");
shifted_exec[32..36].copy_from_slice(&[0xD1, 0x11, 0xC0, 0xDE]);
let blob_shifted_exec = build_synthetic_dxbc(&[(b"DXIL", &shifted_exec)]);
assert_eq!(
inspect_dxbc(&blob_shifted_exec)
.expect("shifted executable")
.kind,
ShaderKind::Dxil
);
// Overflowing bitcode offset / size must reject cleanly as `BadDxilHeader`.
for (bitcode_off, bitcode_sz) in [(16u32, u32::MAX), (u32::MAX - 4, 4u32)] {
let mut overflow = minimal_dxil_program(prog);
overflow[16..20].copy_from_slice(&bitcode_off.to_le_bytes());
overflow[20..24].copy_from_slice(&bitcode_sz.to_le_bytes());
let blob = build_synthetic_dxbc(&[(b"DXIL", &overflow)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
assert_eq!(
summarize_dxbc(&blob).map(|_| ()),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
assert_eq!(
dxil_container_len(&blob),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
}
}
fn fspx_table_with_sections(count: u32) -> Vec<u8> {
let count_usize = count as usize;
let table_end = 16 + count_usize * 12;
@@ -1302,4 +1836,99 @@ mod tests {
fn ptr_sentinel() -> *mut u8 {
std::ptr::dangling_mut()
}
#[test]
fn chunk_payload_returns_sfi0_and_psv0_bytes() {
let sfi0: [u8; 8] = [0x00, 0x40, 0, 0, 0, 0, 0, 0];
let psv0: [u8; 28] = [
24, 0, 0, 0, // info_size = 24
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, // lanes_min
64, 0, 0, 0, // lanes_max
];
let blob = build_synthetic_dxbc(&[(b"SFI0", &sfi0), (b"PSV0", &psv0)]);
let info = inspect_dxbc(&blob).expect("valid container");
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(sfi0.as_slice()));
assert_eq!(info.chunk_payload(&blob, b"PSV0"), Some(psv0.as_slice()));
assert!(info.has_chunk_tag(b"SFI0"));
assert!(info.has_chunk_tag(b"PSV0"));
}
#[test]
fn chunk_payload_rejects_declared_size_past_container() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4])]);
let mut info = inspect_dxbc(&blob).expect("valid container");
// A declared size that runs past container_size must yield None, not
// a panic and not a slice clipped to the container.
info.chunks[0].size = u32::MAX;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// Presence without trusting the size still holds.
assert!(info.has_chunk_tag(b"SFI0"));
// A forged public ChunkInfo must not treat the DXBC header or offset
// table as a chunk header.
info.chunks[0].size = 4;
info.chunks[0].offset = 0;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// A header offset past the container must also yield None.
info.chunks[0].offset = u32::MAX;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// A chunk header that would end exactly one byte past the container.
info.chunks[0].offset = info.container_size - 7;
info.chunks[0].size = 0;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
}
#[test]
fn chunk_payload_absent_fourcc() {
let blob = synthetic_dxil_blob();
let info = inspect_dxbc(&blob).expect("valid");
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
assert!(!info.has_chunk_tag(b"SFI0"));
}
#[test]
fn chunk_payload_zero_size_returns_empty_slice() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[])]);
let info = inspect_dxbc(&blob).expect("valid");
assert!(info.has_chunk_tag(b"SFI0"));
let payload = info.chunk_payload(&blob, b"SFI0");
assert_eq!(payload, Some(&[][..]));
}
#[test]
fn chunk_payload_exact_fit_at_container_end() {
let payload = [0xAA, 0xBB, 0xCC, 0xDD];
let blob = build_synthetic_dxbc(&[(b"SFI0", &payload)]);
let info = inspect_dxbc(&blob).expect("valid");
// The chunk is the last thing in the container; payload ends exactly
// at container_size.
let chunk = &info.chunks[0];
assert_eq!(
u64::from(chunk.offset) + 8 + u64::from(chunk.size),
u64::from(info.container_size)
);
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(payload.as_slice()));
}
#[test]
fn chunk_payload_truncated_container_slice() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4, 5, 6, 7, 8])]);
let info = inspect_dxbc(&blob).expect("valid");
// Pass a slice shorter than container_size.
let short = &blob[..blob.len() - 4];
assert_eq!(info.chunk_payload(short, b"SFI0"), None);
}
#[test]
fn chunk_payload_first_duplicate_wins() {
let first = [0x11, 0x22];
let second = [0x33, 0x44, 0x55];
let blob = build_synthetic_dxbc(&[(b"SFI0", &first), (b"SFI0", &second)]);
let info = inspect_dxbc(&blob).expect("valid");
assert_eq!(info.chunks.len(), 2);
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(first.as_slice()));
}
}
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff. Show more