Compare commits

..
Author SHA1 Message Date
ates 6e0b882691 Scripted input and assert stepping for unattended target-build runs
GameInput: BX_INPUT_SCRIPT presses gamepad buttons at given seconds,
without window focus, so an unattended run gets past screens that wait
for input. bx_runtime_veh: BX_CONTINUE_ASSERTS=1 steps over an int3 in
the title's own executable instead of letting it reach the crash
reporter, logging each address once and keeping the thread's last-error
value. Both are off unless set and documented with the other offline-run
diagnostics.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:24:10 +03:00
Ateş 6c52bfb030 Merge pull request #711 from MacosPorters/track-a/ghidra-results-required
[Process] Require the Ghidra results; check for existing work before any game problem
2026-11-30 04:09:42 +03:00
ates 6059d701e2 Require the Ghidra results; check for existing work before any game problem
The target build, the GDK and the target build's Ghidra results are a
hard requirement: preflight adds a Ghidra results row (present and
covering the target executable), setup --ghidra-results and --find save
them, and an agent lacking any of the three does not work on the repo.

Before investigating any problem the game shows, agents search open and
merged pull requests and open issues, and work on a covering pull
request's branch instead of writing a second fix.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:09:18 +03:00
Ateş d0a1c21a4e Merge pull request #710 from MacosPorters/track-c/gdk-xg-texture-layouts
[Picture] Console texture layouts and BCPack from the GDK's own libraries (ADR 0010)
2026-11-30 04:01:48 +03:00
ates 4fde342db1 Use the GDK's own texture libraries at run time (ADR 0010)
bx-cli run stages the configured GDK's xg_xs.dll and BCPack.dll for the
target build (recognised by their exports, never committed), and names
the decoder to XCRDAPI.dll. d3d12_xs answers GetResourceAllocationInfo
for console texture layouts with the GDK's XG size and alignment and
enables XG's exclusive locking at device creation. Conformance tests
keep BetterXen's own shims; test_d3d12_gdk_xg_sizes checks the d3d12_xs
side with a stand-in XG library.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:01:10 +03:00
Ateş a17edafe3b Merge pull request #709 from MacosPorters/track-b/storage-page-timing-zlib-bcpack
[Picture] DirectStorage: page arrays filled after enqueue, partial zlib reads, BCPack
2026-11-30 03:44:33 +03:00
ates 3cd97c3cc0 xcrdapi: map page destinations when the request runs, deliver partial zlib reads, decode BCPack via the GDK
A title can fill a DestinationIsPhysicalPages request's page array after
EnqueueRequest returns; the array is now read when the request runs.
A zlib request may ask for the first part of a longer block: the whole
stream is decoded and checked and its first DestinationSize bytes are
delivered. BCPack requests are decoded with the GDK's own BCPack.dll
when BX_BCPACK_DLL names it, and stay refused otherwise.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 03:44:01 +03:00
Ateş c504eb8fc8 Merge pull request #701 from 1Bartosz/track-c/get-frame-statistics-x
[Boot] unimplemented XboxDevice slot 81 (GetFrameStatisticsX)
2026-11-30 03:37:51 +03:00
Ateş 0f9a6e1e11 Merge pull request #692 from 1Bartosz/track-a/console-mode-registry
[Boot] exit status 3: the build reads the console type from the registry (ConsoleMode)
2026-11-30 03:37:25 +03:00
ates e24fa6d42f Merge remote-tracking branch 'origin/main' into pr692-r
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-30 03:37:12 +03:00
Ateş c46611ff9d Merge pull request #704 from MacosPorters/track-e/keyboard-gameinput
[Picture] GameInput: expose a keyboard-backed controller
2026-11-30 03:37:01 +03:00
ates 15b11b4be8 Merge remote-tracking branch 'origin/main' into pr701-r
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	shims/d3d12_xs/tools/gen_xbox_tables.py
2026-11-30 03:36:21 +03:00
Bartosz Szczepański 23f73ee906 bx-cli: match --profile without regard to case and refuse unknown values
The shims read BX_PROFILE with _stricmp, while ConsoleMode was chosen with an
exact comparison, so --profile Anaconda published 0x60 (Series S) next to
XSystemGetDeviceType 7 (Series X). The value is now normalized to lower case
and anything other than lockhart or anaconda is refused.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 00:04:35 +01:00
Bartosz Szczepański 8d7c3bf66c Merge remote-tracking branch 'origin/main' into track-c/get-frame-statistics-x
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 22:56:56 +01:00
ates 7f241ad170 Merge committed texture sizing into console profile fix
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:21 +03:00
ates 97947085bf Publish ConsoleMode before the guest starts
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:05 +03:00
ates f5aed211b5 Merge tested main into console profile registry fix
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:05 +03:00
Bartosz Szczepański a1fcd96836 d3d12_xs: implement GetFrameStatisticsX
Slot 81 returned E_NOTIMPL. It now answers frame-event (ORIGIN) and present statistics per frame pipeline token for the last 17 frames, in QueryPerformanceCounter ticks, S_FALSE when nothing of the requested types is available and E_INVALIDARG for unknown tokens, invalid type sets and invalid list arrangements, as documented. Types with no host source are never reported.

Test: test_d3d12_frame_statistics_x; 14 of its checks fail on main.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 21:24:31 +01:00
Bartosz Szczepański 26003c37e2 d3d12_xs: claim: implement GetFrameStatisticsX
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 21:20:00 +01:00
Bartosz Szczepański 75f2ed8c3c Merge remote-tracking branch 'origin/main' into track-a/console-mode-registry
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 19:35:31 +01:00
Bartosz Szczepański c4ceadc39e runtime_veh: publish the console type as ConsoleMode in the registry
A title can read the REG_DWORD ConsoleMode under HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM instead of calling XSystemGetDeviceType. Without it the title takes itself for a PC and sizes its memory for Series X, which does not fit the Lockhart budget. bx_runtime_veh.dll now writes 0x60 (Lockhart) or 0x64 (Anaconda) at attach, from the profile XSystemGetDeviceType answers from.

Test: test_console_mode; it fails on main because the key does not exist.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:20:18 +01:00
Bartosz Szczepański 00782e62e9 runtime_veh: claim: publish the console type in the registry
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:13:15 +01:00
36 changed files with 1990 additions and 80 deletions

No files matched your search

+22 -5
View File
@@ -23,13 +23,16 @@ cargo build --locked -p bx-cli && target/debug/bx-cli preflight
| 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` |
| **The Ghidra results of the target build** (the static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable | Found and saved by `bx-cli setup --find` |
| At least 10 GiB of free disk space | Measured |
**The target build, the GDK and the Ghidra results are a hard requirement.** An agent that lacks even one of them does not work on this repository at all: no code, tests, reviews, merges, issues or documentation.
**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. |
| Target build, GDK, Ghidra results | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header, the build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three. |
| `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. |
@@ -37,13 +40,13 @@ cargo build --locked -p bx-cli && target/debug/bx-cli preflight
- 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).
- `setup --find` reports that the target build, the GDK or the Ghidra results covering the build are 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.
In those cases stop and do not work around it: no fixes, tests, reviews, merges or documentation "for someone else to verify". Work here is found by running the target build, located in the Ghidra results and checked against the GDK; an agent without all three 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).
`bx-cli setup` remembers the three 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`, `BX_GDK_ROOT` and `BX_GHIDRA_RESULTS` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build, the GDK or the Ghidra results into a commit, issue or pull request (Section 6).
### Step 2 — Pick exactly one thing, in this order
@@ -75,6 +78,19 @@ Take the first that applies.
### Step 3 — Work one blocker
**Before touching any problem the game shows you, find out whether someone already has it.** This applies every time: to the blocker you picked, and to every further problem you meet along the way (a failed load, a refused request, an assert, a crash). Search by the log event, stub symbol, error code and the files you would change:
```sh
gh pr list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,headRefName
gh pr list --repo MacosPorters/betterxen --state merged --search "<event, symbol or file>" --limit 10 --json number,title,mergedAt
gh issue list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,labels
```
- **An open pull request covers it:** check out that branch (`gh pr checkout <n>`), run the build with it, and work there: report what you saw on the pull request, and push a fix to its branch or request changes. Do not write a second fix.
- **A merged pull request covers it:** sync with `origin/main` and run again before investigating.
- **An issue covers it:** take it up from the issue's notes, and link it from your pull request.
- **Nothing covers it:** carry on with step 1 below.
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.
@@ -99,6 +115,7 @@ Take the first that applies.
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
- **GDK texture libraries (ADR 0010):** Console texture layouts (tiling) and BCPack decompression come from the GDK's own PC libraries, `xg_xs.dll` and `BCPack.dll`, which `bx-cli run` stages for the target build from the configured GDK. Do not reimplement them, and never commit or ship them.
---
@@ -156,7 +173,7 @@ _Reserved — policy migration in progress._
## 7. Claiming, Git Safety & Changelog
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.
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. Every problem met while running the game, not only the one picked, is searched for in open and merged pull requests and open issues before it is investigated; when a pull request covers it, check that branch out and work there (Section 0, Step 3). 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-<slug> -b track-<a..f>/<slug> origin/main
+18
View File
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- **Check for existing work before investigating any problem the game shows** (AGENTS.md Section 0 Step 3 and Section 7, `docs/process/working-method.md`). Every problem met while running the game, not only the picked blocker, is searched for in open and merged pull requests and open issues by its log event, stub symbol, error code and files. An open pull request that covers it is checked out and worked on, never duplicated. Prompted by a duplicate fix for physical-page DirectStorage requests made alongside #707.
- **The Ghidra results of the target build are required to work on the repository**, like the target build and the GDK (AGENTS.md Section 0, `docs/process/working-method.md`). An agent that lacks any of the three does not work on the repository. `bx-cli preflight` adds a `Ghidra results` row: present, and covering the configured target build's executable. `bx-cli setup --ghidra-results <dir>` saves them, and `setup --find` finds them by layout (`RUN_REPORT.md`, `decompiled/`, `exports/*/manifest.json` naming the program, `functions.csv`). `BX_GHIDRA_RESULTS` overrides the setting for one command. Unit tests cover an unset setting, a folder that isn't a results folder, results for another program, and results covering the target.
- **Roadmap, Picture stage: BetterXen writes its own shader translator** (repository owner's decision, 2026-11-29). The step that said to vendor the upstream GFX10-to-DXIL translator now describes a translator of our own in `shader-transpiler/`: one rule per instruction, control flow as numbered blocks, each rule checked against the console compiler.
- **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.
@@ -27,6 +29,15 @@ remains unsupported.
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
### Added
- **Unattended runs get past input screens and continuable asserts** (`docs/testing/target-build-review.md`, Diagnostics).
- **`GameInput.dll`:** `BX_INPUT_SCRIPT=A@40,DOWN@50.5,...` presses gamepad buttons at given seconds after the first reading, each for 300 ms, without window focus. Each press, and each entry it cannot read, is logged (`input_script`).
- **`bx_runtime_veh.dll`:** `BX_CONTINUE_ASSERTS=1` steps over an `int3` in the title's own executable instead of letting it reach the crash reporter, and logs each address once (`assert_continued`). An `int3` anywhere else is left alone.
- **Tests:** `test_gameinput_script` (readings at fixed times carry exactly the scripted buttons, and unreadable entries are skipped) and `test_veh_continue_asserts` (the executable's `int3` is stepped over twice; one outside any module is not). Both fail on `main`'s shims and pass twice with these.
- **The GDK's texture libraries at run time (ADR 0010).** Console texture layouts and BCPack come from the GDK's own PC libraries instead of being reimplemented.
- **`bx-cli run`** stages the configured GDK's `xg_xs.dll` (in place of the `xg_xs` shim) and `BCPack.dll` (named to `XCRDAPI.dll` through `BX_BCPACK_DLL`) when the executable is the configured target build, or with `--gdk-libraries`; `--no-gdk-libraries` turns it off. The libraries are recognised by their exports (`gdk_libs.rs`), copied into a temporary shim folder for the run, and never committed. Conformance tests keep BetterXen's own shims.
- **`d3d12_xs.dll`** answers `GetResourceAllocationInfo`, `GetResourceAllocationInfo1` and `GetResourceAllocationInfo2` for console texture layouts (`Layout >= 0x100`) with the GDK's XG size and base alignment (`gdk_xg.cpp`), other descriptions with the host's answer, laid out in order at their alignments. It enables XG's exclusive locking at device creation, since the title and the shim both create XG texture computers. Without the GDK's XG, sizes stay as before and the run log says so (`gdk_xg`).
- **Tests:** `test_d3d12_gdk_xg_sizes` loads a stand-in XG library with answers the test computes (not Microsoft's code) and checks the sizes, alignments, the two-description layout and the locking. On the previous `d3d12_xs.dll` 6 checks fail; with this change it passes twice. `bx-cli` unit tests cover recognising the libraries by their exports and merging them beside the shims.
- **Measured** on the target build (Apple Silicon, CrossOver 26.3, offline, scripted input): the launcher staged both libraries; XG answered 48 console-layout size queries; with #709, 0 page-destination errors, 0 zlib failures and 0 refused BCPack requests. 14 partial reads of compressed blocks remain, so the allocation size is not the only place the title gets a short size (#708 stays open).
- `GameInput.dll` exposes one keyboard-backed gamepad through v0 blocking enumeration and current readings. Enter or Space maps to A, Escape or Backspace to B, arrow keys to the D-pad, WASD and IJKL to the two sticks, Q/E to shoulders, Z/C to triggers, F/H to stick clicks, X/Y to the matching face buttons, and P/Tab to Menu/View. Input returns to neutral when another application owns the foreground.
- **D3DMetal capability checks for translated console shaders** (#671). `test_d3dmetal_translator_caps` measures, against the host D3D12 runtime, the features a translator of console code needs: SM 6.6 descriptors fetched by index (UAV, raw and typed SRVs, texture and sampler) run correctly; a 64-lane wave emulated over a 64-thread group gives the 64-lane answers through groupshared memory and through merged 32-lane host waves; amplification and mesh shaders draw correctly. With the 64-bit atomic results of `test_d3dmetal_gpu_limits` (native 64-bit atomics are not run even though D3DMetal reports support; the lock emulation with a 1024 cap is exact), no need is blocked. Results are in [D3DMetal GPU limits](docs/research/d3dmetal-gpu-limits.md#capability-checks-for-translated-console-shaders-671).
- `xgameruntime.dll` serves `XGameSaveGetContainerInfo` (slot 13) and `XGameSaveEnumerateContainerInfoByName` (slot 15) on `IXGameSaveImpl` (#667). `XGameSaveGetContainerInfo` reads container metadata without loading blob payloads and, when the named container does not exist, succeeds without invoking the callback (source rank 3 inference). `XGameSaveEnumerateContainerInfoByName` filters containers by name prefix (treating `nullptr` or empty prefix as all containers), sorts by name, and stops early when the callback returns `false`. `test_xgameruntime_saves` checks both slots through `QueryApiImpl`.
@@ -93,6 +104,12 @@ remains unsupported.
- `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`: physical-page destinations are mapped when the request runs, partial reads of compressed blocks are delivered, and BCPack requests can be decoded.**
- **Page array timing:** a title can fill the `DestinationPageArray` of a `DestinationIsPhysicalPages` request after `EnqueueRequest` returns. #707 read the array at enqueue, so such requests failed (in the target build, about 290 per run named page 0). The array is now read, and its pages mapped, when the request runs; they are unmapped once it is fulfilled.
- **Partial compressed reads:** a title may ask for only the first `DestinationSize` bytes of a zlib block (in the target build, 8 to 128 KiB blocks read 4 to 16 KiB at a time; 16 failures per run). The whole stream is decoded, its Adler-32 checked, and its first `DestinationSize` bytes delivered; a stream shorter than the destination is still an error. Logged as `dstorage_zlib_partial`.
- **BCPack:** a request with `BcpackMode` 1 to 7 is decoded with `BCPackDecompress` from the GDK's own `BCPack.dll` when `BX_BCPACK_DLL` names it (the collaborator's GDK; nothing from the GDK is shipped). Without it, or combined with zlib, BCPack stays refused with `E_NOTIMPL`. Logged as `bcpack_codec` and `dstorage_bcpack_failed`.
- **Tests:** `test_xcrdapi_page_destination` (24 checks) adds a page array filled after `EnqueueRequest` and a 4096-byte zlib destination from a 136000-byte stream (exact first part, nothing written past it). Both fail on the previous shim (4 checks) and pass twice with this one. BCPack needs the GDK's decoder, so it is not covered by a conformance test.
- **`GetFrameStatisticsX` is implemented** (#701). Slot 81 of the Xbox device table returned `E_NOTIMPL`, which the documented method never returns. It now answers as the authorized GDK documentation describes: frame-event (ORIGIN: wait call, signal and wait return) and present (PresentX call and return) statistics per frame pipeline token for the last 17 frames, in QueryPerformanceCounter ticks; `S_FALSE` when none of the requested types is available; `E_INVALIDARG` for unknown tokens, invalid type sets and invalid list arrangements. Interval, power-scaling, render, display and input statistics have no host source and are never reported; `GPUProcessTime` is 0 (not measured). Test: `test_d3d12_frame_statistics_x`.
- **`CreateCommittedResourceX` is implemented** (#696). Slot 76 of the Xbox device table takes a `D3D12XBOX_RESOURCE_DESC`, which is the PC resource description followed by `DccOptions` (authorized GDK header). It now creates the resource from the PC part through the same path as `CreateCommittedResource` (console format translation, the `XMemAlloc` request a title's hook sees); `DccOptions` (a struct of `CompressionLevel` and `ColorTransform`), console colour compression, has no host counterpart; both fields are logged for the first 8 calls and ignored. Until now the slot returned `E_NOTIMPL`, and the target build exited with status 99 about a second after it was refused. `tools/gen_xbox_tables.py` routes the slot to the new entry point; the regenerated table differs only there. Test: `test_d3d12_committed_resource_x`.
- `xmem.dll!XMemGetWorkingSetStatistics` takes the documented `(WorkingSetFlags, Statistics)` and fills the documented 120-byte `XMEM_WORKING_SET_STATISTICS` (source: the authorized GDK header). Before, it took `(out_stats, stats_size)` and wrote BetterXen's own 32-byte `bx_xmem_stats_t`. A title calling it as documented had its flags read as the output address and its structure pointer as the size, and the shim zeroed memory at the flags value. A project-authorized target build calls it on a tools-memory path with the tools and kernel-pool flags and treats `FALSE` as fatal; runs have not reached that path yet.
- **Values:** the whole structure is written, whatever the flags. `GameLimit` is the title cap, `GameUsed` everything the cap counts (XMem heap, virtual commits, physical pages and external charges), `GameUsedPeak` its highest value and `GameAllocatedPhysicalPageCount` the 64 KiB physical pages. The tools fields are 0, since `XMemIsToolsMemAvailable` is `FALSE`. The counters the host does not have or xmem does not count are 0 (stack, GPU-optimal bandwidth, kernel pool, DirectStorage, frame-preserve buffer, page tables), and so are the reserved words. These values are BetterXen's inference.
@@ -104,6 +121,7 @@ remains unsupported.
- **`d3d12_xs.dll`: console rectangle lists are drawn.** `D3D_PRIMITIVE_TOPOLOGY_RECTLIST` (17) and the pipeline topology type `D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT` (19) are Xbox extensions (GDK `d3d12_xs.h`): three vertices per rectangle, the fourth corner `v0 + v2 - v1`. The host knew neither value, so a title's full-screen passes drew half a rectangle or nothing. A rectangle list is now drawn as triangle strips (`rect_list.cpp`): the pipeline is created with the triangle type, and a non-indexed draw builds four vertices per rectangle from the title's vertex data and the pipeline's input layout. Indexed rectangle lists and quad lists are not emulated and are logged as unimplemented. Test: `test_d3d12_rect_list` (25 checks, pixel readback).
- **`bx_runtime_veh.dll`: a CLWB range loop completes in one exception.** A title flushes an address range with `clwb [reg]; add reg, 0x40; cmp reg, <reg64>; jbe|jb`; each CLWB trapped under Rosetta, about 94,000 exception round trips per 6 MiB buffer. CLWB changes no register, flag or memory, so the handler now advances the pointer register to the last value the loop would have used and the title's own add/cmp/jcc leaves the loop. Other forms keep the per-instruction path. Test: `test_veh_clwb_loop` (15 checks; without the fix the four loop cases take one exception per line).
- **Committed render targets request the console's size from XMemAlloc** (#695). The console lays out a 2D render-target or unordered-access texture with one mip and one sample in 64 KB tiles (64KB_R_X for every size: 128x128 elements at 4 bytes, 128x64 at 8, 64x64 at 16, 256x128 at 2, 256x256 at 1; authorized GDK XG library), and a title that hooks XMemAlloc sizes its pool for those requests and asserts that less than 2 MB is left over. `d3d12_xs.dll` requested the host's size instead, 1920x1080 RGBA8 as 128 pages where the console takes 135, and on the Series S path the target build stopped on that assertion. The XMemAlloc request for those textures is now the tile size, computed from the title's format; every other resource keeps the host's size, and XG's render-target compression metadata after the tiles (8 KB to 96 KB in the cases measured) is not modelled. `GetResourceAllocationInfo` still answers with the host's size. Test: `test_d3d12_committed_tile_size`.
- **The console type is published where a title reads it** (#692). A title can read the REG_DWORD `ConsoleMode` under `HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM` instead of calling `XSystemGetDeviceType`: 0x60 is Series S, 0x64 Series X and 0x68 the Scarlett devkit, and without the value the title takes itself for a PC and sizes its memory for Series X. Wine has no such value, so under the Lockhart profile the target build asked for its Series X memory set and stopped on the 8 GiB budget. `bx-cli run` writes the value in the selected Wine environment before launching the guest, using the same profile as `XSystemGetDeviceType` (0x60 for Lockhart, 0x64 for Anaconda). `--profile` is matched without regard to case, as the shims match `BX_PROFILE`, and a value other than `lockhart` or `anaconda` is refused, so the two cannot name different consoles. The test `test_console_mode` reads it the way the title does and checks it against the profile and `XSystemGetDeviceType`.
- **XCRDAPI holds an xmem guard while accessing title memory** (#668). Replacing a mapped view on Windows or Wine can temporarily make pages in that view inaccessible. DirectStorage reads and writes that can touch title memory now hold the shared guard while xmem mapping and freeing operations hold it exclusively. A loaded xmem DLL without both guard exports produces a warning. The guard covers DirectStorage accesses through BetterXen. `test_xcrdapi_remap_guard` exercises memory-to-memory stores into a window, zlib streams inflated into it and memory requests reading out of it while it is remapped; accesses by the title's own threads are not covered.
- **`d3d12_xs.dll`: an index or vertex binding at a title address without a host buffer no longer crashes the process.** A title binds index and vertex data by address in plain title memory, with no Direct3D resource behind it. The address reached D3DMetal unchanged and it read through a null buffer (`IASetIndexBuffer`). Such a binding is now left empty and logged as unimplemented (`IASetIndexBuffer(title memory without a host buffer)`, likewise `IASetVertexBuffers`); bindings inside resources BetterXen created are translated as before. Supplying the data is separate work. Test: `test_d3d12_unbacked_buffers` (13 checks; without the fix it dies with the same null read).
- **`d3d12_xs.dll`: console-only DXGI formats and depth-stencil unordered-access views no longer end the process.** The Xbox Series `DXGI_FORMAT` enumeration has values the PC one lacks (116-120, 189, 190; GDK `d3d12_xs.h`). D3DMetal turns one into an invalid Metal pixel format and Metal aborts, which a target build's crash reporter then turned into either "exit status 5" or a stall with every thread stopped.
+1
View File
@@ -17,6 +17,7 @@
- [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 0010: The GDK's texture libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), staged by `bx-cli run` for the target build from each machine's GDK; never reimplemented, committed or shipped.
- [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
+29
View File
@@ -0,0 +1,29 @@
# ADR 0010: The GDK's texture libraries at run time
Status: **Accepted** (2026-11-30, by the repository owner). The evidence is from local Apple Silicon runs by the implementer.
## Context
Console textures differ from PC textures in two ways that BetterXen had no answer for:
- **Tiled layouts.** A console texture carries a swizzle layout (`D3D12XBOX_TEXTURE_LAYOUT`, `0x100 | XG_SWIZZLE_MODE`; most of the target build's textures use the 4 KB "S" mode). A title sizes its placements and loads from the layout, and the bytes arrive tiled. BetterXen's `xg_xs` shim answers every layout as linear, so sizes were too small (#708) and textures could not be uploaded.
- **BCPack.** Texture data in the target build's archives is BCPack-compressed (`DSTORAGE_BCPACK_MODE` 1 to 7). There is no public specification of the format. `XCRDAPI.dll` refused those requests (34 per run).
The GDK the project is authorized to use contains Microsoft's **PC builds** of both: the XG library (`xg_xs.dll`, which computes layouts and copies between tiled and linear data) and the BCPack decoder (`BCPack.dll`). Both are pure computation, with only standard Windows imports, and load under CrossOver. Measured on the target build with them in place: the GDK's XG answers the device's console-layout size queries, detiling through it produced the first real image of the title's menu artwork, and BCPack requests decode.
Reimplementing either would mean deriving the console's tiling rules and the BCPack format from observation, with the result only ever approximating Microsoft's.
## Decision
1. **Use Microsoft's libraries at run time; do not reimplement them.** `bx-cli run` stages the GDK's `xg_xs.dll` in place of BetterXen's shim and `BCPack.dll` beside it, and names the decoder to `XCRDAPI.dll` through `BX_BCPACK_DLL` (`launcher/crates/bx-cli/src/gdk_libs.rs`). `d3d12_xs` uses the XG library when it is the loaded `xg_xs.dll` (`shims/d3d12_xs/gdk_xg.cpp`).
2. **From each machine's own GDK.** The libraries come from the GDK configured by `bx-cli setup`, which preflight already requires. They are found by their exports, not their place in the GDK.
3. **Never committed or shipped**, unless the project records an authorization that covers redistributing them. Commits name only the documented interfaces (`XGCreateTextureComputer`, `BCPackDecompress`, ...), as with every other GDK contract.
4. **Only for the target build.** Conformance tests check BetterXen's own shims, so the GDK's libraries are staged only when the executable is the configured target build, or with `--gdk-libraries`. `--no-gdk-libraries` turns them off.
5. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
## Consequences
- Correct console layouts and BCPack decoding now, without a reverse-engineering effort for either.
- Running the title needs the GDK on the machine. Preflight already requires it.
- Conformance tests cannot call Microsoft's libraries in CI. Tests cover BetterXen's side of the contract with stand-ins whose answers the test computes (`test_d3d12_gdk_xg_sizes`). Microsoft's results are exercised on machines with the GDK.
- Agents need no special knowledge: the target build's run protocol stages the libraries automatically, and `CLAUDE.md` Section 1 says not to reimplement them.
+12 -8
View File
@@ -2,7 +2,7 @@
**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?*
BetterXen is built by collaborators who each have the project-authorized target build, the GDK and the target build's Ghidra results, 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.
@@ -13,11 +13,14 @@ No agent works without all of these. `bx-cli preflight` checks them and fails if
- 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;
- **the Ghidra results of the target build**: the static-analysis run (`RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable;
- 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.
The target build, the GDK and the Ghidra results are a hard requirement: an agent that lacks even one of them does not work on the repository at all.
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".
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, the target build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three 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, located in the Ghidra results and checked against the GDK. Without all three 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, the GDK or the Ghidra results are 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
@@ -82,11 +85,12 @@ run → signature → draft pull request (the claim) → evidence → smallest f
```
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.
2. **Is it already someone's?** Before investigating any problem the game shows (the picked blocker or one met along the way), search open and merged pull requests and open issues for its log event, stub symbol, error code and the files a fix would touch. If an open pull request covers it, check that branch out, run with it and work there. If a merged one does, sync and run again. On 2026-11-30 a session fixed physical-page DirectStorage requests in parallel with an open pull request for the same problem (#707), and found the overlap only afterwards.
3. **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.
4. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
5. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
6. **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.
7. **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.
+3 -1
View File
@@ -94,7 +94,7 @@ sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null
# 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 \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 BX_PRESENT_DUMP='Z:\<frames folder>' BX_INPUT_SCRIPT=A@40,A@50 \
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>
@@ -116,6 +116,8 @@ All switches are off unless set, and none changes behaviour beyond what its row
| `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 |
| `BX_INPUT_SCRIPT=<presses>` | `GameInput` | Scripted gamepad presses for unattended runs, without window focus: comma-separated `BUTTON@SECONDS` (`A@40,DOWN@50.5,A@52`), each held 300 ms, timed from the first gamepad reading. Buttons `MENU VIEW A B X Y UP DOWN LEFT RIGHT`. Each press is logged (`input_script`), and so is each entry that cannot be read |
| `BX_CONTINUE_ASSERTS=1` | `bx_runtime_veh` | Steps over an `int3` in the title's own executable (a continuable assert) instead of letting it reach the title's crash reporter. Each address is logged once (`assert_continued`), so the report still lists every assert. Use it to get past a known assert to the next blocker, and say so in the evidence |
Their output can contain title addresses and file names, so it goes only into the private evidence store.
+184
View File
@@ -0,0 +1,184 @@
//! The GDK's own texture libraries, staged for runs of the target build (ADR 0010).
//!
//! Console textures use tiled layouts and BCPack compression. BetterXen does not reimplement
//! either: a run of the target build loads Microsoft's PC builds of the GDK's XG library
//! (`xg_xs.dll`, in place of BetterXen's `xg_xs` shim) and BCPack decoder (`BCPack.dll`, named to
//! `XCRDAPI.dll` through `BX_BCPACK_DLL`) from the GDK configured on this machine. Nothing from
//! the GDK is committed or shipped.
//!
//! The libraries are recognised by what they export, never by their place in the GDK: an
//! x86-64 PE32+ file named `xg_xs.dll` that exports `XGComputeTexture2DLayout` and does not
//! import `xmem.dll` (the console build does), and one named `BCPack.dll` that exports
//! `BCPackDecompress`. Conformance tests keep BetterXen's own shim: the GDK's are staged only
//! for the configured target build, or with `--gdk-libraries`.
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use bx_probe::probe_pe32_plus;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct GdkLibraries {
pub xg: Option<PathBuf>,
pub bcpack: Option<PathBuf>,
}
fn contains(bytes: &[u8], needle: &[u8]) -> bool {
bytes.windows(needle.len()).any(|w| w == needle)
}
/// Whether `bytes` are the PC build of the GDK's XG library.
pub fn is_pc_xg(bytes: &[u8]) -> bool {
let Ok(summary) = probe_pe32_plus(bytes) else {
return false;
};
contains(bytes, b"XGComputeTexture2DLayout\0")
&& contains(bytes, b"XGCreateTextureComputer\0")
&& !summary
.imports
.keys()
.any(|dll| dll.eq_ignore_ascii_case("xmem.dll"))
}
/// Whether `bytes` are the GDK's BCPack decoder.
pub fn is_bcpack(bytes: &[u8]) -> bool {
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"BCPackDecompress\0")
}
/// Finds the two libraries under `root` (bounded depth). When the GDK holds several builds,
/// the first by path order is used, so the choice is the same on every run.
pub fn find(root: &Path) -> GdkLibraries {
let mut xg = Vec::new();
let mut bcpack = Vec::new();
let mut stack = vec![(root.to_path_buf(), 0usize)];
while let Some((dir, depth)) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_dir() {
if depth < 14 {
stack.push((path, depth + 1));
}
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
if name != "xg_xs.dll" && name != "bcpack.dll" {
continue;
}
let Ok(bytes) = fs::read(&path) else {
continue;
};
if name == "xg_xs.dll" && is_pc_xg(&bytes) {
xg.push(path);
} else if name == "bcpack.dll" && is_bcpack(&bytes) {
bcpack.push(path);
}
}
}
xg.sort();
bcpack.sort();
GdkLibraries {
xg: xg.into_iter().next(),
bcpack: bcpack.into_iter().next(),
}
}
/// Builds `out` as a copy of the shim folder's files with the GDK's libraries added: its
/// `xg_xs.dll` replaces BetterXen's shim, and `BCPack.dll` sits beside it. Returns the path of
/// the staged `BCPack.dll`, when there is one.
pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<Option<PathBuf>> {
fs::create_dir_all(out)?;
for entry in fs::read_dir(shims)? {
let entry = entry?;
if entry.file_type()?.is_file() {
fs::copy(entry.path(), out.join(entry.file_name()))?;
}
}
if let Some(xg) = &libs.xg {
fs::copy(xg, out.join("xg_xs.dll"))?;
}
match &libs.bcpack {
Some(bcpack) => {
let staged = out.join("BCPack.dll");
fs::copy(bcpack, &staged)?;
Ok(Some(staged))
}
None => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A minimal x86-64 PE32+ image with no sections, followed by `tail`. Import tables are
/// not modelled, so "imports xmem.dll" is covered by `is_pc_xg` on a real probe only.
fn pe(tail: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 0x200];
b[0..2].copy_from_slice(b"MZ");
b[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
b[0x40..0x44].copy_from_slice(b"PE\0\0");
b[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes()); // machine
b[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // SizeOfOptionalHeader
b[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes()); // PE32+
b[0x58 + 108..0x58 + 112].copy_from_slice(&16u32.to_le_bytes()); // NumberOfRvaAndSizes
b.extend_from_slice(tail);
b
}
#[test]
fn recognises_the_libraries_by_their_exports() {
assert!(is_pc_xg(&pe(
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
)));
// BetterXen's own shim exports only what titles import.
assert!(!is_pc_xg(&pe(
b"XGCreateTextureComputer\0XGSuggestSwizzleMode\0"
)));
assert!(!is_pc_xg(
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
));
assert!(is_bcpack(&pe(b"BCPackCompress\0BCPackDecompress\0")));
assert!(!is_bcpack(&pe(b"BCPackCompress\0")));
}
#[test]
fn finds_by_content_and_merges_beside_the_shims() {
let root = std::env::temp_dir().join(format!("bx-gdk-libs-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let gdk = root.join("gdk");
fs::create_dir_all(gdk.join("a/b")).unwrap();
fs::create_dir_all(gdk.join("c")).unwrap();
fs::write(
gdk.join("a/b/xg_xs.dll"),
pe(b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"),
)
.unwrap();
fs::write(gdk.join("c/xg_xs.dll"), pe(b"XGCreateTextureComputer\0")).unwrap(); // not the PC library
fs::write(gdk.join("c/BCPack.dll"), pe(b"BCPackDecompress\0")).unwrap();
let libs = find(&gdk);
assert_eq!(libs.xg, Some(gdk.join("a/b/xg_xs.dll")));
assert_eq!(libs.bcpack, Some(gdk.join("c/BCPack.dll")));
let shims = root.join("shims");
fs::create_dir_all(&shims).unwrap();
fs::write(shims.join("xg_xs.dll"), b"shim").unwrap();
fs::write(shims.join("d3d12_xs.dll"), b"d3d12").unwrap();
let out = root.join("out");
let staged = merge_shims(&shims, &libs, &out).unwrap();
assert_eq!(staged, Some(out.join("BCPack.dll")));
assert_eq!(fs::read(out.join("d3d12_xs.dll")).unwrap(), b"d3d12");
assert_eq!(
fs::read(out.join("xg_xs.dll")).unwrap(),
fs::read(gdk.join("a/b/xg_xs.dll")).unwrap()
);
assert_eq!(fs::read(shims.join("xg_xs.dll")).unwrap(), b"shim");
let _ = fs::remove_dir_all(&root);
}
}
+338 -28
View File
@@ -1,6 +1,7 @@
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
mod drives;
mod gdk_libs;
mod stage;
mod supervise;
@@ -10,7 +11,7 @@ use std::fmt::Write as _;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::process::{Command, ExitCode, Stdio};
use std::time::{Duration, Instant};
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
@@ -26,6 +27,11 @@ ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1
/// Accepted `--backend` values. CrossOver ignores an unknown value silently, so one is refused.
const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"];
/// Accepted `--profile` values. The shims compare `BX_PROFILE` without regard to case and take
/// anything but "anaconda" for Lockhart, while `ConsoleMode` is chosen here, so the value is
/// normalized and an unknown one is refused instead of the two disagreeing.
const PROFILES: [&str; 2] = ["lockhart", "anaconda"];
const SAFE_CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
const HOST_ENV_ALLOWLIST: &[&str] = &[
@@ -63,12 +69,12 @@ fn usage_text() -> &'static str {
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] Remember where the target build and the GDK are on this machine (saved outside the repository); --find searches the home folder for them\n\
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, disk space. Fails if anything is missing\n\
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] Remember where the target build, the GDK and the target build's Ghidra results are on this machine (saved outside the repository); --find searches the home folder for them\n\
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, the Ghidra results, disk space. Fails if anything is missing\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli report <log.jsonl>... Run report per log (one log = one run), then a summary with blocker signatures\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)] [--gdk-libraries | --no-gdk-libraries]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix; the GDK's XG and BCPack libraries are staged for the configured target build)\n"
}
fn run_capture(program: &str, args: &[&str]) -> Option<String> {
@@ -233,6 +239,57 @@ fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -
const TARGET_EXE_KEY: &str = "target_exe";
const GDK_ROOT_KEY: &str = "gdk_root";
const GHIDRA_RESULTS_KEY: &str = "ghidra_results";
/// The static-analysis results of the target build, recognised by structure: a folder with the
/// run's `RUN_REPORT.md`, a `decompiled/` folder, and `exports/<program>/` folders each holding a
/// `manifest.json` (naming the program) and a `functions.csv`.
const GHIDRA_REPORT: &str = "RUN_REPORT.md";
/// The `"program"` value of an exports manifest, read without a JSON parser.
fn manifest_program(text: &str) -> Option<String> {
let rest = &text[text.find("\"program\"")? + "\"program\"".len()..];
let rest = rest
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
Some(rest[..rest.find('"')?].to_owned())
}
/// The programs a Ghidra results folder covers, or `None` when it is not one.
fn ghidra_programs(root: &Path) -> Option<Vec<String>> {
if !root.join(GHIDRA_REPORT).is_file() || !root.join("decompiled").is_dir() {
return None;
}
let mut programs = Vec::new();
for entry in fs::read_dir(root.join("exports")).ok()?.flatten() {
let dir = entry.path();
if !dir.join("functions.csv").is_file() {
continue;
}
if let Some(program) = fs::read_to_string(dir.join("manifest.json"))
.ok()
.and_then(|text| manifest_program(&text))
{
programs.push(program);
}
}
(!programs.is_empty()).then_some(programs)
}
/// Whether the results cover the executable at `target` (by its file name, compared on this
/// machine only).
fn ghidra_covers(root: &Path, target: &Path) -> bool {
let Some(name) = target
.file_name()
.map(|n| n.to_string_lossy().to_ascii_lowercase())
else {
return false;
};
ghidra_programs(root)
.is_some_and(|programs| programs.iter().any(|p| p.to_ascii_lowercase() == name))
}
/// An Xbox Series title's executable is recognised by structure, never by name: a large PE32+
/// file that imports the console's D3D12 library. BetterXen's own test executables import it
@@ -273,6 +330,7 @@ fn gdk_root_for(home: &Path, header: &Path) -> Option<PathBuf> {
struct Found {
gdk_roots: Vec<PathBuf>,
target_exes: Vec<PathBuf>,
ghidra_results: Vec<PathBuf>,
/// The search gave up before visiting everything.
truncated: bool,
}
@@ -318,7 +376,13 @@ fn search_for_materials(home: &Path) -> Found {
stack.push((path, depth + 1));
}
} else if kind.is_file() {
if name_text == GDK_MARKER {
if name_text == GHIDRA_REPORT {
if let Some(dir) = path.parent()
&& ghidra_programs(dir).is_some()
{
found.ghidra_results.push(dir.to_path_buf());
}
} else if name_text == GDK_MARKER {
if let Some(root) = gdk_root_for(home, &path)
&& !found.gdk_roots.contains(&root)
&& check_gdk_root(root.to_str()).is_ok()
@@ -335,6 +399,7 @@ fn search_for_materials(home: &Path) -> Found {
}
found.gdk_roots.sort();
found.target_exes.sort();
found.ghidra_results.sort();
// The GDK ships tools that import the same library; they are not titles.
let roots = found.gdk_roots.clone();
found
@@ -409,7 +474,12 @@ fn distinct_builds_by(candidates: Vec<PathBuf>, siblings: impl Fn(&Path) -> usiz
fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
let need_target = check_target_exe(config.get(TARGET_EXE_KEY).map(String::as_str)).is_err();
let need_gdk = check_gdk_root(config.get(GDK_ROOT_KEY).map(String::as_str)).is_err();
if !need_target && !need_gdk {
let need_ghidra = check_ghidra_for_target(
config.get(GHIDRA_RESULTS_KEY).map(String::as_str),
config.get(TARGET_EXE_KEY).map(String::as_str),
)
.is_err();
if !need_target && !need_gdk && !need_ghidra {
return false;
}
let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
@@ -417,7 +487,7 @@ fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
return false;
};
println!(
"Searching the home folder for the GDK and the target build (this can take a minute)..."
"Searching the home folder for the GDK, the target build and its Ghidra results (this can take a minute)..."
);
let found = search_for_materials(&home);
let mut changed = false;
@@ -453,6 +523,30 @@ fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
}
}
}
if need_ghidra {
// Results are only useful for the build being worked on: the first that covers it.
let target = config.get(TARGET_EXE_KEY).map(PathBuf::from);
let covering = target
.as_deref()
.and_then(|t| found.ghidra_results.iter().find(|r| ghidra_covers(r, t)));
match (covering, target.is_some(), found.ghidra_results.is_empty()) {
(Some(results), _, _) => {
config.insert(
GHIDRA_RESULTS_KEY.to_owned(),
results.to_string_lossy().into_owned(),
);
changed = true;
println!(" Ghidra results: found and saved");
}
(None, false, _) => {
println!(" Ghidra results: set the target build first, then run --find again")
}
(None, true, true) => println!(" Ghidra results: not found in the home folder"),
(None, true, false) => {
println!(" Ghidra results: found, but none covers the target build")
}
}
}
if found.truncated {
println!(" (the search stopped early: the home folder has too many entries)");
}
@@ -480,6 +574,7 @@ fn cmd_setup(args: &[String]) -> ExitCode {
let (key, check): (&str, SettingCheck) = match args[i].as_str() {
"--target-exe" => (TARGET_EXE_KEY, check_target_exe),
"--gdk-root" => (GDK_ROOT_KEY, check_gdk_root),
"--ghidra-results" => (GHIDRA_RESULTS_KEY, check_ghidra_results),
other => {
eprintln!("error: unknown argument: {other}");
return ExitCode::FAILURE;
@@ -520,6 +615,10 @@ fn cmd_setup(args: &[String]) -> ExitCode {
state(TARGET_EXE_KEY, check_target_exe)
);
println!(" GDK : {}", state(GDK_ROOT_KEY, check_gdk_root));
println!(
" Ghidra results: {}",
state(GHIDRA_RESULTS_KEY, check_ghidra_results)
);
println!("They are kept outside the repository. Run `bx-cli preflight` to check everything.");
ExitCode::SUCCESS
}
@@ -538,6 +637,33 @@ fn check_target_exe(value: Option<&str>) -> Result<String, String> {
}
}
/// The Ghidra results: the setting must be a results folder (see [`ghidra_programs`]).
fn check_ghidra_results(value: Option<&str>) -> Result<String, String> {
let root = value.filter(|v| !v.is_empty()).ok_or(
"not set; run `bx-cli setup --find`, or `bx-cli setup --ghidra-results <folder with RUN_REPORT.md, exports/ and decompiled/>`",
)?;
match ghidra_programs(Path::new(root)) {
Some(programs) => Ok(format!("present ({} programs analysed)", programs.len())),
None => Err("that folder is not a Ghidra results folder (RUN_REPORT.md, exports/*/manifest.json, decompiled/)".to_owned()),
}
}
/// Preflight's view of the Ghidra results: present, and covering the configured target build.
fn check_ghidra_for_target(results: Option<&str>, target: Option<&str>) -> Result<String, String> {
let found = check_ghidra_results(results)?;
match target.filter(|t| !t.is_empty()) {
Some(target)
if ghidra_covers(Path::new(results.unwrap_or_default()), Path::new(target)) =>
{
Ok(found)
}
Some(_) => {
Err("the results do not cover the configured target build's executable".to_owned())
}
None => Err("cannot be matched: the target build is not set".to_owned()),
}
}
/// The GDK: the setting must be a folder that contains the GDK's `d3d12_xs.h`.
fn check_gdk_root(value: Option<&str>) -> Result<String, String> {
let root = value
@@ -588,7 +714,7 @@ fn render_preflight(requirements: &[Requirement]) -> (String, bool) {
"Ready to work.\n"
} else {
"Not ready. Fix what you can yourself (AGENTS.md section 0, step 1): `bx-cli setup --find` for the \
target build and the GDK, Homebrew for missing tools, your own scratch files for disk space. \
target build, the GDK and the Ghidra results, Homebrew for missing tools, your own scratch files for disk space. \
Stop only for what is not on this machine.\n"
});
(out, ready)
@@ -650,6 +776,13 @@ fn cmd_preflight() -> ExitCode {
"GDK",
check_gdk_root(local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config).as_deref()),
),
(
"Ghidra results",
check_ghidra_for_target(
local_setting("BX_GHIDRA_RESULTS", GHIDRA_RESULTS_KEY, &config).as_deref(),
local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config).as_deref(),
),
),
(
"Free disk space",
match free {
@@ -1045,6 +1178,9 @@ struct RunArgs {
inherit_env: bool,
timeout: Option<Duration>,
backend: Option<String>,
/// The GDK's texture libraries (gdk_libs): `Some` when asked for or refused, `None` to use
/// them only for the configured target build.
gdk_libraries: Option<bool>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
@@ -1057,6 +1193,7 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut inherit_env = false;
let mut timeout = None;
let mut backend: Option<String> = None;
let mut gdk_libraries: Option<bool> = None;
let mut i = 0;
while i < args.len() {
@@ -1070,7 +1207,15 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
i += 2;
}
"--profile" if i + 1 < args.len() => {
profile = args[i + 1].clone();
let name = args[i + 1].to_ascii_lowercase();
if !PROFILES.contains(&name.as_str()) {
return Err(format!(
"unknown profile {:?}; use one of {}",
args[i + 1],
PROFILES.join(", ")
));
}
profile = name;
i += 2;
}
"--bottle" if i + 1 < args.len() => {
@@ -1109,6 +1254,14 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
inherit_env = true;
i += 1;
}
"--gdk-libraries" => {
gdk_libraries = Some(true);
i += 1;
}
"--no-gdk-libraries" => {
gdk_libraries = Some(false);
i += 1;
}
other => return Err(format!("unknown argument: {other}")),
}
}
@@ -1133,6 +1286,7 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
inherit_env,
timeout,
backend,
gdk_libraries,
})
}
@@ -1450,6 +1604,7 @@ fn cmd_run(args: &[String]) -> ExitCode {
inherit_env,
timeout,
backend,
gdk_libraries,
} = run;
let cx_root = Path::new("/Applications/CrossOver.app/Contents/SharedSupport/CrossOver");
@@ -1460,8 +1615,62 @@ fn cmd_run(args: &[String]) -> ExitCode {
return ExitCode::FAILURE;
}
let abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
let mut abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
let abs_exe = fs::canonicalize(&exe).unwrap_or(exe);
// The GDK's texture libraries (gdk_libs.rs, ADR 0010): staged for the configured target
// build, or with --gdk-libraries, from the GDK configured on this machine.
let config = local_config_path()
.map(|p| read_local_config(&p))
.unwrap_or_default();
let is_target = local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config)
.and_then(|t| fs::canonicalize(t).ok())
.is_some_and(|t| t == abs_exe);
let mut staged_bcpack: Option<PathBuf> = None;
let mut gdk_shims_dir: Option<PathBuf> = None;
if gdk_libraries.unwrap_or(is_target) {
match local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config) {
Some(root) => {
let libs = gdk_libs::find(Path::new(&root));
let out = env::temp_dir().join(format!("bx-gdk-shims-{}", std::process::id()));
match gdk_libs::merge_shims(&abs_shims, &libs, &out) {
Ok(bcpack) => {
diag(format_args!(
"bx-cli: GDK texture libraries: XG {}, BCPack {}",
if libs.xg.is_some() {
"staged"
} else {
"not found"
},
if bcpack.is_some() {
"staged"
} else {
"not found"
}
));
staged_bcpack = bcpack;
abs_shims = out.clone();
gdk_shims_dir = Some(out);
}
Err(e) => diag(format_args!(
"warning: GDK texture libraries not staged: {e}"
)),
}
}
None => diag(
"warning: GDK texture libraries not staged: no GDK configured (bx-cli setup --find)",
),
}
}
struct RemoveOnDrop(Option<PathBuf>);
impl Drop for RemoveOnDrop {
fn drop(&mut self) {
if let Some(dir) = &self.0 {
let _ = fs::remove_dir_all(dir);
}
}
}
let _gdk_shims_cleanup = RemoveOnDrop(gdk_shims_dir);
let wine_shims_path = unix_to_wine_z_path(&abs_shims);
let resolved_prefix =
@@ -1575,30 +1784,89 @@ fn cmd_run(args: &[String]) -> ExitCode {
None => diag("warning: Xbox drive G: not mapped: the executable has no parent directory"),
}
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()))
.arg(&abs_exe);
c
} else {
let _ = fs::create_dir_all(&resolved_prefix);
let mut c = Command::new(&wineloader);
c.arg(&abs_exe);
c
let guest_command = || {
let mut command = if let Some(ref bname) = bottle {
let mut command = Command::new(&wine_wrapper);
command
.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()));
command
} else {
Command::new(&wineloader)
};
apply_host_env(&mut command, inherit_env);
if bottle.is_none() {
apply_prefix_env(&mut command, cx_root, &resolved_prefix, &wineloader);
}
command.env("WINEDEBUG", "-all");
command
};
apply_host_env(&mut cmd, inherit_env);
if bottle.is_none() {
apply_prefix_env(&mut cmd, cx_root, &resolved_prefix, &wineloader);
if staged_names.iter().any(|name| name == "bx_runtime_veh.dll") {
// This title reads the console profile before it calls any shim entry point.
// Publish the same profile as XSystemGetDeviceType while the prefix is locked.
let mode = if profile == "anaconda" {
"0x64"
} else {
"0x60"
};
let mut registry = guest_command();
registry
.args([
"reg.exe",
"add",
r"HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM",
"/v",
"ConsoleMode",
"/t",
"REG_DWORD",
"/d",
mode,
"/f",
])
.stdout(Stdio::null());
let active = active_time(started.elapsed(), supervise::suspended_time());
let remaining = match guest_time_left(timeout, active) {
Ok(remaining) => remaining,
Err(e) => {
diag(format_args!("timed out before setting ConsoleMode: {e}"));
return ExitCode::from(124);
}
};
match supervise::supervise(registry, remaining, supervise::received_signal) {
Ok(Outcome::Exited(status)) if status.success() => {
diag(format_args!("bx-cli: ConsoleMode={mode} profile={profile}"));
}
Ok(Outcome::Exited(status)) => {
diag(format_args!("warning: could not set ConsoleMode: {status}"));
}
Ok(outcome @ Outcome::Stopped(stop)) => {
let failed = stop_environment(
stop,
cx_root,
&environment_dir,
bottle.as_deref(),
inherit_env,
);
let code = outcome.exit_code();
return ExitCode::from(if failed { code.max(1) } else { code });
}
Err(e) => diag(format_args!("warning: could not set ConsoleMode: {e}")),
}
}
if bottle.is_none() {
let _ = fs::create_dir_all(&resolved_prefix);
}
let mut cmd = guest_command();
cmd.arg(&abs_exe);
cmd.env("ROSETTA_ADVERTISE_AVX", "1")
.env("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES)
.env("WINEPATH", &wine_shims_path)
.env("BX_PROFILE", &profile)
.env("WINEDEBUG", "-all");
.env("BX_PROFILE", &profile);
if let Some(bcpack) = &staged_bcpack {
cmd.env("BX_BCPACK_DLL", unix_to_wine_z_path(bcpack));
}
let abs_log = log_file.map(|lf| {
if lf.is_absolute() {
@@ -2111,12 +2379,16 @@ mod tests {
assert_eq!(run.backend.as_deref(), Some("d3dmetal"));
assert_eq!(run.shims_dir, PathBuf::from("build-shims/bin"));
assert_eq!(run.profile, "lockhart");
// ConsoleMode and BX_PROFILE must name the same console whatever the case.
let mixed = parse_run_args(&args(&["--exe", "a.exe", "--profile", "Anaconda"])).unwrap();
assert_eq!(mixed.profile, "anaconda");
let plain = parse_run_args(&args(&["--exe", "a.exe"])).unwrap();
assert!(plain.timeout.is_none() && plain.bottle.is_none() && plain.prefix.is_none());
for bad in [
&["--exe", "a.exe", "--timeout", "0"][..],
&["--exe", "a.exe", "--timeout", "soon"],
&["--exe", "a.exe", "--backend", "dmxt2"],
&["--exe", "a.exe", "--profile", "scarlett"],
&["--exe", "a.exe", "--bottle", "../x"],
&["--exe", "a.exe", "--timeout"],
&["--bottle", "b"],
@@ -2592,6 +2864,44 @@ sub setup_bottle_wineprefix {
fs::write(dir.join("a/b/include").join(GDK_MARKER), b"// header").unwrap();
assert!(check_gdk_root(dir.to_str()).unwrap().contains("found"));
// Ghidra results: unset, not a results folder, results for another program, results
// covering the target build (matched by its file name, whatever the case).
assert!(check_ghidra_results(None).unwrap_err().contains("not set"));
let results = dir.join("results");
fs::create_dir_all(results.join("exports/other")).unwrap();
assert!(
check_ghidra_results(results.to_str())
.unwrap_err()
.contains("not a Ghidra results folder")
);
fs::create_dir_all(results.join("decompiled")).unwrap();
fs::write(results.join(GHIDRA_REPORT), b"# RUN_REPORT").unwrap();
fs::write(results.join("exports/other/functions.csv"), b"").unwrap();
fs::write(
results.join("exports/other/manifest.json"),
br#"{"program": "other.dll", "rows": {}}"#,
)
.unwrap();
assert!(check_ghidra_results(results.to_str()).is_ok());
assert!(
check_ghidra_for_target(results.to_str(), pe.to_str())
.unwrap_err()
.contains("do not cover")
);
assert!(
check_ghidra_for_target(results.to_str(), None)
.unwrap_err()
.contains("target build is not set")
);
fs::create_dir_all(results.join("exports/t")).unwrap();
fs::write(results.join("exports/t/functions.csv"), b"").unwrap();
fs::write(
results.join("exports/t/manifest.json"),
br#"{"program":"TITLE.exe"}"#,
)
.unwrap();
assert!(check_ghidra_for_target(results.to_str(), pe.to_str()).is_ok());
// One missing requirement makes the whole preflight not ready, and says so.
let (text, ready) = render_preflight(&[
("Target build", Ok("present".to_owned())),
+1
View File
@@ -8,6 +8,7 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
xbox_facade.cpp
frame_pacing.cpp
placed_x.cpp
gdk_xg.cpp
descriptor_heaps.cpp
committed.cpp
console_formats.cpp
+75 -3
View File
@@ -11,6 +11,7 @@
#include "console_formats.h"
#include "xbox_facade.h"
#include "gdk_xg.h"
#include <atomic>
#include <cstdio>
@@ -74,6 +75,68 @@ private:
std::vector<Desc> copy_;
};
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC& d) { return d; }
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC1& d) {
D3D12_RESOURCE_DESC out{};
out.Dimension = d.Dimension;
out.Alignment = d.Alignment;
out.Width = d.Width;
out.Height = d.Height;
out.DepthOrArraySize = d.DepthOrArraySize;
out.MipLevels = d.MipLevels;
out.Format = d.Format;
out.SampleDesc = d.SampleDesc;
out.Layout = d.Layout;
out.Flags = d.Flags;
return out;
}
/* Allocation info for descriptions that include a console texture layout. The console sizes come
from the GDK's XG (gdk_xg.h); other descriptions keep the host's answer, one at a time. The
total follows Direct3D 12: each resource at its alignment, in order; the total alignment is the
largest. Returns false (the host answers everything) when no description has a console layout
or XG is not loaded. */
template <typename Desc>
bool console_allocation(ID3D12Device* device, UINT mask, UINT count, const Desc* descs, D3D12_RESOURCE_ALLOCATION_INFO* total,
D3D12_RESOURCE_ALLOCATION_INFO1* each, const char* method) {
if (!descs || !count || !bx_gdk_xg_available()) return false;
bool any = false;
for (UINT i = 0; i < count && !any; ++i) any = bx_is_console_texture_layout(as_desc(descs[i]));
if (!any) return false;
uint64_t offset = 0, max_alignment = 0;
for (UINT i = 0; i < count; ++i) {
const D3D12_RESOURCE_DESC desc = as_desc(descs[i]);
uint64_t size = 0, alignment = 0;
if (!bx_is_console_texture_layout(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
D3D12_RESOURCE_DESC host = desc;
if (bx_is_console_only_format(host.Format)) host.Format = bx_host_resource_format(host.Format);
if (bx_is_console_texture_layout(host)) host.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
D3D12_RESOURCE_ALLOCATION_INFO one{};
device->GetResourceAllocationInfo(&one, mask, 1, &host);
size = one.SizeInBytes;
alignment = one.Alignment;
} else {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 24) {
char detail[192];
std::snprintf(detail, sizeof(detail), "%s %llux%ux%u mips=%u format=%d layout=0x%x: console size %llu, alignment %llu",
method, static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
static_cast<int>(desc.Format), static_cast<UINT>(desc.Layout), static_cast<unsigned long long>(size),
static_cast<unsigned long long>(alignment));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_allocation", detail);
}
}
if (size == UINT64_MAX || !alignment) return false;
offset = (offset + alignment - 1) / alignment * alignment;
if (each) each[i] = D3D12_RESOURCE_ALLOCATION_INFO1{offset, alignment, size};
offset += size;
if (alignment > max_alignment) max_alignment = alignment;
}
total->SizeInBytes = offset;
total->Alignment = max_alignment;
return true;
}
} // namespace
extern "C" {
@@ -81,8 +144,11 @@ extern "C" {
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
const D3D12_RESOURCE_DESC* descs) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, nullptr, "GetResourceAllocationInfo")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, mask, count, host.get());
return result;
}
@@ -90,8 +156,11 @@ D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_all
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info1(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo1")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, mask, count, host.get(), each);
return result;
}
@@ -99,8 +168,11 @@ D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_all
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info2(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo2")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, mask, count, host.get(), each);
return result;
}
+5
View File
@@ -79,7 +79,12 @@ extern "C" {
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
* IID.
*/
extern "C" void bx_gdk_xg_enable_locking();
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
// The title creates XG texture computers on its own threads; the shim does too (gdk_xg.h).
static const bool xg_locking = (bx_gdk_xg_enable_locking(), true);
(void)xg_locking;
if (!ppv) {
return E_POINTER;
}
+104 -1
View File
@@ -7,10 +7,17 @@
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
* new frame pipeline token. Each signal also sets the ancillary events given to
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
*
* GetFrameStatisticsX (authorized GDK documentation) answers from a history of the last 17
* frames, kept per pipeline token: the ORIGIN event (wait call, signal and wait return times)
* and PresentX (call and return times), in QueryPerformanceCounter ticks as documented. The
* other statistics types (interval, power scaling, render, display, input) have no host source
* and are never reported; a query for only those answers S_FALSE, "not available yet".
*/
#include "xbox_facade.h"
#include <cstdio>
#include <cstring>
#include <mutex>
#include <thread>
@@ -43,6 +50,35 @@ UINT64 g_next_token = 1;
UINT64 g_last_origin_token = 0;
bool g_thread_started = false;
// Frame statistics history (GetFrameStatisticsX): the runtime keeps the last 17 frames.
constexpr UINT kHistory = 17;
struct FrameRecord {
UINT64 token = 0;
UINT64 wait_call = 0, signal = 0, wait_return = 0;
UINT offset_us = 0;
bool signaled = false;
bool waited = false;
bool presented = false;
UINT64 present_call = 0, present_return = 0;
};
FrameRecord g_history[kHistory];
UINT64 qpc_now() {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return static_cast<UINT64>(t.QuadPart);
}
// The record for `token`, created when `create` (replacing the one 17 frames older); else null.
FrameRecord* record_for(UINT64 token, bool create) {
FrameRecord& r = g_history[token % kHistory];
if (r.token == token) return &r;
if (!create) return nullptr;
r = FrameRecord{};
r.token = token;
return &r;
}
void close_ancillary(Scheduled& e) {
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
e.ancillary_count = 0;
@@ -52,7 +88,13 @@ void signal(UINT type) {
std::lock_guard<std::mutex> guard(g_lock);
const Scheduled& e = g_events[type];
if (!e.active) return;
if (type == kOrigin) g_last_origin_token = g_next_token++;
if (type == kOrigin) {
g_last_origin_token = g_next_token++;
FrameRecord* r = record_for(g_last_origin_token, true);
r->signal = qpc_now();
r->offset_us = e.offset_us;
r->signaled = true;
}
SetEvent(g_signal[type]);
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
}
@@ -156,6 +198,7 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
}
const UINT ancillary = waits ? waits->Count : 0;
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
const UINT64 wait_call = qpc_now();
const DWORD result = WaitForMultipleObjects(1 + ancillary, handles, (flags & kWaitAll) != 0,
timeout_ms == kInfinite ? INFINITE : timeout_ms);
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
@@ -166,8 +209,68 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
std::lock_guard<std::mutex> guard(g_lock);
*token = satisfied ? g_last_origin_token : g_next_token++;
if (FrameRecord* r = record_for(*token, true)) {
r->wait_call = wait_call;
r->wait_return = qpc_now();
r->waited = true;
}
}
return satisfied ? S_OK : S_FALSE;
}
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time) {
if (!token) return;
std::lock_guard<std::mutex> guard(g_lock);
if (FrameRecord* r = record_for(token, false)) {
r->presented = true;
r->present_call = call_time;
r->present_return = return_time;
}
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void*, UINT64 token, UINT type_set, UINT* count,
void* statistics) {
BX_D3D_TRACE("XboxDevice", "GetFrameStatisticsX");
if (!count || type_set == 0 || (type_set & ~kStatsKnownTypes) != 0 || (*count && !statistics)) return E_INVALIDARG;
BxXboxFrameStatistics found[2];
UINT n = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
if (token == 0 || token >= g_next_token) return E_INVALIDARG; // documented: unknown pipeline token
if (const FrameRecord* r = record_for(token, false)) {
if ((type_set & kStatsFrameEvent) && (r->signaled || r->waited)) {
BxXboxFrameStatistics& out = found[n++];
std::memset(&out, 0, sizeof(out));
out.Type = kStatsFrameEvent;
out.Event.EventType = kOrigin;
out.Event.WaitCallTime = r->wait_call;
out.Event.SignalTime = r->signal;
out.Event.WaitReturnTime = r->wait_return;
out.Event.IntervalOffsetInMicroseconds = r->offset_us;
out.Event.StatisticsFlags = r->signaled ? 0 : kEventSignalPending;
}
if ((type_set & kStatsPresent) && r->presented) {
BxXboxFrameStatistics& out = found[n++];
std::memset(&out, 0, sizeof(out));
out.Type = kStatsPresent;
out.Present.PlaneIndex = 0;
out.Present.PlaneCount = 1;
out.Present.ViewCount = 1;
out.Present.PresentCallTime = r->present_call;
out.Present.PresentQueueTime = r->present_call; // queued in the call itself
out.Present.PresentReturnTime = r->present_return;
out.Present.PlaneSwapMask = 1; // GPUProcessTime: not measured, 0
}
}
}
if (!statistics) { // a size query
*count = n;
return n ? S_OK : S_FALSE;
}
const UINT written = n < *count ? n : *count;
std::memcpy(statistics, found, written * sizeof(BxXboxFrameStatistics));
*count = written;
return n ? S_OK : S_FALSE;
}
} // extern "C"
+94
View File
@@ -0,0 +1,94 @@
/* Console texture layouts through the GDK's own XG library (see gdk_xg.h).
*
* The documented interface (GDK xg_xs.h):
* HRESULT XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**);
* XG_RESOURCE_DESC has the field order and sizes of D3D12_RESOURCE_DESC, with
* XG12_RESOURCE_MISC_FLAG in place of D3D12_RESOURCE_FLAGS; the title's console flags
* (render target, depth, UAV, deny-compression) are those values.
* XGTextureAddressComputer vtable: 0 AddRef, 1 Release, 2 GetResourceLayout,
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, ...
* void XGEnableExclusiveLocking(BOOL), to be called before any computer is created.
*/
#include "gdk_xg.h"
#include "bx_log.h"
#include <atomic>
#include <cstdio>
namespace {
struct XgComputer;
struct XgComputerVtbl {
ULONG(__cdecl* AddRef)(XgComputer*);
ULONG(__cdecl* Release)(XgComputer*);
void* GetResourceLayout;
UINT64 (*GetResourceSizeBytes)(XgComputer*);
UINT64 (*GetResourceBaseAlignmentBytes)(XgComputer*);
};
struct XgComputer {
const XgComputerVtbl* vtbl;
};
using CreateTextureComputerFn = HRESULT(__cdecl*)(const D3D12_RESOURCE_DESC*, XgComputer**);
using EnableLockingFn = void(__cdecl*)(BOOL);
HMODULE microsoft_xg() {
static const HMODULE module = [] {
HMODULE xg = GetModuleHandleW(L"xg_xs.dll");
if (!xg) xg = LoadLibraryW(L"xg_xs.dll");
const bool microsoft = xg && GetProcAddress(xg, "XGComputeTexture2DLayout");
bx_log_emit(microsoft ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "gdk_xg",
microsoft ? "GDK XG library loaded: console texture layouts are computed by it"
: "GDK XG library not loaded: console textures are sized linearly (bx-cli run stages it "
"from the configured GDK)");
return microsoft ? xg : static_cast<HMODULE>(nullptr);
}();
return module;
}
CreateTextureComputerFn create_computer() {
static const CreateTextureComputerFn fn = [] {
HMODULE xg = microsoft_xg();
return xg ? reinterpret_cast<CreateTextureComputerFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGCreateTextureComputer")))
: nullptr;
}();
return fn;
}
} // namespace
bool bx_gdk_xg_available() { return create_computer() != nullptr; }
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc) {
return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN &&
static_cast<UINT>(desc.Layout) >= 0x100;
}
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment) {
const CreateTextureComputerFn create = create_computer();
if (!create || !bx_is_console_texture_layout(desc)) return false;
XgComputer* computer = nullptr;
const HRESULT hr = create(&desc, &computer);
if (FAILED(hr) || !computer) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[160];
std::snprintf(detail, sizeof(detail), "XGCreateTextureComputer refused %llux%u layout=0x%x format=%d: hr=0x%08lx",
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<UINT>(desc.Layout),
static_cast<int>(desc.Format), static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gdk_xg", detail);
}
return false;
}
*size = computer->vtbl->GetResourceSizeBytes(computer);
*alignment = computer->vtbl->GetResourceBaseAlignmentBytes(computer);
computer->vtbl->Release(computer);
return true;
}
extern "C" void bx_gdk_xg_enable_locking() {
HMODULE xg = microsoft_xg();
if (!xg) return;
auto enable = reinterpret_cast<EnableLockingFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGEnableExclusiveLocking")));
if (enable) enable(TRUE);
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
/* Console texture layouts through the GDK's own XG library.
*
* Console textures are laid out in tiled swizzle modes (D3D12XBOX_TEXTURE_LAYOUT / XG_TEXTURE_LAYOUT,
* 0x100 | XG_SWIZZLE_MODE). A title sizes its loads and placements from those layouts, so a
* linear answer makes it read less than the tiled data it stored. The layouts are computed by
* Microsoft's xg_xs.dll from the collaborator's own GDK, staged by `bx-cli run` in place of
* BetterXen's xg_xs shim (which exports only the two functions titles import). Nothing from the
* GDK is shipped. Without it these helpers report that no console layout is available.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
/* True when Microsoft's XG library is the loaded xg_xs.dll (it exports XGComputeTexture2DLayout). */
bool bx_gdk_xg_available();
/* A console texture layout (Layout >= 0x100) that the GDK's XG can describe. */
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc);
/* Size and base alignment of `desc` in the console layout. False when XG is not available or
refuses the description; `size` and `alignment` are then untouched. */
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment);
/* Enables XG's internal lock (XGEnableExclusiveLocking) before any texture computer is created,
so the title's threads and the shim can both create computers. Called at device creation. */
extern "C" void bx_gdk_xg_enable_locking();
+15
View File
@@ -281,6 +281,21 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
const void* parameters) {
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
(void)parameters;
// Call and return times for GetFrameStatisticsX, kept for the first plane's pipeline token.
struct PresentTimes {
UINT64 token;
UINT64 call;
~PresentTimes() {
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
bx_xbox_frame_stats_present(token, call, static_cast<UINT64>(now.QuadPart));
}
} times{plane_count && planes_raw ? static_cast<const PlaneParameters*>(planes_raw)[0].Token : 0, 0};
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
times.call = static_cast<UINT64>(now.QuadPart);
}
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
+1
View File
@@ -54,6 +54,7 @@ CUSTOM = {
"WaitFrameEventX": "bx_xbox_device_wait_frame_event_x",
"CreatePlacedResourceX": "bx_xbox_device_create_placed_resource_x",
"CreatePlacedResourceX1": "bx_xbox_device_create_placed_resource_x1",
"GetFrameStatisticsX": "bx_xbox_device_get_frame_statistics_x",
"CreateCommittedResourceX": "bx_xbox_device_create_committed_resource_x",
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
+42
View File
@@ -154,6 +154,48 @@ struct BxXboxFrameObjectList {
UINT Count;
HANDLE* pObjects;
};
// GetFrameStatisticsX (authorized GDK header): D3D12XBOX_FRAME_STATISTICS is a 32-bit Type and,
// 8 bytes in, a union of the per-type structures; the two this layer fills are mirrored here.
constexpr UINT kStatsFrameEvent = 0x2, kStatsPresent = 0x1000;
constexpr UINT kStatsKnownTypes = 0x1 | 0x2 | 0x4 | 0x100 | 0x1000 | 0x10000 | 0x100000;
constexpr UINT kEventSignalPending = 0x1; // D3D12XBOX_FRAME_EVENT_STATISTICS_FLAG_SIGNAL_PENDING
struct BxXboxFrameEventStatistics { // D3D12XBOX_FRAME_EVENT_STATISTICS
UINT32 EventType;
UINT64 WaitCallTime;
UINT64 SignalTime;
UINT64 WaitReturnTime;
UINT32 IntervalOffsetInMicroseconds;
UINT32 SignalFlags;
UINT32 StatisticsFlags;
};
struct BxXboxPresentStatistics { // D3D12XBOX_PRESENT_STATISTICS
UINT8 PlaneIndex;
UINT8 PlaneCount;
UINT8 ViewCount;
UINT64 PresentCallTime;
UINT64 PresentQueueTime;
UINT64 PresentReturnTime;
UINT64 GPUProcessTime;
UINT8 QueuedFrameCount;
UINT16 PlaneSwapMask;
UINT32 Flags;
};
struct BxXboxFrameStatistics { // D3D12XBOX_FRAME_STATISTICS
UINT32 Type;
union {
BxXboxFrameEventStatistics Event;
BxXboxPresentStatistics Present;
UINT8 Bytes[48]; // the union's size: its largest members are 48 bytes
};
};
static_assert(sizeof(BxXboxFrameEventStatistics) == 48 && sizeof(BxXboxPresentStatistics) == 48, "statistics layout");
static_assert(sizeof(BxXboxFrameStatistics) == 56 && offsetof(BxXboxFrameStatistics, Event) == 8, "frame statistics layout");
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void* self, UINT64 token, UINT type_set, UINT* count,
void* statistics);
// Records PresentX for its frame pipeline token (frame_pacing.cpp keeps the history).
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time);
struct BxXboxFrameWaitList {
UINT Count;
HANDLE* pObjects;
+2 -4
View File
@@ -189,8 +189,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_72(void*) { BX_VTABLE_STUB_LOG("XboxDe
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_77(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 77u, "CreateComponentPlacedResourceX1"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_81(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 81u, "GetFrameStatisticsX"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_82(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 82u, "CreateCounterSetX"); return E_NOTIMPL; }
static HRESULT STDMETHODCALLTYPE x_Device_83(void* self, const void * a0, SIZE_T a1, REFIID a2, void ** a3) {
BX_D3D_TRACE("XboxDevice", "CreatePipelineLibrary");
@@ -483,7 +481,7 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&bx_xbox_device_set_frame_interval_x),
reinterpret_cast<const void*>(&bx_xbox_device_schedule_frame_event_x),
reinterpret_cast<const void*>(&bx_xbox_device_wait_frame_event_x),
reinterpret_cast<const void*>(&x_Device_81),
reinterpret_cast<const void*>(&bx_xbox_device_get_frame_statistics_x),
reinterpret_cast<const void*>(&x_Device_82),
reinterpret_cast<const void*>(&x_Device_83),
reinterpret_cast<const void*>(&x_Device_84),
@@ -559,7 +557,7 @@ const IID kDeviceIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12Device11: 139 slots (54 forwarded, 45 shared, 40 stubs); hosted on ID3D12Device10. */
/* ID3D12Device11: 139 slots (54 forwarded, 46 shared, 39 stubs); hosted on ID3D12Device10. */
const IID kHostDevice = __uuidof(ID3D12Device10);
static HRESULT STDMETHODCALLTYPE x_Resource_3(void* self, REFGUID a0, UINT * a1, void * a2) {
+89 -2
View File
@@ -3,6 +3,7 @@
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <new>
@@ -188,9 +189,93 @@ void sample_stick(int left, int right, int down, int up, float& x, float& y) {
}
}
/* Diagnostic (off unless BX_INPUT_SCRIPT is set): scripted gamepad presses, so an unattended run
can get past screens that wait for input without window focus. The script is a comma-separated
list of BUTTON@SECONDS, for example "A@40,DOWN@50.5,A@52"; each press holds the button for
300 ms, timed from the first reading of the keyboard gamepad. Buttons: MENU VIEW A B X Y UP DOWN
LEFT RIGHT. Each press is logged once (input_script); an entry it cannot read is logged and
skipped. */
struct ScriptedPress {
uint32_t button;
uint64_t at_ms;
};
constexpr size_t kMaxScriptedPresses = 128;
constexpr uint64_t kScriptedHoldMs = 300;
struct InputScript {
ScriptedPress presses[kMaxScriptedPresses];
std::atomic<bool> logged[kMaxScriptedPresses];
size_t count = 0;
uint64_t start_ms = 0;
};
uint32_t script_button(const char* name, size_t length) {
constexpr struct { const char* name; uint32_t bit; } names[] = {
{"MENU", 0x1}, {"VIEW", 0x2}, {"A", 0x4}, {"B", 0x8}, {"X", 0x10},
{"Y", 0x20}, {"UP", 0x40}, {"DOWN", 0x80}, {"LEFT", 0x100}, {"RIGHT", 0x200},
};
for (const auto& n : names) {
if (std::strlen(n.name) == length && std::strncmp(n.name, name, length) == 0) return n.bit;
}
return 0;
}
InputScript* load_script() {
char spec[2048] = {};
const DWORD n = GetEnvironmentVariableA("BX_INPUT_SCRIPT", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return nullptr;
auto* script = new (std::nothrow) InputScript();
if (!script) return nullptr;
for (const char* item = spec; *item && script->count < kMaxScriptedPresses;) {
const char* end = std::strchr(item, ',');
const size_t length = end ? static_cast<size_t>(end - item) : std::strlen(item);
const char* at = static_cast<const char*>(std::memchr(item, '@', length));
char seconds[32] = {};
uint32_t button = 0;
if (at && static_cast<size_t>(item + length - at - 1) < sizeof(seconds)) {
std::memcpy(seconds, at + 1, static_cast<size_t>(item + length - at - 1));
button = script_button(item, static_cast<size_t>(at - item));
}
char* parsed_end = nullptr;
const double when = std::strtod(seconds, &parsed_end);
if (button && parsed_end != seconds && *parsed_end == 0 && when >= 0) {
script->presses[script->count++] = {button, static_cast<uint64_t>(when * 1000.0)};
} else {
char detail[96];
std::snprintf(detail, sizeof(detail), "unreadable entry '%.*s' skipped", static_cast<int>(length < 40 ? length : 40), item);
bx_log_emit(BX_LOG_WARN, "gameinput", "input_script", detail);
}
item = end ? end + 1 : item + length;
}
script->start_ms = GetTickCount64();
return script;
}
uint32_t scripted_buttons() {
static InputScript* const script = load_script();
if (!script) return 0;
const uint64_t now = GetTickCount64() - script->start_ms;
uint32_t buttons = 0;
for (size_t i = 0; i < script->count; ++i) {
const ScriptedPress& press = script->presses[i];
if (now < press.at_ms || now >= press.at_ms + kScriptedHoldMs) continue;
buttons |= press.button;
if (!script->logged[i].exchange(true)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "scripted press 0x%x at %.1f s", press.button, now / 1000.0);
bx_log_emit(BX_LOG_INFO, "gameinput", "input_script", detail);
}
}
return buttons;
}
GamepadState sample_keyboard() {
GamepadState state{};
if (!owns_foreground()) return state;
const uint32_t scripted = scripted_buttons();
if (!owns_foreground()) {
state.buttons = scripted;
return state;
}
constexpr struct KeyBinding { int key; uint32_t button; } buttons[] = {
{'P', 0x1}, {VK_TAB, 0x2}, {VK_RETURN, 0x4}, {VK_SPACE, 0x4},
@@ -205,7 +290,9 @@ GamepadState sample_keyboard() {
state.right_trigger = pressed('C') ? 1.0f : 0.0f;
sample_stick('A', 'D', 'S', 'W', state.left_x, state.left_y);
sample_stick('J', 'L', 'K', 'I', state.right_x, state.right_y);
return owns_foreground() ? state : GamepadState{};
if (!owns_foreground()) state = GamepadState{};
state.buttons |= scripted;
return state;
}
struct Sample {
+51
View File
@@ -1330,6 +1330,56 @@ void disarm_diagnostics() {
}
}
/* Diagnostic (off unless BX_CONTINUE_ASSERTS=1): a title's continuable assert is an int3 in its
own executable followed by code that carries on when no debugger is attached to take it. With
the switch, such an int3 in the main executable is stepped over instead of reaching the title's
crash reporter. Each address is logged once (assert_continued), so the run report still lists
every assert that fired. An int3 anywhere else (BetterXen, system or other modules) is left as
it was. */
static bool continue_assert(PEXCEPTION_POINTERS ep) {
// Reading the switch and querying memory must not change the faulting thread's last-error
// value, which the title may read after it continues (test_veh_breakpoint checks it).
struct KeepLastError {
DWORD saved = GetLastError();
~KeepLastError() { SetLastError(saved); }
} keep_last_error;
static const bool enabled = [] {
char v[4] = {};
const DWORD n = GetEnvironmentVariableA("BX_CONTINUE_ASSERTS", v, sizeof(v));
return n == 1 && v[0] == '1';
}();
if (!enabled) return false;
const auto at = reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress);
const auto exe = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(at), &region, sizeof(region)) ||
reinterpret_cast<uintptr_t>(region.AllocationBase) != exe || *reinterpret_cast<const uint8_t*>(at) != 0xCC) {
return false;
}
static std::atomic<uintptr_t> seen[256];
bool first = true;
for (auto& slot : seen) {
uintptr_t value = slot.load();
if (value == at) {
first = false;
break;
}
if (value == 0 && slot.compare_exchange_strong(value, at)) break;
if (value == at) {
first = false;
break;
}
}
if (first) {
char detail[96];
std::snprintf(detail, sizeof(detail), "title assert at rva 0x%llx stepped over",
static_cast<unsigned long long>(at - exe));
bx_log_emit(BX_LOG_WARN, "runtime_veh", "assert_continued", detail);
}
ep->ContextRecord->Rip = at + 1;
return true;
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
return EXCEPTION_CONTINUE_SEARCH;
@@ -1340,6 +1390,7 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
log_breakpoint(*ep->ExceptionRecord);
if (code == EXCEPTION_BREAKPOINT && continue_assert(ep)) return EXCEPTION_CONTINUE_EXECUTION;
return EXCEPTION_CONTINUE_SEARCH;
}
if (code == EXCEPTION_ACCESS_VIOLATION) {
+7 -3
View File
@@ -55,9 +55,13 @@ struct Request {
UINT compression;
ID3D12Resource* resource = nullptr;
UINT64 resource_offset = 0;
DWORD output_size = 0; // compression_zlib: bytes the stream inflates to at `destination`
// Xbox physical-page destination: the span of xmem.dll pages this request writes through,
// mapped when it was enqueued and unmapped once it has been fulfilled (0 when unused).
DWORD output_size = 0; // compression_zlib/bcpack: bytes the stream decodes to at `destination`
UINT bcpack_mode = 0; // compression_bcpack: DSTORAGE_BCPACK_MODE (BCn format 1-7)
// Xbox physical-page destination: the title's array of 64 KB page numbers and the offset into
// the first page. The title may fill the array after it enqueues the request, so the pages are
// mapped into `page_span` only when the request runs, and unmapped once it has been fulfilled.
const ULONG_PTR* page_array = nullptr;
UINT32 page_offset = 0;
void* page_span = nullptr;
ULONG_PTR page_span_count = 0;
};
+120 -21
View File
@@ -456,6 +456,79 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
return staged.finish(win32_error());
}
/* A title may read only the first part of a compressed block: the stream then holds more than
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and its first
`output_size` bytes are delivered. A stream shorter than the destination stays an error. */
BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& request) {
const size_t capacity = static_cast<size_t>(request.output_size) * 64 + 0x40000;
auto* whole = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, capacity));
if (!whole) return BxInflateResult::output_mismatch;
size_t produced = 0;
BxInflateResult r = bx_zlib_inflate_any(compressed, request.size, whole, capacity, &produced);
if (r == BxInflateResult::ok && produced > request.output_size) {
std::memcpy(request.destination, whole, request.output_size);
} else if (r == BxInflateResult::ok) {
r = BxInflateResult::output_mismatch;
}
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes holds %llu bytes, destination %lu: %s", request.size,
static_cast<unsigned long long>(produced), request.output_size,
r == BxInflateResult::ok ? "first part delivered" : bx_inflate_result_name(r));
bx_log_emit(r == BxInflateResult::ok ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "dstorage_zlib_partial", detail);
}
HeapFree(GetProcessHeap(), 0, whole);
return r;
}
/* BCPack (Xbox texture block compression, DSTORAGE_BCPACK_MODE). The codec is Microsoft's
BCPack.dll from the GDK's PC tools, loaded from BX_BCPACK_DLL when set (each collaborator's own
GDK; never shipped). Its documented entry point (GDK BCPack.h): BCPackDecompress(bcIndex,
output, outputSize, packed, packedSize). Without it, BCPack requests stay refused (E_NOTIMPL). */
using BcpackDecompressFn = HRESULT(__cdecl*)(size_t, void*, size_t, const void*, size_t);
BcpackDecompressFn bcpack_decompress() {
static const BcpackDecompressFn fn = [] {
wchar_t path[MAX_PATH];
const DWORD n = GetEnvironmentVariableW(L"BX_BCPACK_DLL", path, MAX_PATH);
if (n == 0 || n >= MAX_PATH) return static_cast<BcpackDecompressFn>(nullptr);
HMODULE dll = LoadLibraryW(path);
auto found = dll ? reinterpret_cast<BcpackDecompressFn>(reinterpret_cast<void*>(GetProcAddress(dll, "BCPackDecompress")))
: nullptr;
char detail[96];
std::snprintf(detail, sizeof(detail), "BX_BCPACK_DLL %s (error %lu)", found ? "loaded" : "not usable",
found ? 0ul : GetLastError());
bx_log_emit(found ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "bcpack_codec", detail);
return found;
}();
return fn;
}
HRESULT bcpack_request(HANDLE file, const Request& request) {
const BcpackDecompressFn decompress = bcpack_decompress();
if (!decompress) return E_NOTIMPL;
if (!request.destination || !request.output_size || !request.size) return E_INVALIDARG;
auto* packed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
if (!packed) return E_OUTOFMEMORY;
HRESULT hr = read_bytes(file, request.file_offset, packed, request.source, request.size);
if (SUCCEEDED(hr)) {
RemapGuard remap_guard;
hr = decompress(request.bcpack_mode, request.destination, request.output_size, packed, request.size);
if (FAILED(hr)) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
std::snprintf(detail, sizeof(detail), "BCPack BC%u stream of %lu bytes to %lu bytes: hr=0x%08lx", request.bcpack_mode,
request.size, request.output_size, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_bcpack_failed", detail);
}
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
}
}
HeapFree(GetProcessHeap(), 0, packed);
return hr;
}
HRESULT inflate_request(HANDLE file, const Request& request) {
if (!request.destination || !request.output_size || request.size >= request.output_size) return E_INVALIDARG;
auto* compressed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
@@ -463,8 +536,9 @@ HRESULT inflate_request(HANDLE file, const Request& request) {
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
if (SUCCEEDED(hr)) {
RemapGuard remap_guard;
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
if (r == BxInflateResult::output_mismatch) r = inflate_first_part(compressed, request);
if (r != BxInflateResult::ok) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
@@ -498,7 +572,8 @@ CopyResult fulfill(HANDLE file, const Request& request) {
if (!dstorage_trace_enabled() || request.resource) return result;
static std::atomic<UINT> traced{0};
if (traced.fetch_add(1) >= 20000) return result;
const DWORD out = request.compression == compression_zlib ? request.output_size : request.size;
const DWORD out = (request.compression == compression_zlib || request.compression == compression_bcpack) ? request.output_size
: request.size;
uint64_t head[2] = {0, 0};
if (SUCCEEDED(result.hr) && request.destination && out >= 16) {
RemapGuard remap_guard;
@@ -515,6 +590,10 @@ CopyResult fulfill(HANDLE file, const Request& request) {
}
CopyResult fulfill_request(HANDLE file, const Request& request) {
if (request.compression == compression_bcpack && request.bcpack_mode) {
if (request.resource) return {E_NOTIMPL, false};
return {bcpack_request(file, request), false};
}
if (request.compression == compression_zlib) {
if (request.resource) return {E_NOTIMPL, false};
return {inflate_request(file, request), false};
@@ -571,6 +650,25 @@ MapPhysicalPagesFn map_physical_pages() {
return fn;
}
/* Maps a physical-page destination's pages when the request runs. The title can fill its page
array after EnqueueRequest returns, so the array is read here, not at enqueue. */
HRESULT map_page_destination(Request& request) {
if (!request.page_array) return S_OK;
const MapPhysicalPagesFn map = map_physical_pages();
void* span = map ? map(nullptr, request.page_span_count, const_cast<PULONG_PTR>(request.page_array)) : nullptr;
if (!span) {
const DWORD error = map ? GetLastError() : ERROR_PROC_NOT_FOUND;
char detail[128];
std::snprintf(detail, sizeof(detail), "mapping %llu destination pages failed error=%lu",
static_cast<unsigned long long>(request.page_span_count), error);
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
return HRESULT_FROM_WIN32(error);
}
request.page_span = span;
request.destination = static_cast<BYTE*>(span) + request.page_offset;
return S_OK;
}
void unmap_page_span(Request& request) {
if (!request.page_span) return;
const MapPhysicalPagesFn map = map_physical_pages();
@@ -609,7 +707,8 @@ public:
Entry entry{Kind::request, *request};
if (request->resource) request->resource->AddRef();
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
if (request->file && (request->compression == compression_none || request->compression == compression_zlib)) {
if (request->file && (request->compression == compression_none || request->compression == compression_zlib ||
request->compression == compression_bcpack)) {
const HRESULT result = request->file->GetHandle(&entry.handle);
if (FAILED(result)) {
if (request->resource) request->resource->Release();
@@ -800,7 +899,8 @@ private:
HRESULT result = S_OK;
switch (entry.kind) {
case Kind::request: {
const CopyResult outcome = fulfill(entry.handle, entry.request);
const HRESULT mapped = map_page_destination(entry.request);
const CopyResult outcome = SUCCEEDED(mapped) ? fulfill(entry.handle, entry.request) : CopyResult{mapped, false};
result = outcome.hr;
unmap_page_span(entry.request);
if (entry.handle) CloseHandle(entry.handle);
@@ -1598,7 +1698,10 @@ public:
return;
}
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
if (request->options & kXboxRequestBcpackMask) {
// BCPack (BcpackMode, DSTORAGE_BCPACK_MODE 1-7) is decoded by the GDK's BCPack.dll when
// BX_BCPACK_DLL names it; combined with zlib, or without the codec, it stays refused.
const UINT bcpack_mode = static_cast<UINT>((request->options & kXboxRequestBcpackMask) >> 1);
if (bcpack_mode && ((request->options & kXboxRequestCompressedBit) || bcpack_mode > 7 || !bcpack_decompress())) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
@@ -1616,7 +1719,7 @@ public:
const bool to_pages = (request->options & kXboxRequestDestinationPagesBit) != 0;
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
if (!request->destination || (zlib ? request->source_size >= request->destination_size
: request->source_size != request->destination_size)) {
: (!bcpack_mode && request->source_size != request->destination_size))) {
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
return;
}
@@ -1627,6 +1730,10 @@ public:
if (zlib) {
translated.compression = compression_zlib;
translated.output_size = request->destination_size;
} else if (bcpack_mode) {
translated.compression = compression_bcpack;
translated.bcpack_mode = bcpack_mode;
translated.output_size = request->destination_size;
}
if (is_memory) {
if (!request->source_ptr) {
@@ -1649,24 +1756,16 @@ public:
constexpr UINT64 page = 64 * 1024;
const UINT64 end = static_cast<UINT64>(request->destination_page_offset) + request->destination_size;
const ULONG_PTR count = static_cast<ULONG_PTR>((end + page - 1) / page);
const MapPhysicalPagesFn map = map_physical_pages();
void* span = map ? map(nullptr, count, static_cast<PULONG_PTR>(request->destination)) : nullptr;
if (!span) {
const DWORD error = map ? GetLastError() : ERROR_PROC_NOT_FOUND;
char detail[128];
std::snprintf(detail, sizeof(detail), "mapping %llu destination pages failed error=%lu",
static_cast<unsigned long long>(count), error);
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
reject(HRESULT_FROM_WIN32(error), Kind::request, "EnqueueRequest");
if (!map_physical_pages()) {
reject(HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND), Kind::request, "EnqueueRequest");
return;
}
translated.destination = static_cast<BYTE*>(span) + request->destination_page_offset;
translated.page_span = span;
// The array stays the title's: it is read when the request runs (map_page_destination).
translated.page_array = static_cast<const ULONG_PTR*>(request->destination);
translated.page_offset = request->destination_page_offset;
translated.page_span_count = count;
}
const HRESULT queued = queue_->EnqueueRequest(&translated);
if (FAILED(queued)) unmap_page_span(translated);
accept(queued, Kind::request, "EnqueueRequest");
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
}
void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) override {
+13 -3
View File
@@ -191,7 +191,7 @@ uint32_t adler32(const uint8_t* data, size_t size) {
} // namespace
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size, size_t* produced) {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
const uint8_t cmf = input[0], flg = input[1];
@@ -225,7 +225,8 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
if (r != BxInflateResult::ok) return r;
if (final_block) break;
}
if (out.pos != out.size) return BxInflateResult::output_mismatch;
if (produced) *produced = out.pos;
else if (out.pos != out.size) return BxInflateResult::output_mismatch;
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
in.align_to_byte();
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
@@ -233,7 +234,16 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
const uint8_t* t = in.data + trailer;
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
(static_cast<uint32_t>(t[2]) << 8) | t[3];
return adler32(output, output_size) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
return adler32(output, out.pos) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
}
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
return inflate_impl(input, input_size, output, output_size, nullptr);
}
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced) {
*produced = 0;
return inflate_impl(input, input_size, output, capacity, produced);
}
const char* bx_inflate_result_name(BxInflateResult result) {
+4
View File
@@ -25,4 +25,8 @@ enum class BxInflateResult {
/* Decodes `input` into exactly `output_size` bytes at `output`. */
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size);
/* Decodes `input` into at most `capacity` bytes and reports how many the stream produced
(checksum verified over those bytes). */
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced);
const char* bx_inflate_result_name(BxInflateResult result);
@@ -0,0 +1,2 @@
add_executable(test_console_mode main.cpp)
target_link_libraries(test_console_mode PRIVATE xgameruntime advapi32 kernel32)
@@ -0,0 +1,69 @@
/*
* The console type in the registry. A title can read the REG_DWORD ConsoleMode under
* HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM instead of calling XSystemGetDeviceType
* (target-build observation): it opens the key with RegOpenKeyW, reads the value with
* RegQueryValueExW and maps 0x60 to Series S, 0x64 to Series X and 0x68 to the Scarlett devkit;
* with no key it takes itself for a PC and sizes its memory for Series X. The XSystemDeviceType
* numbers below are those of the authorized GDK (XboxScarlettLockhart 6, XboxScarlettAnaconda 7,
* XboxScarlettDevkit 8, Pc 1). This test reads the value the same way and checks it against the
* BetterXen profile (BX_PROFILE, as bx-cli run sets it) and against XSystemGetDeviceType.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint32_t WINAPI XSystemGetDeviceType();
namespace {
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::fprintf(stderr, "console mode:%d: %s\n", __LINE__, #condition); \
return 1; \
} \
} while (false)
// The title's mapping of ConsoleMode to XSystemDeviceType, written out from the observation.
uint32_t device_type_for(DWORD mode) {
switch (mode) {
case 0x10: case 0x20: case 0x21: case 0x30: case 0x31: return 2; // XboxOne
case 0x40: return 3; // XboxOneS
case 0x50: return 4; // XboxOneX
case 0x58: return 5; // XboxOneXDevkit
case 0x60: return 6; // XboxScarlettLockhart
case 0x64: return 7; // XboxScarlettAnaconda
case 0x68: return 8; // XboxScarlettDevkit
default: return 0; // Unknown
}
}
} // namespace
int main() {
char profile[32] = {};
GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile));
const bool anaconda = _stricmp(profile, "anaconda") == 0;
const DWORD expected_mode = anaconda ? 0x64 : 0x60;
HKEY key = nullptr;
CHECK(RegOpenKeyW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM", &key) ==
ERROR_SUCCESS); // without it the title takes itself for a PC
DWORD mode = 0;
DWORD type = 0;
DWORD size = sizeof(mode);
const LSTATUS status = RegQueryValueExW(key, L"ConsoleMode", nullptr, &type, reinterpret_cast<BYTE*>(&mode), &size);
RegCloseKey(key);
CHECK(status == ERROR_SUCCESS);
CHECK(type == REG_DWORD && size == sizeof(DWORD));
std::printf("ConsoleMode=0x%lx profile=%s XSystemGetDeviceType=%u\n", static_cast<unsigned long>(mode),
anaconda ? "anaconda" : "lockhart", XSystemGetDeviceType());
CHECK(mode == expected_mode);
CHECK(device_type_for(mode) == (anaconda ? 7u : 6u));
CHECK(device_type_for(mode) == XSystemGetDeviceType()); // both ways of asking agree
std::puts("PASS: test_console_mode");
return 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_frame_statistics_x main.cpp)
target_compile_definitions(test_d3d12_frame_statistics_x PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_frame_statistics_x PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,228 @@
/*
* GetFrameStatisticsX (Xbox device table slot 81), against the authorized GDK documentation:
* GetFrameStatisticsX(Token, TypeSet, pCount, pStatistics) returns S_OK when one or more sets of
* the requested types are available (written subject to list space, *pCount updated to the
* number written), S_FALSE when none is available yet, and E_INVALIDARG for unknown frame
* pipeline tokens, invalid type sets and invalid list arrangements. The runtime keeps the last
* 17 frames. Times are QueryPerformanceCounter values.
* D3D12XBOX_FRAME_STATISTICS is written out below from the header's field list: a 32-bit Type,
* then (8 bytes in) a union whose largest members are 48 bytes. Tokens come from WaitFrameEventX
* on the ORIGIN event; PresentX gets the token through its plane parameters.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr UINT kTypeFrameEvent = 0x2, kTypeRender = 0x100, kTypePresent = 0x1000;
constexpr UINT kOrigin = 0;
struct FrameEventStatistics {
UINT32 EventType;
UINT64 WaitCallTime;
UINT64 SignalTime;
UINT64 WaitReturnTime;
UINT32 IntervalOffsetInMicroseconds;
UINT32 SignalFlags;
UINT32 StatisticsFlags;
};
struct PresentStatistics {
UINT8 PlaneIndex;
UINT8 PlaneCount;
UINT8 ViewCount;
UINT64 PresentCallTime;
UINT64 PresentQueueTime;
UINT64 PresentReturnTime;
UINT64 GPUProcessTime;
UINT8 QueuedFrameCount;
UINT16 PlaneSwapMask;
UINT32 Flags;
};
struct FrameStatistics {
UINT32 Type;
union {
FrameEventStatistics Event;
PresentStatistics Present;
UINT8 Bytes[48];
};
};
static_assert(sizeof(FrameStatistics) == 56 && offsetof(FrameStatistics, Event) == 8, "D3D12XBOX_FRAME_STATISTICS");
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
UINT64 Token;
UINT ResourceCount;
void** ppResources;
D3D12_RECT* pSrcViewRects;
void* pDestPlacementBase;
UINT ColorSpace;
UINT ScaleFilter;
UINT ExtendedDescCount;
void* pExtendedDescs;
UINT Flags;
};
constexpr int kRelease = 2, kDevCreateCommandQueue = 8, kDevCreateCommittedResource = 27;
constexpr int kDevSetFrameIntervalX = 78, kDevScheduleFrameEventX = 79, kDevWaitFrameEventX = 80;
constexpr int kDevGetFrameStatisticsX = 81, kQueuePresentX = 32;
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMMAND_QUEUE_DESC*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using SetIntervalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT, UINT, UINT);
using ScheduleFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, const void*, UINT);
using WaitFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, const void*, UINT, UINT64*);
using StatsFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, UINT, UINT*, FrameStatistics*);
using PresentFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const PlaneParameters*, const void*);
int g_failed = 0, g_checks = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_frame_statistics_x:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
} // namespace
int main() {
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004;
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_frame_statistics_x: host lacks the Xbox-layout device interface\n");
return 77;
}
if (FAILED(hr) || !dev) {
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
auto stats = slot<StatsFn>(dev, kDevGetFrameStatisticsX);
FrameStatistics out[4]{};
UINT count = 4;
// Invalid arrangements, type sets and tokens.
CHECK(stats(dev, 1, kTypeFrameEvent, nullptr, out) == E_INVALIDARG, "null pCount");
CHECK(stats(dev, 1, 0, &count, out) == E_INVALIDARG, "empty type set");
count = 4;
CHECK(stats(dev, 1, 0x8, &count, out) == E_INVALIDARG, "unknown type bit");
count = 4;
CHECK(stats(dev, 1, kTypeFrameEvent, &count, nullptr) == E_INVALIDARG, "entries but no list");
count = 4;
CHECK(stats(dev, 0, kTypeFrameEvent, &count, out) == E_INVALIDARG, "token 0");
count = 4;
CHECK(stats(dev, 1ull << 40, kTypeFrameEvent, &count, out) == E_INVALIDARG, "token never issued");
// One frame: the ORIGIN event gives a token.
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 1, 0) == S_OK, "SetFrameIntervalX");
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == S_OK, "ScheduleFrameEventX");
auto wait = slot<WaitFn>(dev, kDevWaitFrameEventX);
UINT64 token = 0;
hr = wait(dev, kOrigin, 2000, nullptr, 0, &token);
CHECK(hr == S_OK && token != 0, "WaitFrameEventX(ORIGIN) hr=0x%08lx token=%llu", static_cast<unsigned long>(hr),
static_cast<unsigned long long>(token));
count = 4;
hr = stats(dev, token, kTypeFrameEvent, &count, out);
CHECK(hr == S_OK && count == 1, "FRAME_EVENT: hr=0x%08lx count=%u", static_cast<unsigned long>(hr), count);
if (hr == S_OK && count == 1) {
const FrameEventStatistics& e = out[0].Event;
CHECK(out[0].Type == kTypeFrameEvent && e.EventType == kOrigin, "FRAME_EVENT type %u event %u", out[0].Type,
e.EventType);
CHECK(e.SignalTime && e.WaitCallTime && e.WaitReturnTime >= e.SignalTime && e.WaitReturnTime >= e.WaitCallTime,
"FRAME_EVENT times wait=%llu signal=%llu return=%llu", static_cast<unsigned long long>(e.WaitCallTime),
static_cast<unsigned long long>(e.SignalTime), static_cast<unsigned long long>(e.WaitReturnTime));
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
CHECK(e.WaitReturnTime <= static_cast<UINT64>(now.QuadPart), "times are QueryPerformanceCounter values");
}
count = 4;
CHECK(stats(dev, token, kTypePresent, &count, out) == S_FALSE && count == 0, "PRESENT before PresentX: S_FALSE");
count = 4;
CHECK(stats(dev, token, kTypeRender, &count, out) == S_FALSE && count == 0, "RENDER (no host source): S_FALSE");
// PresentX with that token records the present.
D3D12_COMMAND_QUEUE_DESC queue_desc{};
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
void* queue = nullptr;
hr = slot<CreateQueueFn>(dev, kDevCreateCommandQueue)(dev, &queue_desc, __uuidof(ID3D12CommandQueue), &queue);
CHECK(hr == S_OK && queue, "CreateCommandQueue hr=0x%08lx", static_cast<unsigned long>(hr));
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
D3D12_RESOURCE_DESC rt{};
rt.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
rt.Width = 64;
rt.Height = 64;
rt.DepthOrArraySize = 1;
rt.MipLevels = 1;
rt.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
rt.SampleDesc.Count = 1;
rt.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
void* target = nullptr;
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &rt,
D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), &target);
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
if (queue && target) {
PlaneParameters plane{};
plane.Token = token;
plane.ResourceCount = 1;
plane.ppResources = &target;
slot<PresentFn>(queue, kQueuePresentX)(queue, 1, &plane, nullptr);
count = 4;
hr = stats(dev, token, kTypeFrameEvent | kTypePresent, &count, out);
CHECK(hr == S_OK && count == 2, "FRAME_EVENT|PRESENT after PresentX: hr=0x%08lx count=%u",
static_cast<unsigned long>(hr), count);
for (UINT i = 0; i < count; ++i) {
if (out[i].Type != kTypePresent) continue;
const PresentStatistics& p = out[i].Present;
CHECK(p.PresentCallTime && p.PresentReturnTime >= p.PresentCallTime && p.PlaneCount == 1,
"PRESENT call=%llu return=%llu planes=%u", static_cast<unsigned long long>(p.PresentCallTime),
static_cast<unsigned long long>(p.PresentReturnTime), p.PlaneCount);
}
// A size query (no list) reports how many are available; a short list gets what fits.
count = 0;
CHECK(stats(dev, token, kTypeFrameEvent | kTypePresent, &count, nullptr) == S_OK && count == 2, "size query: %u",
count);
count = 1;
CHECK(stats(dev, token, kTypeFrameEvent | kTypePresent, &count, out) == S_OK && count == 1, "short list: %u",
count);
}
// Seventeen frames later the token has no statistics left.
UINT64 later = token;
for (int i = 0; i < 18; ++i) wait(dev, kOrigin, 2000, nullptr, 0, &later);
count = 4;
CHECK(stats(dev, token, kTypeFrameEvent, &count, out) == S_FALSE && count == 0, "token 18 frames old: S_FALSE");
count = 4;
CHECK(stats(dev, later, kTypeFrameEvent, &count, out) == S_OK && count == 1, "latest token: S_OK");
if (target) slot<ReleaseFn>(target, kRelease)(target);
if (queue) slot<ReleaseFn>(queue, kRelease)(queue);
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) {
std::printf("FAIL: test_d3d12_frame_statistics_x (%d of %d checks failed)\n", g_failed, g_checks);
return 1;
}
std::printf("PASS: test_d3d12_frame_statistics_x (%d checks)\n", g_checks);
return 0;
}
@@ -0,0 +1,13 @@
# A stand-in for the GDK's XG library with known answers, built as xg_xs.dll in its own folder so
# it never replaces the xg_xs shim beside the other DLLs. The test loads it by full path.
add_library(test_gdk_xg_fake SHARED fake_xg.cpp)
# Its import library goes to its own folder too, or it would replace the xg_xs shim's.
set_target_properties(test_gdk_xg_fake PROPERTIES OUTPUT_NAME xg_xs PREFIX ""
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/gdk_xg_fake"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/gdk_xg_fake_lib")
target_link_libraries(test_gdk_xg_fake PRIVATE kernel32)
add_executable(test_d3d12_gdk_xg_sizes main.cpp)
target_compile_definitions(test_d3d12_gdk_xg_sizes PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_gdk_xg_sizes PRIVATE d3d12_xs kernel32 uuid)
add_dependencies(test_d3d12_gdk_xg_sizes test_gdk_xg_fake)
@@ -0,0 +1,66 @@
/*
* A stand-in for the GDK's XG library (xg_xs.dll) with answers the test can compute. It has the
* documented shape the shim relies on (GDK xg_xs.h): the exports XGComputeTexture2DLayout (whose
* presence marks Microsoft's library), XGCreateTextureComputer and XGEnableExclusiveLocking, and a
* texture computer whose vtable starts AddRef, Release, GetResourceLayout, GetResourceSizeBytes,
* GetResourceBaseAlignmentBytes. It is not Microsoft's code and computes no real layout.
*
* Its answer for a texture: size = Width * Height * DepthOrArraySize * 16 + (Layout & 0xFF) * 0x1000,
* alignment = 0x10000 when the layout is 0x109 (a 64 KB mode), otherwise 0x1000.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
namespace {
struct Computer;
struct Vtbl {
ULONG(__cdecl* AddRef)(Computer*);
ULONG(__cdecl* Release)(Computer*);
HRESULT(__cdecl* GetResourceLayout)(Computer*, void*);
UINT64 (*GetResourceSizeBytes)(Computer*);
UINT64 (*GetResourceBaseAlignmentBytes)(Computer*);
};
struct Computer {
const Vtbl* vtbl;
LONG refs;
UINT64 size;
UINT64 alignment;
};
ULONG __cdecl add_ref(Computer* c) { return static_cast<ULONG>(InterlockedIncrement(&c->refs)); }
ULONG __cdecl release(Computer* c) {
const LONG left = InterlockedDecrement(&c->refs);
if (!left) HeapFree(GetProcessHeap(), 0, c);
return static_cast<ULONG>(left);
}
HRESULT __cdecl layout(Computer*, void*) { return E_NOTIMPL; }
UINT64 size_bytes(Computer* c) { return c->size; }
UINT64 alignment_bytes(Computer* c) { return c->alignment; }
const Vtbl kVtbl = {add_ref, release, layout, size_bytes, alignment_bytes};
LONG g_locking = 0;
} // namespace
extern "C" __declspec(dllexport) HRESULT __cdecl XGComputeTexture2DLayout(const void*, void*) { return E_NOTIMPL; }
extern "C" __declspec(dllexport) HRESULT __cdecl XGCreateTextureComputer(const D3D12_RESOURCE_DESC* desc, Computer** out) {
if (!desc || !out) return E_INVALIDARG;
auto* c = static_cast<Computer*>(HeapAlloc(GetProcessHeap(), 0, sizeof(Computer)));
if (!c) return E_OUTOFMEMORY;
const UINT layout_value = static_cast<UINT>(desc->Layout);
c->vtbl = &kVtbl;
c->refs = 1;
c->size = desc->Width * desc->Height * desc->DepthOrArraySize * 16ull + (layout_value & 0xFF) * 0x1000ull;
c->alignment = layout_value == 0x109 ? 0x10000 : 0x1000;
*out = c;
return S_OK;
}
extern "C" __declspec(dllexport) void __cdecl XGEnableExclusiveLocking(BOOL enabled) { g_locking = enabled ? 1 : 0; }
// For the test: whether the shim enabled XG's locking.
extern "C" __declspec(dllexport) LONG __cdecl FakeXGLockingEnabled() { return g_locking; }
@@ -0,0 +1,125 @@
/*
* GetResourceAllocationInfo for console texture layouts, answered by the GDK's XG library.
*
* Console textures carry a tiled layout (D3D12XBOX_TEXTURE_LAYOUT, 0x100 | swizzle mode), and a
* title sizes its loads and placements from the allocation size the device reports. When the
* GDK's XG library is the loaded xg_xs.dll, d3d12_xs answers console layouts with XG's size and
* base alignment, and everything else with the host's answer; several descriptions are laid out
* one after another at their alignments (Direct3D 12 rules), the total aligned to the largest.
*
* The library here is a stand-in with answers this test computes (fake_xg.cpp), not Microsoft's.
* The test also checks that the shim enabled XG's exclusive locking at device creation.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2, kDevGetResourceAllocationInfo = 25;
int g_failed = 0;
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using AllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*);
D3D12_RESOURCE_DESC texture(UINT64 w, UINT h, UINT16 slices, DXGI_FORMAT format, UINT layout) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = w;
d.Height = h;
d.DepthOrArraySize = slices;
d.MipLevels = 1;
d.Format = format;
d.SampleDesc.Count = 1;
d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(layout);
return d;
}
// The stand-in library's answer (fake_xg.cpp), written out independently here.
UINT64 fake_size(const D3D12_RESOURCE_DESC& d) {
return d.Width * d.Height * d.DepthOrArraySize * 16ull + (static_cast<UINT>(d.Layout) & 0xFF) * 0x1000ull;
}
UINT64 fake_alignment(const D3D12_RESOURCE_DESC& d) { return static_cast<UINT>(d.Layout) == 0x109 ? 0x10000 : 0x1000; }
void expect(const char* what, UINT64 got, UINT64 want) {
std::printf("%-52s got=0x%llx expected=0x%llx\n", what, static_cast<unsigned long long>(got),
static_cast<unsigned long long>(want));
if (got != want) {
std::fprintf(stderr, "FAIL: test_d3d12_gdk_xg_sizes: %s\n", what);
++g_failed;
}
}
} // namespace
int main() {
// Load the stand-in as xg_xs.dll before the device exists, as bx-cli stages the GDK's.
wchar_t path[MAX_PATH];
const DWORD n = GetModuleFileNameW(nullptr, path, MAX_PATH);
wchar_t* slash = n ? wcsrchr(path, L'\\') : nullptr;
if (!slash || wcslen(path) + 32 >= MAX_PATH) return 1;
wcscpy(slash + 1, L"gdk_xg_fake\\xg_xs.dll");
HMODULE fake = LoadLibraryW(path);
if (!fake) {
std::fprintf(stderr, "FAIL: test_d3d12_gdk_xg_sizes: the stand-in XG library did not load (error %lu)\n", GetLastError());
return 1;
}
using LockingFn = LONG(__cdecl*)();
auto locking = reinterpret_cast<LockingFn>(reinterpret_cast<void*>(GetProcAddress(fake, "FakeXGLockingEnabled")));
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_gdk_xg_sizes: host lacks the Xbox-layout device interface\n");
return 77;
}
if (FAILED(hr) || !dev) {
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
expect("XG exclusive locking enabled at device creation", locking ? static_cast<UINT64>(locking()) : 0, 1);
const auto info = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo);
// One console texture: XG's size and alignment.
const D3D12_RESOURCE_DESC tiled = texture(128, 4, 1, DXGI_FORMAT_R16G16B16A16_UNORM, 0x105);
D3D12_RESOURCE_ALLOCATION_INFO got = info(dev, 0, 1, &tiled);
expect("128x4 RGBA16 layout 0x105: size", got.SizeInBytes, fake_size(tiled));
expect("128x4 RGBA16 layout 0x105: alignment", got.Alignment, fake_alignment(tiled));
const D3D12_RESOURCE_DESC big = texture(256, 256, 6, DXGI_FORMAT_BC7_UNORM, 0x109);
got = info(dev, 0, 1, &big);
expect("256x256x6 BC7 layout 0x109: size", got.SizeInBytes, fake_size(big));
expect("256x256x6 BC7 layout 0x109: alignment", got.Alignment, fake_alignment(big));
// A PC-layout texture keeps the host's answer.
const D3D12_RESOURCE_DESC pc = texture(256, 256, 1, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_TEXTURE_LAYOUT_UNKNOWN);
const D3D12_RESOURCE_ALLOCATION_INFO host = info(dev, 0, 1, &pc);
expect("PC-layout texture: host size is answered", host.SizeInBytes != 0 && host.SizeInBytes != UINT64_MAX, 1);
// Console then PC texture: each at its alignment, in order; total alignment the largest.
const D3D12_RESOURCE_DESC pair[2] = {tiled, pc};
got = info(dev, 0, 2, pair);
const UINT64 second = (fake_size(tiled) + host.Alignment - 1) / host.Alignment * host.Alignment;
expect("console + PC texture: total size", got.SizeInBytes, second + host.SizeInBytes);
expect("console + PC texture: total alignment", got.Alignment,
host.Alignment > fake_alignment(tiled) ? host.Alignment : fake_alignment(tiled));
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) return 1;
std::puts("PASS: test_d3d12_gdk_xg_sizes");
return 0;
}
@@ -0,0 +1,2 @@
add_executable(test_gameinput_script main.cpp)
target_link_libraries(test_gameinput_script PRIVATE kernel32 uuid)
@@ -0,0 +1,92 @@
/*
* BX_INPUT_SCRIPT (GameInput diagnostic): scripted gamepad presses for unattended runs.
*
* The script "A@0.6,DOWN@0.6,B@1.6,BOGUS@1,X" asks for A and DOWN held from 0.6 s to 0.9 s and B
* from 1.6 s to 1.9 s after the first reading; the two unreadable entries are skipped. The test has
* no window, so the keyboard contributes nothing; readings taken at fixed times must carry exactly
* the scripted buttons inside each press and none outside. The times sit at least 0.2 s from every
* press boundary.
*/
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
#include <cstdio>
namespace {
constexpr uint32_t gamepad_kind = 0x00040000;
constexpr uint32_t connected = 1;
struct State {
uint32_t buttons;
float lt, rt, lx, ly, rx, ry;
};
static_assert(sizeof(State) == 28);
template <typename Fn>
Fn slot(IUnknown* object, unsigned index) {
return reinterpret_cast<Fn>((*reinterpret_cast<void***>(object))[index]);
}
using Create = HRESULT(WINAPI*)(void**);
using Current = HRESULT(WINAPI*)(IUnknown*, uint32_t, IUnknown*, IUnknown**);
using DeviceCallback = void(WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
using Register = HRESULT(WINAPI*)(IUnknown*, IUnknown*, uint32_t, uint32_t, uint32_t, void*, DeviceCallback, uint64_t*);
using StateFn = bool(WINAPI*)(IUnknown*, State*);
void WINAPI note_device(uint64_t, void* context, IUnknown* device, uint64_t, uint32_t, uint32_t) {
*static_cast<IUnknown**>(context) = device;
}
IUnknown* g_input = nullptr;
IUnknown* g_pad = nullptr;
uint64_t g_start = 0;
// Waits until `seconds` after the first reading, then returns the buttons of a fresh reading.
uint32_t buttons_at(double seconds) {
while (GetTickCount64() - g_start < static_cast<uint64_t>(seconds * 1000.0)) Sleep(5);
IUnknown* reading = nullptr;
if (slot<Current>(g_input, 4)(g_input, gamepad_kind, g_pad, &reading) != S_OK || !reading) return 0xFFFFFFFF;
State state{};
const bool ok = slot<StateFn>(reading, 22)(reading, &state);
reading->Release();
return ok ? state.buttons : 0xFFFFFFFF;
}
int g_failed = 0;
void expect(const char* what, uint32_t got, uint32_t want) {
std::printf("%-34s buttons=0x%x expected=0x%x\n", what, got, want);
if (got != want) {
std::fprintf(stderr, "FAIL: test_gameinput_script: %s\n", what);
++g_failed;
}
}
} // namespace
int main() {
SetEnvironmentVariableA("BX_INPUT_SCRIPT", "A@0.6,DOWN@0.6,B@1.6,BOGUS@1,X");
HMODULE module = LoadLibraryW(L"GameInput.dll");
const auto create = module ? reinterpret_cast<Create>(reinterpret_cast<void*>(GetProcAddress(module, MAKEINTRESOURCEA(1)))) : nullptr;
if (!create || create(reinterpret_cast<void**>(&g_input)) != S_OK || !g_input) {
std::fprintf(stderr, "FAIL: test_gameinput_script: GameInput is not available\n");
return 1;
}
uint64_t token = 0;
if (slot<Register>(g_input, 9)(g_input, nullptr, gamepad_kind, connected, 2, &g_pad, note_device, &token) != S_OK || !g_pad) {
std::fprintf(stderr, "FAIL: test_gameinput_script: no gamepad device\n");
return 1;
}
g_start = GetTickCount64();
expect("first reading (0 s)", buttons_at(0.0), 0);
expect("0.3 s: before the first press", buttons_at(0.3), 0);
expect("0.75 s: A and DOWN held", buttons_at(0.75), 0x4 | 0x80);
expect("1.2 s: between presses", buttons_at(1.2), 0);
expect("1.75 s: B held", buttons_at(1.75), 0x8);
expect("2.2 s: after the script", buttons_at(2.2), 0);
if (g_failed) return 1;
std::puts("PASS: test_gameinput_script");
return 0;
}
@@ -0,0 +1,2 @@
add_executable(test_veh_continue_asserts main.cpp)
target_link_libraries(test_veh_continue_asserts PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,90 @@
/*
* BX_CONTINUE_ASSERTS=1 (bx_runtime_veh diagnostic): an int3 in the main executable is stepped
* over, as a continuable assert is when no debugger takes it; an int3 anywhere else is not.
*
* The test sets the switch, then executes an int3 in its own code twice (the same address, so the
* second is a repeat) and once in a page outside any module. A vectored handler of its own,
* registered after bx_runtime_veh's, counts every breakpoint that reaches it and steps over it so
* the test can report: the executable's int3s must never reach it, the other one must. Stepping
* over must leave the thread's last-error value as it was.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
namespace {
volatile LONG g_exe_reached = 0;
volatile LONG g_other_reached = 0;
uintptr_t g_other_page = 0;
LONG CALLBACK last_handler(PEXCEPTION_POINTERS ep) {
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_SEARCH;
const auto at = reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress);
if (g_other_page && at >= g_other_page && at < g_other_page + 4096) {
InterlockedIncrement(&g_other_reached);
} else {
InterlockedIncrement(&g_exe_reached);
}
ep->ContextRecord->Rip = at + 1;
return EXCEPTION_CONTINUE_EXECUTION;
}
__attribute__((noinline)) int assert_site(int value) {
__asm__ volatile("int3" ::: "memory");
return value + 1;
}
} // namespace
int main() {
SetErrorMode(SEM_NOGPFAULTERRORBOX);
// Keep a static import on bx_runtime_veh.dll so its handler is installed at load.
volatile uint64_t attached = bx_veh_get_clwb_trap_count();
(void)attached;
SetEnvironmentVariableA("BX_CONTINUE_ASSERTS", "1");
AddVectoredExceptionHandler(0, last_handler);
SetLastError(0x1234);
int value = assert_site(1);
value = assert_site(value);
const DWORD last_error = GetLastError();
// An int3 outside any module: int3; ret.
auto* page = static_cast<uint8_t*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));
if (!page) return 1;
g_other_page = reinterpret_cast<uintptr_t>(page);
page[0] = 0xCC;
page[1] = 0xC3;
FlushInstructionCache(GetCurrentProcess(), page, 2);
reinterpret_cast<void (*)()>(page)();
int failed = 0;
if (value != 3) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: execution after the int3 did not continue (value %d)\n", value);
++failed;
}
if (last_error != 0x1234) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: a stepped-over int3 changed the last-error value (0x%lx)\n",
static_cast<unsigned long>(last_error));
++failed;
}
if (g_exe_reached != 0) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: %ld int3s in the executable were not stepped over\n",
static_cast<long>(g_exe_reached));
++failed;
}
if (g_other_reached != 1) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: an int3 outside the executable must be left alone (reached %ld)\n",
static_cast<long>(g_other_reached));
++failed;
}
VirtualFree(page, 0, MEM_RELEASE);
if (failed) return 1;
std::puts("PASS: test_veh_continue_asserts");
return 0;
}
@@ -274,7 +274,7 @@ int main() {
HRESULT hr = DStorageGetFactory(kXboxFactoryIid, reinterpret_cast<void**>(&factory));
check(hr == S_OK && factory, "DStorageGetFactory(Xbox) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
IXboxDStorageStatusArray* status = nullptr;
hr = factory ? factory->CreateStatusArray(4, "pages", kXboxStatusArrayIid, reinterpret_cast<void**>(&status)) : E_FAIL;
hr = factory ? factory->CreateStatusArray(8, "pages", kXboxStatusArrayIid, reinterpret_cast<void**>(&status)) : E_FAIL;
check(hr == S_OK && status, "CreateStatusArray must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
if (g_failed) return 1;
@@ -339,6 +339,29 @@ int main() {
"a request naming an unallocated page must fail (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(1)));
check_written("unallocated page", bad, 0, 0, g_plain, 0);
/* 5. A title may read only the first part of a compressed block: a 4096-byte destination
* from the 136000-byte stream receives exactly the stream's first 4096 bytes, and the
* bytes after the destination keep their fill. */
static BYTE part[4096 + 64];
std::memset(part, 0xA5, sizeof(part));
XboxRequest f{};
f.options = kZlibDecompress;
f.destination = part;
f.destination_size = 4096;
f.source_ptr = file;
f.file_offset = 100;
f.source_size = sizeof(kZlibStream);
file_q->EnqueueRequest(&f);
file_q->EnqueueStatus(status, 4);
file_q->Submit();
check(wait_complete(status, 4) && status->GetHResult(4) == S_OK,
"a zlib request for the first 4096 bytes of a longer stream must succeed (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(4)));
check(std::memcmp(part, g_plain, 4096) == 0, "the first 4096 bytes of the stream must be delivered");
bool tail_kept = true;
for (size_t i = 4096; i < sizeof(part); ++i) tail_kept = tail_kept && part[i] == 0xA5;
check(tail_kept, "bytes after a partial zlib destination must not be written");
file_q->Close();
}
@@ -384,6 +407,23 @@ int main() {
"a physical-page source must be refused with E_NOTIMPL (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(3)));
check_written("physical-page source", array, 0, 0, source, 0);
/* 6. The title fills its page array after EnqueueRequest returns and before it submits:
* the pages it names then are the ones written. */
ULONG_PTR late[2] = {0, 0};
fill_view();
XboxRequest l = m;
l.destination = late;
l.destination_page_offset = 0x100;
mem_q->EnqueueRequest(&l);
late[0] = g_pages[2];
late[1] = g_pages[0];
mem_q->EnqueueStatus(status, 5);
mem_q->Submit();
check(wait_complete(status, 5) && status->GetHResult(5) == S_OK,
"a page array filled after EnqueueRequest must be used (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(5)));
check_written("page array filled after enqueue", late, 1, 0x100, source, sizeof(source));
mem_q->Close();
mem_q->Release();
}