mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-12-03 02:12:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d00bcdcbbf | ||
|
|
caf043e5d4 | ||
|
|
e7af7fbb6d | ||
|
|
864c4bed40 | ||
|
|
635066b67f | ||
|
|
d5d3696e83 | ||
|
|
7ae6bf81bc |
No files matched your search
@@ -4,59 +4,46 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. What to Do When Told "Work"
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
|
||||
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
|
||||
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
|
||||
|
||||
**"Work" authorizes, for the one item you pick:** posting a claim or a review, committing with DCO sign-off, pushing a branch, and opening a pull request. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
|
||||
### Step 1 — Preflight
|
||||
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`. If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`). Verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor`. It must report the toolchain, CrossOver, at least 10 GB of free disk space, and no other game run on this machine.
|
||||
- Work in your own worktree and your own bottle. Never use a bottle another session is using.
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
Take the first that applies. Do not skip ahead because a later one looks more interesting.
|
||||
|
||||
1. **Your person's pull requests that need attention.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
If one has requested changes, unresolved review comments, failing checks or conflicts: fix that pull request. Resolve every review point, re-run Section 8, push, and reply to each point.
|
||||
|
||||
2. **Review someone else's pull request.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
|
||||
```
|
||||
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test, confirm the test fails without the fix, read its proof, and post an approval or a change request with what you ran. If it needs deep review (the list is in the working method) and you can give one, do. If it is approved, green and not your person's, merge it (Section 7).
|
||||
|
||||
3. **Fix one blocker of the current stage.**
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label blocker --label "stage: <current>" --json number,title,labels,comments
|
||||
```
|
||||
The current stage is named on the pinned issue labelled `ladder`. Take the top unclaimed blocker: those labelled `first`, then lowest number. A blocker is claimed if it has a `Claiming —` comment less than 3 days old or an open pull request. Then follow Step 3.
|
||||
|
||||
4. **Discover.** If the current stage has no unclaimed blocker, run the stage's gate check (ten runs, [run protocol](docs/process/working-method.md#run-protocol)). For each signature in the report that has no issue, open or closed, file a blocker issue in the fixed shape. If the gate passes, post the ten-run result on the ladder issue and label it `needs-human`.
|
||||
|
||||
5. **Nothing applies.** Say so and stop. Do not invent work, open research documents, or start on a later stage's blockers while the current stage has claimed, unfinished ones — unless your person tells you to.
|
||||
|
||||
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
|
||||
|
||||
### Step 3 — Work one blocker
|
||||
|
||||
1. **Claim:** comment `Claiming — branch: track-<a..f>/<issue>-<slug>` and branch from `origin/main`.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. If you cannot explain the blocker in this session, write what you learned on the issue, release the claim, and stop. Do not guess a fix.
|
||||
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix.
|
||||
5. **Verify:** every command in Section 8. Without CrossOver you can still run the Rust checks, `scripts/build-shims.sh` and the docs check; say plainly which live checks were not run. Never report an unrun check as passed.
|
||||
6. **Proof:** ten runs before and ten after, every run reported, with the machine and the `main` commit.
|
||||
7. **Pull request:** one blocker; the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof); `Closes #<issue>`; DCO sign-off; no AI trailers. Watch CI until `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
8. **Stop.** The next "work" starts again at Step 2.
|
||||
|
||||
Nothing from the target build goes into a commit, issue or pull request (Section 6): keep run logs, dumps and captures in your private evidence folder outside the repository.
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **Select work in strict priority order:**
|
||||
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
|
||||
- **Priority 2 — Pick an unclaimed open issue:**
|
||||
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
|
||||
```
|
||||
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
|
||||
- **Priority 3 — Review & independently verify open PRs needing review:**
|
||||
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
|
||||
```
|
||||
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
|
||||
3. **Claim & isolate (for Priority 2 issue work):**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
|
||||
---
|
||||
|
||||
@@ -134,7 +121,7 @@ _Reserved — policy migration in progress._
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
|
||||
### Merge eligibility
|
||||
|
||||
+1
-25
@@ -10,36 +10,17 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
|
||||
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
|
||||
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
|
||||
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
|
||||
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
|
||||
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
|
||||
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
|
||||
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail.
|
||||
|
||||
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
|
||||
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
|
||||
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
|
||||
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
|
||||
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
|
||||
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
|
||||
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
|
||||
|
||||
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
|
||||
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
|
||||
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
|
||||
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
|
||||
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
|
||||
- `AcpHal.dll`:
|
||||
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
|
||||
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
|
||||
- **The default APU heap** is 64 MB.
|
||||
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
|
||||
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
|
||||
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
|
||||
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
|
||||
@@ -82,11 +63,6 @@ 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` Xbox DirectStorage fixes:
|
||||
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
|
||||
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
|
||||
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
|
||||
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
|
||||
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
|
||||
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
|
||||
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
|
||||
|
||||
+1
-4
@@ -3,8 +3,7 @@
|
||||
## Getting Started & Architecture
|
||||
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
|
||||
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
@@ -21,14 +20,12 @@
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
|
||||
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
|
||||
## Governance, Security & Legal
|
||||
|
||||
@@ -268,13 +268,3 @@ retrieved = "2026-11-22"
|
||||
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
|
||||
test = "Read slides 12 and 13. No console execution."
|
||||
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
|
||||
|
||||
[[claim]]
|
||||
id = "CLAIM-XBOX-CS-ENTRY-ABI"
|
||||
class = "U"
|
||||
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
|
||||
sources = ["docs/research/console-shader-abi.md"]
|
||||
retrieved = "2026-11-28"
|
||||
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
|
||||
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
|
||||
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
|
||||
@@ -1,200 +0,0 @@
|
||||
# Working Method: the Blocker Queue
|
||||
|
||||
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
|
||||
|
||||
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
|
||||
|
||||
There are no meetings, no rotating roles and no plan to interpret. The state of the project is in GitHub; the rules are here and in AGENTS.md.
|
||||
|
||||
## Why this shape
|
||||
|
||||
What the first target-build runs taught us:
|
||||
|
||||
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
|
||||
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
|
||||
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
|
||||
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
|
||||
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
|
||||
|
||||
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
|
||||
|
||||
## The stages
|
||||
|
||||
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
|
||||
|
||||
## Where the state lives
|
||||
|
||||
| What | Where | Who writes it |
|
||||
| --- | --- | --- |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) | Any agent that runs the gate check |
|
||||
| Everything the build is known to stop on | One **blocker issue** each (label `blocker`, plus `stage: <name>` and a track label) | The agent that found it |
|
||||
| Who is working on what | A claim comment on the blocker issue | The claiming agent |
|
||||
| What needs a person | Label `needs-human` | Any agent |
|
||||
| Rules | AGENTS.md and this document | Maintainers, by pull request |
|
||||
|
||||
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
|
||||
|
||||
### Blocker issues
|
||||
|
||||
A blocker issue is small and has a fixed shape, so that two agents that find the same thing file the same issue.
|
||||
|
||||
- **Title:** `[blocker] <signature>`. The signature is taken from the run report, not invented: for example `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll (write, unmapped)`, `exit status 1 after save query`, `stall: presenting thread in trapped instruction`. Before filing, search open and closed issues for the signature.
|
||||
- **Body:** the stage it blocks; how many of ten runs hit it; the run-report lines; what is known and not known. No bytes, names, hashes or addresses from the build.
|
||||
- **Order:** within a stage, the label `first` marks blockers that every run hits before any other; after those, lower issue number first.
|
||||
|
||||
## What an agent does when told "work"
|
||||
|
||||
AGENTS.md §0 has the binding version. In short, in strict order:
|
||||
|
||||
1. **Preflight.** Tools, login, disk space, an own bottle, a current `main`.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks or conflicts on a pull request your person opened.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Review it, and merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
|
||||
4. **Then one blocker.** The top unclaimed blocker of the current stage. Claim it, and do only that.
|
||||
5. **Then discover.** If the current stage has no unclaimed blocker, run the stage's gate check and file what it finds. If the gate passes, post the result on the ladder issue and label it `needs-human`: a person confirms the stage change.
|
||||
6. **Otherwise stop.** Report that the queue is empty. Do not invent work.
|
||||
|
||||
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
|
||||
|
||||
## Working one blocker
|
||||
|
||||
```text
|
||||
claim → evidence → smallest fix + test → ten runs → pull request → (someone else reviews and merges)
|
||||
```
|
||||
|
||||
1. **Claim.** Comment `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue. A claim with no commits or pull request after 3 days is free to take; say so in a comment when you take it.
|
||||
2. **Evidence before code.** Find what the build asked for and what it got. Use the run report, then the diagnostics (thread sampler, fault context, call trace). If that does not explain it within the session, write what was learned on the issue and release the claim; do not guess a fix.
|
||||
3. **Smallest fix.** Only what removes this blocker, inside the track directories it needs. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
4. **A test for the contract.** Every contract the fix teaches a shim gets a synthetic conformance test that fails without the fix.
|
||||
5. **Proof.** Ten runs before and ten after. Report every run.
|
||||
6. **Pull request.** One blocker, five short parts (below). Then stop: the next "work" starts from the top of the list.
|
||||
|
||||
### Pull-request description
|
||||
|
||||
Five parts and nothing else:
|
||||
|
||||
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
|
||||
2. **Contract:** what the console does, and which source says so (ranks below).
|
||||
3. **Fix:** what changed.
|
||||
4. **Test:** the conformance test, and that it fails without the fix.
|
||||
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
|
||||
|
||||
### Review
|
||||
|
||||
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
|
||||
|
||||
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
|
||||
|
||||
- a change under `abi/`;
|
||||
- a new or changed translator instruction class;
|
||||
- a contract from source rank 4 or 5;
|
||||
- anything touching the sandbox, security or licensing.
|
||||
|
||||
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
|
||||
|
||||
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
|
||||
|
||||
## Run protocol
|
||||
|
||||
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
|
||||
|
||||
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
|
||||
|
||||
- **Build:** current `main`, or `main` plus exactly the one branch under test.
|
||||
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
|
||||
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
|
||||
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
|
||||
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
|
||||
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
|
||||
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
|
||||
|
||||
**The run report** is generated, not written. Per run:
|
||||
|
||||
- outcome: frames presented, clean timeout, early exit with its status, or hang;
|
||||
- the start-up path taken;
|
||||
- every unimplemented call reached, counted;
|
||||
- every fault inside a BetterXen module;
|
||||
- pipelines drawn with: translated, passed through, skipped;
|
||||
- on a stall: every thread's stack.
|
||||
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings blocker issues are titled with.
|
||||
|
||||
## Sources of truth
|
||||
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
|
||||
|
||||
| Rank | Source | Notes |
|
||||
| --- | --- | --- |
|
||||
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
|
||||
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
|
||||
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
|
||||
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
|
||||
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
|
||||
|
||||
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
|
||||
|
||||
## Evidence and references
|
||||
|
||||
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
|
||||
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
|
||||
|
||||
## Finding blockers once the game runs
|
||||
|
||||
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
|
||||
|
||||
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
|
||||
|
||||
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
|
||||
|
||||
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
|
||||
|
||||
**How a problem is recognised,** from most to least reliable without a person:
|
||||
|
||||
| Signal | Catches | Needs a person |
|
||||
| --- | --- | --- |
|
||||
| Crash, hang, early exit | Stability | No |
|
||||
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
|
||||
| Frame compared with the last good capture of the same route | Regressions | No |
|
||||
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
|
||||
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
|
||||
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
|
||||
|
||||
Findings enter the queue as blocker issues with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
|
||||
|
||||
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
|
||||
|
||||
## What people do
|
||||
|
||||
People are needed for exactly four things, each marked `needs-human`:
|
||||
|
||||
1. confirming a stage change after a gate passes;
|
||||
2. deciding a decision gate (for example the graphics back end);
|
||||
3. licence, provenance and legal questions;
|
||||
4. changing these rules.
|
||||
|
||||
Everything else is the queue.
|
||||
|
||||
## Starting the queue
|
||||
|
||||
The queue starts with what the first target-build runs already found. Each line was filed as an issue on 2026-11-29 (#664–#680); the table is kept as a record of the starting point, and the issues are the live state.
|
||||
|
||||
| Stage | Signature or task | Track |
|
||||
| --- | --- | --- |
|
||||
| Boot | Run tooling in the repository: offline runner, per-run report with signatures, ten-run summary, thread sampler, machine-wide run lock, per-session bottle | A |
|
||||
| Boot | `stall: presenting thread in trapped CLZERO loop` | A |
|
||||
| Boot | `unimplemented IXUser slot 3` (handle duplication) | E |
|
||||
| Boot | `unimplemented IXGameRuntimeCore slots 6, 13, 14, 15` (async run; task-queue composite, port, duplicate) | E |
|
||||
| Boot | `unimplemented IXGameSaveImpl slot 13` (container info; and slot 15) | E |
|
||||
| Boot | `fault in XCRDAPI.dll (write, unmapped)` — page remapping is not atomic | B |
|
||||
| Boot | `serialized-pipeline calls succeed with a null pipeline` — they must fail and be logged | C |
|
||||
| Boot | `exit status 1, nothing logged` (1 run in 5) | A |
|
||||
| Picture | D3DMetal capability checks: direct heap indexing, 64-lane compute through the translator, 64-bit atomics, mesh and amplification shaders | D, F |
|
||||
| Picture | Vendor the upstream translator with provenance entries; amend ADR 0008 | D |
|
||||
| Picture | Translator behind `bx_shader_bridge.dll`; host pipelines created on first use | C, D |
|
||||
| Picture | `placed texture contents not uploaded` | C |
|
||||
| Picture | `build waits after sign-in with nothing unimplemented` — needs evidence | E |
|
||||
| Picture | Reference images for the first screens | `needs-human` |
|
||||
| Menus | Input record and replay in the `GameInput` shim; routes as ten-run regression tests | E, A |
|
||||
| Menus | Play-session recording in the launcher: input stream, starting saves, mark hotkey | A |
|
||||
| Fidelity | Frame capture in `d3d12_xs` and an offline frame replayer | C |
|
||||
|
||||
Fixes for several Boot lines exist on a local experiment branch; they still go through the queue, one pull request each, with tests and ten-run proof.
|
||||
@@ -1,75 +0,0 @@
|
||||
# Console compute shader entry ABI (probe results)
|
||||
|
||||
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
|
||||
|
||||
What this is:
|
||||
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
|
||||
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
|
||||
|
||||
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
|
||||
|
||||
## Method
|
||||
|
||||
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
|
||||
|
||||
| Probe | Root signature | Shader |
|
||||
| --- | --- | --- |
|
||||
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
|
||||
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
|
||||
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
|
||||
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
|
||||
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
|
||||
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
|
||||
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
|
||||
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
|
||||
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
|
||||
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
|
||||
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
|
||||
|
||||
## Observations
|
||||
|
||||
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
|
||||
|
||||
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
|
||||
- A root constant takes one SGPR (p01: `s4`–`s7`).
|
||||
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
|
||||
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
|
||||
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
|
||||
|
||||
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
|
||||
|
||||
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
|
||||
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
|
||||
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
|
||||
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
|
||||
|
||||
**Descriptor tables.** Descriptors are loaded from the table address:
|
||||
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
|
||||
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
|
||||
|
||||
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
|
||||
|
||||
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
|
||||
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
|
||||
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
|
||||
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
|
||||
|
||||
## Open
|
||||
|
||||
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
|
||||
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
|
||||
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
|
||||
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
|
||||
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
|
||||
- **`s0`–`s3`:** what they hold when root data fits in registers.
|
||||
- **One compiler build, one host:** a different GDK version may differ.
|
||||
|
||||
## Provenance
|
||||
|
||||
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
|
||||
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
|
||||
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
|
||||
+20
-81
@@ -1,6 +1,6 @@
|
||||
# BetterXen Roadmap
|
||||
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
|
||||
## Direction
|
||||
|
||||
@@ -19,7 +19,7 @@ External Foundation (user-installed, never bundled):
|
||||
Apple Silicon: ARM64, Metal, unified memory
|
||||
```
|
||||
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
|
||||
|
||||
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
|
||||
|
||||
@@ -35,95 +35,34 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
---
|
||||
|
||||
## Foundation and stages
|
||||
## Milestones (M0 → M6)
|
||||
|
||||
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
|
||||
|
||||
### Foundation (history)
|
||||
|
||||
| Milestone | What it established | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
|
||||
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
|
||||
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
|
||||
|
||||
### The stages
|
||||
|
||||
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
|
||||
|
||||
| Stage | The target build… | Exit gate | Status |
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
|
||||
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
|
||||
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
|
||||
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
|
||||
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
|
||||
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), integrate the shipped xmem-configured D3D12 placed heap (#464) into the first-frame fixture (#469), bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
|
||||
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
|
||||
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
|
||||
|
||||
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
|
||||
### Startup diagnosis
|
||||
|
||||
### Boot
|
||||
The product goal is to reach a frame presented by the target software. Under the current [contribution rules](../CONTRIBUTING.md), project runs use original synthetic workloads. Start with `test_integration_boot.exe` for startup and `test_veh_unhandled.exe` as a crash-logging control. Use a focused synthetic reproducer once a failing contract is identified.
|
||||
|
||||
**Known work, all found by running the target build:**
|
||||
Before treating either startup warning as causal, add diagnostics that record the requested DirectStorage factory IID and returned HRESULT (#483) and distinguish null, unrecognized and supported BetterXen virtual-memory configurations (#464 follow-up). On a pinned launcher, shim set and backend, repeat the synthetic case before and after a fix. Record normal exit, crash or timeout, the last completed checkpoint, and the exception thread and module offset when available. Progress means reaching the next named checkpoint in the same reproducer. Startup diagnosis and the budget fix proceed alongside the M2 exit gates.
|
||||
|
||||
| Blocker | Effect | State |
|
||||
| --- | --- | --- |
|
||||
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
|
||||
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
|
||||
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
|
||||
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
|
||||
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
|
||||
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
|
||||
### M2 first-frame acceptance and parallel memory work
|
||||
|
||||
**Not needed for the gate:** audio output, correct pictures, performance.
|
||||
|
||||
### Picture
|
||||
|
||||
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
|
||||
|
||||
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
|
||||
2. **The translator.** Vendor a pinned copy of the authorized upstream GFX10-to-DXIL translator into `shader-transpiler/` (per-file licence check, upstream registry and reuse matrix entries, ADR 0008 amendment), and expose it through `bx_shader_bridge.dll`. BetterXen owns its copy and fixes it.
|
||||
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
|
||||
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
|
||||
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
|
||||
|
||||
### Menus to Playable — known work and unknowns
|
||||
|
||||
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
|
||||
|
||||
| Stage | Known work | Main unknown |
|
||||
| --- | --- | --- |
|
||||
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
|
||||
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
|
||||
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
|
||||
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
|
||||
|
||||
### Decision gates
|
||||
|
||||
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
|
||||
|
||||
| Gate | When | Question | If the answer is no |
|
||||
| --- | --- | --- | --- |
|
||||
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
|
||||
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
|
||||
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
|
||||
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
|
||||
|
||||
### What counts as progress
|
||||
|
||||
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
|
||||
|
||||
1. remove a blocker of the current stage (shown by the run report before and after);
|
||||
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
|
||||
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
|
||||
4. retire a risk at a decision gate.
|
||||
|
||||
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
|
||||
- **First frame (#465, #469).** The synthetic placement criterion uses BetterXen's `BXVM` block to configure the separate D3D12-owned WRITE_BACK heap shipped in #486. On the recorded overlay, #494 copied the backbuffer before the flip, counted one host `Present`, then compared 256 RGBA8 pixels through the D3D12 mapping after waiting. The xmem sentinel shows that the original page remained separate. Visibility through the original xmem address remains an open compatibility question for M3, informed by #473. Displayed-image verification is outside this fixture's measurements. Record a single `main` commit containing the integrated presentation and fixture changes, confirm that the fixture executable built, and have someone who authored neither the fixture nor the presentation bridge verify the D3DMetal run and pixel-mismatch control. The shader gate still requires a recorded D1/D2 selection. [Fixture and receipts](https://github.com/MacosPorters/betterxen/pull/494) · [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Shader format gate (#466, ADR 0008).** D1 remains the only branch with end-to-end execution evidence, and the static scan gives it measured inputs in the target workload: 52 DXIL SM 6.5 compute containers with LLVM bitcode. The same scan makes D2 a concrete compatibility candidate rather than a hypothesis: the workload's FidelityFX upscaler component embeds 29 ACCC-only containers. Select D2 work only when a required pipeline-creation path refuses an ACCC-only container at runtime — if that refusal precedes the first presented frame, treat it as a first-frame blocker; if it appears only with upscaling enabled, track it under M4 upscaling. Two Track D parser prerequisites precede any D2 trial: extend the clean-room `FSPX` section-table layout to accept the observed tables (a maintainer provenance decision, since no public format description exists), and stop the classifier from treating a `NOBC` header-only program as executable DXIL. The first `shader_gate` record the target workload writes names the shader path its first pipeline creation actually submits. [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Title budget (#550, #552).** Keep current allocation ownership and give xmem atomic admission authority through an ABI-first contract. The initial scope combines xmem usage with the existing charged `CreateHeap` path. Under a 512 MiB cap, an xmem allocation of 256 MiB followed by a 384 MiB heap was refused, while the reverse admitted 640 MiB. Test both orders, concurrent admission and rollback. Charge a backing allocation once across aliases. Accounting for `CreateHeap1`, committed and reserved resources, and internal buffers such as XCRDAPI staging remains an open scope decision. Placement and wrapper lifetime have separate checks (#554, #572). [Merged-base reproduction](https://github.com/MacosPorters/betterxen/pull/486#issuecomment-7209751182)
|
||||
- **M3 resource handling.** Keep explicit paths for fixed addresses, existing contents, pre-device allocations, sections/scatter and opaque textures. The draft eligibility analysis found no reliable end-to-end classifier. Resolve the `XMemVirtualAlloc` argument-count question (#518) before using graphics flags as evidence. A mapped-buffer trial is optional and opt-in, with the existing path as fallback. Require a known consumer before returning a pointer, verify its alignment and lifetime, and confirm completion on every participating queue before reusing memory for work BetterXen submits. #483 retains its DirectStorage interface scope. [Draft eligibility analysis](https://github.com/MacosPorters/betterxen/blob/7e0b515131150fec6b5117c9498b6c0faf0ca382/docs/architecture/proposals/001-unified-memory/appendix/eligibility.md)
|
||||
- **M6 optimization.** Compare the existing path with a candidate allocator or bounded pool on the same 16 GB host and backend. Check correct output for both paths across repeated matched workloads. Include cold setup, transfers, fragmentation, pending retirements, post-release footprint and whole-frame time. Require a repeatable workload benefit before choosing a default.
|
||||
|
||||
---
|
||||
|
||||
## How Progress Is Reported
|
||||
|
||||
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
|
||||
|
||||
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
|
||||
@@ -1,137 +0,0 @@
|
||||
# Target-Build Bring-Up: Development Cycle and Review
|
||||
|
||||
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
|
||||
|
||||
## Authorization is recorded, not assumed
|
||||
|
||||
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
|
||||
|
||||
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
|
||||
- the build;
|
||||
- the evidence class: target-build observation, or authorized SDK documentation;
|
||||
- the maintainer who approved it;
|
||||
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
|
||||
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
|
||||
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
|
||||
- **The note's ID goes into every PR and every review** that relies on that evidence.
|
||||
|
||||
## Roles
|
||||
|
||||
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
|
||||
- **Author.** Turns one finding into one single-track PR.
|
||||
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
|
||||
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
|
||||
|
||||
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
|
||||
|
||||
## Cycle
|
||||
|
||||
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
|
||||
2. **Record the evidence privately,** under an evidence note ID.
|
||||
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
|
||||
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
|
||||
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
|
||||
6. **Review independently** (see "What a reviewer does").
|
||||
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
|
||||
|
||||
### Bring-up checkpoints
|
||||
|
||||
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
|
||||
|
||||
1. **Starts:** reaches its first graphics device.
|
||||
2. **Presents:** presents its first frame, whatever it contains.
|
||||
3. **Frame loop:** keeps presenting for a recorded duration.
|
||||
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
|
||||
5. **Interactive:** reaches a menu that accepts input.
|
||||
|
||||
Each PR states which checkpoint it affects, and the measured result before and after.
|
||||
|
||||
## PR description template
|
||||
|
||||
```text
|
||||
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
|
||||
Source: "authorized SDK documentation" and/or "target-build observation";
|
||||
never quote header or documentation text, never name the title or build
|
||||
Authorization: authorization note ID
|
||||
Evidence: evidence note ID(s)
|
||||
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
|
||||
Test: the conformance test that asserts the contract, and how its expected
|
||||
values were derived independently of the implementation
|
||||
Checkpoint: the checkpoint this affects, with the measured result before and after
|
||||
```
|
||||
|
||||
## What a reviewer does
|
||||
|
||||
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
|
||||
|
||||
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
|
||||
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
|
||||
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
|
||||
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
|
||||
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
|
||||
|
||||
## Offline-run procedure
|
||||
|
||||
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
|
||||
|
||||
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
|
||||
|
||||
```sh
|
||||
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
|
||||
BOTTLE=<bottle name>
|
||||
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
|
||||
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
|
||||
|
||||
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
|
||||
# serve the title outside it.
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
|
||||
|
||||
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
|
||||
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
|
||||
&& echo REACHABLE || echo BLOCKED
|
||||
|
||||
# 3. Run the title inside the same profile. Every process it starts, including the new
|
||||
# wineserver, inherits the sandbox.
|
||||
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
|
||||
BX_TRACE_D3D=0 BX_NULL_RENDER=1 \
|
||||
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
|
||||
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
|
||||
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
|
||||
```
|
||||
|
||||
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
|
||||
|
||||
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
|
||||
|
||||
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
|
||||
|
||||
| Switch | Where | Effect |
|
||||
| --- | --- | --- |
|
||||
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
|
||||
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
|
||||
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
|
||||
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
|
||||
|
||||
Their output can contain title addresses and file names, so it goes only into the private evidence store.
|
||||
|
||||
## Evidence
|
||||
|
||||
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
|
||||
|
||||
## What never enters the repository
|
||||
|
||||
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
|
||||
|
||||
- SDK header or documentation text;
|
||||
- the title's name or file names;
|
||||
- identifiers derived from the title or build: its hashes, addresses or raw logs;
|
||||
- decompiled code or disassembly;
|
||||
- screenshots of the title;
|
||||
- personal paths.
|
||||
|
||||
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
|
||||
@@ -41,21 +41,6 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
|
||||
"XPC_SERVICE_NAME",
|
||||
];
|
||||
|
||||
/// Opt-in `bx_runtime_veh.dll` diagnostic switches. They carry addresses and counts, never
|
||||
/// credentials, so the isolated guest environment lets them through by name; every other
|
||||
/// variable is still stripped.
|
||||
const DIAGNOSTIC_ENV_ALLOWLIST: &[&str] = &[
|
||||
"BX_VEH_AV_CONTEXT",
|
||||
"BX_VEH_AV_ALL",
|
||||
"BX_VEH_WATCH",
|
||||
"BX_VEH_WATCH_RANGE",
|
||||
"BX_VEH_WATCH_RANGE_MAX",
|
||||
"BX_VEH_HIT",
|
||||
"BX_VEH_HIT_ALL",
|
||||
"BX_VEH_HIT_RDX",
|
||||
"BX_VEH_SAMPLE",
|
||||
];
|
||||
|
||||
fn usage_text() -> &'static str {
|
||||
"BetterXen Hybrid CLI (bx-cli)\n\
|
||||
\n\
|
||||
@@ -399,24 +384,16 @@ fn render_trace(text: &str) -> String {
|
||||
for hit in &summary.breakpoint_exceptions {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" code={} {} + RVA={} (module_base={} address={})",
|
||||
" code={} {} + RVA={} (module_base={})",
|
||||
hit.exception_code.as_deref().unwrap_or("unknown"),
|
||||
hit.module.as_deref().unwrap_or("?"),
|
||||
hit.rva.as_deref().unwrap_or("unknown"),
|
||||
hit.module_base.as_deref().unwrap_or("unknown"),
|
||||
hit.address.as_deref().unwrap_or("unknown"),
|
||||
);
|
||||
}
|
||||
// Any record at the cap counts: concurrent threads, or several processes appending to one
|
||||
// log, can write the capped record before a lower-numbered one.
|
||||
if let Some(limit) =
|
||||
summary
|
||||
.breakpoint_exceptions
|
||||
.iter()
|
||||
.find_map(|hit| match (hit.record, hit.limit) {
|
||||
(Some(record), Some(limit)) if limit > 0 && record >= limit => Some(limit),
|
||||
_ => None,
|
||||
})
|
||||
if let Some(last) = summary.breakpoint_exceptions.last()
|
||||
&& let (Some(record), Some(limit)) = (last.record, last.limit)
|
||||
&& record >= limit
|
||||
{
|
||||
let _ = writeln!(
|
||||
out,
|
||||
@@ -451,7 +428,7 @@ where
|
||||
{
|
||||
let mut env_map = BTreeMap::new();
|
||||
env_map.insert("PATH".to_string(), SAFE_CHILD_PATH.to_string());
|
||||
for &key in HOST_ENV_ALLOWLIST.iter().chain(DIAGNOSTIC_ENV_ALLOWLIST) {
|
||||
for &key in HOST_ENV_ALLOWLIST {
|
||||
if let Some(val) = lookup(key) {
|
||||
env_map.insert(key.to_string(), val);
|
||||
}
|
||||
@@ -1706,26 +1683,6 @@ sub setup_bottle_wineprefix {
|
||||
assert!(!child.contains_key("CX_GRAPHICS_BACKEND"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_env_passes_only_the_named_veh_diagnostics() {
|
||||
let host = BTreeMap::from([
|
||||
("BX_VEH_AV_CONTEXT", "1"),
|
||||
("BX_VEH_SAMPLE", "5"),
|
||||
("BX_VEH_UNKNOWN", "x"),
|
||||
("BX_LOG_FILE", "/tmp/elsewhere.jsonl"),
|
||||
("GH_TOKEN", "secret_token"),
|
||||
]);
|
||||
let child = collect_isolated_host_env(|k| host.get(k).map(|s| (*s).to_string()));
|
||||
assert_eq!(
|
||||
child.get("BX_VEH_AV_CONTEXT").map(String::as_str),
|
||||
Some("1")
|
||||
);
|
||||
assert_eq!(child.get("BX_VEH_SAMPLE").map(String::as_str), Some("5"));
|
||||
assert!(!child.contains_key("BX_VEH_UNKNOWN"));
|
||||
assert!(!child.contains_key("BX_LOG_FILE"));
|
||||
assert!(!child.contains_key("GH_TOKEN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_unix_path_to_wine_z_drive() {
|
||||
assert_eq!(
|
||||
@@ -1800,8 +1757,7 @@ sub setup_bottle_wineprefix {
|
||||
assert!(
|
||||
rendered.contains(
|
||||
"\nBreakpoint/assert exceptions, first chance (1):\n code=0x80000003 \
|
||||
title.exe + RVA=0x0000000002236178 (module_base=0x0000000140000000 \
|
||||
address=0x0000000142236178)\n"
|
||||
title.exe + RVA=0x0000000002236178 (module_base=0x0000000140000000)\n"
|
||||
),
|
||||
"{rendered}"
|
||||
);
|
||||
@@ -1824,30 +1780,6 @@ sub setup_bottle_wineprefix {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_the_cap_when_a_capped_record_is_not_the_last_line() {
|
||||
// Two threads (or processes) appending: the capped record lands before record 15.
|
||||
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
|
||||
{"ts_ms":6,"tid":8,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(
|
||||
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_the_address_of_a_breakpoint_outside_any_image() {
|
||||
let log = r#"{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(
|
||||
rendered.contains("address=0x0000000000410000"),
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_decisions_kinds_stages_gaps_and_missing_bridge() {
|
||||
// Realistic records, matching the emitter in shims/d3d12_xs/shader_gate.cpp.
|
||||
|
||||
@@ -191,8 +191,6 @@ pub struct BreakpointException {
|
||||
pub module: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
/// The faulting address, which locates a breakpoint outside any image (module `?`).
|
||||
pub address: Option<String>,
|
||||
/// 1-based index of this record and the per-process cap, so a reader can tell a run
|
||||
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
|
||||
pub record: Option<u32>,
|
||||
@@ -377,7 +375,6 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
module: extract_json_str(trimmed, "module").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
address: extract_json_str(trimmed, "address").map(str::to_owned),
|
||||
record: extract_json_u32(trimmed, "record"),
|
||||
limit: extract_json_u32(trimmed, "limit"),
|
||||
});
|
||||
@@ -474,7 +471,6 @@ mod tests {
|
||||
module: Some("title.exe".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000002236178".into()),
|
||||
address: Some("0x0000000142236178".into()),
|
||||
record: Some(1),
|
||||
limit: Some(16),
|
||||
},
|
||||
@@ -483,7 +479,6 @@ mod tests {
|
||||
module: Some("?".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
address: Some("0x0000000000410000".into()),
|
||||
record: Some(2),
|
||||
limit: Some(16),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Experimental RDNA 2 (gfx1030) -> HLSL translator for straight-line console VS/PS pairs.
|
||||
|
||||
Input: the GPU instruction blobs of a deserialized console graphics pipeline (VS and PS).
|
||||
Output, in --out: <vs>_<ps>.vs.hlsl / .ps.hlsl, compiled .vs.dxil / .ps.dxil (when --dxc is
|
||||
given), and <vs>_<ps>.il, the input layout the shim creates the host pipeline with.
|
||||
|
||||
Model (inferences from the console compiler's listings and the target build's code; see the
|
||||
first-frame notes):
|
||||
* Code starts after a header of 12-byte `v_nop` + literal records (VOP3 word top half 0xD580).
|
||||
* VS user data: s[0:1] = vertex-buffer descriptor table (16-byte V#s), s2 = base vertex.
|
||||
Both stages: s8 = 32-bit pointer to root parameter 0's descriptor table (32-byte entries).
|
||||
* A buffer V# loaded from the root table is a constant buffer; an 8-dword T# is a texture.
|
||||
* PS v0:v1 are barycentrics; `v_interp_p1/p2 ... attrN.c` is attribute N, component c.
|
||||
* VS `exp paramN` pairs with PS `attrN`; `exp pos0` is the position.
|
||||
HLSL resources use register space 100 (+ root parameter index); the shim widens each title root
|
||||
signature with overlapping ranges in that space so table entry k is register k.
|
||||
|
||||
Only straight-line code with the instructions below is accepted; anything else fails loudly.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
LLVM_MC = os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc")
|
||||
|
||||
DXGI = {"R32_UINT": 42, "R32G32_UINT": 17, "R32G32B32_UINT": 7, "R32G32B32A32_UINT": 3,
|
||||
"R8G8B8A8_UNORM": 28, "R16G16_FLOAT": 34, "R16G16B16A16_FLOAT": 10, "R32G32_FLOAT": 16}
|
||||
TBUF_FMT = {"BUF_FMT_8_8_8_8_UNORM": ("R8G8B8A8_UNORM", 4, "float"),
|
||||
"BUF_FMT_16_16_FLOAT": ("R16G16_FLOAT", 2, "float"),
|
||||
"BUF_FMT_16_16_16_16_FLOAT": ("R16G16B16A16_FLOAT", 4, "float"),
|
||||
"BUF_FMT_32_32_FLOAT": ("R32G32_FLOAT", 2, "float")}
|
||||
|
||||
|
||||
class Unsupported(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def code_words(blob):
|
||||
off = 0
|
||||
while off + 12 <= len(blob) and struct.unpack_from("<I", blob, off)[0] >> 16 == 0xD580:
|
||||
off += 12
|
||||
return blob[off:]
|
||||
|
||||
|
||||
def disassemble(blob):
|
||||
body = code_words(blob)
|
||||
text = " ".join("0x%02x" % b for b in body)
|
||||
r = subprocess.run([LLVM_MC, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
|
||||
capture_output=True, text=True)
|
||||
out = []
|
||||
for line in r.stdout.splitlines():
|
||||
line = line.split(";")[0].strip()
|
||||
if not line or line.startswith("."):
|
||||
continue
|
||||
out.append(line)
|
||||
if line == "s_endpgm":
|
||||
break
|
||||
if "s_endpgm" not in out:
|
||||
raise Unsupported("no s_endpgm in decoded code")
|
||||
return out
|
||||
|
||||
|
||||
def split_ops(rest):
|
||||
ops, depth, cur = [], 0, ""
|
||||
for ch in rest:
|
||||
if ch in "[(":
|
||||
depth += 1
|
||||
elif ch in "])":
|
||||
depth -= 1
|
||||
if ch == "," and depth == 0:
|
||||
ops.append(cur.strip())
|
||||
cur = ""
|
||||
else:
|
||||
cur += ch
|
||||
if cur.strip():
|
||||
ops.append(cur.strip())
|
||||
return ops
|
||||
|
||||
|
||||
def reg_range(op):
|
||||
m = re.fullmatch(r"([sv])\[(\d+):(\d+)\]", op)
|
||||
if m:
|
||||
return m.group(1), int(m.group(2)), int(m.group(3))
|
||||
m = re.fullmatch(r"([sv])(\d+)", op)
|
||||
if m:
|
||||
return m.group(1), int(m.group(2)), int(m.group(2))
|
||||
return None
|
||||
|
||||
|
||||
class Translator:
|
||||
def __init__(self, stage):
|
||||
self.stage = stage
|
||||
self.lines = []
|
||||
self.sprov = {} # sgpr -> provenance tuple
|
||||
self.cbs = set() # table indices used as constant buffers
|
||||
self.textures = set()
|
||||
self.inputs = [] # VS: (semantic index, fmt, slot, offset, ncomp, kind)
|
||||
self.attrs = set() # PS attribute indices read
|
||||
self.exports = {} # name -> list of 4 expressions
|
||||
self.used_v = set()
|
||||
self.used_s = set()
|
||||
|
||||
# ---- operands -------------------------------------------------------------
|
||||
def src(self, op, as_float=False):
|
||||
"""HLSL expression (uint) for a 32-bit source operand."""
|
||||
neg = False
|
||||
if op.startswith("-"):
|
||||
neg, op = True, op[1:]
|
||||
m = re.fullmatch(r"neg\((.+)\)", op)
|
||||
if m:
|
||||
neg, op = True, m.group(1)
|
||||
r = reg_range(op)
|
||||
if r and r[1] == r[2]:
|
||||
kind, n, _ = r
|
||||
(self.used_v if kind == "v" else self.used_s).add(n)
|
||||
e = "%s%d" % (kind, n)
|
||||
elif re.fullmatch(r"-?\d+\.\d+", op):
|
||||
e = "asuint(%sf)" % op
|
||||
elif re.fullmatch(r"0x[0-9a-fA-F]+", op):
|
||||
e = "0x%xu" % int(op, 16)
|
||||
elif re.fullmatch(r"-?\d+", op):
|
||||
v = int(op)
|
||||
e = "%du" % (v & 0xFFFFFFFF)
|
||||
else:
|
||||
raise Unsupported("operand %r" % op)
|
||||
if neg:
|
||||
e = "(asuint(-asfloat(%s)))" % e
|
||||
return "asfloat(%s)" % e if as_float else e
|
||||
|
||||
def dst(self, op):
|
||||
r = reg_range(op)
|
||||
if not r or r[1] != r[2]:
|
||||
raise Unsupported("destination %r" % op)
|
||||
(self.used_v if r[0] == "v" else self.used_s).add(r[1])
|
||||
return "%s%d" % (r[0], r[1])
|
||||
|
||||
def emit(self, s):
|
||||
self.lines.append(" " + s)
|
||||
|
||||
# ---- instructions -----------------------------------------------------------
|
||||
def run(self, insts):
|
||||
ignore = re.compile(r"^(s_waitcnt|s_clause|s_inst_prefetch|s_setprio|s_nop|s_wqm_b64|s_endpgm|v_nop)\b")
|
||||
for line in insts:
|
||||
if ignore.match(line):
|
||||
continue
|
||||
parts = line.split(None, 1)
|
||||
op, rest = parts[0], parts[1] if len(parts) > 1 else ""
|
||||
mods = ""
|
||||
ops = split_ops(rest)
|
||||
# modifiers after operands (e.g. "0 idxen offset:12", "dmask:0xf dim:...")
|
||||
handler = getattr(self, "i_" + op, None)
|
||||
if handler is None:
|
||||
raise Unsupported("instruction %r" % line)
|
||||
handler(ops, line)
|
||||
|
||||
def exec_write(self, ops):
|
||||
return ops and ops[0].startswith("exec")
|
||||
|
||||
def i_s_mov_b32(self, ops, line):
|
||||
if ops[0] == "m0":
|
||||
return
|
||||
r = reg_range(ops[0])
|
||||
s = reg_range(ops[1])
|
||||
if s and s[0] == "s":
|
||||
self.sprov[r[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
|
||||
else:
|
||||
self.sprov[r[1]] = ("imm", int(self.src(ops[1]).rstrip("u"), 0))
|
||||
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
|
||||
|
||||
def i_s_mov_b64(self, ops, line):
|
||||
if ops[0] == "exec" or ops[1] == "exec":
|
||||
return
|
||||
d = reg_range(ops[0])
|
||||
s = reg_range(ops[1])
|
||||
if s:
|
||||
self.sprov[d[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
|
||||
self.sprov[d[1] + 1] = self.sprov.get(s[1] + 1, ("sgpr", s[1] + 1))
|
||||
else:
|
||||
v = int(ops[1], 0)
|
||||
self.sprov[d[1]] = ("imm", v & 0xFFFFFFFF)
|
||||
self.sprov[d[1] + 1] = ("imm", (v >> 32) & 0xFFFFFFFF)
|
||||
|
||||
def i_s_bfe_u32(self, ops, line):
|
||||
pass # masks the high half of a copied table pointer; provenance is unchanged
|
||||
|
||||
def table_of(self, base):
|
||||
b = reg_range(base)
|
||||
p = self.sprov.get(b[1], ("sgpr", b[1]))
|
||||
if p == ("sgpr", 0) and self.stage == "vs":
|
||||
return "vbtable"
|
||||
if p == ("sgpr", 8):
|
||||
return "root0"
|
||||
raise Unsupported("descriptor load from %r (provenance %r)" % (base, p))
|
||||
|
||||
def smem_load(self, ops, line, ndw):
|
||||
d = reg_range(ops[0])
|
||||
table = self.table_of(ops[1])
|
||||
off = 0 if ops[2] == "null" else int(ops[2], 0)
|
||||
if table == "vbtable":
|
||||
prov = ("vb", off // 16)
|
||||
elif ndw == 4:
|
||||
prov = ("cb", off // 32)
|
||||
elif ndw == 8:
|
||||
prov = ("tex", off // 32)
|
||||
else:
|
||||
raise Unsupported(line)
|
||||
for i in range(ndw):
|
||||
self.sprov[d[1] + i] = prov
|
||||
|
||||
def i_s_load_dwordx4(self, ops, line):
|
||||
self.smem_load(ops, line, 4)
|
||||
|
||||
def i_s_load_dwordx8(self, ops, line):
|
||||
self.smem_load(ops, line, 8)
|
||||
|
||||
def s_buffer_load(self, ops, line, ndw):
|
||||
d = reg_range(ops[0])
|
||||
desc = reg_range(ops[1])
|
||||
p = self.sprov.get(desc[1])
|
||||
if not p or p[0] != "cb":
|
||||
raise Unsupported("s_buffer_load from %r" % (p,))
|
||||
cb = p[1]
|
||||
self.cbs.add(cb)
|
||||
off = 0 if ops[2] == "null" else int(ops[2], 0)
|
||||
for i in range(ndw):
|
||||
word = off // 4 + i
|
||||
self.sprov[d[1] + i] = ("cbword", cb, word)
|
||||
self.emit("s%d = cb%d_word(%d);" % (d[1] + i, cb, word))
|
||||
self.used_s.add(d[1] + i)
|
||||
|
||||
def i_s_buffer_load_dword(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 1)
|
||||
|
||||
def i_s_buffer_load_dwordx2(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 2)
|
||||
|
||||
def i_s_buffer_load_dwordx4(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 4)
|
||||
|
||||
def i_s_buffer_load_dwordx8(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 8)
|
||||
|
||||
def i_s_buffer_load_dwordx16(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 16)
|
||||
|
||||
# vertex fetch -> input layout element
|
||||
def vb_slot(self, op):
|
||||
p = self.sprov.get(reg_range(op)[1])
|
||||
if not p or p[0] != "vb":
|
||||
raise Unsupported("vertex fetch through %r" % (p,))
|
||||
return p[1]
|
||||
|
||||
def fetch(self, ops, line, ncomp, fmt, kind):
|
||||
if "idxen" not in line or "offen" in line:
|
||||
raise Unsupported(line)
|
||||
d = reg_range(ops[0])
|
||||
slot = self.vb_slot(ops[2])
|
||||
m = re.search(r"offset:(\d+)", line)
|
||||
off = int(m.group(1)) if m else 0
|
||||
sem = len(self.inputs)
|
||||
self.inputs.append((sem, fmt, slot, off, ncomp, kind))
|
||||
comps = "xyzw"
|
||||
for i in range(d[2] - d[1] + 1):
|
||||
src = "in%d.%s" % (sem, comps[i])
|
||||
self.emit("v%d = %s;" % (d[1] + i, "asuint(%s)" % src if kind == "float" else src))
|
||||
self.used_v.add(d[1] + i)
|
||||
|
||||
def i_buffer_load_dword(self, ops, line):
|
||||
self.fetch(ops, line, 1, "R32_UINT", "uint")
|
||||
|
||||
def i_buffer_load_dwordx2(self, ops, line):
|
||||
self.fetch(ops, line, 2, "R32G32_UINT", "uint")
|
||||
|
||||
def i_buffer_load_dwordx3(self, ops, line):
|
||||
self.fetch(ops, line, 3, "R32G32B32_UINT", "uint")
|
||||
|
||||
def i_buffer_load_dwordx4(self, ops, line):
|
||||
self.fetch(ops, line, 4, "R32G32B32A32_UINT", "uint")
|
||||
|
||||
def i_tbuffer_load_format_xyzw(self, ops, line):
|
||||
m = re.search(r"format:\[(\w+)\]", line)
|
||||
if not m or m.group(1) not in TBUF_FMT:
|
||||
raise Unsupported(line)
|
||||
fmt, n, kind = TBUF_FMT[m.group(1)]
|
||||
self.fetch(ops, line, 4, fmt, kind)
|
||||
|
||||
# ALU
|
||||
def vop2f(self, ops, expr):
|
||||
a, b = self.src(ops[1], True), self.src(ops[2], True)
|
||||
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr % (a, b)))
|
||||
|
||||
def i_v_mul_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "%s * %s")
|
||||
|
||||
i_v_mul_f32_e64 = i_v_mul_f32_e32
|
||||
|
||||
def i_v_add_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "%s + %s")
|
||||
|
||||
i_v_add_f32_e64 = i_v_add_f32_e32
|
||||
|
||||
def i_v_sub_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "%s - %s")
|
||||
|
||||
def i_v_max_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "max(%s, %s)")
|
||||
|
||||
def i_v_min_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "min(%s, %s)")
|
||||
|
||||
def i_v_fmac_f32_e32(self, ops, line):
|
||||
d = self.dst(ops[0])
|
||||
self.emit("%s = asuint(mad(%s, %s, asfloat(%s)));" % (d, self.src(ops[1], True), self.src(ops[2], True), d))
|
||||
|
||||
def i_v_fma_f32(self, ops, line):
|
||||
self.emit("%s = asuint(mad(%s, %s, %s));" % (self.dst(ops[0]), self.src(ops[1], True),
|
||||
self.src(ops[2], True), self.src(ops[3], True)))
|
||||
|
||||
def i_v_mov_b32_e32(self, ops, line):
|
||||
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
|
||||
|
||||
def i_v_add_nc_u32_e32(self, ops, line):
|
||||
# only the vertex-index computation uses it here; the index itself is the IA's job
|
||||
if self.stage == "vs":
|
||||
return
|
||||
self.emit("%s = %s + %s;" % (self.dst(ops[0]), self.src(ops[1]), self.src(ops[2])))
|
||||
|
||||
def fma_mix(self, ops, line, hi):
|
||||
m = re.search(r"op_sel_hi:\[(\d),(\d),(\d)\]", line)
|
||||
if "op_sel:" in line or not m:
|
||||
raise Unsupported(line)
|
||||
srcs = []
|
||||
for i, sel in enumerate(m.groups()):
|
||||
o = ops[1 + i].split()[0]
|
||||
neg = False
|
||||
mm = re.fullmatch(r"neg\((.+)\)", o)
|
||||
if mm:
|
||||
neg, o = True, mm.group(1)
|
||||
e = self.src(o)
|
||||
f = "f16tof32(%s & 0xffffu)" % e if sel == "1" else "asfloat(%s)" % e
|
||||
srcs.append("(-%s)" % f if neg else f)
|
||||
d = self.dst(ops[0])
|
||||
val = "f32tof16(mad(%s, %s, %s))" % tuple(srcs)
|
||||
if hi:
|
||||
self.emit("%s = (%s & 0xffffu) | (%s << 16);" % (d, d, val))
|
||||
else:
|
||||
self.emit("%s = (%s & 0xffff0000u) | %s;" % (d, d, val))
|
||||
|
||||
def i_v_fma_mixlo_f16(self, ops, line):
|
||||
self.fma_mix(ops, line, False)
|
||||
|
||||
def i_v_fma_mixhi_f16(self, ops, line):
|
||||
self.fma_mix(ops, line, True)
|
||||
|
||||
# PS interpolation
|
||||
def i_v_interp_p1_f32_e32(self, ops, line):
|
||||
pass
|
||||
|
||||
def i_v_interp_p2_f32_e32(self, ops, line):
|
||||
m = re.fullmatch(r"attr(\d+)\.([xyzw])", ops[2])
|
||||
if not m:
|
||||
raise Unsupported(line)
|
||||
n = int(m.group(1))
|
||||
self.attrs.add(n)
|
||||
self.emit("%s = asuint(attr%d.%s);" % (self.dst(ops[0]), n, m.group(2)))
|
||||
|
||||
def i_image_sample(self, ops, line):
|
||||
d = reg_range(ops[0])
|
||||
c = reg_range(ops[1])
|
||||
t = self.sprov.get(reg_range(ops[2])[1])
|
||||
if not t or t[0] != "tex" or "dim:SQ_RSRC_IMG_2D" not in line or "dmask:0xf" not in line:
|
||||
raise Unsupported(line)
|
||||
self.textures.add(t[1])
|
||||
self.used_v.update([c[1], c[1] + 1])
|
||||
self.emit("{ float4 r = tex%d.Sample(smp0, float2(asfloat(v%d), asfloat(v%d)));" % (t[1], c[1], c[1] + 1))
|
||||
for i in range(4):
|
||||
self.emit(" v%d = asuint(r.%s);" % (d[1] + i, "xyzw"[i]))
|
||||
self.used_v.add(d[1] + i)
|
||||
self.emit("}")
|
||||
|
||||
def i_exp(self, ops, line):
|
||||
target = ops[0]
|
||||
vals = [o.split()[0] for o in ops[1:5]]
|
||||
compr = " compr" in line
|
||||
if compr:
|
||||
a, b = self.src(vals[0]), self.src(vals[2])
|
||||
ex = ["f16tof32(%s & 0xffffu)" % a, "f16tof32(%s >> 16)" % a,
|
||||
"f16tof32(%s & 0xffffu)" % b, "f16tof32(%s >> 16)" % b]
|
||||
else:
|
||||
ex = ["0.0f" if v == "off" else self.src(v, True) for v in vals]
|
||||
self.exports[target] = ex
|
||||
|
||||
# ---- output -----------------------------------------------------------------
|
||||
def resources(self):
|
||||
out = []
|
||||
for cb in sorted(self.cbs):
|
||||
out.append("cbuffer CB%d : register(b%d, space100) { uint4 cb%d[256]; };" % (cb, cb, cb))
|
||||
out.append("uint cb%d_word(uint w) { return cb%d[w >> 2][w & 3]; }" % (cb, cb))
|
||||
for t in sorted(self.textures):
|
||||
out.append("Texture2D<float4> tex%d : register(t%d, space100);" % (t, t))
|
||||
if self.textures:
|
||||
out.append("SamplerState smp0 : register(s0, space100);")
|
||||
return out
|
||||
|
||||
def regs(self):
|
||||
decl = ["uint v%d = 0;" % n for n in sorted(self.used_v)]
|
||||
decl += ["uint s%d = 0;" % n for n in sorted(self.used_s)]
|
||||
return [" " + d for d in decl]
|
||||
|
||||
|
||||
def build_vs(t):
|
||||
ins = []
|
||||
for sem, fmt, slot, off, n, kind in t.inputs:
|
||||
ty = ("float%d" if kind == "float" else "uint%d") % n if n > 1 else ("float" if kind == "float" else "uint")
|
||||
ins.append("%s in%d : ATTR%d" % (ty, sem, sem))
|
||||
params = sorted(k for k in t.exports if k.startswith("param"))
|
||||
outs = ["float4 pos : SV_Position"] + ["float4 %s : PARAM%s" % (p, p[5:]) for p in params]
|
||||
src = t.resources()
|
||||
src.append("struct VSOut { %s; };" % "; ".join(outs))
|
||||
src.append("VSOut main(%s) {" % ", ".join(ins))
|
||||
src += t.regs() + t.lines
|
||||
src.append(" VSOut o;")
|
||||
pos = t.exports.get("pos0")
|
||||
if not pos:
|
||||
raise Unsupported("VS exports no position")
|
||||
src.append(" o.pos = float4(%s);" % ", ".join(pos))
|
||||
for p in params:
|
||||
src.append(" o.%s = float4(%s);" % (p, ", ".join(t.exports[p])))
|
||||
src.append(" return o;\n}")
|
||||
return "\n".join(src) + "\n", params
|
||||
|
||||
|
||||
def build_ps(t, vs_params):
|
||||
for a in t.attrs:
|
||||
if "param%d" % a not in vs_params:
|
||||
raise Unsupported("PS reads attr%d that the VS does not export" % a)
|
||||
ins = ["float4 pos : SV_Position"] + ["float4 attr%s : PARAM%s" % (p[5:], p[5:]) for p in vs_params]
|
||||
if "mrt0" not in t.exports:
|
||||
raise Unsupported("PS exports no mrt0")
|
||||
src = t.resources()
|
||||
src.append("float4 main(%s) : SV_Target0 {" % ", ".join(ins))
|
||||
src += t.regs() + t.lines
|
||||
src.append(" return float4(%s);\n}" % ", ".join(t.exports["mrt0"]))
|
||||
return "\n".join(src) + "\n"
|
||||
|
||||
|
||||
def fnv1a(data):
|
||||
h = 1469598103934665603
|
||||
for b in data:
|
||||
h = ((h ^ b) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
|
||||
return "%016x" % h
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("vs")
|
||||
ap.add_argument("ps")
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--dxc", help="command prefix that runs a Windows dxc.exe (e.g. a wine wrapper)")
|
||||
a = ap.parse_args()
|
||||
vsb, psb = open(a.vs, "rb").read(), open(a.ps, "rb").read()
|
||||
key = "%s_%s" % (fnv1a(vsb), fnv1a(psb))
|
||||
vt, pt = Translator("vs"), Translator("ps")
|
||||
vt.run(disassemble(vsb))
|
||||
pt.run(disassemble(psb))
|
||||
vs_src, params = build_vs(vt)
|
||||
ps_src = build_ps(pt, params)
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
base = os.path.join(a.out, key)
|
||||
open(base + ".vs.hlsl", "w").write(vs_src)
|
||||
open(base + ".ps.hlsl", "w").write(ps_src)
|
||||
with open(base + ".il", "w") as f:
|
||||
for sem, fmt, slot, off, n, kind in vt.inputs:
|
||||
f.write("ATTR %d %d %d %d\n" % (sem, DXGI[fmt], slot, off))
|
||||
for cb in sorted(vt.cbs | pt.cbs):
|
||||
f.write("USE CB %d\n" % cb)
|
||||
for tex in sorted(vt.textures | pt.textures):
|
||||
f.write("USE TEX %d\n" % tex)
|
||||
if a.dxc:
|
||||
for st, prof in (("vs", "vs_6_0"), ("ps", "ps_6_0")):
|
||||
cmd = a.dxc.split() + ["-T", prof, "-E", "main", "-Fo", base + ".%s.dxil" % st, base + ".%s.hlsl" % st]
|
||||
r = subprocess.run(cmd, capture_output=True, text=True)
|
||||
err = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if "fixme" not in l)
|
||||
if r.returncode or not os.path.exists(base + ".%s.dxil" % st):
|
||||
sys.exit("dxc failed for %s:\n%s" % (st, err))
|
||||
print(key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Unsupported as e:
|
||||
sys.exit("unsupported: %s" % e)
|
||||
+120
-16
@@ -9,44 +9,148 @@
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
extern "C" void* WINAPI ApuMapApuAddress(uint32_t address);
|
||||
|
||||
namespace {
|
||||
// IAcpHal (authorized GDK documentation; slot order derived from it): not a COM interface. Its
|
||||
// six methods are Connect(numCommands, numMessages), Disconnect(), SubmitCommand(command,
|
||||
// commandId, audioFrame, data, notification), PopMessage(ACP_MESSAGE*), GetNumMessages() and
|
||||
// Release(). BetterXen has no audio control processor: commands are accepted and logged once,
|
||||
// and no message ever arrives.
|
||||
// Release().
|
||||
//
|
||||
// BetterXen has no audio control processor. Every command completes at once and is
|
||||
// acknowledged the way titles wait for: message registrations take effect, a flowgraph load is
|
||||
// reported complete, a command submitted with an id gets a command-completed message, and a
|
||||
// notification word in the APU heap is set. SHAPE processing itself (XMA decoding, rate
|
||||
// conversion, mixing) is not done, so SHAPE voices stay silent; each command kind is logged once.
|
||||
// The acknowledgement behaviour, the command and message numbers and the 28-byte message layout
|
||||
// follow VIctory's audio module (GPL-3.0-or-later; see docs/research/upstream-registry.md).
|
||||
constexpr UINT32 kLoadFlowgraph = 1;
|
||||
constexpr UINT32 kRegisterMessages = 2;
|
||||
constexpr UINT32 kUnregisterMessages = 3;
|
||||
constexpr UINT32 kMessageFlowgraphCompleted = 0x02;
|
||||
constexpr UINT32 kMessageCommandCompleted = 0x10;
|
||||
constexpr UINT32 kMessageDisconnected = 0x80;
|
||||
constexpr UINT64 kAudioFramesPerSecond = 375; // 128-sample frames at 48 kHz
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct AcpMessage {
|
||||
UINT32 kind;
|
||||
UINT32 dropped;
|
||||
UINT32 usec;
|
||||
UINT8 data[16];
|
||||
};
|
||||
#pragma pack(pop)
|
||||
static_assert(sizeof(AcpMessage) == 28, "ACP_MESSAGE size");
|
||||
|
||||
class AcpHal {
|
||||
UINT32 commands_ = 0, messages_ = 0;
|
||||
std::mutex lock_;
|
||||
bool connected_ = false;
|
||||
UINT32 mask_ = 0;
|
||||
UINT32 capacity_ = 0;
|
||||
UINT32 dropped_ = 0;
|
||||
UINT32 count_ = 0, head_ = 0;
|
||||
AcpMessage* queue_ = nullptr;
|
||||
LARGE_INTEGER start_{}, frequency_{};
|
||||
|
||||
UINT64 usec() const {
|
||||
LARGE_INTEGER now;
|
||||
QueryPerformanceCounter(&now);
|
||||
return static_cast<UINT64>(now.QuadPart - start_.QuadPart) * 1000000ull / static_cast<UINT64>(frequency_.QuadPart);
|
||||
}
|
||||
// Queues a registered message; a full queue drops it and counts it in the next one that fits.
|
||||
void post(UINT32 kind, const void* data, size_t size) {
|
||||
if (!(mask_ & kind) || !queue_) return;
|
||||
if (count_ >= capacity_) {
|
||||
if (dropped_ != UINT32_MAX) ++dropped_;
|
||||
return;
|
||||
}
|
||||
AcpMessage& m = queue_[(head_ + count_) % capacity_];
|
||||
m = {};
|
||||
m.kind = kind;
|
||||
m.dropped = dropped_;
|
||||
dropped_ = 0;
|
||||
m.usec = static_cast<UINT32>(usec());
|
||||
if (data && size) std::memcpy(m.data, data, size > sizeof(m.data) ? sizeof(m.data) : size);
|
||||
++count_;
|
||||
}
|
||||
|
||||
public:
|
||||
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
|
||||
if (num_commands == 0) return E_INVALIDARG;
|
||||
std::lock_guard<std::mutex> guard(lock_);
|
||||
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
|
||||
commands_ = num_commands;
|
||||
messages_ = num_messages;
|
||||
delete[] queue_;
|
||||
queue_ = num_messages ? new (std::nothrow) AcpMessage[num_messages] : nullptr;
|
||||
if (num_messages && !queue_) return E_OUTOFMEMORY;
|
||||
capacity_ = num_messages;
|
||||
count_ = head_ = dropped_ = 0;
|
||||
QueryPerformanceFrequency(&frequency_);
|
||||
QueryPerformanceCounter(&start_);
|
||||
connected_ = true;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (commands are acknowledged, SHAPE is not processed)",
|
||||
num_commands, num_messages);
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI Disconnect() {
|
||||
std::lock_guard<std::mutex> guard(lock_);
|
||||
if (!connected_) return E_FAIL;
|
||||
post(kMessageDisconnected, nullptr, 0);
|
||||
connected_ = false;
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
|
||||
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64 id, UINT32, const void* data, UINT32 notification) {
|
||||
static LONG64 seen = 0;
|
||||
if (command < 64 && !(InterlockedOr64(&seen, 1ll << command) & (1ll << command))) {
|
||||
char detail[112];
|
||||
std::snprintf(detail, sizeof(detail), "first command of type %u: acknowledged%s", command,
|
||||
command >= 1 && command <= 3 ? "" : ", not carried out (no SHAPE processing)");
|
||||
bx_log_emit(command >= 1 && command <= 3 ? BX_LOG_INFO : BX_LOG_WARN, "acphal", "submit_command", detail);
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(lock_);
|
||||
if (!connected_) return E_UNEXPECTED;
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) == 1) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "first command type %u accepted; ACP commands are not processed", command);
|
||||
bx_log_emit(BX_LOG_WARN, "acphal", "submit_command", detail);
|
||||
auto word = [data](size_t at) {
|
||||
UINT32 value = 0;
|
||||
if (data) std::memcpy(&value, static_cast<const UINT8*>(data) + at * 4, sizeof(value));
|
||||
return value;
|
||||
};
|
||||
if (command == kRegisterMessages) mask_ |= word(0);
|
||||
else if (command == kUnregisterMessages) mask_ &= ~word(0);
|
||||
else if (command == kLoadFlowgraph) {
|
||||
const UINT32 flowgraph = word(1);
|
||||
post(kMessageFlowgraphCompleted, &flowgraph, sizeof(flowgraph));
|
||||
}
|
||||
if (id != 0) {
|
||||
UINT8 done[16];
|
||||
const UINT32 frame = static_cast<UINT32>(usec() * kAudioFramesPerSecond / 1000000ull);
|
||||
std::memcpy(done, &command, 4);
|
||||
std::memcpy(done + 4, &id, 8);
|
||||
std::memcpy(done + 12, &frame, 4);
|
||||
post(kMessageCommandCompleted, done, sizeof(done));
|
||||
}
|
||||
if (notification != 0) {
|
||||
if (void* target = ApuMapApuAddress(notification)) {
|
||||
const UINT32 one = 1;
|
||||
std::memcpy(target, &one, sizeof(one));
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
virtual bool WINAPI PopMessage(void*) { return false; }
|
||||
virtual UINT32 WINAPI GetNumMessages() { return 0; }
|
||||
virtual bool WINAPI PopMessage(void* out) {
|
||||
std::lock_guard<std::mutex> guard(lock_);
|
||||
if (!count_) return false;
|
||||
if (out) std::memcpy(out, &queue_[head_], sizeof(AcpMessage));
|
||||
head_ = (head_ + 1) % capacity_;
|
||||
--count_;
|
||||
return true;
|
||||
}
|
||||
virtual UINT32 WINAPI GetNumMessages() {
|
||||
std::lock_guard<std::mutex> guard(lock_);
|
||||
return count_;
|
||||
}
|
||||
virtual void WINAPI Release() { delete this; }
|
||||
virtual ~AcpHal() = default;
|
||||
virtual ~AcpHal() { delete[] queue_; }
|
||||
};
|
||||
|
||||
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
|
||||
|
||||
@@ -11,6 +11,7 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
descriptor_heaps.cpp
|
||||
committed.cpp
|
||||
pipelines.cpp
|
||||
console_translate.cpp
|
||||
gpu_writes.cpp
|
||||
fences.cpp
|
||||
presentx_xbox.cpp
|
||||
|
||||
@@ -0,0 +1,849 @@
|
||||
/*
|
||||
* Experimental translation of deserialized console pipelines (raw RDNA 2 code).
|
||||
*
|
||||
* Part 1: root signature registry. The title creates root signatures from serialized blobs; the
|
||||
* translator needs their layout to map the console shader's user-data registers and descriptor
|
||||
* table offsets to HLSL registers, so each blob is kept with its host object.
|
||||
*/
|
||||
#include "console_translate.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Recorded {
|
||||
ID3D12VersionedRootSignatureDeserializer* deserializer;
|
||||
const D3D12_ROOT_SIGNATURE_DESC1* desc;
|
||||
};
|
||||
|
||||
std::mutex g_root_lock;
|
||||
std::unordered_map<ID3D12RootSignature*, Recorded> g_roots;
|
||||
|
||||
using CreateDeserializerFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, REFIID, void**);
|
||||
|
||||
CreateDeserializerFn create_deserializer() {
|
||||
static CreateDeserializerFn fn = [] {
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
return d3d12 ? reinterpret_cast<CreateDeserializerFn>(reinterpret_cast<void*>(
|
||||
GetProcAddress(d3d12, "D3D12CreateVersionedRootSignatureDeserializer")))
|
||||
: nullptr;
|
||||
}();
|
||||
return fn;
|
||||
}
|
||||
|
||||
const char* range_name(D3D12_DESCRIPTOR_RANGE_TYPE t) {
|
||||
switch (t) {
|
||||
case D3D12_DESCRIPTOR_RANGE_TYPE_SRV: return "SRV";
|
||||
case D3D12_DESCRIPTOR_RANGE_TYPE_UAV: return "UAV";
|
||||
case D3D12_DESCRIPTOR_RANGE_TYPE_CBV: return "CBV";
|
||||
default: return "SMP";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_root_signature_created(ID3D12RootSignature* host, const void* blob, size_t size) {
|
||||
if (!host || !blob || !size) return;
|
||||
CreateDeserializerFn fn = create_deserializer();
|
||||
if (!fn) return;
|
||||
ID3D12VersionedRootSignatureDeserializer* d = nullptr;
|
||||
if (FAILED(fn(blob, size, __uuidof(ID3D12VersionedRootSignatureDeserializer), reinterpret_cast<void**>(&d))) || !d) {
|
||||
return;
|
||||
}
|
||||
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* v = nullptr;
|
||||
if (FAILED(d->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &v)) || !v) {
|
||||
d->Release();
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_root_lock);
|
||||
auto& slot = g_roots[host];
|
||||
if (slot.deserializer) slot.deserializer->Release();
|
||||
slot = {d, &v->Desc_1_1};
|
||||
}
|
||||
char value[8] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_PSO_PROFILE", value, sizeof(value));
|
||||
if (n > 0 && n < sizeof(value) && value[0] == '1') {
|
||||
static char text[16384];
|
||||
static std::mutex text_lock;
|
||||
std::lock_guard<std::mutex> guard(text_lock);
|
||||
bx_console_describe_root_signature(host, text, sizeof(text));
|
||||
const size_t len = std::strlen(text);
|
||||
for (size_t off = 0, part = 0; off < len; off += 600, ++part) {
|
||||
char detail[700];
|
||||
std::snprintf(detail, sizeof(detail), "root=%p part=%zu %.600s", static_cast<void*>(host), part, text + off);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_root", detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const D3D12_ROOT_SIGNATURE_DESC1* bx_console_root_signature_desc(ID3D12RootSignature* host) {
|
||||
std::lock_guard<std::mutex> guard(g_root_lock);
|
||||
auto it = g_roots.find(host);
|
||||
return it == g_roots.end() ? nullptr : it->second.desc;
|
||||
}
|
||||
|
||||
void bx_console_describe_root_signature(ID3D12RootSignature* host, char* out, size_t room) {
|
||||
if (!room) return;
|
||||
out[0] = 0;
|
||||
const D3D12_ROOT_SIGNATURE_DESC1* d = bx_console_root_signature_desc(host);
|
||||
if (!d) {
|
||||
std::snprintf(out, room, "root=unrecorded");
|
||||
return;
|
||||
}
|
||||
size_t used = 0;
|
||||
auto put = [&](const char* fmt, auto... args) {
|
||||
if (used >= room) return;
|
||||
const int n = std::snprintf(out + used, room - used, fmt, args...);
|
||||
if (n > 0) used += static_cast<size_t>(n);
|
||||
};
|
||||
put("root params=%u static_samplers=%u flags=0x%x", d->NumParameters, d->NumStaticSamplers, d->Flags);
|
||||
for (UINT i = 0; i < d->NumParameters; ++i) {
|
||||
const D3D12_ROOT_PARAMETER1& p = d->pParameters[i];
|
||||
put(" p%u(vis%u)=", i, p.ShaderVisibility);
|
||||
switch (p.ParameterType) {
|
||||
case D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE:
|
||||
put("table[");
|
||||
for (UINT r = 0; r < p.DescriptorTable.NumDescriptorRanges; ++r) {
|
||||
const D3D12_DESCRIPTOR_RANGE1& rg = p.DescriptorTable.pDescriptorRanges[r];
|
||||
put("%s%s%u+%u/s%u@%d", r ? "," : "", range_name(rg.RangeType), rg.BaseShaderRegister,
|
||||
rg.NumDescriptors, rg.RegisterSpace, static_cast<int>(rg.OffsetInDescriptorsFromTableStart));
|
||||
}
|
||||
put("]");
|
||||
break;
|
||||
case D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS:
|
||||
put("const(b%u/s%u x%u)", p.Constants.ShaderRegister, p.Constants.RegisterSpace, p.Constants.Num32BitValues);
|
||||
break;
|
||||
case D3D12_ROOT_PARAMETER_TYPE_CBV: put("cbv(b%u/s%u)", p.Descriptor.ShaderRegister, p.Descriptor.RegisterSpace); break;
|
||||
case D3D12_ROOT_PARAMETER_TYPE_SRV: put("srv(t%u/s%u)", p.Descriptor.ShaderRegister, p.Descriptor.RegisterSpace); break;
|
||||
case D3D12_ROOT_PARAMETER_TYPE_UAV: put("uav(u%u/s%u)", p.Descriptor.ShaderRegister, p.Descriptor.RegisterSpace); break;
|
||||
}
|
||||
}
|
||||
for (UINT i = 0; i < d->NumStaticSamplers; ++i) {
|
||||
const D3D12_STATIC_SAMPLER_DESC& s = d->pStaticSamplers[i];
|
||||
put(" ss%u=s%u/s%u f0x%x a%u%u%u vis%u", i, s.ShaderRegister, s.RegisterSpace, s.Filter, s.AddressU, s.AddressV,
|
||||
s.AddressW, s.ShaderVisibility);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Part 2: translated pipelines (opt-in, BX_CONSOLE_SHADER_CACHE=<folder>).
|
||||
*
|
||||
* The folder holds, per console VS/PS pair, <vs>_<ps>.vs.dxil, .ps.dxil and .il (input layout)
|
||||
* produced by scripts/console-shader/translate.py from the stage code (FNV-1a hashes of the
|
||||
* GPU instruction blobs). Those shaders bind root parameter i's descriptor table entry k as
|
||||
* register k in space 100 + i, so every title root signature is widened with overlapping
|
||||
* ranges there. Pipeline state that the console register packet carries (blend, rasterizer,
|
||||
* depth) is not decoded yet: translated pipelines use alpha blending, no culling and no depth
|
||||
* test, and are created per bound render-target formats at draw time.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
const char* cache_folder() {
|
||||
static char folder[512] = {};
|
||||
static const bool on = GetEnvironmentVariableA("BX_CONSOLE_SHADER_CACHE", folder, sizeof(folder)) > 0;
|
||||
return on ? folder : nullptr;
|
||||
}
|
||||
|
||||
using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
|
||||
|
||||
SerializeFn serialize_fn() {
|
||||
static SerializeFn fn = [] {
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
return d3d12 ? reinterpret_cast<SerializeFn>(reinterpret_cast<void*>(
|
||||
GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
|
||||
: nullptr;
|
||||
}();
|
||||
return fn;
|
||||
}
|
||||
|
||||
uint64_t fnv1a64(const void* data, size_t size) {
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
const auto* p = static_cast<const uint8_t*>(data);
|
||||
for (size_t i = 0; data && i < size; ++i) h = (h ^ p[i]) * 1099511628211ull;
|
||||
return h;
|
||||
}
|
||||
|
||||
bool read_file(const std::string& path, std::vector<uint8_t>& out) {
|
||||
FILE* f = std::fopen(path.c_str(), "rb");
|
||||
if (!f) return false;
|
||||
std::fseek(f, 0, SEEK_END);
|
||||
const long n = std::ftell(f);
|
||||
std::fseek(f, 0, SEEK_SET);
|
||||
out.resize(n > 0 ? static_cast<size_t>(n) : 0);
|
||||
const bool ok = n > 0 && std::fread(out.data(), 1, out.size(), f) == out.size();
|
||||
std::fclose(f);
|
||||
return ok;
|
||||
}
|
||||
|
||||
std::mutex g_rt_lock;
|
||||
std::unordered_map<SIZE_T, DXGI_FORMAT> g_rtv_formats;
|
||||
std::unordered_map<SIZE_T, DXGI_FORMAT> g_dsv_formats;
|
||||
struct ListTargets {
|
||||
UINT count = 0;
|
||||
DXGI_FORMAT rtv[8] = {};
|
||||
DXGI_FORMAT dsv = DXGI_FORMAT_UNKNOWN;
|
||||
SIZE_T handle0 = 0;
|
||||
};
|
||||
std::unordered_map<const void*, ListTargets> g_list_targets;
|
||||
|
||||
} // namespace
|
||||
|
||||
struct BxTranslated {
|
||||
ID3D12Device* device = nullptr; // host device, referenced
|
||||
ID3D12RootSignature* root = nullptr; // host root signature, referenced
|
||||
std::vector<uint8_t> vs, ps;
|
||||
std::vector<D3D12_INPUT_ELEMENT_DESC> layout;
|
||||
std::vector<std::pair<int, UINT>> uses; // (1 CB | 2 texture, root table 0 entry)
|
||||
std::string key;
|
||||
std::mutex lock;
|
||||
std::unordered_map<std::string, ID3D12PipelineState*> pipelines;
|
||||
~BxTranslated() {
|
||||
for (auto& kv : pipelines) {
|
||||
if (kv.second) kv.second->Release();
|
||||
}
|
||||
if (root) root->Release();
|
||||
if (device) device->Release();
|
||||
}
|
||||
};
|
||||
|
||||
bool bx_console_translation_enabled() { return cache_folder() != nullptr; }
|
||||
|
||||
ID3DBlob* bx_console_widen_root_signature(const void* blob, size_t size) {
|
||||
if (!cache_folder() || !blob || !size) return nullptr;
|
||||
CreateDeserializerFn make = create_deserializer();
|
||||
SerializeFn serialize = serialize_fn();
|
||||
if (!make || !serialize) return nullptr;
|
||||
ID3D12VersionedRootSignatureDeserializer* d = nullptr;
|
||||
if (FAILED(make(blob, size, __uuidof(ID3D12VersionedRootSignatureDeserializer), reinterpret_cast<void**>(&d))) || !d) {
|
||||
return nullptr;
|
||||
}
|
||||
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* v = nullptr;
|
||||
ID3DBlob* out = nullptr;
|
||||
if (SUCCEEDED(d->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &v)) && v) {
|
||||
const D3D12_ROOT_SIGNATURE_DESC1& src = v->Desc_1_1;
|
||||
std::vector<D3D12_ROOT_PARAMETER1> params(src.pParameters, src.pParameters + src.NumParameters);
|
||||
std::vector<std::vector<D3D12_DESCRIPTOR_RANGE1>> ranges(params.size());
|
||||
for (size_t i = 0; i < params.size(); ++i) {
|
||||
if (params[i].ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) continue;
|
||||
const auto& t = params[i].DescriptorTable;
|
||||
if (t.NumDescriptorRanges && t.pDescriptorRanges[0].RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) continue;
|
||||
ranges[i].assign(t.pDescriptorRanges, t.pDescriptorRanges + t.NumDescriptorRanges);
|
||||
for (D3D12_DESCRIPTOR_RANGE_TYPE type : {D3D12_DESCRIPTOR_RANGE_TYPE_CBV, D3D12_DESCRIPTOR_RANGE_TYPE_SRV}) {
|
||||
D3D12_DESCRIPTOR_RANGE1 r{};
|
||||
r.RangeType = type;
|
||||
r.NumDescriptors = 8;
|
||||
r.BaseShaderRegister = 0;
|
||||
r.RegisterSpace = 100 + static_cast<UINT>(i);
|
||||
r.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
|
||||
r.OffsetInDescriptorsFromTableStart = 0;
|
||||
ranges[i].push_back(r);
|
||||
}
|
||||
params[i].DescriptorTable.NumDescriptorRanges = static_cast<UINT>(ranges[i].size());
|
||||
params[i].DescriptorTable.pDescriptorRanges = ranges[i].data();
|
||||
}
|
||||
std::vector<D3D12_STATIC_SAMPLER_DESC> samplers(src.pStaticSamplers, src.pStaticSamplers + src.NumStaticSamplers);
|
||||
D3D12_STATIC_SAMPLER_DESC s{};
|
||||
s.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
|
||||
s.AddressU = s.AddressV = s.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
|
||||
s.MaxLOD = D3D12_FLOAT32_MAX;
|
||||
s.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
|
||||
s.ShaderRegister = 0;
|
||||
s.RegisterSpace = 100;
|
||||
s.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
samplers.push_back(s);
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC wide{};
|
||||
wide.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
|
||||
wide.Desc_1_1 = src;
|
||||
wide.Desc_1_1.NumParameters = static_cast<UINT>(params.size());
|
||||
wide.Desc_1_1.pParameters = params.data();
|
||||
wide.Desc_1_1.NumStaticSamplers = static_cast<UINT>(samplers.size());
|
||||
wide.Desc_1_1.pStaticSamplers = samplers.data();
|
||||
ID3DBlob* errors = nullptr;
|
||||
if (FAILED(serialize(&wide, &out, &errors))) {
|
||||
if (errors) {
|
||||
char detail[512];
|
||||
std::snprintf(detail, sizeof(detail), "widening refused: %.400s",
|
||||
static_cast<const char*>(errors->GetBufferPointer()));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "console_root_widen", detail);
|
||||
}
|
||||
out = nullptr;
|
||||
}
|
||||
if (errors) errors->Release();
|
||||
}
|
||||
d->Release();
|
||||
return out;
|
||||
}
|
||||
|
||||
std::shared_ptr<BxTranslated> bx_console_translate_graphics(ID3D12Device* device, ID3D12RootSignature* host_root,
|
||||
const void* vs, size_t vs_size, const void* ps,
|
||||
size_t ps_size) {
|
||||
const char* folder = cache_folder();
|
||||
if (!folder || !device || !host_root || !vs || !ps) return nullptr;
|
||||
char key[40];
|
||||
std::snprintf(key, sizeof(key), "%016llx_%016llx", static_cast<unsigned long long>(fnv1a64(vs, vs_size)),
|
||||
static_cast<unsigned long long>(fnv1a64(ps, ps_size)));
|
||||
const std::string base = std::string(folder) + "\\" + key;
|
||||
auto t = std::make_shared<BxTranslated>();
|
||||
std::vector<uint8_t> il;
|
||||
if (!read_file(base + ".vs.dxil", t->vs) || !read_file(base + ".ps.dxil", t->ps) || !read_file(base + ".il", il)) {
|
||||
return nullptr;
|
||||
}
|
||||
il.push_back(0);
|
||||
const char* p = reinterpret_cast<const char*>(il.data());
|
||||
unsigned sem, fmt, slot, off;
|
||||
int used = 0;
|
||||
while (std::sscanf(p, " ATTR %u %u %u %u%n", &sem, &fmt, &slot, &off, &used) == 4) {
|
||||
D3D12_INPUT_ELEMENT_DESC e{};
|
||||
e.SemanticName = "ATTR";
|
||||
e.SemanticIndex = sem;
|
||||
e.Format = static_cast<DXGI_FORMAT>(fmt);
|
||||
e.InputSlot = slot;
|
||||
e.AlignedByteOffset = off;
|
||||
e.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
|
||||
t->layout.push_back(e);
|
||||
p += used;
|
||||
}
|
||||
for (const char* q = reinterpret_cast<const char*>(il.data()); (q = std::strstr(q, "USE ")) != nullptr; q += 4) {
|
||||
char kind[8] = {};
|
||||
unsigned entry = 0;
|
||||
if (std::sscanf(q, "USE %7s %u", kind, &entry) == 2) {
|
||||
t->uses.push_back({std::strcmp(kind, "CB") == 0 ? 1 : 2, entry});
|
||||
}
|
||||
}
|
||||
t->device = device;
|
||||
device->AddRef();
|
||||
t->root = host_root;
|
||||
host_root->AddRef();
|
||||
t->key = key;
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s: translated shaders found (%zu input elements)", key, t->layout.size());
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_translated", detail);
|
||||
return t;
|
||||
}
|
||||
|
||||
void bx_console_rtv_created(SIZE_T host_cpu, DXGI_FORMAT format) {
|
||||
std::lock_guard<std::mutex> guard(g_rt_lock);
|
||||
g_rtv_formats[host_cpu] = format;
|
||||
}
|
||||
|
||||
void bx_console_dsv_created(SIZE_T host_cpu, DXGI_FORMAT format) {
|
||||
std::lock_guard<std::mutex> guard(g_rt_lock);
|
||||
g_dsv_formats[host_cpu] = format;
|
||||
}
|
||||
|
||||
void bx_console_list_set_render_targets(ID3D12GraphicsCommandList* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv) {
|
||||
std::lock_guard<std::mutex> guard(g_rt_lock);
|
||||
ListTargets t;
|
||||
t.count = count > 8 ? 8 : count;
|
||||
if (rtvs && t.count) t.handle0 = rtvs[0].ptr;
|
||||
for (UINT i = 0; rtvs && i < t.count; ++i) {
|
||||
const SIZE_T h = single_range ? rtvs[0].ptr : rtvs[i].ptr; // single range: first handle only
|
||||
auto it = g_rtv_formats.find(h);
|
||||
t.rtv[i] = it == g_rtv_formats.end() ? DXGI_FORMAT_UNKNOWN : it->second;
|
||||
if (single_range && i) t.rtv[i] = t.rtv[0];
|
||||
}
|
||||
if (dsv) {
|
||||
auto it = g_dsv_formats.find(dsv->ptr);
|
||||
t.dsv = it == g_dsv_formats.end() ? DXGI_FORMAT_UNKNOWN : it->second;
|
||||
}
|
||||
g_list_targets[list] = t;
|
||||
}
|
||||
|
||||
bool bx_console_apply(BxTranslated* t, ID3D12GraphicsCommandList* list) {
|
||||
if (!t) return false;
|
||||
ListTargets targets;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_rt_lock);
|
||||
auto it = g_list_targets.find(list);
|
||||
if (it != g_list_targets.end()) targets = it->second;
|
||||
}
|
||||
if (!targets.count || targets.rtv[0] == DXGI_FORMAT_UNKNOWN) {
|
||||
static std::atomic<int> shown{0};
|
||||
if (shown.fetch_add(1) < 6) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s: render target unknown (count=%u handle0=0x%llx fmt0=%d)",
|
||||
t->key.c_str(), targets.count, static_cast<unsigned long long>(targets.handle0), targets.rtv[0]);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "console_translated", detail);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
char key[96];
|
||||
int n = std::snprintf(key, sizeof(key), "%u", targets.dsv);
|
||||
for (UINT i = 0; i < targets.count; ++i) n += std::snprintf(key + n, sizeof(key) - n, ",%u", targets.rtv[i]);
|
||||
ID3D12PipelineState* pso = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(t->lock);
|
||||
auto it = t->pipelines.find(key);
|
||||
if (it != t->pipelines.end()) {
|
||||
pso = it->second;
|
||||
} else {
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
|
||||
d.pRootSignature = t->root;
|
||||
d.VS = {t->vs.data(), t->vs.size()};
|
||||
d.PS = {t->ps.data(), t->ps.size()};
|
||||
for (UINT i = 0; i < 8; ++i) {
|
||||
auto& rt = d.BlendState.RenderTarget[i];
|
||||
rt.BlendEnable = i == 0;
|
||||
rt.SrcBlend = D3D12_BLEND_SRC_ALPHA;
|
||||
rt.DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
rt.BlendOp = D3D12_BLEND_OP_ADD;
|
||||
rt.SrcBlendAlpha = D3D12_BLEND_ONE;
|
||||
rt.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
rt.BlendOpAlpha = D3D12_BLEND_OP_ADD;
|
||||
rt.LogicOp = D3D12_LOGIC_OP_NOOP;
|
||||
rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
|
||||
}
|
||||
d.SampleMask = UINT_MAX;
|
||||
d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
|
||||
d.RasterizerState.DepthClipEnable = TRUE;
|
||||
d.DepthStencilState.DepthEnable = FALSE;
|
||||
d.DepthStencilState.StencilEnable = FALSE;
|
||||
d.InputLayout = {t->layout.data(), static_cast<UINT>(t->layout.size())};
|
||||
d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
d.NumRenderTargets = targets.count;
|
||||
for (UINT i = 0; i < targets.count; ++i) d.RTVFormats[i] = targets.rtv[i];
|
||||
d.DSVFormat = targets.dsv;
|
||||
d.SampleDesc.Count = 1;
|
||||
const HRESULT hr = t->device->CreateGraphicsPipelineState(&d, __uuidof(ID3D12PipelineState),
|
||||
reinterpret_cast<void**>(&pso));
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s formats %s: host pipeline hr=0x%08lx", t->key.c_str(), key,
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "console_translated", detail);
|
||||
if (FAILED(hr)) pso = nullptr;
|
||||
t->pipelines[key] = pso;
|
||||
}
|
||||
}
|
||||
if (!pso) return false;
|
||||
list->SetPipelineState(pso);
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Part 3: draw-time evidence for translated pipelines (BX_PSO_PROFILE=1, local only): what the
|
||||
* title created at the bound descriptor-table entries, the start of each constant buffer and
|
||||
* of vertex buffer 0, for the first draws of each translated pipeline.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
struct Entry {
|
||||
char what[96];
|
||||
uint64_t va = 0; // CBV: title buffer address
|
||||
};
|
||||
std::mutex g_ev_lock;
|
||||
std::unordered_map<uint64_t, Entry> g_entries; // title descriptor address -> creation
|
||||
std::unordered_map<const void*, uint64_t> g_list_table0; // host list -> title table address (param 0)
|
||||
std::unordered_map<const void*, D3D12_VERTEX_BUFFER_VIEW> g_list_vb0; // host list -> title VB 0
|
||||
|
||||
bool profile_on() {
|
||||
static const bool on = [] {
|
||||
char v[8] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_PSO_PROFILE", v, sizeof(v));
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
bool readable(uint64_t va, size_t size) {
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
if (!va || !VirtualQuery(reinterpret_cast<void*>(va), &mbi, sizeof(mbi))) return false;
|
||||
if (mbi.State != MEM_COMMIT || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) return false;
|
||||
return va + size <= reinterpret_cast<uint64_t>(mbi.BaseAddress) + mbi.RegionSize;
|
||||
}
|
||||
|
||||
void floats(char* out, size_t room, uint64_t va, int count) {
|
||||
if (!readable(va, count * 4)) {
|
||||
std::snprintf(out, room, "unreadable");
|
||||
return;
|
||||
}
|
||||
size_t used = 0;
|
||||
for (int i = 0; i < count && used < room; ++i) {
|
||||
float f;
|
||||
std::memcpy(&f, reinterpret_cast<const void*>(va + 4 * i), 4);
|
||||
const int n = std::snprintf(out + used, room - used, "%s%g", i ? "," : "", f);
|
||||
if (n > 0) used += static_cast<size_t>(n);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_note_cbv(uint64_t title_handle, uint64_t va, UINT size) {
|
||||
if (!profile_on()) return;
|
||||
static std::atomic<int> n{0};
|
||||
if (n.fetch_add(1) < 4000) {
|
||||
char d[160];
|
||||
std::snprintf(d, sizeof(d), "cbv dest=0x%llx va=0x%llx size=%u", static_cast<unsigned long long>(title_handle),
|
||||
static_cast<unsigned long long>(va), size);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_note", d);
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(g_ev_lock);
|
||||
Entry& e = g_entries[title_handle];
|
||||
std::snprintf(e.what, sizeof(e.what), "CBV va=0x%llx size=%u", static_cast<unsigned long long>(va), size);
|
||||
e.va = va;
|
||||
}
|
||||
|
||||
void bx_console_note_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc) {
|
||||
if (!profile_on()) return;
|
||||
D3D12_RESOURCE_DESC r{};
|
||||
if (host) r = host->GetDesc();
|
||||
std::lock_guard<std::mutex> guard(g_ev_lock);
|
||||
Entry& e = g_entries[title_handle];
|
||||
std::snprintf(e.what, sizeof(e.what), "SRV dim=%d view=%d fmt=%d %llux%u", static_cast<int>(r.Dimension),
|
||||
desc ? static_cast<int>(desc->ViewDimension) : -1, desc ? static_cast<int>(desc->Format) : r.Format,
|
||||
static_cast<unsigned long long>(r.Width), r.Height);
|
||||
e.va = 0;
|
||||
}
|
||||
|
||||
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle) {
|
||||
if (profile_on()) {
|
||||
static std::atomic<int> n{0};
|
||||
if (n.fetch_add(1) < 4000) {
|
||||
char d[160];
|
||||
std::snprintf(d, sizeof(d), "table param=%u handle=0x%llx", param, static_cast<unsigned long long>(title_handle));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_note", d);
|
||||
}
|
||||
}
|
||||
if (!cache_folder() || param != 0) return;
|
||||
std::lock_guard<std::mutex> guard(g_ev_lock);
|
||||
g_list_table0[list] = title_handle;
|
||||
}
|
||||
|
||||
void bx_console_note_vb(ID3D12GraphicsCommandList* list, UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) {
|
||||
if (!cache_folder() || start != 0 || !count || !views) return;
|
||||
std::lock_guard<std::mutex> guard(g_ev_lock);
|
||||
g_list_vb0[list] = views[0];
|
||||
}
|
||||
|
||||
void bx_console_evidence(const char* key, ID3D12GraphicsCommandList* list, UINT vertices) {
|
||||
if (!profile_on()) return;
|
||||
static std::mutex count_lock;
|
||||
static std::unordered_map<std::string, int> counts;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(count_lock);
|
||||
if (++counts[key] > 2) return;
|
||||
}
|
||||
uint64_t table = 0;
|
||||
D3D12_VERTEX_BUFFER_VIEW vb{};
|
||||
Entry entries[4];
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_ev_lock);
|
||||
auto t = g_list_table0.find(list);
|
||||
if (t != g_list_table0.end()) table = t->second;
|
||||
auto v = g_list_vb0.find(list);
|
||||
if (v != g_list_vb0.end()) vb = v->second;
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
auto e = g_entries.find(table + 32ull * k);
|
||||
if (e != g_entries.end()) entries[k] = e->second;
|
||||
else std::snprintf(entries[k].what, sizeof(entries[k].what), "none");
|
||||
}
|
||||
}
|
||||
char detail[700];
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s vertices=%u table0=0x%llx e0={%s} e1={%s} e2={%s} e3={%s}", key, vertices,
|
||||
static_cast<unsigned long long>(table), entries[0].what, entries[1].what, entries[2].what, entries[3].what);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
if (readable(table, 128)) {
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
uint32_t w[8];
|
||||
std::memcpy(w, reinterpret_cast<const void*>(table + 32ull * k), sizeof(w));
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s raw e%d: %08x %08x %08x %08x %08x %08x %08x %08x", key, k, w[0], w[1],
|
||||
w[2], w[3], w[4], w[5], w[6], w[7]);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
if (!entries[k].va) continue;
|
||||
char f[600];
|
||||
floats(f, sizeof(f), entries[k].va, 24);
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s e%d words0-23: %s", key, k, f);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
floats(f, sizeof(f), entries[k].va + 0x160, 16);
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s e%d words88-103: %s", key, k, f);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
}
|
||||
char f[600];
|
||||
floats(f, sizeof(f), vb.BufferLocation, 18);
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s vb0 va=0x%llx stride=%u size=%u first: %s", key,
|
||||
static_cast<unsigned long long>(vb.BufferLocation), vb.StrideInBytes, vb.SizeInBytes, f);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
}
|
||||
|
||||
const char* bx_console_key(const BxTranslated* t) { return t ? t->key.c_str() : ""; }
|
||||
|
||||
/*
|
||||
* Part 4: inline console descriptors. The title writes console-format descriptors straight into
|
||||
* its shader-visible heap memory and binds them with SetGraphicsRootDescriptorTable. Each
|
||||
* translated draw records the table it used; when the list is submitted, the entries its
|
||||
* shaders read are decoded and written to the host heap at the same index.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
struct PendingDraw {
|
||||
std::shared_ptr<BxTranslated> translated;
|
||||
uint64_t table;
|
||||
D3D12_VERTEX_BUFFER_VIEW vb; // title view of slot 0
|
||||
};
|
||||
std::mutex g_pending_lock;
|
||||
std::unordered_map<const void*, std::vector<PendingDraw>> g_pending;
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_list_reset(ID3D12GraphicsCommandList* list) {
|
||||
std::lock_guard<std::mutex> guard(g_pending_lock);
|
||||
g_pending.erase(list);
|
||||
}
|
||||
|
||||
void bx_console_record_draw(const std::shared_ptr<BxTranslated>& translated, ID3D12GraphicsCommandList* list) {
|
||||
uint64_t table = 0;
|
||||
D3D12_VERTEX_BUFFER_VIEW vb{};
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_ev_lock);
|
||||
auto t = g_list_table0.find(list);
|
||||
if (t != g_list_table0.end()) table = t->second;
|
||||
auto v = g_list_vb0.find(list);
|
||||
if (v != g_list_vb0.end()) vb = v->second;
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(g_pending_lock);
|
||||
g_pending[list].push_back({translated, table, vb});
|
||||
}
|
||||
|
||||
void bx_console_resolve(ID3D12Device* device, uint64_t table, const std::vector<std::pair<int, UINT>>& uses,
|
||||
const char* key);
|
||||
|
||||
void bx_console_submit(ID3D12CommandList* const* lists, UINT count) {
|
||||
std::vector<PendingDraw> draws;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_pending_lock);
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
auto it = g_pending.find(lists[i]);
|
||||
if (it == g_pending.end()) continue;
|
||||
draws.insert(draws.end(), it->second.begin(), it->second.end());
|
||||
}
|
||||
}
|
||||
for (const PendingDraw& d : draws) {
|
||||
if (d.vb.BufferLocation) bx_xbox_sync_title_range(d.vb.BufferLocation, d.vb.SizeInBytes);
|
||||
if (d.translated && d.table) bx_console_resolve(d.translated->device, d.table, d.translated->uses, d.translated->key.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Part 5: descriptor markers. On the console a descriptor is 32 bytes of memory the driver writes
|
||||
* at the handle, and titles copy those bytes themselves (memcpy into per-draw tables). With
|
||||
* translation enabled, every CBV/SRV creation also writes a marker there: a magic word and the
|
||||
* id of a registry entry holding the host view. At submission, the table entries a translated
|
||||
* draw reads are decoded from their markers and written to the host heap at the same index.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kMarkerMagic = 0x31445842u; // "BXD1"
|
||||
|
||||
struct View {
|
||||
int kind = 0; // 1 CBV, 2 SRV
|
||||
D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{};
|
||||
uint64_t title_va = 0; // title address of the viewed bytes (CBV, placed buffer SRV)
|
||||
uint64_t title_size = 0;
|
||||
ID3D12Resource* resource = nullptr; // SRV: host resource, referenced
|
||||
bool has_srv_desc = false;
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
|
||||
};
|
||||
|
||||
std::mutex g_view_lock;
|
||||
std::vector<View> g_views(1); // id 0 unused
|
||||
std::unordered_map<std::string, uint32_t> g_view_ids;
|
||||
|
||||
bool writable(uint64_t va, size_t size) {
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
if (!va || !VirtualQuery(reinterpret_cast<void*>(va), &mbi, sizeof(mbi))) return false;
|
||||
if (mbi.State != MEM_COMMIT) return false;
|
||||
const DWORD p = mbi.Protect & 0xff;
|
||||
if (p != PAGE_READWRITE && p != PAGE_EXECUTE_READWRITE && p != PAGE_WRITECOPY) return false;
|
||||
return va + size <= reinterpret_cast<uint64_t>(mbi.BaseAddress) + mbi.RegionSize;
|
||||
}
|
||||
|
||||
uint32_t intern(const std::string& key, const View& v) {
|
||||
std::lock_guard<std::mutex> guard(g_view_lock);
|
||||
auto it = g_view_ids.find(key);
|
||||
if (it != g_view_ids.end()) return it->second;
|
||||
const uint32_t id = static_cast<uint32_t>(g_views.size());
|
||||
g_views.push_back(v);
|
||||
if (v.resource) v.resource->AddRef();
|
||||
g_view_ids[key] = id;
|
||||
return id;
|
||||
}
|
||||
|
||||
void write_marker(uint64_t dest, uint32_t id) {
|
||||
if (!writable(dest, 32)) return;
|
||||
uint32_t w[8] = {kMarkerMagic, id, ~id, 0, 0, 0, 0, 0};
|
||||
std::memcpy(reinterpret_cast<void*>(dest), w, sizeof(w));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_mark_cbv(uint64_t dest, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc, uint64_t title_va) {
|
||||
if (!cache_folder() || !dest) return;
|
||||
View v;
|
||||
v.kind = 1;
|
||||
v.cbv = host_desc;
|
||||
v.title_va = title_va;
|
||||
v.title_size = host_desc.SizeInBytes;
|
||||
char key[64];
|
||||
std::snprintf(key, sizeof(key), "c%llx:%u", static_cast<unsigned long long>(host_desc.BufferLocation), host_desc.SizeInBytes);
|
||||
write_marker(dest, intern(key, v));
|
||||
}
|
||||
|
||||
void bx_console_mark_srv(uint64_t dest, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
|
||||
uint64_t title_va, uint64_t title_size) {
|
||||
if (!cache_folder() || !dest || !host) return;
|
||||
View v;
|
||||
v.kind = 2;
|
||||
v.resource = host;
|
||||
v.title_va = title_va;
|
||||
v.title_size = title_size;
|
||||
v.has_srv_desc = desc != nullptr;
|
||||
if (desc) v.srv = *desc;
|
||||
std::string key = "s" + std::to_string(reinterpret_cast<uintptr_t>(host)) + ":" + std::to_string(title_va) + ":";
|
||||
if (desc) key.append(reinterpret_cast<const char*>(desc), sizeof(*desc));
|
||||
write_marker(dest, intern(key, v));
|
||||
}
|
||||
|
||||
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count) {
|
||||
if (!cache_folder() || !dest || !src || dest == src) return;
|
||||
if (!readable(src, 32ull * count) || !writable(dest, 32ull * count)) return;
|
||||
std::memmove(reinterpret_cast<void*>(dest), reinterpret_cast<const void*>(src), 32ull * count);
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* Constant data is copied from title memory into a BetterXen upload ring at 256-byte-aligned
|
||||
offsets, so it does not depend on the view kind, the shadow buffers or the title's alignment.
|
||||
The ring wraps; with a few draws per frame, data in flight is never overwritten. */
|
||||
bool constant_copy(ID3D12Device* device, uint64_t title_va, uint64_t size, D3D12_CONSTANT_BUFFER_VIEW_DESC* out) {
|
||||
constexpr uint64_t kRing = 16ull << 20;
|
||||
static ID3D12Resource* ring = nullptr;
|
||||
static uint8_t* mapped = nullptr;
|
||||
static uint64_t cursor = 0;
|
||||
static std::mutex lock;
|
||||
if (size > 65536 || !readable(title_va, size)) return false;
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
if (!ring) {
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
D3D12_RESOURCE_DESC d{};
|
||||
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
d.Width = kRing;
|
||||
d.Height = d.DepthOrArraySize = d.MipLevels = 1;
|
||||
d.SampleDesc.Count = 1;
|
||||
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&ring))) ||
|
||||
FAILED(ring->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) {
|
||||
ring = nullptr;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const uint64_t aligned = (size + 255) & ~255ull;
|
||||
if (cursor + aligned > kRing) cursor = 0;
|
||||
std::memset(mapped + cursor, 0, aligned);
|
||||
std::memcpy(mapped + cursor, reinterpret_cast<const void*>(title_va), size);
|
||||
out->BufferLocation = ring->GetGPUVirtualAddress() + cursor;
|
||||
out->SizeInBytes = static_cast<UINT>(aligned);
|
||||
cursor += aligned;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void bx_console_resolve(ID3D12Device* device, uint64_t table, const std::vector<std::pair<int, UINT>>& uses,
|
||||
const char* key) {
|
||||
static std::atomic<int> logged{0};
|
||||
for (const auto& use : uses) {
|
||||
const uint64_t entry = table + 32ull * use.second;
|
||||
uint32_t w[8] = {};
|
||||
if (!readable(entry, sizeof(w))) continue;
|
||||
std::memcpy(w, reinterpret_cast<const void*>(entry), sizeof(w));
|
||||
View v;
|
||||
bool ok = w[0] == kMarkerMagic && w[2] == ~w[1];
|
||||
if (ok) {
|
||||
std::lock_guard<std::mutex> guard(g_view_lock);
|
||||
ok = w[1] < g_views.size();
|
||||
if (ok) v = g_views[w[1]];
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE host = bx_xbox_host_cpu_handle({static_cast<SIZE_T>(entry)});
|
||||
D3D12_CONSTANT_BUFFER_VIEW_DESC c{};
|
||||
if (ok && use.first == 1 && v.title_va && v.title_size && constant_copy(device, v.title_va, v.title_size, &c)) {
|
||||
device->CreateConstantBufferView(&c, host);
|
||||
static std::atomic<int> shown{0};
|
||||
if (profile_on() && shown.fetch_add(1) < 8) {
|
||||
char f[600], detail[760];
|
||||
floats(f, sizeof(f), v.title_va, 16);
|
||||
std::snprintf(detail, sizeof(detail), "resolve %s entry %u kind %d va=0x%llx size=%llu w0-15: %s", key, use.second,
|
||||
v.kind, static_cast<unsigned long long>(v.title_va),
|
||||
static_cast<unsigned long long>(v.title_size), f);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
if (v.title_size >= 416) {
|
||||
floats(f, sizeof(f), v.title_va + 0x160, 16);
|
||||
std::snprintf(detail, sizeof(detail), "resolve %s entry %u w88-103: %s", key, use.second, f);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
}
|
||||
}
|
||||
} else if (ok && use.first == 2 && v.kind == 2) {
|
||||
device->CreateShaderResourceView(v.resource, v.has_srv_desc ? &v.srv : nullptr, host);
|
||||
static std::atomic<int> shown{0};
|
||||
if (profile_on() && (shown.fetch_add(1) % 200) < 2) {
|
||||
const D3D12_RESOURCE_DESC r = v.resource->GetDesc();
|
||||
char detail[240];
|
||||
std::snprintf(detail, sizeof(detail), "resolve %s entry %u texture dim=%d %llux%u mips=%u fmt=%d viewfmt=%d viewdim=%d",
|
||||
key, use.second, static_cast<int>(r.Dimension), static_cast<unsigned long long>(r.Width), r.Height,
|
||||
r.MipLevels, static_cast<int>(r.Format), v.has_srv_desc ? static_cast<int>(v.srv.Format) : -1,
|
||||
v.has_srv_desc ? static_cast<int>(v.srv.ViewDimension) : -1);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
const uint64_t va = bx_xbox_shadow_title_va(v.resource);
|
||||
uint64_t nonzero = 0, sampled = 0;
|
||||
if (va && r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D) {
|
||||
const uint64_t bytes = r.Width * r.Height * 4;
|
||||
for (uint64_t off = 0; off + 4096 <= bytes; off += 1ull << 20) {
|
||||
if (!readable(va + off, 4096)) break;
|
||||
const auto* px = reinterpret_cast<const uint8_t*>(va + off);
|
||||
for (int k = 0; k < 4096; ++k) nonzero += px[k] != 0;
|
||||
sampled += 4096;
|
||||
}
|
||||
}
|
||||
std::snprintf(detail, sizeof(detail), "resolve %s entry %u texture title_va=0x%llx sampled=%llu nonzero=%llu", key,
|
||||
use.second, static_cast<unsigned long long>(va), static_cast<unsigned long long>(sampled),
|
||||
static_cast<unsigned long long>(nonzero));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
}
|
||||
} else if (logged.fetch_add(1) < 24) {
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail), "pipeline %s entry %u (%s): no usable marker (kind %d): %08x %08x %08x %08x %08x %08x %08x %08x",
|
||||
key, use.second, use.first == 1 ? "CB" : "texture", ok ? v.kind : 0, w[0], w[1], w[2], w[3], w[4], w[5],
|
||||
w[6], w[7]);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "console_descriptor", detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void bx_console_note_root_srv(ID3D12GraphicsCommandList*, UINT param, uint64_t title_va) {
|
||||
if (!profile_on()) return;
|
||||
static std::atomic<int> n{0};
|
||||
if (n.fetch_add(1) >= 6) return;
|
||||
char detail[700] = "unreadable";
|
||||
if (readable(title_va, 160)) {
|
||||
uint32_t w[8];
|
||||
std::memcpy(w, reinterpret_cast<const void*>(title_va), sizeof(w));
|
||||
char f[420];
|
||||
floats(f, sizeof(f), title_va + 32, 32);
|
||||
std::snprintf(detail, sizeof(detail), "root_srv param=%u va=0x%llx hdr: %08x %08x %08x %08x %08x %08x %08x %08x data@32: %s", param,
|
||||
static_cast<unsigned long long>(title_va), w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7], f);
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_evidence", detail);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#pragma once
|
||||
/*
|
||||
* Experimental translation of deserialized console pipelines (raw RDNA 2 code) for the first
|
||||
* frames of a project-authorized target build. See console_translate.cpp.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
|
||||
/* Records a created root signature's serialized form (host object -> description). */
|
||||
void bx_console_root_signature_created(ID3D12RootSignature* host, const void* blob, size_t size);
|
||||
|
||||
/* The 1.1-converted description of a recorded root signature, or nullptr. */
|
||||
const D3D12_ROOT_SIGNATURE_DESC1* bx_console_root_signature_desc(ID3D12RootSignature* host);
|
||||
|
||||
/* Writes a compact description of a recorded root signature. */
|
||||
void bx_console_describe_root_signature(ID3D12RootSignature* host, char* out, size_t room);
|
||||
|
||||
/* True when BX_CONSOLE_SHADER_CACHE names a folder of translated shaders (opt-in). */
|
||||
bool bx_console_translation_enabled();
|
||||
|
||||
/* With translation enabled: a serialized root signature widened with the translator's register
|
||||
space (overlapping CBV/SRV ranges per descriptor table, one static sampler). The caller
|
||||
creates the host root signature from it and falls back to the original on failure. */
|
||||
ID3DBlob* bx_console_widen_root_signature(const void* blob, size_t size);
|
||||
|
||||
/* A console graphics pipeline whose stages have translated shaders in the cache. */
|
||||
struct BxTranslated;
|
||||
|
||||
/* Looks the VS/PS pair up in the cache; nullptr when either is missing. */
|
||||
std::shared_ptr<BxTranslated> bx_console_translate_graphics(ID3D12Device* device, ID3D12RootSignature* host_root,
|
||||
const void* vs, size_t vs_size, const void* ps,
|
||||
size_t ps_size);
|
||||
|
||||
/* Render-target bookkeeping, so translated pipelines are created with the bound formats. */
|
||||
void bx_console_rtv_created(SIZE_T host_cpu, DXGI_FORMAT format);
|
||||
void bx_console_dsv_created(SIZE_T host_cpu, DXGI_FORMAT format);
|
||||
void bx_console_list_set_render_targets(ID3D12GraphicsCommandList* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv);
|
||||
|
||||
/* Draw-time evidence (BX_PSO_PROFILE=1, local only). Handles are title descriptor addresses. */
|
||||
void bx_console_note_cbv(uint64_t title_handle, uint64_t va, UINT size);
|
||||
void bx_console_note_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc);
|
||||
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle);
|
||||
void bx_console_note_vb(ID3D12GraphicsCommandList* list, UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views);
|
||||
void bx_console_evidence(const char* key, ID3D12GraphicsCommandList* list, UINT vertices);
|
||||
const char* bx_console_key(const BxTranslated* translated);
|
||||
|
||||
/* Inline console descriptors: draws are recorded per list and decoded when it is submitted. */
|
||||
void bx_console_list_reset(ID3D12GraphicsCommandList* list);
|
||||
void bx_console_record_draw(const std::shared_ptr<BxTranslated>& translated, ID3D12GraphicsCommandList* list);
|
||||
void bx_console_submit(ID3D12CommandList* const* lists, UINT count);
|
||||
|
||||
/* Descriptor markers in title memory (see console_translate.cpp, part 5). */
|
||||
void bx_console_mark_cbv(uint64_t dest, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc, uint64_t title_va);
|
||||
void bx_console_mark_srv(uint64_t dest, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
|
||||
uint64_t title_va = 0, uint64_t title_size = 0);
|
||||
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count);
|
||||
|
||||
/* placed_x.cpp: copies a title-memory range to the host shadow its address resolves to. */
|
||||
extern "C" bool bx_xbox_sync_title_range(uint64_t title_va, uint64_t size);
|
||||
extern "C" uint64_t bx_xbox_shadow_title_va(ID3D12Resource* host);
|
||||
|
||||
void bx_console_note_root_srv(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_va);
|
||||
|
||||
/* Binds a translated pipeline to a host list before a draw; false when it cannot be created. */
|
||||
bool bx_console_apply(BxTranslated* translated, ID3D12GraphicsCommandList* list);
|
||||
@@ -13,6 +13,7 @@
|
||||
* other titles' descriptor writes on the out-of-line path, which reaches the host heap.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
#include "console_translate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
@@ -187,6 +188,8 @@ void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, co
|
||||
host_desc.BufferLocation = bx_xbox_host_gpu_va(desc->BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateConstantBufferView(desc ? &host_desc : nullptr, bx_xbox_host_cpu_handle(dest));
|
||||
if (desc) bx_console_note_cbv(dest.ptr, desc->BufferLocation, desc->SizeInBytes);
|
||||
if (desc) bx_console_mark_cbv(dest.ptr, host_desc, desc->BufferLocation);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
|
||||
@@ -198,6 +201,17 @@ void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ran
|
||||
if (!dst) return;
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE* src = dst + dest_ranges;
|
||||
for (UINT i = 0; i < dest_ranges; ++i) dst[i] = bx_xbox_host_cpu_handle(dest_starts[i]);
|
||||
if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && dest_starts && src_starts) {
|
||||
// console descriptors are bytes: copy the title's too (range by range, sizes default to 1)
|
||||
UINT di = 0, dn = 0, si = 0, sn = 0;
|
||||
auto dsize = [&](UINT i) { return dest_sizes ? dest_sizes[i] : 1u; };
|
||||
auto ssize = [&](UINT i) { return src_sizes ? src_sizes[i] : 1u; };
|
||||
while (di < dest_ranges && si < src_ranges) {
|
||||
bx_console_copy_title(dest_starts[di].ptr + 32ull * dn, src_starts[si].ptr + 32ull * sn, 1);
|
||||
if (++dn >= dsize(di)) { ++di; dn = 0; }
|
||||
if (++sn >= ssize(si)) { ++si; sn = 0; }
|
||||
}
|
||||
}
|
||||
for (UINT i = 0; i < src_ranges; ++i) src[i] = bx_xbox_host_cpu_handle(src_starts[i]);
|
||||
bx_xbox_host<ID3D12Device>(self)->CopyDescriptors(dest_ranges, dst, dest_sizes, src_ranges, src, src_sizes, type);
|
||||
delete[] dst;
|
||||
@@ -212,6 +226,10 @@ void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE host_dsv = dsv ? bx_xbox_host_cpu_handle(*dsv) : D3D12_CPU_DESCRIPTOR_HANDLE{};
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->OMSetRenderTargets(n, rtvs ? host_rtvs : nullptr, single_range,
|
||||
dsv ? &host_dsv : nullptr);
|
||||
if (bx_console_translation_enabled()) {
|
||||
bx_console_list_set_render_targets(bx_xbox_host<ID3D12GraphicsCommandList>(self), n, rtvs ? host_rtvs : nullptr,
|
||||
single_range, dsv ? &host_dsv : nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
@@ -224,6 +242,7 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start
|
||||
host[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
|
||||
bx_console_note_vb(bx_xbox_host<ID3D12GraphicsCommandList>(self), start, n, views);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
@@ -43,6 +45,22 @@ UINT64 g_next_token = 1;
|
||||
UINT64 g_last_origin_token = 0;
|
||||
bool g_thread_started = false;
|
||||
|
||||
/* Origin occurrences by token, for GetFrameStatisticsX (host QueryPerformanceCounter ticks). */
|
||||
struct OriginRecord {
|
||||
UINT64 token = 0;
|
||||
UINT64 signal_qpc = 0;
|
||||
UINT64 wait_call_qpc = 0;
|
||||
UINT64 wait_return_qpc = 0;
|
||||
};
|
||||
constexpr size_t kOriginRing = 256;
|
||||
OriginRecord g_origins[kOriginRing];
|
||||
|
||||
UINT64 qpc_now() {
|
||||
LARGE_INTEGER t;
|
||||
QueryPerformanceCounter(&t);
|
||||
return static_cast<UINT64>(t.QuadPart);
|
||||
}
|
||||
|
||||
void close_ancillary(Scheduled& e) {
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
|
||||
e.ancillary_count = 0;
|
||||
@@ -52,7 +70,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++;
|
||||
OriginRecord& r = g_origins[g_last_origin_token % kOriginRing];
|
||||
r = {};
|
||||
r.token = g_last_origin_token;
|
||||
r.signal_qpc = qpc_now();
|
||||
}
|
||||
SetEvent(g_signal[type]);
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
|
||||
}
|
||||
@@ -156,6 +180,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 +191,115 @@ 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++;
|
||||
OriginRecord& r = g_origins[*token % kOriginRing];
|
||||
if (r.token != *token) {
|
||||
r = {};
|
||||
r.token = *token;
|
||||
r.signal_qpc = wait_call;
|
||||
}
|
||||
r.wait_call_qpc = wait_call;
|
||||
r.wait_return_qpc = qpc_now();
|
||||
}
|
||||
return satisfied ? S_OK : S_FALSE;
|
||||
}
|
||||
|
||||
/*
|
||||
* GetFrameStatisticsX (structures from the authorized GDK header; semantics inferred, there is
|
||||
* no documentation text for this call): one D3D12XBOX_FRAME_STATISTICS element per requested
|
||||
* type, at most *pCount, with host QueryPerformanceCounter ticks for every time. There is no
|
||||
* display here: the vertical sync and flip are reported one frame interval after the origin,
|
||||
* and GPU durations as half an interval. Each first request per type set is logged.
|
||||
*/
|
||||
struct BxFrameStatistics {
|
||||
UINT type;
|
||||
UINT pad;
|
||||
union {
|
||||
struct { UINT length_us, period, flags; } interval;
|
||||
struct { UINT event_type; UINT pad; UINT64 wait_call, signal, wait_return; UINT offset_us, signal_flags, stat_flags; } event;
|
||||
struct { UINT64 context, origin, available, query; } input;
|
||||
struct { UINT8 plane; UINT8 pad[7]; UINT64 write_complete, busy; } render;
|
||||
struct { UINT8 plane, plane_count, view_count; UINT8 pad[5]; UINT64 call, queue, ret, gpu; UINT8 queued; UINT8 pad2;
|
||||
UINT16 swap_mask; UINT flags; } present;
|
||||
struct { UINT8 plane; UINT8 pad[7]; UINT64 vsync, flip; FLOAT scanned; } display;
|
||||
struct { UINT8 plane; UINT8 pad[7]; UINT64 busy_scaled; double factor; } power;
|
||||
};
|
||||
};
|
||||
static_assert(sizeof(BxFrameStatistics) == 56, "D3D12XBOX_FRAME_STATISTICS size");
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void*, UINT64 token, UINT type_set, UINT* count,
|
||||
BxFrameStatistics* stats) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetFrameStatisticsX");
|
||||
if (!count) return E_INVALIDARG;
|
||||
const UINT capacity = *count;
|
||||
LARGE_INTEGER freq;
|
||||
QueryPerformanceFrequency(&freq);
|
||||
OriginRecord origin;
|
||||
UINT interval_us, period;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
origin = g_origins[token % kOriginRing];
|
||||
interval_us = g_interval_us ? g_interval_us : 16667;
|
||||
period = g_period ? g_period : 1;
|
||||
}
|
||||
const UINT64 now = qpc_now();
|
||||
if (origin.token != token || !origin.signal_qpc) {
|
||||
origin = {};
|
||||
origin.token = token;
|
||||
origin.signal_qpc = origin.wait_call_qpc = origin.wait_return_qpc = now;
|
||||
}
|
||||
const UINT64 frame_ticks = static_cast<UINT64>(freq.QuadPart) * interval_us * period / 1000000ull;
|
||||
UINT written = 0;
|
||||
auto next = [&](UINT type) -> BxFrameStatistics* {
|
||||
if (!(type_set & type) || written >= capacity || !stats) return nullptr;
|
||||
BxFrameStatistics* s = &stats[written++];
|
||||
std::memset(s, 0, sizeof(*s));
|
||||
s->type = type;
|
||||
return s;
|
||||
};
|
||||
if (BxFrameStatistics* s = next(0x1)) {
|
||||
s->interval.length_us = interval_us;
|
||||
s->interval.period = period;
|
||||
}
|
||||
if (BxFrameStatistics* s = next(0x2)) {
|
||||
s->event.event_type = kOrigin;
|
||||
s->event.wait_call = origin.wait_call_qpc ? origin.wait_call_qpc : origin.signal_qpc;
|
||||
s->event.signal = origin.signal_qpc;
|
||||
s->event.wait_return = origin.wait_return_qpc ? origin.wait_return_qpc : origin.signal_qpc;
|
||||
}
|
||||
if (BxFrameStatistics* s = next(0x4)) {
|
||||
s->power.busy_scaled = frame_ticks / 2;
|
||||
s->power.factor = 1.0;
|
||||
}
|
||||
if (BxFrameStatistics* s = next(0x100)) {
|
||||
s->render.write_complete = origin.signal_qpc + frame_ticks / 2;
|
||||
s->render.busy = frame_ticks / 2;
|
||||
}
|
||||
if (BxFrameStatistics* s = next(0x1000)) {
|
||||
s->present.plane_count = 1;
|
||||
s->present.view_count = 1;
|
||||
s->present.call = s->present.queue = s->present.ret = origin.signal_qpc + frame_ticks / 2;
|
||||
s->present.gpu = frame_ticks / 2;
|
||||
s->present.swap_mask = 1;
|
||||
}
|
||||
if (BxFrameStatistics* s = next(0x10000)) {
|
||||
s->display.vsync = origin.signal_qpc + frame_ticks;
|
||||
s->display.flip = origin.signal_qpc + frame_ticks;
|
||||
s->display.scanned = 0.0f;
|
||||
}
|
||||
if (BxFrameStatistics* s = next(0x100000)) {
|
||||
s->input.origin = origin.signal_qpc;
|
||||
s->input.available = origin.signal_qpc;
|
||||
s->input.query = origin.wait_return_qpc ? origin.wait_return_qpc : origin.signal_qpc;
|
||||
}
|
||||
*count = written;
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 6) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "token=%llu type_set=0x%x capacity=%u written=%u (host clock, no display)",
|
||||
static_cast<unsigned long long>(token), type_set, capacity, written);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "frame_statistics", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -8,6 +8,7 @@
|
||||
* writes are therefore synchronous (logged once); executes without writes are not changed.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
#include "console_translate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
@@ -158,6 +159,7 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) apply_wait(queue, w);
|
||||
}
|
||||
bx_console_submit(host.data(), count);
|
||||
queue->ExecuteCommandLists(count, host.data());
|
||||
bool any_write = false;
|
||||
for (const Write& w : pending) any_write = any_write || !w.wait;
|
||||
|
||||
+270
-17
@@ -18,12 +18,14 @@
|
||||
|
||||
#include "proxy.h"
|
||||
#include "shader_gate.h"
|
||||
#include "console_translate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -38,10 +40,30 @@ bool null_render_enabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/* BX_PSO_PROFILE=1 (local diagnostics, off by default): each null pipeline gets an id, its
|
||||
creation is described in a `pso_profile` record, and skipped draws and dispatches name the id
|
||||
they were recorded with. The records hold title-derived sizes and hashes: they belong in
|
||||
private evidence, never in the repository. */
|
||||
bool pso_profile_enabled() {
|
||||
static const bool enabled = [] {
|
||||
char value[8] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_PSO_PROFILE", value, sizeof(value));
|
||||
return n > 0 && n < sizeof(value) && value[0] == '1';
|
||||
}();
|
||||
return enabled;
|
||||
}
|
||||
thread_local const char* t_pending_profile = nullptr; // description of the pipeline being refused
|
||||
thread_local std::shared_ptr<BxTranslated> t_pending_translated; // translation for the pipeline being refused
|
||||
std::atomic<uint32_t> g_next_null_id{1};
|
||||
|
||||
/* A pipeline-state object with no host pipeline behind it. */
|
||||
class NullPipelineState final : public ID3D12PipelineState {
|
||||
public:
|
||||
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
|
||||
explicit NullPipelineState(ID3D12Device* device) : device_(device), id_(g_next_null_id.fetch_add(1)) {
|
||||
device_->AddRef();
|
||||
}
|
||||
uint32_t id() const { return id_; }
|
||||
std::shared_ptr<BxTranslated> translated; // console stages with translated shaders, if any
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
@@ -78,6 +100,7 @@ public:
|
||||
|
||||
private:
|
||||
ID3D12Device* device_;
|
||||
uint32_t id_;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
};
|
||||
|
||||
@@ -88,6 +111,9 @@ size_t g_null_capacity = 0;
|
||||
ID3D12GraphicsCommandList** g_lists = nullptr; // lists whose bound pipeline is a null pipeline
|
||||
size_t g_list_count = 0;
|
||||
size_t g_list_capacity = 0;
|
||||
std::unordered_map<const void*, uint32_t> g_list_pso; // profile: null pipeline id bound per list
|
||||
std::unordered_map<uint32_t, uint64_t> g_pso_uses; // profile: skipped work per null pipeline id
|
||||
std::unordered_map<const void*, std::shared_ptr<BxTranslated>> g_list_translated; // translated pipeline bound per list
|
||||
|
||||
template <typename T>
|
||||
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
|
||||
@@ -124,24 +150,67 @@ bool contains(T* const* items, size_t count, const T* item) {
|
||||
}
|
||||
|
||||
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
|
||||
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
|
||||
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null, uint32_t* null_id = nullptr,
|
||||
std::shared_ptr<BxTranslated>* translated = nullptr) {
|
||||
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
*is_null = host && contains(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
|
||||
auto* as_null = static_cast<NullPipelineState*>(static_cast<void*>(host));
|
||||
*is_null = host && contains(g_nulls, g_null_count, as_null);
|
||||
if (null_id) *null_id = *is_null ? as_null->id() : 0;
|
||||
if (translated) *translated = *is_null ? as_null->translated : nullptr;
|
||||
return *is_null ? nullptr : host;
|
||||
}
|
||||
|
||||
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
|
||||
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound, uint32_t null_id = 0,
|
||||
std::shared_ptr<BxTranslated> translated = nullptr) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (translated) {
|
||||
g_list_translated[list] = std::move(translated);
|
||||
} else {
|
||||
g_list_translated.erase(list);
|
||||
}
|
||||
if (pso_profile_enabled()) g_list_pso[list] = null_bound ? null_id : 0;
|
||||
const bool present = contains(g_lists, g_list_count, list);
|
||||
if (null_bound && !present) push(g_lists, g_list_count, g_list_capacity, list);
|
||||
if (!null_bound && present) erase(g_lists, g_list_count, list);
|
||||
}
|
||||
|
||||
bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
|
||||
bool list_skips(ID3D12GraphicsCommandList* list, const char* what, bool is_draw = false) {
|
||||
uint32_t id = 0;
|
||||
uint64_t uses = 0;
|
||||
std::shared_ptr<BxTranslated> translated;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!contains(g_lists, g_list_count, list)) return false;
|
||||
if (is_draw) {
|
||||
auto it = g_list_translated.find(list);
|
||||
if (it != g_list_translated.end()) translated = it->second;
|
||||
}
|
||||
}
|
||||
if (translated && bx_console_apply(translated.get(), list)) {
|
||||
bx_console_evidence(bx_console_key(translated.get()), list, 0);
|
||||
bx_console_record_draw(translated, list);
|
||||
static std::atomic<uint64_t> drawn{0};
|
||||
const uint64_t k = ++drawn;
|
||||
if ((k & (k - 1)) == 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s with a translated console pipeline; total=%llu", what,
|
||||
static_cast<unsigned long long>(k));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_draw", detail);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (pso_profile_enabled()) {
|
||||
id = g_list_pso[list];
|
||||
uses = ++g_pso_uses[id];
|
||||
}
|
||||
}
|
||||
if (pso_profile_enabled() && (uses & (uses - 1)) == 0) { // each id's 1st, 2nd, 4th, ... use
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "use id=%u %s uses=%llu", id, what, static_cast<unsigned long long>(uses));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_profile", detail);
|
||||
}
|
||||
static std::atomic<uint64_t> skipped{0};
|
||||
const uint64_t n = ++skipped;
|
||||
@@ -169,6 +238,15 @@ HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid,
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
if (pso_profile_enabled()) {
|
||||
char detail[1800];
|
||||
std::snprintf(detail, sizeof(detail), "create id=%u kind=%s %s", null_pso->id(), kind,
|
||||
t_pending_profile ? t_pending_profile : "");
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_profile", detail);
|
||||
}
|
||||
t_pending_profile = nullptr;
|
||||
null_pso->translated = std::move(t_pending_translated);
|
||||
t_pending_translated.reset();
|
||||
*ppv = static_cast<ID3D12PipelineState*>(null_pso);
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
@@ -230,16 +308,37 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
ID3D12RootSignature* root = nullptr;
|
||||
std::memcpy(&root, &stream[root_offset], sizeof(root));
|
||||
root = bx_xbox_unwrap_as(root);
|
||||
if (pso_profile_enabled()) {
|
||||
char d[64];
|
||||
std::snprintf(d, sizeof(d), "stream pipeline root=%p", static_cast<void*>(root));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_profile", d);
|
||||
}
|
||||
std::memcpy(&stream[root_offset], &root, sizeof(root));
|
||||
}
|
||||
BxShaderGate gate;
|
||||
for (size_t i = 0; i < offsets.size() && SUCCEEDED(hr); ++i) {
|
||||
HRESULT first_failure = S_OK;
|
||||
for (size_t i = 0; i < offsets.size(); ++i) {
|
||||
D3D12_SHADER_BYTECODE in{};
|
||||
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
|
||||
D3D12_SHADER_BYTECODE out = in;
|
||||
{ // BX_PSO_DUMP=<folder>: stream shader blobs (local evidence only)
|
||||
static char folder[512] = {};
|
||||
static const bool on = GetEnvironmentVariableA("BX_PSO_DUMP", folder, sizeof(folder)) > 0;
|
||||
static std::atomic<int> n{0};
|
||||
if (on && in.pShaderBytecode && in.BytecodeLength && n.load() < 64) {
|
||||
char path[640];
|
||||
std::snprintf(path, sizeof(path), "%s\\stream_%02d_%s.bin", folder, n.fetch_add(1), names[i]);
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(in.pShaderBytecode, 1, in.BytecodeLength, f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
hr = gate.admit("stream", names[i], in, out);
|
||||
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
else if (SUCCEEDED(first_failure)) first_failure = hr;
|
||||
}
|
||||
hr = first_failure;
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
|
||||
@@ -305,8 +404,10 @@ void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12Pipelin
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
uint32_t null_id = 0;
|
||||
std::shared_ptr<BxTranslated> translated;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &null_id, &translated);
|
||||
set_list_null(list, is_null, null_id, std::move(translated));
|
||||
if (!is_null) list->SetPipelineState(host);
|
||||
}
|
||||
|
||||
@@ -314,9 +415,12 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator*
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
uint32_t null_id = 0;
|
||||
std::shared_ptr<BxTranslated> translated;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &null_id, &translated);
|
||||
set_list_null(list, is_null, null_id, std::move(translated));
|
||||
bx_xbox_gpu_writes_reset(list);
|
||||
bx_console_list_reset(list);
|
||||
return list->Reset(bx_xbox_unwrap_as(allocator), host);
|
||||
}
|
||||
|
||||
@@ -324,14 +428,14 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UI
|
||||
UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
|
||||
if (!list_skips(list, "DrawInstanced", true)) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
|
||||
INT base_vertex, UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawIndexedInstanced")) {
|
||||
if (!list_skips(list, "DrawIndexedInstanced", true)) {
|
||||
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
|
||||
}
|
||||
}
|
||||
@@ -431,24 +535,163 @@ void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, U
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace {
|
||||
/* Layouts from the authorized GDK header (D3D12XBOX_DESERIALIZE_*_PIPELINE_STATE). */
|
||||
struct DeserializeShader {
|
||||
const void* instructions;
|
||||
SIZE_T instructions_size;
|
||||
const void* metadata;
|
||||
SIZE_T metadata_size;
|
||||
};
|
||||
struct DeserializeGraphics {
|
||||
ID3D12RootSignature* root;
|
||||
void* packet;
|
||||
SIZE_T packet_size;
|
||||
void* metadata;
|
||||
SIZE_T metadata_size;
|
||||
DeserializeShader stages[7]; // PS, VS, GS, ES, HS, LS, FS
|
||||
};
|
||||
struct DeserializeCompute {
|
||||
ID3D12RootSignature* root;
|
||||
void* packet;
|
||||
SIZE_T packet_size;
|
||||
void* metadata;
|
||||
SIZE_T metadata_size;
|
||||
DeserializeShader cs;
|
||||
};
|
||||
|
||||
uint64_t fnv1a(const void* data, size_t size) {
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
const auto* p = static_cast<const uint8_t*>(data);
|
||||
for (size_t i = 0; data && i < size; ++i) h = (h ^ p[i]) * 1099511628211ull;
|
||||
return h;
|
||||
}
|
||||
|
||||
/* BX_PSO_DUMP=<folder> with BX_PSO_DUMP_HASHES=<hex,hex,...>: writes the stages whose
|
||||
instruction hash is listed (local evidence only). */
|
||||
void dump_blob(const char* name, uint64_t hash, const char* part, const void* data, size_t size) {
|
||||
static char folder[512] = {};
|
||||
static char hashes[1024] = {};
|
||||
static const bool on = [] {
|
||||
return GetEnvironmentVariableA("BX_PSO_DUMP", folder, sizeof(folder)) > 0 &&
|
||||
GetEnvironmentVariableA("BX_PSO_DUMP_HASHES", hashes, sizeof(hashes)) > 0;
|
||||
}();
|
||||
if (!on || !data || !size) return;
|
||||
char hex[20];
|
||||
std::snprintf(hex, sizeof(hex), "%016llx", static_cast<unsigned long long>(hash));
|
||||
if (!std::strstr(hashes, hex)) return;
|
||||
char path[640];
|
||||
std::snprintf(path, sizeof(path), "%s\\%s_%s.%s.bin", folder, hex, name, part);
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(data, 1, size, f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
size_t describe_stage(char* out, size_t room, const char* name, const DeserializeShader& s) {
|
||||
if (!s.instructions || !s.instructions_size || room < 2) return 0;
|
||||
{
|
||||
const uint64_t h = fnv1a(s.instructions, s.instructions_size);
|
||||
dump_blob(name, h, "code", s.instructions, s.instructions_size);
|
||||
dump_blob(name, h, "meta", s.metadata, s.metadata_size);
|
||||
}
|
||||
const int n = std::snprintf(out, room, " %s=%llu/%llu#%016llx", name,
|
||||
static_cast<unsigned long long>(s.instructions_size),
|
||||
static_cast<unsigned long long>(s.metadata_size),
|
||||
static_cast<unsigned long long>(fnv1a(s.instructions, s.instructions_size)));
|
||||
return n > 0 && static_cast<size_t>(n) < room ? static_cast<size_t>(n) : 0;
|
||||
}
|
||||
|
||||
thread_local char t_profile_buffer[1600];
|
||||
|
||||
/* BX_DESERIALIZE_FAIL=1 (experiment): the serialized-pipeline calls fail with E_NOTIMPL and a null
|
||||
object even in null-render mode, so a title falls back to creating pipelines from shader
|
||||
containers, as it does when its serialized cache does not apply. */
|
||||
bool deserialize_fails() {
|
||||
static const bool on = [] {
|
||||
char v[4] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_DESERIALIZE_FAIL", v, sizeof(v));
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
HRESULT deserialize_failed(const char* what) {
|
||||
static std::atomic<uint64_t> count{0};
|
||||
const uint64_t n = ++count;
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s refused with E_NOTIMPL (BX_DESERIALIZE_FAIL); total=%llu", what,
|
||||
static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_deserialize_refused", detail);
|
||||
}
|
||||
t_pending_profile = nullptr;
|
||||
t_pending_translated.reset();
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
size_t describe_header(const void* packet, SIZE_T packet_size, SIZE_T metadata_size) {
|
||||
dump_blob("pipeline", fnv1a(packet, packet_size), "packet", packet, packet_size);
|
||||
const int n = std::snprintf(t_profile_buffer, sizeof(t_profile_buffer), "packet=%llu#%016llx meta=%llu",
|
||||
static_cast<unsigned long long>(packet_size),
|
||||
static_cast<unsigned long long>(fnv1a(packet, packet_size)),
|
||||
static_cast<unsigned long long>(metadata_size));
|
||||
return n > 0 ? static_cast<size_t>(n) : 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
/*
|
||||
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
|
||||
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
|
||||
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void* state,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (pso_profile_enabled() && state) {
|
||||
const auto* d = static_cast<const DeserializeGraphics*>(state);
|
||||
static const char* const names[7] = {"PS", "VS", "GS", "ES", "HS", "LS", "FS"};
|
||||
size_t used = describe_header(d->packet, d->packet_size, d->metadata_size);
|
||||
for (int i = 0; i < 7 && used < sizeof(t_profile_buffer); ++i) {
|
||||
used += describe_stage(t_profile_buffer + used, sizeof(t_profile_buffer) - used, names[i], d->stages[i]);
|
||||
}
|
||||
if (used + 2 < sizeof(t_profile_buffer)) {
|
||||
std::snprintf(t_profile_buffer + used, sizeof(t_profile_buffer) - used, " root=%p",
|
||||
static_cast<void*>(bx_xbox_unwrap_as(d->root)));
|
||||
}
|
||||
t_pending_profile = t_profile_buffer;
|
||||
}
|
||||
if (state && bx_console_translation_enabled()) {
|
||||
const auto* d = static_cast<const DeserializeGraphics*>(state);
|
||||
const DeserializeShader& ps = d->stages[0];
|
||||
const DeserializeShader& vs = d->stages[1];
|
||||
bool other_stages = false;
|
||||
for (int i = 2; i < 7; ++i) other_stages |= d->stages[i].instructions_size != 0;
|
||||
if (!other_stages && vs.instructions_size && ps.instructions_size) {
|
||||
t_pending_translated = bx_console_translate_graphics(bx_xbox_host<ID3D12Device>(self), bx_xbox_unwrap_as(d->root),
|
||||
vs.instructions, vs.instructions_size, ps.instructions,
|
||||
ps.instructions_size);
|
||||
}
|
||||
}
|
||||
if (deserialize_fails()) return deserialize_failed("DeserializeGraphicsPipelineStateX");
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void* state,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (pso_profile_enabled() && state) {
|
||||
const auto* d = static_cast<const DeserializeCompute*>(state);
|
||||
size_t used = describe_header(d->packet, d->packet_size, d->metadata_size);
|
||||
if (used < sizeof(t_profile_buffer)) {
|
||||
describe_stage(t_profile_buffer + used, sizeof(t_profile_buffer) - used, "CS", d->cs);
|
||||
}
|
||||
t_pending_profile = t_profile_buffer;
|
||||
}
|
||||
if (deserialize_fails()) return deserialize_failed("DeserializeComputePipelineStateX");
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
|
||||
}
|
||||
|
||||
@@ -462,7 +705,16 @@ namespace {
|
||||
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
const bool from_null = bx_xbox_pipeline_is_null(source);
|
||||
bool from_null = false;
|
||||
uint32_t source_id = 0;
|
||||
std::shared_ptr<BxTranslated> inherited;
|
||||
host_pipeline(source, &from_null, &source_id, &inherited);
|
||||
t_pending_translated = std::move(inherited); // a derived pipeline runs the same shaders
|
||||
thread_local char derived_profile[48];
|
||||
if (pso_profile_enabled()) {
|
||||
std::snprintf(derived_profile, sizeof(derived_profile), "source=%u", source_id);
|
||||
t_pending_profile = derived_profile;
|
||||
}
|
||||
if (!from_null) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
@@ -470,6 +722,7 @@ HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv
|
||||
"deriving from a host pipeline is not implemented (its creation description is not kept)");
|
||||
}
|
||||
}
|
||||
if (deserialize_fails() && !t_pending_translated) return deserialize_failed(kind);
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
* title addresses in GPU calls, are not done yet; both are logged when reached.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
#include "console_translate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
@@ -208,6 +209,21 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
bx_console_mark_srv(dest.ptr, resource, &pc, view_location(xbox_desc), resource_desc->Width);
|
||||
{
|
||||
static std::atomic<int> n{0};
|
||||
char v[8] = {};
|
||||
const DWORD k = GetEnvironmentVariableA("BX_PSO_PROFILE", v, sizeof(v));
|
||||
if (k > 0 && k < sizeof(v) && v[0] == '1' && n.fetch_add(1) < 60) {
|
||||
char d[200];
|
||||
std::snprintf(d, sizeof(d), "raw_srv dest=0x%llx va=0x%llx width=%llu first=%llu num=%u stride=%u flags=%u",
|
||||
static_cast<unsigned long long>(dest.ptr), static_cast<unsigned long long>(view_location(xbox_desc)),
|
||||
static_cast<unsigned long long>(resource_desc->Width),
|
||||
static_cast<unsigned long long>(pc.Buffer.FirstElement), pc.Buffer.NumElements,
|
||||
pc.Buffer.StructureByteStride, static_cast<unsigned>(pc.Buffer.Flags));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_note", d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
@@ -229,6 +245,7 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Reso
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
bx_console_mark_srv(dest.ptr, bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
@@ -250,6 +267,32 @@ D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
|
||||
return title; // not a title address this layer knows: a host address already, or untranslated
|
||||
}
|
||||
|
||||
/* The title address a host shadow resource was created for (0 when it is not a shadow). */
|
||||
uint64_t bx_xbox_shadow_title_va(ID3D12Resource* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_shadows[i].host == host) return g_shadows[i].title_va;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Copies [title_va, title_va + size) from title memory to the host shadow that
|
||||
bx_xbox_host_gpu_va resolves the address to (first match). False when there is none. */
|
||||
bool bx_xbox_sync_title_range(uint64_t title_va, uint64_t size) {
|
||||
if (!title_va || !size) return false;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (title_va >= s.title_va && title_va < s.title_va + s.size) {
|
||||
const uint64_t begin = title_va - s.title_va;
|
||||
const uint64_t end = begin + size > s.size ? s.size : begin + size;
|
||||
if (!readable(reinterpret_cast<const void*>(title_va), end - begin)) return false;
|
||||
return copy_buffer(s, true, begin, end);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes) {
|
||||
return remember({host, title_va, size, host->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, host->GetDesc(),
|
||||
attributes});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Generated by shims/d3d12_xs/tools/gen_xbox_tables.py from the Xbox Series D3D12 header (slot
|
||||
// order, names and types only) and the toolchain's <d3d12.h>. Do not edit by hand.
|
||||
#include "xbox_tables_generated.h"
|
||||
#include "console_translate.h"
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -58,13 +59,21 @@ static HRESULT STDMETHODCALLTYPE x_Device_13(void* self, D3D12_FEATURE a0, void
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_16(void* self, UINT a0, const void * a1, SIZE_T a2, REFIID a3, void ** a4) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRootSignature");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, a1, a2, a3, a4);
|
||||
HRESULT hr = E_FAIL;
|
||||
if (ID3DBlob* wide = bx_console_widen_root_signature(a1, a2)) { // opt-in console translation
|
||||
hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, wide->GetBufferPointer(), wide->GetBufferSize(), a3, a4);
|
||||
wide->Release();
|
||||
}
|
||||
if (FAILED(hr)) hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, a1, a2, a3, a4);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
|
||||
if (SUCCEEDED(hr) && a4 && *a4) bx_console_root_signature_created(static_cast<ID3D12RootSignature*>(*a4), a1, a2);
|
||||
return bx_xbox_wrap_result(hr, a3, a4);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_18(void* self, ID3D12Resource * a0, const D3D12_SHADER_RESOURCE_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
|
||||
bx_console_note_srv(a2.ptr, bx_xbox_unwrap_as<ID3D12Resource>(a0), a1);
|
||||
bx_console_mark_srv(a2.ptr, bx_xbox_unwrap_as<ID3D12Resource>(a0), a1);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_19(void* self, ID3D12Resource * a0, ID3D12Resource * a1, const D3D12_UNORDERED_ACCESS_VIEW_DESC * a2, D3D12_CPU_DESCRIPTOR_HANDLE a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateUnorderedAccessView");
|
||||
@@ -73,10 +82,20 @@ static void STDMETHODCALLTYPE x_Device_19(void* self, ID3D12Resource * a0, ID3D1
|
||||
static void STDMETHODCALLTYPE x_Device_20(void* self, ID3D12Resource * a0, const D3D12_RENDER_TARGET_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
|
||||
if (bx_console_translation_enabled()) {
|
||||
DXGI_FORMAT f = a1 ? a1->Format : DXGI_FORMAT_UNKNOWN;
|
||||
if (f == DXGI_FORMAT_UNKNOWN && a0) f = bx_xbox_unwrap_as<ID3D12Resource>(a0)->GetDesc().Format;
|
||||
bx_console_rtv_created(bx_xbox_host_cpu_handle(a2).ptr, f);
|
||||
}
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_21(void* self, ID3D12Resource * a0, const D3D12_DEPTH_STENCIL_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
|
||||
if (bx_console_translation_enabled()) {
|
||||
DXGI_FORMAT f = a1 ? a1->Format : DXGI_FORMAT_UNKNOWN;
|
||||
if (f == DXGI_FORMAT_UNKNOWN && a0) f = bx_xbox_unwrap_as<ID3D12Resource>(a0)->GetDesc().Format;
|
||||
bx_console_dsv_created(bx_xbox_host_cpu_handle(a2).ptr, f);
|
||||
}
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC * a0, D3D12_CPU_DESCRIPTOR_HANDLE a1) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateSampler");
|
||||
@@ -85,6 +104,7 @@ static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC *
|
||||
static void STDMETHODCALLTYPE x_Device_24(void* self, UINT a0, const D3D12_CPU_DESCRIPTOR_HANDLE a1, const D3D12_CPU_DESCRIPTOR_HANDLE a2, D3D12_DESCRIPTOR_HEAP_TYPE a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
|
||||
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(a0, bx_xbox_host_cpu_handle(a1), bx_xbox_host_cpu_handle(a2), a3);
|
||||
if (a3 == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) bx_console_copy_title(a1.ptr, a2.ptr, a0);
|
||||
}
|
||||
static D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE x_Device_25(void* self, UINT a0, UINT a1, const D3D12_RESOURCE_DESC * a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
|
||||
@@ -225,7 +245,7 @@ static HRESULT STDMETHODCALLTYPE x_Device_76(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; }
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void*, UINT64, UINT, UINT*, void*);
|
||||
/* 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) {
|
||||
@@ -531,7 +551,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),
|
||||
@@ -1409,6 +1429,7 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_35(void* self, UINT a0, D3D1
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_36(void* self, UINT a0, D3D12_GPU_DESCRIPTOR_HANDLE a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootDescriptorTable");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootDescriptorTable(a0, bx_xbox_host_gpu_handle(a1));
|
||||
bx_console_note_table(bx_xbox_host<ID3D12GraphicsCommandList>(self), a0, a1.ptr);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_37(void* self, UINT a0, UINT a1, UINT a2) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRoot32BitConstant");
|
||||
@@ -1441,6 +1462,7 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_43(void* self, UINT a0, D3D1
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_44(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
|
||||
bx_console_note_root_srv(bx_xbox_host<ID3D12GraphicsCommandList>(self), a0, a1);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_45(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootUnorderedAccessView");
|
||||
|
||||
+175
-249
@@ -2,11 +2,9 @@
|
||||
#include <tlhelp32.h>
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstdarg>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <initializer_list>
|
||||
#include <intrin.h>
|
||||
|
||||
#include "bx_config.h"
|
||||
@@ -279,12 +277,72 @@ bool zero_guest_cache_line(uint64_t address, EXCEPTION_RECORD& exception) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A title that zeroes memory with CLZERO does it in a loop, and each iteration would trap again
|
||||
// (an exception round trip per 64 bytes: seconds per 100 MB). When the trapped CLZERO is followed
|
||||
// by exactly
|
||||
// add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
|
||||
// the remaining iterations are done here: every further line below the limit is zeroed and RAX is
|
||||
// left at the last one, so the title's own add/cmp/jb then leaves the loop. The range is zeroed
|
||||
// region by region and stops early at memory that is not committed and writable, where the
|
||||
// title's next CLZERO traps as before. Returns the number of extra lines zeroed.
|
||||
uint64_t clzero_loop_fast_path(CONTEXT& context) {
|
||||
const auto* code = reinterpret_cast<const uint8_t*>(context.Rip);
|
||||
MEMORY_BASIC_INFORMATION text{};
|
||||
if (!VirtualQuery(code, &text, sizeof(text)) || text.State != MEM_COMMIT ||
|
||||
reinterpret_cast<uintptr_t>(code) + 12 > reinterpret_cast<uintptr_t>(text.BaseAddress) + text.RegionSize) {
|
||||
return 0;
|
||||
}
|
||||
if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return 0; // clzero
|
||||
if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return 0; // add rax, 0x40
|
||||
if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) return 0; // cmp rax, r64
|
||||
if (code[10] != 0x72 || code[11] != 0xF4) return 0; // jb -12
|
||||
const unsigned reg = ((code[9] >> 3) & 7) | (code[7] == 0x4C ? 8 : 0);
|
||||
const DWORD64* registers = &context.Rax; // Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8..R15
|
||||
const uint64_t limit = registers[reg];
|
||||
constexpr uint64_t line = 64;
|
||||
uint64_t next = context.Rax + line;
|
||||
if (reg == 0 || next >= limit || limit - next > (1ull << 32)) return 0;
|
||||
const uint64_t last = next + ((limit - 1 - next) / line) * line; // largest next + 64k below limit
|
||||
constexpr DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
uint64_t done = 0;
|
||||
while (next <= last) {
|
||||
const uint64_t start = next & ~(line - 1);
|
||||
MEMORY_BASIC_INFORMATION page{};
|
||||
if (!VirtualQuery(reinterpret_cast<const void*>(start), &page, sizeof(page)) || page.State != MEM_COMMIT ||
|
||||
!(page.Protect & writable) || (page.Protect & PAGE_GUARD)) {
|
||||
break;
|
||||
}
|
||||
const uint64_t region_end = reinterpret_cast<uintptr_t>(page.BaseAddress) + page.RegionSize;
|
||||
uint64_t lines = (last - next) / line + 1;
|
||||
const uint64_t fit = (region_end - start) / line;
|
||||
if (fit == 0) break;
|
||||
if (lines > fit) lines = fit;
|
||||
std::memset(reinterpret_cast<void*>(start), 0, static_cast<size_t>(lines * line));
|
||||
context.Rax = next + (lines - 1) * line;
|
||||
next += lines * line;
|
||||
done += lines;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
|
||||
EXCEPTION_RECORD& exception) {
|
||||
switch (instruction.kind) {
|
||||
case kClzero:
|
||||
return zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax)
|
||||
: context.Rax, exception);
|
||||
case kClzero: {
|
||||
if (!zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax) : context.Rax,
|
||||
exception)) {
|
||||
return false;
|
||||
}
|
||||
if (!instruction.address32) {
|
||||
static std::atomic<uint64_t> batched{0};
|
||||
const uint64_t lines = clzero_loop_fast_path(context);
|
||||
if (lines && batched.fetch_add(1) == 0) {
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clzero_loop",
|
||||
"CLZERO loop (add rax,0x40; cmp; jb) completed in one trap; later loops are not logged");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case kMonitorx:
|
||||
// There is no host monitor state. MWAITX may complete immediately.
|
||||
return true;
|
||||
@@ -371,17 +429,10 @@ LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
|
||||
// breakpoints and assertion failures with their module offset. They are first-chance, so the
|
||||
// guest may still handle them; handling is left unchanged.
|
||||
void log_breakpoint(const EXCEPTION_RECORD& record) {
|
||||
// Past the cap the counter is not advanced again, so it cannot wrap around to 1.
|
||||
if (g_breakpoint_records.load(std::memory_order_relaxed) >= kMaxBreakpointRecords) {
|
||||
return;
|
||||
}
|
||||
const uint32_t index = g_breakpoint_records.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
if (index > kMaxBreakpointRecords) {
|
||||
return;
|
||||
}
|
||||
// The calls below can change the thread's last-error value; a resumed first-chance exception
|
||||
// must leave the guest's error state as it was.
|
||||
const DWORD last_error = GetLastError();
|
||||
const uintptr_t address = reinterpret_cast<uintptr_t>(record.ExceptionAddress);
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t module_base = 0;
|
||||
@@ -417,7 +468,6 @@ void log_breakpoint(const EXCEPTION_RECORD& record) {
|
||||
if (length > 0 && length < static_cast<int>(sizeof(line))) {
|
||||
write_log_line(line, static_cast<size_t>(length));
|
||||
}
|
||||
SetLastError(last_error);
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_AV_CONTEXT is set): the first access violations in an image
|
||||
@@ -433,104 +483,27 @@ bool readable_bytes(uintptr_t address, size_t size) {
|
||||
return address + size <= reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
|
||||
// A JSONL line built with bounded appends: an append that does not fit is dropped and marks the
|
||||
// line truncated, so the length never passes the buffer. Four bytes stay reserved for the closing
|
||||
// "\"}\n". Text from the environment or module names goes through add_escaped.
|
||||
class LineBuf {
|
||||
public:
|
||||
LineBuf(char* p, size_t cap) : p_(p), cap_(cap - 4) { p_[0] = '\0'; }
|
||||
void add(const char* fmt, ...) {
|
||||
if (truncated_) return;
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
const int n = std::vsnprintf(p_ + len_, cap_ - len_, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n < 0 || static_cast<size_t>(n) >= cap_ - len_) {
|
||||
p_[len_] = '\0'; // drop the partial append
|
||||
truncated_ = true;
|
||||
return;
|
||||
}
|
||||
len_ += static_cast<size_t>(n);
|
||||
}
|
||||
// JSON string escaping for " \ and control characters; other bytes (UTF-8) pass through.
|
||||
void add_escaped(const char* text, size_t max) {
|
||||
for (size_t i = 0; text[i] && i < max && !truncated_; ++i) {
|
||||
const unsigned char ch = static_cast<unsigned char>(text[i]);
|
||||
if (ch == '"' || ch == '\\') add("\\%c", ch);
|
||||
else if (ch < 0x20) add("\\u%04x", ch);
|
||||
else add("%c", ch);
|
||||
}
|
||||
}
|
||||
bool room(size_t n) const { return !truncated_ && cap_ - len_ > n; }
|
||||
// Closes the JSON string and object and writes the line.
|
||||
void finish() {
|
||||
std::memcpy(p_ + len_, "\"}\n", 4);
|
||||
write_log_line(p_, len_ + 3);
|
||||
}
|
||||
|
||||
private:
|
||||
char* p_;
|
||||
size_t cap_;
|
||||
size_t len_ = 0;
|
||||
bool truncated_ = false;
|
||||
};
|
||||
|
||||
// A module's file name (without the directory) in UTF-8, or "?" when it cannot be read.
|
||||
void module_name_utf8(uintptr_t base, char* out, size_t size) {
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD n = base ? GetModuleFileNameW(reinterpret_cast<HMODULE>(base), path, MAX_PATH) : 0;
|
||||
if (n == 0 || n >= MAX_PATH) {
|
||||
std::snprintf(out, size, "?");
|
||||
return;
|
||||
}
|
||||
const wchar_t* slash = std::wcsrchr(path, L'\\');
|
||||
const wchar_t* name = slash ? slash + 1 : path;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, out, static_cast<int>(size), nullptr, nullptr) == 0) {
|
||||
std::snprintf(out, size, "?");
|
||||
}
|
||||
}
|
||||
|
||||
// BX_VEH_AV_CONTEXT and BX_VEH_AV_ALL, read once when runtime_veh attaches. With the context
|
||||
// switch unset the access-violation path does nothing at all.
|
||||
char g_av_spec[512];
|
||||
bool g_av_context_on = false;
|
||||
bool g_av_all = false;
|
||||
|
||||
void read_av_switches() {
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_CONTEXT", g_av_spec, sizeof(g_av_spec));
|
||||
g_av_context_on = n > 0 && n < sizeof(g_av_spec);
|
||||
char v[4];
|
||||
const DWORD k = GetEnvironmentVariableA("BX_VEH_AV_ALL", v, sizeof(v));
|
||||
g_av_all = k > 0 && k < sizeof(v) && v[0] == '1';
|
||||
}
|
||||
|
||||
void log_av_context(const EXCEPTION_POINTERS& ep) {
|
||||
static std::atomic<uint32_t> logged{0};
|
||||
if (!g_av_context_on || logged.fetch_add(1) >= 16) return;
|
||||
char spec[512];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_CONTEXT", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec) || logged.fetch_add(1) >= 16) return;
|
||||
const CONTEXT& c = *ep.ContextRecord;
|
||||
char line[1600];
|
||||
LineBuf out(line, sizeof(line));
|
||||
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"av_context\","
|
||||
"\"detail\":\"rip=%llx fault=%llx rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx "
|
||||
"rsp=%llx r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)c.Rip,
|
||||
(unsigned long long)(ep.ExceptionRecord->NumberParameters >= 2 ? ep.ExceptionRecord->ExceptionInformation[1] : 0),
|
||||
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx,
|
||||
(unsigned long long)c.Rdx, (unsigned long long)c.Rsi, (unsigned long long)c.Rdi,
|
||||
(unsigned long long)c.Rbp, (unsigned long long)c.Rsp, (unsigned long long)c.R8,
|
||||
(unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
|
||||
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14,
|
||||
(unsigned long long)c.R15);
|
||||
// The comma-separated spec, scanned without shared state (several threads can fault at once).
|
||||
for (const char* cursor = g_av_spec; *cursor && out.room(220);) {
|
||||
const char* comma = std::strchr(cursor, ',');
|
||||
const size_t length = comma ? static_cast<size_t>(comma - cursor) : std::strlen(cursor);
|
||||
char item[64];
|
||||
const size_t take = length < sizeof(item) - 1 ? length : sizeof(item) - 1;
|
||||
std::memcpy(item, cursor, take);
|
||||
item[take] = '\0';
|
||||
cursor += length + (comma ? 1 : 0);
|
||||
int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"av_context\","
|
||||
"\"detail\":\"rip=%llx fault=%llx rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx "
|
||||
"rsp=%llx r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)c.Rip, (unsigned long long)ep.ExceptionRecord->ExceptionInformation[1],
|
||||
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx,
|
||||
(unsigned long long)c.Rdx, (unsigned long long)c.Rsi, (unsigned long long)c.Rdi,
|
||||
(unsigned long long)c.Rbp, (unsigned long long)c.Rsp, (unsigned long long)c.R8,
|
||||
(unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
|
||||
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14,
|
||||
(unsigned long long)c.R15);
|
||||
for (char* item = std::strtok(spec, ","); item && len > 0 && len < static_cast<int>(sizeof(line)) - 220;
|
||||
item = std::strtok(nullptr, ",")) {
|
||||
// "*A+O": dump at [A]+O. "**A+O1+O2": dump at [[A]+O1]+O2.
|
||||
const int derefs = item[0] == '*' ? (item[1] == '*' ? 2 : 1) : 0;
|
||||
char* rest = nullptr;
|
||||
@@ -542,41 +515,40 @@ void log_av_context(const EXCEPTION_POINTERS& ep) {
|
||||
ok = readable_bytes(address, 8);
|
||||
if (ok) address = *reinterpret_cast<const uintptr_t*>(address) + offsets[k];
|
||||
}
|
||||
out.add(" | ");
|
||||
out.add_escaped(item, sizeof(item));
|
||||
if (!ok) {
|
||||
out.add(" unresolved");
|
||||
continue;
|
||||
}
|
||||
if (!ok) continue;
|
||||
if (derefs == 0) address += offsets[0];
|
||||
out.add(" @%llx:", (unsigned long long)address);
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " | %s @%llx:", item, (unsigned long long)address);
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
if (VirtualQuery(reinterpret_cast<void*>(address), &mbi, sizeof(mbi))) {
|
||||
out.add(" [type=%lx prot=%lx alloc=%llx region=%llx+%llx]", static_cast<unsigned long>(mbi.Type),
|
||||
static_cast<unsigned long>(mbi.Protect), (unsigned long long)reinterpret_cast<uintptr_t>(mbi.AllocationBase),
|
||||
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.BaseAddress), (unsigned long long)mbi.RegionSize);
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " [type=%lx prot=%lx alloc=%llx region=%llx+%llx]",
|
||||
static_cast<unsigned long>(mbi.Type), static_cast<unsigned long>(mbi.Protect),
|
||||
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.AllocationBase),
|
||||
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.BaseAddress),
|
||||
(unsigned long long)mbi.RegionSize);
|
||||
}
|
||||
if (!readable_bytes(address, 64)) {
|
||||
out.add(" unreadable");
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " unreadable");
|
||||
continue;
|
||||
}
|
||||
const auto* q = reinterpret_cast<const uint64_t*>(address);
|
||||
for (int i = 0; i < 8; ++i) out.add(" %llx", (unsigned long long)q[i]);
|
||||
for (int i = 0; i < 8 && len < static_cast<int>(sizeof(line)) - 24; ++i) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %llx", (unsigned long long)q[i]);
|
||||
}
|
||||
}
|
||||
// The faulting thread's stack: up to eight frames, unwound from its context, as module+offset.
|
||||
out.add(" | stack:");
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line)) - 64) len += std::snprintf(line + len, sizeof(line) - len, " | stack:");
|
||||
CONTEXT walk = c;
|
||||
for (int i = 0; i < 8 && walk.Rip && out.room(64); ++i) {
|
||||
for (int i = 0; i < 8 && walk.Rip && len > 0 && len < static_cast<int>(sizeof(line)) - 64; ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(walk.Rip), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
char name[96] = "anon";
|
||||
if (base) module_name_utf8(base, name, sizeof(name));
|
||||
out.add(" ");
|
||||
out.add_escaped(name, 24);
|
||||
out.add("+%llx", (unsigned long long)(walk.Rip - base));
|
||||
char path[MAX_PATH] = "anon";
|
||||
if (base) GetModuleFileNameA(reinterpret_cast<HMODULE>(base), path, sizeof(path));
|
||||
const char* name = std::strrchr(path, '\\') ? std::strrchr(path, '\\') + 1 : path;
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %.24s+%llx", name,
|
||||
(unsigned long long)(walk.Rip - base));
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
|
||||
if (!fn) {
|
||||
@@ -589,24 +561,12 @@ void log_av_context(const EXCEPTION_POINTERS& ep) {
|
||||
DWORD64 frame = 0;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
out.finish();
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
}
|
||||
|
||||
// A diagnostic that had to stop (a protection change failed): logged once per kind.
|
||||
void log_disarmed(const char* what, uintptr_t address) {
|
||||
char line[256];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"diagnostic_disarmed\","
|
||||
"\"detail\":\"%s address=%llx error=%lu\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), what,
|
||||
(unsigned long long)address, GetLastError());
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
|
||||
// Set when runtime_veh detaches: helper threads stop at their next step and log nothing more.
|
||||
std::atomic<bool> g_diag_stop{false};
|
||||
std::atomic<int> g_diag_threads{0};
|
||||
|
||||
// Diagnostics (off unless BX_VEH_WATCH=ADDR:LEN, hex): a software write watch. A helper thread
|
||||
// makes the page holding [ADDR, ADDR+LEN) read-only as soon as that page is committed. Each
|
||||
// write fault in the page is allowed by restoring write access and single-stepping the writing
|
||||
@@ -638,7 +598,7 @@ bool resolve_watch(uintptr_t* out) {
|
||||
}
|
||||
|
||||
DWORD WINAPI watch_arm_thread(LPVOID) {
|
||||
for (int i = 0; i < 600000 && !g_watch_armed.load() && !g_diag_stop.load(); ++i) {
|
||||
for (int i = 0; i < 600000 && !g_watch_armed.load(); ++i) {
|
||||
uintptr_t begin = 0;
|
||||
DWORD old = 0;
|
||||
if (resolve_watch(&begin) && readable_bytes(begin, g_watch_length)) {
|
||||
@@ -657,11 +617,7 @@ DWORD WINAPI watch_arm_thread(LPVOID) {
|
||||
}
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
if (VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
|
||||
g_watch_armed = true;
|
||||
} else {
|
||||
log_disarmed("watch: could not protect the page", g_watch_page);
|
||||
}
|
||||
if (VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) g_watch_armed = true;
|
||||
break;
|
||||
}
|
||||
Sleep(1);
|
||||
@@ -679,11 +635,7 @@ void start_write_watch() {
|
||||
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) g_watch_offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
|
||||
if (rest && *rest == ':') g_watch_length = static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16));
|
||||
g_watch_tls = TlsAlloc();
|
||||
if (g_watch_tls == TLS_OUT_OF_INDEXES) return;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, watch_arm_thread, nullptr, 0, nullptr)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
if (HANDLE t = CreateThread(nullptr, 0, watch_arm_thread, nullptr, 0, nullptr)) CloseHandle(t);
|
||||
}
|
||||
|
||||
void log_watched_write(uintptr_t rip, uintptr_t address, uint64_t value) {
|
||||
@@ -711,12 +663,7 @@ bool handle_write_watch(PEXCEPTION_POINTERS ep) {
|
||||
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
|
||||
if ((address & ~static_cast<uintptr_t>(4095)) != g_watch_page) return false;
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old)) {
|
||||
// Fail open: the write cannot be allowed, so the guest gets its access violation.
|
||||
g_watch_armed = false;
|
||||
log_disarmed("watch: could not unprotect the page", g_watch_page);
|
||||
return false;
|
||||
}
|
||||
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old);
|
||||
// Remember the write for the single-step that follows it (+1 so 0 means "none").
|
||||
TlsSetValue(g_watch_tls, reinterpret_cast<void*>(address + 1));
|
||||
ep->ContextRecord->EFlags |= 0x100;
|
||||
@@ -733,9 +680,7 @@ bool handle_write_watch(PEXCEPTION_POINTERS ep) {
|
||||
*reinterpret_cast<const uint64_t*>(slot));
|
||||
}
|
||||
DWORD old = 0;
|
||||
if (!g_watch_armed.load() || !VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
|
||||
if (g_watch_armed.exchange(false)) log_disarmed("watch: could not re-protect the page", g_watch_page);
|
||||
}
|
||||
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -770,7 +715,6 @@ uintptr_t g_rw_root = 0, g_rw_offset = 0, g_rw_length = 0;
|
||||
DWORD WINAPI range_watch_thread(LPVOID) {
|
||||
if (g_rw_root) {
|
||||
for (int i = 0; i < 600000; ++i) {
|
||||
if (g_diag_stop.load()) return 0;
|
||||
if (readable_bytes(g_rw_root, 8) && *reinterpret_cast<const uintptr_t*>(g_rw_root)) break;
|
||||
Sleep(1);
|
||||
}
|
||||
@@ -787,7 +731,7 @@ DWORD WINAPI range_watch_thread(LPVOID) {
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
const size_t pages = (g_rw_end - g_rw_begin) / 4096;
|
||||
for (int round = 0; round < 600000 && g_rw_on.load() && !g_diag_stop.load(); ++round) {
|
||||
for (int round = 0; round < 600000 && g_rw_on.load(); ++round) {
|
||||
bool all = true;
|
||||
for (size_t i = 0; i < pages && g_rw_on.load(); ++i) {
|
||||
if (g_rw_armed[i].load()) continue;
|
||||
@@ -829,10 +773,7 @@ void start_range_watch() {
|
||||
g_rw_end = (g_rw_begin + length + 4095) & ~static_cast<uintptr_t>(4095);
|
||||
}
|
||||
g_rw_on = true;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, range_watch_thread, nullptr, 0, nullptr)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
if (HANDLE t = CreateThread(nullptr, 0, range_watch_thread, nullptr, 0, nullptr)) CloseHandle(t);
|
||||
}
|
||||
|
||||
void log_range_write(const CONTEXT& c, uintptr_t address) {
|
||||
@@ -885,11 +826,7 @@ bool handle_range_watch(PEXCEPTION_POINTERS ep) {
|
||||
const size_t index = (address - g_rw_begin) / 4096;
|
||||
if (!g_rw_armed[index].load()) return false;
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READWRITE, &old)) {
|
||||
g_rw_armed[index] = 0; // fail open: the guest gets its access violation
|
||||
log_disarmed("range watch: could not unprotect a page", g_rw_begin + index * 4096);
|
||||
return false;
|
||||
}
|
||||
VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READWRITE, &old);
|
||||
TlsSetValue(g_rw_tls, reinterpret_cast<void*>(address + 1));
|
||||
ep->ContextRecord->EFlags |= 0x100;
|
||||
return true;
|
||||
@@ -912,11 +849,7 @@ bool handle_range_watch(PEXCEPTION_POINTERS ep) {
|
||||
} else if (g_rw_on.load()) {
|
||||
DWORD old = 0;
|
||||
const size_t index = (address - g_rw_begin) / 4096;
|
||||
if (g_rw_armed[index].load() &&
|
||||
!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READONLY, &old)) {
|
||||
g_rw_armed[index] = 0;
|
||||
log_disarmed("range watch: could not re-protect a page", g_rw_begin + index * 4096);
|
||||
}
|
||||
if (g_rw_armed[index].load()) VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READONLY, &old);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -937,16 +870,12 @@ CodeHit g_code_hits[8];
|
||||
int g_code_hit_count = 0;
|
||||
DWORD g_code_hit_tls = TLS_OUT_OF_INDEXES;
|
||||
|
||||
// False when the byte could not be written. A failure to restore the page's original protection
|
||||
// is logged: the page then stays writable, which the log record makes visible.
|
||||
bool write_code_byte(uintptr_t address, uint8_t value) {
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, PAGE_EXECUTE_READWRITE, &old)) return false;
|
||||
*reinterpret_cast<volatile uint8_t*>(address) = value;
|
||||
DWORD unused = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, old, &unused)) {
|
||||
log_disarmed("code hit: could not restore the page protection", address);
|
||||
}
|
||||
VirtualProtect(reinterpret_cast<void*>(address), 1, old, &unused);
|
||||
FlushInstructionCache(GetCurrentProcess(), reinterpret_cast<void*>(address), 1);
|
||||
return true;
|
||||
}
|
||||
@@ -1006,30 +935,32 @@ void sample_thread(DWORD tid) {
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
char line[760];
|
||||
LineBuf out(line, sizeof(line));
|
||||
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"sample\",\"detail\":\"thread=%lu",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), tid);
|
||||
for (int i = 0; i < count && out.room(64); ++i) {
|
||||
int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"sample\",\"detail\":\"thread=%lu",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), tid);
|
||||
for (int i = 0; i < count && len < static_cast<int>(sizeof(line)) - 64; ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
// The thread runs again, so the loader lock taken by GetModuleFileNameW cannot be held by it.
|
||||
char name[96] = "anon";
|
||||
if (base) module_name_utf8(base, name, sizeof(name));
|
||||
out.add(" ");
|
||||
out.add_escaped(name, 24);
|
||||
out.add("+%llx", (unsigned long long)(frames[i] - base));
|
||||
// The thread runs again, so the loader lock taken by GetModuleFileNameA cannot be held by it.
|
||||
char path[MAX_PATH] = "?";
|
||||
if (base) GetModuleFileNameA(reinterpret_cast<HMODULE>(base), path, sizeof(path));
|
||||
const char* name = std::strrchr(path, '\\') ? std::strrchr(path, '\\') + 1 : path;
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %.24s+%llx", base ? name : "anon",
|
||||
(unsigned long long)(frames[i] - base));
|
||||
}
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
if (!g_diag_stop.load()) out.finish();
|
||||
}
|
||||
|
||||
DWORD WINAPI sampler_main(LPVOID) {
|
||||
const DWORD pid = GetCurrentProcessId();
|
||||
for (int logged = 0; logged < 20000 && !g_diag_stop.load();) {
|
||||
for (int logged = 0; logged < 20000;) {
|
||||
Sleep(g_sample_interval);
|
||||
if (g_diag_stop.load()) break;
|
||||
DWORD tids[256];
|
||||
int n = 0;
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
@@ -1051,10 +982,7 @@ void start_sampler() {
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_sample_interval = static_cast<DWORD>(std::strtoul(spec, nullptr, 10));
|
||||
if (g_sample_interval == 0) return;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, sampler_main, nullptr, 0, &g_sample_self)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
if (HANDLE t = CreateThread(nullptr, 0, sampler_main, nullptr, 0, &g_sample_self)) CloseHandle(t);
|
||||
}
|
||||
|
||||
void start_code_hits() {
|
||||
@@ -1063,11 +991,8 @@ void start_code_hits() {
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_code_hit_tls = TlsAlloc();
|
||||
if (g_code_hit_tls == TLS_OUT_OF_INDEXES) return;
|
||||
for (const char* item = spec; *item && g_code_hit_count < 8;) {
|
||||
char* end = nullptr;
|
||||
const uintptr_t address = static_cast<uintptr_t>(std::strtoull(item, &end, 16));
|
||||
const char* comma = std::strchr(item, ',');
|
||||
item = comma ? comma + 1 : item + std::strlen(item);
|
||||
for (char* item = std::strtok(spec, ","); item && g_code_hit_count < 8; item = std::strtok(nullptr, ",")) {
|
||||
const uintptr_t address = static_cast<uintptr_t>(std::strtoull(item, nullptr, 16));
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!address || !VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) ||
|
||||
region.Type != MEM_IMAGE || region.State != MEM_COMMIT) {
|
||||
@@ -1161,13 +1086,7 @@ bool handle_code_hit(PEXCEPTION_POINTERS ep) {
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
if (count <= 16 || count % 256 == 0 || (every && count <= 20000)) log_code_hit(hit, count, c);
|
||||
if (!write_code_byte(hit.address, hit.original)) {
|
||||
// The original instruction cannot be put back: stop handling this address and let
|
||||
// the breakpoint reach the guest instead of looping on it.
|
||||
log_disarmed("code hit: could not restore the original byte", hit.address);
|
||||
hit.address = 0;
|
||||
return false;
|
||||
}
|
||||
write_code_byte(hit.address, hit.original);
|
||||
c.Rip = hit.address;
|
||||
c.EFlags |= 0x100;
|
||||
TlsSetValue(g_code_hit_tls, reinterpret_cast<void*>(static_cast<uintptr_t>(i + 1)));
|
||||
@@ -1179,42 +1098,56 @@ bool handle_code_hit(PEXCEPTION_POINTERS ep) {
|
||||
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_code_hit_tls));
|
||||
if (!pending) return false;
|
||||
TlsSetValue(g_code_hit_tls, nullptr);
|
||||
CodeHit& hit = g_code_hits[pending - 1];
|
||||
if (hit.address && !g_diag_stop.load() && !write_code_byte(hit.address, 0xCC)) {
|
||||
log_disarmed("code hit: could not re-insert the breakpoint", hit.address);
|
||||
hit.address = 0;
|
||||
}
|
||||
write_code_byte(g_code_hits[pending - 1].address, 0xCC);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Restores every page and code byte the diagnostics changed (used at detach).
|
||||
void disarm_diagnostics() {
|
||||
if (g_watch_armed.exchange(false)) {
|
||||
DWORD old = 0;
|
||||
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old);
|
||||
// A title remaps the pages of its streaming windows while DirectStorage requests are writing
|
||||
// into them. The console changes a mapping atomically; xmem replaces a view by unmapping and
|
||||
// mapping, so a BetterXen storage worker can touch a page inside that gap. A fault taken by code
|
||||
// in XCRDAPI.dll on memory that is not mapped is therefore retried: the thread sleeps and the
|
||||
// instruction runs again, for up to about two seconds per faulting page, after which the fault
|
||||
// is passed on as before. The first retry and every abandoned one are logged.
|
||||
bool retry_storage_fault(PEXCEPTION_POINTERS ep) {
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
if (r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r.NumberParameters < 2) return false;
|
||||
static const HMODULE storage = GetModuleHandleA("XCRDAPI.dll");
|
||||
if (!storage) return false;
|
||||
MEMORY_BASIC_INFORMATION code{};
|
||||
if (!VirtualQuery(r.ExceptionAddress, &code, sizeof(code)) || code.AllocationBase != storage) return false;
|
||||
constexpr int kMaxRetries = 400; // x 5 ms
|
||||
thread_local uintptr_t page = 0;
|
||||
thread_local int retries = 0;
|
||||
const uintptr_t fault_page = static_cast<uintptr_t>(r.ExceptionInformation[1]) & ~uintptr_t{0xFFFF};
|
||||
if (fault_page != page) {
|
||||
page = fault_page;
|
||||
retries = 0;
|
||||
}
|
||||
if (g_rw_on.load() || g_rw_begin) range_watch_stop();
|
||||
for (int i = 0; i < g_code_hit_count; ++i) {
|
||||
CodeHit& hit = g_code_hits[i];
|
||||
if (hit.address && *reinterpret_cast<const volatile uint8_t*>(hit.address) == 0xCC) {
|
||||
write_code_byte(hit.address, hit.original);
|
||||
}
|
||||
hit.address = 0;
|
||||
static std::atomic<uint32_t> logged{0};
|
||||
if (++retries > kMaxRetries) {
|
||||
bx_log_emit(BX_LOG_ERROR, "runtime_veh", "storage_fault_retry",
|
||||
"a storage write faulted on unmapped memory for 2 s; the fault is passed on");
|
||||
retries = 0;
|
||||
return false;
|
||||
}
|
||||
for (DWORD* tls : {&g_watch_tls, &g_rw_tls, &g_code_hit_tls}) {
|
||||
if (*tls != TLS_OUT_OF_INDEXES) {
|
||||
TlsFree(*tls);
|
||||
*tls = TLS_OUT_OF_INDEXES;
|
||||
}
|
||||
if (retries == 1 && logged.fetch_add(1) < 16) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "storage code faulted at 0x%llx (%s); retrying while the page is remapped",
|
||||
static_cast<unsigned long long>(r.ExceptionInformation[1]),
|
||||
r.ExceptionInformation[0] == 1 ? "write" : "read");
|
||||
bx_log_emit(BX_LOG_WARN, "runtime_veh", "storage_fault_retry", detail);
|
||||
}
|
||||
Sleep(5);
|
||||
return true;
|
||||
}
|
||||
|
||||
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (retry_storage_fault(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (handle_code_hit(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (handle_range_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (handle_write_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
@@ -1224,9 +1157,13 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (code == EXCEPTION_ACCESS_VIOLATION) {
|
||||
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, ®ion, sizeof(region)) && region.Type == MEM_IMAGE)) {
|
||||
static const bool all = [] {
|
||||
char v[4];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_ALL", v, sizeof(v));
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
if (all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, ®ion, sizeof(region)) && region.Type == MEM_IMAGE)) {
|
||||
log_av_context(*ep);
|
||||
}
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
@@ -1353,9 +1290,6 @@ int bx_veh_install(void) {
|
||||
if (!g_veh_handle) {
|
||||
g_veh_handle = AddVectoredExceptionHandler(1, bx_veh_handler);
|
||||
if (g_veh_handle) {
|
||||
read_av_switches();
|
||||
// The helper threads below start running only after the loader lock is released; nothing
|
||||
// here waits for them. They check g_diag_stop and stop at detach.
|
||||
start_write_watch();
|
||||
start_code_hits();
|
||||
start_sampler();
|
||||
@@ -1385,23 +1319,15 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
|
||||
if (current_filter != log_unhandled_exception) {
|
||||
SetUnhandledExceptionFilter(current_filter);
|
||||
}
|
||||
// Stop the diagnostics and take them out of the guest's memory: restore watched pages and
|
||||
// original code bytes. Nothing waits for the helper threads (that would deadlock on the
|
||||
// loader lock); they stop at their next step.
|
||||
g_diag_stop = true;
|
||||
disarm_diagnostics();
|
||||
if (g_veh_handle) {
|
||||
RemoveVectoredExceptionHandler(g_veh_handle);
|
||||
g_veh_handle = nullptr;
|
||||
}
|
||||
// A helper thread may still be inside write_log_line when this runs. While any helper was
|
||||
// started, the log handle and its lock are left alive (the process is ending, or the DLL is
|
||||
// being unloaded with threads that only touch them); otherwise they are released.
|
||||
if (g_diag_threads.load() == 0 && g_log_handle != INVALID_HANDLE_VALUE) {
|
||||
if (g_log_handle != INVALID_HANDLE_VALUE) {
|
||||
CloseHandle(g_log_handle);
|
||||
g_log_handle = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
if (g_diag_threads.load() == 0 && g_log_lock_ready) {
|
||||
if (g_log_lock_ready) {
|
||||
DeleteCriticalSection(&g_log_lock);
|
||||
g_log_lock_ready = false;
|
||||
}
|
||||
|
||||
@@ -504,12 +504,9 @@ CopyResult fulfill_request(HANDLE file, const Request& request) {
|
||||
}
|
||||
|
||||
// Each queue is drained serially, in FIFO order, by a single threadpool work item.
|
||||
// A `blocking` queue makes a full enqueue wait for a free slot instead of failing
|
||||
// with ERROR_BUSY. A non-zero `auto_submit` submits once that many entries are
|
||||
// waiting, and a full queue submits what is pending before it waits. With
|
||||
// `auto_submit` 0 (Xbox DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled) nothing runs
|
||||
// before Submit: a full queue stalls the enqueuer until Submit is called on
|
||||
// another thread and the drain frees a slot. The public DirectStorage queues use
|
||||
// A `blocking` queue makes a full enqueue wait for a free slot (submitting what is
|
||||
// pending first) instead of failing with ERROR_BUSY. A non-zero `auto_submit`
|
||||
// submits once that many entries are waiting. The public DirectStorage queues use
|
||||
// both; the BetterXen synthetic queues use neither.
|
||||
class WorkQueue final : public Object<Queue, queue_iid> {
|
||||
public:
|
||||
@@ -678,7 +675,7 @@ private:
|
||||
if (closed_) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
|
||||
if (size_ < capacity_) return S_OK;
|
||||
if (!blocking_) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
if (auto_submit_ && submitted_ < size_) submit();
|
||||
if (submitted_ < size_) submit();
|
||||
SleepConditionVariableSRW(&space_, &mutex_, INFINITE, 0);
|
||||
}
|
||||
}
|
||||
|
||||
+19
-63
@@ -13,10 +13,8 @@
|
||||
*
|
||||
* The one exception is an explicit request for XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S on a 2D
|
||||
* texture that fits in one 64 KiB tile (one mip, one slice, 4-, 8- or 16-byte elements): that
|
||||
* gets the RDNA 2 SW_64KB_S addresses (see Sw64kbS). Any other explicit swizzle mode, and
|
||||
* SW_64KB_S on a texture larger than one tile, is laid out linearly, reported as LINEAR
|
||||
* (SwizzleMode 0) and logged once per mode: titles do not check XGCreateTextureComputer for a
|
||||
* mode they request, so refusing it crashed one.
|
||||
* gets the RDNA 2 SW_64KB_S addresses (see Sw64kbS). Any other explicit swizzle mode is refused
|
||||
* with E_NOTIMPL and logged rather than silently laid out linearly.
|
||||
*/
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
@@ -56,7 +54,7 @@ enum : uint32_t { kPlaneUnused = 0, kPlaneDefault = 1, kPlaneDepth = 7, kPlaneSt
|
||||
// the public D3D12 standard-swizzle xBytesMask 0xAA8F without its two intra-texel bits, and the y
|
||||
// mask equals D3D12's 0x5570. Each row is a bijection over its tile. How tiles are ordered across a
|
||||
// larger surface is not established from public sources, so only surfaces that fit in one tile
|
||||
// are addressed; larger ones fall back to the logged linear layout.
|
||||
// are addressed; larger ones are refused and logged.
|
||||
struct Sw64kbS {
|
||||
uint32_t bytes;
|
||||
uint32_t x_mask;
|
||||
@@ -357,56 +355,30 @@ public:
|
||||
// smaller rest are packed into a mip tail per array slice, as on the console, whose titles
|
||||
// expect few standard mips. Tiles are numbered over the subresources in order (mip-major
|
||||
// within a slice), each slice's packed tail after its standard mips.
|
||||
// 3D resources use the D3D12 standard 3D tile shapes (64x32x32 one-byte elements down to
|
||||
// 16x16x16 sixteen-byte ones), 1D textures a 64 KiB row of elements, buffers 64 KiB.
|
||||
const uint32_t bpe = layout_.Plane[0].BytesPerElement;
|
||||
const bool volume = layout_.Dimension == kDimTexture3D;
|
||||
uint32_t tile_w = 128, tile_h = 128, tile_d = 1;
|
||||
if (layout_.Dimension == kDimBuffer) {
|
||||
tile_w = 65536;
|
||||
tile_h = 1;
|
||||
} else if (layout_.Dimension == kDimTexture1D) {
|
||||
tile_w = 65536 / (bpe ? bpe : 1) * block_;
|
||||
tile_h = 1;
|
||||
} else if (volume) {
|
||||
switch (bpe) {
|
||||
case 1: tile_w = 64; tile_h = 32; tile_d = 32; break;
|
||||
case 2: tile_w = 32; tile_h = 32; tile_d = 32; break;
|
||||
case 4: tile_w = 32; tile_h = 32; tile_d = 16; break;
|
||||
case 8: tile_w = 32; tile_h = 16; tile_d = 16; break;
|
||||
case 16: tile_w = 16; tile_h = 16; tile_d = 16; break;
|
||||
default: tile_w = 32; tile_h = 32; tile_d = 16; break;
|
||||
}
|
||||
tile_w *= block_;
|
||||
tile_h *= block_;
|
||||
} else {
|
||||
switch (bpe) {
|
||||
case 1: tile_w = 256; tile_h = 256; break;
|
||||
case 2: tile_w = 256; tile_h = 128; break;
|
||||
case 4: tile_w = 128; tile_h = 128; break;
|
||||
case 8: tile_w = 128; tile_h = 64; break;
|
||||
case 16: tile_w = 64; tile_h = 64; break;
|
||||
default: break;
|
||||
}
|
||||
tile_w *= block_;
|
||||
tile_h *= block_;
|
||||
uint32_t tile_w = 128, tile_h = 128;
|
||||
switch (bpe) {
|
||||
case 1: tile_w = 256; tile_h = 256; break;
|
||||
case 2: tile_w = 256; tile_h = 128; break;
|
||||
case 4: tile_w = 128; tile_h = 128; break;
|
||||
case 8: tile_w = 128; tile_h = 64; break;
|
||||
case 16: tile_w = 64; tile_h = 64; break;
|
||||
default: break;
|
||||
}
|
||||
auto depth_of = [&](UINT32 m) { return volume ? layout_.Plane[0].MipLayout[m].DepthOrArraySize : 1u; };
|
||||
tile_w *= block_;
|
||||
tile_h *= block_;
|
||||
const UINT32 mips = layout_.MipLevels;
|
||||
UINT32 standard = 0;
|
||||
while (standard < mips && layout_.Plane[0].MipLayout[standard].WidthPixels >= tile_w &&
|
||||
layout_.Plane[0].MipLayout[standard].HeightPixels >= tile_h && depth_of(standard) >= tile_d) {
|
||||
layout_.Plane[0].MipLayout[standard].HeightPixels >= tile_h) {
|
||||
++standard;
|
||||
}
|
||||
uint64_t tail_bytes = 0;
|
||||
for (UINT32 m = standard; m < mips; ++m) {
|
||||
tail_bytes += volume ? layout_.Plane[0].MipLayout[m].SizeBytes : layout_.Plane[0].MipLayout[m].Slice2DSizeBytes;
|
||||
}
|
||||
for (UINT32 m = standard; m < mips; ++m) tail_bytes += layout_.Plane[0].MipLayout[m].Slice2DSizeBytes;
|
||||
const UINT32 tail_tiles = standard < mips ? static_cast<UINT32>((tail_bytes + kResourceAlign - 1) / kResourceAlign) : 0;
|
||||
auto tiles_of = [&](UINT32 m) {
|
||||
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
|
||||
return ((l.WidthPixels + tile_w - 1) / tile_w) * ((l.HeightPixels + tile_h - 1) / tile_h) *
|
||||
((depth_of(m) + tile_d - 1) / tile_d);
|
||||
return ((l.WidthPixels + tile_w - 1) / tile_w) * ((l.HeightPixels + tile_h - 1) / tile_h);
|
||||
};
|
||||
UINT32 per_slice = tail_tiles;
|
||||
for (UINT32 m = 0; m < standard; ++m) per_slice += tiles_of(m);
|
||||
@@ -417,7 +389,7 @@ public:
|
||||
*packed = {static_cast<UINT8>(standard), static_cast<UINT8>(mips - standard), tail_tiles,
|
||||
standard < mips ? standard_tiles : 0};
|
||||
}
|
||||
if (shape) *shape = {tile_w, tile_h, tile_d};
|
||||
if (shape) *shape = {tile_w, tile_h, 1};
|
||||
if (count) {
|
||||
const UINT32 total = mips * slices_;
|
||||
UINT32 written = 0;
|
||||
@@ -431,8 +403,7 @@ public:
|
||||
for (UINT32 k = 0; k < m; ++k) start += tiles_of(k);
|
||||
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
|
||||
tilings[written] = {(l.WidthPixels + tile_w - 1) / tile_w,
|
||||
static_cast<UINT16>((l.HeightPixels + tile_h - 1) / tile_h),
|
||||
static_cast<UINT16>((depth_of(m) + tile_d - 1) / tile_d), start};
|
||||
static_cast<UINT16>((l.HeightPixels + tile_h - 1) / tile_h), 1, start};
|
||||
}
|
||||
*count = written;
|
||||
}
|
||||
@@ -462,7 +433,7 @@ private:
|
||||
const XgPlaneLayout& p = layout_.Plane[plane];
|
||||
const XgMipLevelLayout& m = p.MipLayout[mip];
|
||||
const bool volume = layout_.Dimension == kDimTexture3D;
|
||||
if (slice >= slices_) return E_INVALIDARG; // slices_ is 1 for a volume: its subresources are its mips
|
||||
if (!volume && slice >= slices_) return E_INVALIDARG;
|
||||
const UINT32 depth = volume ? m.DepthOrArraySize : 1;
|
||||
if (swizzled_) { // one 2D tile, one mip, one slice: element by element
|
||||
if (subresource != 0) return E_INVALIDARG;
|
||||
@@ -510,21 +481,6 @@ HRESULT LayoutComputer::create(const XgResourceDesc& d, XGTextureAddressComputer
|
||||
log_rejected(&d, "invalid description");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// The public D3D12 resource limits (D3D12_REQ_TEXTURE1D/2D_U_DIMENSION 16384,
|
||||
// D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION 2048, D3D12_REQ_TEXTURE1D/2D_ARRAY_AXIS_DIMENSION
|
||||
// 2048). Within them every pitch fits 32 bits and no size computation overflows. A buffer
|
||||
// only needs its 64 KiB-aligned size to fit 64 bits.
|
||||
{
|
||||
const bool volume = d.Dimension == kDimTexture3D;
|
||||
const uint64_t max_xy = volume ? 2048 : 16384;
|
||||
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : d.Height;
|
||||
const bool too_big = buffer ? d.Width > UINT64_MAX - kResourceAlign
|
||||
: d.Width > max_xy || height > max_xy || d.DepthOrArraySize > 2048;
|
||||
if (too_big) {
|
||||
log_rejected(&d, "dimension past the D3D12 resource limits");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
auto* c = new (std::nothrow) LayoutComputer();
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
XgResourceLayout& L = c->layout_;
|
||||
|
||||
@@ -37,6 +37,9 @@ HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLB
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
|
||||
void (CALLBACK*)(void*, bool));
|
||||
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
|
||||
HRESULT WINAPI bx_xtq_duplicate_handle(void*, void**);
|
||||
HRESULT WINAPI bx_xtq_get_port(void*, bx::gdk::Port, void**);
|
||||
HRESULT WINAPI bx_xtq_create_composite(void*, void*, void**);
|
||||
|
||||
HRESULT WINAPI XAsyncGetStatus(void*, bool);
|
||||
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
|
||||
@@ -45,6 +48,8 @@ void WINAPI XAsyncCancel(void*);
|
||||
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
|
||||
HRESULT WINAPI XUserAddResult(void*, void**);
|
||||
void WINAPI XUserCloseHandle(void*);
|
||||
HRESULT WINAPI bx_xuser_duplicate_handle(void*, void**);
|
||||
bool WINAPI bx_xuser_is_handle(void*);
|
||||
HRESULT WINAPI XUserGetId(void*, uint64_t*);
|
||||
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
|
||||
@@ -176,6 +181,32 @@ HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
|
||||
void WINAPI core_async_cancel(void*, void* async) {
|
||||
XAsyncCancel(async);
|
||||
}
|
||||
// XAsyncRun: the title's work callback runs on the block's work port and its return value
|
||||
// completes the block (no result payload).
|
||||
struct AsyncRunOp final : bx::gdk::AsyncOp {
|
||||
using Work = HRESULT (CALLBACK*)(void*);
|
||||
Work work;
|
||||
void* block;
|
||||
AsyncRunOp(Work work, void* block) : work(work), block(block) {}
|
||||
uint32_t kind() const override { return 0x4E5552u; } // "RUN"
|
||||
HRESULT execute() override { return work(block); }
|
||||
size_t result_size() const override { return 0; }
|
||||
};
|
||||
HRESULT WINAPI core_async_run(void*, void* async, AsyncRunOp::Work work) {
|
||||
if (!async || !work) return E_INVALIDARG;
|
||||
auto op = std::unique_ptr<bx::gdk::AsyncOp>(new (std::nothrow) AsyncRunOp(work, async));
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
return bx::gdk::begin_async_op(async, std::move(op));
|
||||
}
|
||||
HRESULT WINAPI core_tq_create_composite(void*, void* work_port, void* completion_port, void** out) {
|
||||
return bx_xtq_create_composite(work_port, completion_port, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_get_port(void*, void* queue, Port port, void** out) {
|
||||
return bx_xtq_get_port(queue, port, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_duplicate(void*, void* queue, void** out) {
|
||||
return bx_xtq_duplicate_handle(queue, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
|
||||
return XTaskQueueCreate(work, comp, out);
|
||||
}
|
||||
@@ -220,7 +251,11 @@ const std::array<const void*, 36> kCoreVtbl = [] {
|
||||
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
|
||||
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
|
||||
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
|
||||
v[6] = reinterpret_cast<const void*>(&core_async_run);
|
||||
v[12] = reinterpret_cast<const void*>(&core_tq_create);
|
||||
v[13] = reinterpret_cast<const void*>(&core_tq_create_composite);
|
||||
v[14] = reinterpret_cast<const void*>(&core_tq_get_port);
|
||||
v[15] = reinterpret_cast<const void*>(&core_tq_duplicate);
|
||||
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
|
||||
v[17] = reinterpret_cast<const void*>(&core_tq_close);
|
||||
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
|
||||
@@ -433,8 +468,16 @@ std::unordered_set<uint64_t> user_event_tokens;
|
||||
void WINAPI user_close_handle(void*, void* h) {
|
||||
XUserCloseHandle(h);
|
||||
}
|
||||
HRESULT WINAPI user_duplicate_handle(void*, void* user, void** out) {
|
||||
const HRESULT hr = bx_xuser_duplicate_handle(user, out);
|
||||
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "xgameruntime", "XUserDuplicateHandle",
|
||||
SUCCEEDED(hr) ? "duplicate handle for the offline user" : "invalid user handle");
|
||||
return hr;
|
||||
}
|
||||
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
|
||||
if (u1 == u2) return 0;
|
||||
// One offline user: every valid handle (duplicates included) names the same user.
|
||||
if (bx_xuser_is_handle(u1) && bx_xuser_is_handle(u2)) return 0;
|
||||
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
|
||||
}
|
||||
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
|
||||
@@ -517,6 +560,7 @@ HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, ch
|
||||
|
||||
const std::array<const void*, 64> kUserVtbl = [] {
|
||||
auto v = make_default_vtbl<64>();
|
||||
v[3] = reinterpret_cast<const void*>(&user_duplicate_handle);
|
||||
v[4] = reinterpret_cast<const void*>(&user_close_handle);
|
||||
v[5] = reinterpret_cast<const void*>(&user_compare);
|
||||
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
|
||||
@@ -742,8 +786,6 @@ BX_HR(gs_quota_result, "IXGameSaveImpl", 9, "XGameSaveGetRemainingQuotaResult")
|
||||
BX_HR(gs_delete, "IXGameSaveImpl", 10, "XGameSaveDeleteContainer")
|
||||
BX_HR(gs_delete_async, "IXGameSaveImpl", 11, "XGameSaveDeleteContainerAsync")
|
||||
BX_HR(gs_delete_result, "IXGameSaveImpl", 12, "XGameSaveDeleteContainerResult")
|
||||
BX_HR(gs_container_info, "IXGameSaveImpl", 13, "XGameSaveGetContainerInfo")
|
||||
BX_HR(gs_enum_by_name, "IXGameSaveImpl", 15, "XGameSaveEnumerateContainerInfoByName")
|
||||
BX_HR(gs_enum_blobs, "IXGameSaveImpl", 18, "XGameSaveEnumerateBlobInfo")
|
||||
BX_HR(gs_enum_blobs_by_name, "IXGameSaveImpl", 19, "XGameSaveEnumerateBlobInfoByName")
|
||||
BX_HR(gs_blob_delete, "IXGameSaveImpl", 26, "XGameSaveSubmitBlobDelete")
|
||||
@@ -776,6 +818,68 @@ BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalle
|
||||
#undef BX_VOID
|
||||
#undef BX_BOOL
|
||||
|
||||
// Installation monitors (documented XPackage installation-monitor functions). The running
|
||||
// package is fully present on local storage, so a monitor always reports it installed,
|
||||
// launchable and complete; progress never changes, so a registered callback is never called.
|
||||
struct XPackageInstallationProgress {
|
||||
uint64_t totalBytes;
|
||||
uint64_t installedBytes;
|
||||
uint64_t launchBytes;
|
||||
bool launchable;
|
||||
bool completed;
|
||||
};
|
||||
struct InstallationMonitor {
|
||||
uint32_t magic;
|
||||
};
|
||||
constexpr uint32_t kMonitorMagic = 0x4D505842u; // "BXPM"
|
||||
|
||||
HRESULT WINAPI pk_create_monitor(void*, const char* package, uint32_t, const void*, uint32_t, void*, void** monitor) {
|
||||
if (!monitor) return E_INVALIDARG;
|
||||
auto* m = new (std::nothrow) InstallationMonitor{kMonitorMagic};
|
||||
if (!m) return E_OUTOFMEMORY;
|
||||
*monitor = m;
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageCreateInstallationMonitor",
|
||||
package ? "monitor for the running package: reported fully installed" : "monitor: reported fully installed");
|
||||
return S_OK;
|
||||
}
|
||||
void WINAPI pk_close_monitor(void*, void* monitor) {
|
||||
auto* m = static_cast<InstallationMonitor*>(monitor);
|
||||
if (m && m->magic == kMonitorMagic) {
|
||||
m->magic = 0;
|
||||
delete m;
|
||||
}
|
||||
}
|
||||
void WINAPI pk_get_progress(void*, void*, XPackageInstallationProgress* progress) {
|
||||
if (!progress) return;
|
||||
*progress = {1, 1, 1, true, true};
|
||||
}
|
||||
bool WINAPI pk_update_monitor(void*, void*) { return false; } // nothing changed
|
||||
HRESULT WINAPI pk_reg_progress(void*, void*, void*, void* callback, uint64_t* token) {
|
||||
if (!callback || !token) return E_INVALIDARG;
|
||||
*token = 1;
|
||||
return S_OK;
|
||||
}
|
||||
bool WINAPI pk_unreg_progress(void*, void*, uint64_t, bool) { return true; }
|
||||
|
||||
// XPackageEnumeratePackages(kind, scope, context, callback): offline, no other package
|
||||
// (content or related game) is installed, so the callback is never called.
|
||||
HRESULT enumerate_packages(uint32_t kind, uint32_t scope, void* callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: no other packages installed (offline)", kind, scope);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI pk_enum_packages(void*, uint32_t kind, uint32_t scope, void*, void* callback) {
|
||||
return enumerate_packages(kind, scope, callback);
|
||||
}
|
||||
HRESULT WINAPI pk_enum_packages_2(void*, uint32_t kind, uint32_t scope, void*, void* callback) {
|
||||
return enumerate_packages(kind, scope, callback);
|
||||
}
|
||||
HRESULT WINAPI pk_enum_packages_3(void*, uint32_t kind, uint32_t scope, void*, void* callback) {
|
||||
return enumerate_packages(kind, scope, callback);
|
||||
}
|
||||
|
||||
const std::array<const void*, 33> kGameSaveVtbl = [] {
|
||||
auto v = make_default_vtbl<33>();
|
||||
v[0] = reinterpret_cast<const void*>(&game_save_query_interface);
|
||||
@@ -789,9 +893,9 @@ const std::array<const void*, 33> kGameSaveVtbl = [] {
|
||||
v[10] = reinterpret_cast<const void*>(&gs_delete);
|
||||
v[11] = reinterpret_cast<const void*>(&gs_delete_async);
|
||||
v[12] = reinterpret_cast<const void*>(&gs_delete_result);
|
||||
v[13] = reinterpret_cast<const void*>(&gs_container_info);
|
||||
v[13] = reinterpret_cast<const void*>(&get_container_info);
|
||||
v[14] = reinterpret_cast<const void*>(&enumerate_container_info);
|
||||
v[15] = reinterpret_cast<const void*>(&gs_enum_by_name);
|
||||
v[15] = reinterpret_cast<const void*>(&enumerate_container_info_by_name);
|
||||
v[16] = reinterpret_cast<const void*>(&create_container);
|
||||
v[17] = reinterpret_cast<const void*>(&close_container);
|
||||
v[18] = reinterpret_cast<const void*>(&gs_enum_blobs);
|
||||
@@ -818,12 +922,12 @@ const std::array<const void*, 42> kPackageVtbl = [] {
|
||||
v[0] = reinterpret_cast<const void*>(&package_query_interface);
|
||||
v[3] = reinterpret_cast<const void*>(&get_current_process_package_identifier);
|
||||
v[4] = reinterpret_cast<const void*>(&is_packaged_process);
|
||||
v[5] = reinterpret_cast<const void*>(&create_installation_monitor);
|
||||
v[6] = reinterpret_cast<const void*>(&close_installation_monitor);
|
||||
v[7] = reinterpret_cast<const void*>(&get_installation_progress);
|
||||
v[8] = reinterpret_cast<const void*>(&update_installation_monitor);
|
||||
v[9] = reinterpret_cast<const void*>(®ister_installation_progress);
|
||||
v[10] = reinterpret_cast<const void*>(&unregister_installation_progress);
|
||||
v[5] = reinterpret_cast<const void*>(&pk_create_monitor);
|
||||
v[6] = reinterpret_cast<const void*>(&pk_close_monitor);
|
||||
v[7] = reinterpret_cast<const void*>(&pk_get_progress);
|
||||
v[8] = reinterpret_cast<const void*>(&pk_update_monitor);
|
||||
v[9] = reinterpret_cast<const void*>(&pk_reg_progress);
|
||||
v[10] = reinterpret_cast<const void*>(&pk_unreg_progress);
|
||||
v[11] = reinterpret_cast<const void*>(&pk_locale);
|
||||
v[12] = reinterpret_cast<const void*>(&pk_find_chunk);
|
||||
v[13] = reinterpret_cast<const void*>(&pk_enum_chunk);
|
||||
@@ -841,18 +945,18 @@ const std::array<const void*, 42> kPackageVtbl = [] {
|
||||
v[25] = reinterpret_cast<const void*>(&get_mount_path);
|
||||
v[26] = reinterpret_cast<const void*>(&close_mount_handle);
|
||||
v[27] = reinterpret_cast<const void*>(&pk_unknown_27);
|
||||
v[28] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
v[28] = reinterpret_cast<const void*>(&pk_enum_packages);
|
||||
v[29] = reinterpret_cast<const void*>(&pk_reg_installed);
|
||||
v[30] = reinterpret_cast<const void*>(&pk_write_stats);
|
||||
v[31] = reinterpret_cast<const void*>(&pk_unknown_31);
|
||||
v[32] = reinterpret_cast<const void*>(&pk_uninstall_uwp);
|
||||
v[33] = reinterpret_cast<const void*>(&pk_enum_features);
|
||||
v[34] = reinterpret_cast<const void*>(&pk_uninstall);
|
||||
v[35] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
v[35] = reinterpret_cast<const void*>(&pk_enum_packages_2);
|
||||
v[36] = reinterpret_cast<const void*>(&pk_reg_installed_2);
|
||||
v[37] = reinterpret_cast<const void*>(&mount_with_ui_async);
|
||||
v[38] = reinterpret_cast<const void*>(&mount_with_ui_result);
|
||||
v[39] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
v[39] = reinterpret_cast<const void*>(&pk_enum_packages_3);
|
||||
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
|
||||
v[41] = reinterpret_cast<const void*>(&get_package_kind);
|
||||
return v;
|
||||
|
||||
@@ -841,7 +841,34 @@ HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, void* blob
|
||||
});
|
||||
}
|
||||
|
||||
namespace {
|
||||
// name == nullptr: every container; exact: the container called `name`; otherwise: containers
|
||||
// whose name starts with `name`.
|
||||
HRESULT enumerate_containers_filtered(void* provider, const char* name, bool exact, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
} // namespace
|
||||
|
||||
// XGameSaveGetContainerInfo: the callback gets the named container's info, or is not called
|
||||
// when no such container exists (the call still succeeds; inferred, see the PR notes).
|
||||
HRESULT WINAPI get_container_info(void*, void* provider, const char* name, void* context,
|
||||
GameSaveContainerInfoCallback callback) {
|
||||
if (!name) return E_INVALIDARG;
|
||||
return enumerate_containers_filtered(provider, name, true, context, callback);
|
||||
}
|
||||
|
||||
// XGameSaveEnumerateContainerInfoByName: containers whose name starts with the prefix.
|
||||
HRESULT WINAPI enumerate_container_info_by_name(void*, void* provider, const char* prefix, void* context,
|
||||
GameSaveContainerInfoCallback callback) {
|
||||
return enumerate_containers_filtered(provider, prefix ? prefix : "", false, context, callback);
|
||||
}
|
||||
|
||||
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, GameSaveContainerInfoCallback callback) {
|
||||
return enumerate_containers_filtered(provider, nullptr, false, context, callback);
|
||||
}
|
||||
|
||||
namespace {
|
||||
HRESULT enumerate_containers_filtered(void* provider, const char* name, bool exact, void* context,
|
||||
GameSaveContainerInfoCallback callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
const auto typed = reinterpret_cast<ContainerInfoCallback>(callback);
|
||||
const auto generation = active_runtime_generation();
|
||||
@@ -864,6 +891,10 @@ HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, Ga
|
||||
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.name < b.name; });
|
||||
// No lock is held here, so the callback may call back into XGameSave.
|
||||
for (const auto& data : list) {
|
||||
if (name) {
|
||||
const std::string wanted(name);
|
||||
if (exact ? data.name != wanted : data.name.compare(0, wanted.size(), wanted) != 0) continue;
|
||||
}
|
||||
const ContainerInfo info{data.name.c_str(), data.display_name.c_str(),
|
||||
static_cast<uint32_t>(data.blobs.size()), data.total_size,
|
||||
static_cast<time_t>(data.last_modified), false};
|
||||
@@ -871,6 +902,7 @@ HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, Ga
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Synchronous public slots. Each one runs the async operation above on the process task
|
||||
// queue (a null XAsyncBlock queue) and waits. syncOnDemand is passed through and has no
|
||||
|
||||
@@ -22,18 +22,9 @@
|
||||
* mounted; BetterXen allows the game's own package so titles can locate their files. Offline
|
||||
* there is no license or parental-consent prompt, so the asynchronous form shows no UI; an
|
||||
* identifier mismatch is reported as the operation's status (ERROR_NOT_FOUND).
|
||||
* - The last XGameRuntimeUninitialize closes every mount handle and installation monitor.
|
||||
* - Installation monitors (XPackageCreateInstallationMonitor and the functions taking its
|
||||
* handle) accept only that identifier. The package is fully on local storage, so progress is
|
||||
* {1, 1, 1, launchable, completed} and never changes: a registered progress callback is
|
||||
* accepted, logged and never called. Handles share the mount table's lock and generation, so
|
||||
* a closed or stale handle is rejected and closing twice is harmless.
|
||||
* - XPackageEnumeratePackages reports this game for XPackageKind::Game in every scope (the
|
||||
* documented ThisOnly output is the calling game; offline there are no related or publisher
|
||||
* games), and no packages for Content or PublisherContent: none are installed offline.
|
||||
* - The last XGameRuntimeUninitialize closes every mount handle.
|
||||
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
|
||||
*/
|
||||
#include "bx_log.h"
|
||||
#include "runtime_internal.h"
|
||||
#include "synthetic_keys.h"
|
||||
|
||||
@@ -46,7 +37,6 @@
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
@@ -260,148 +250,6 @@ void WINAPI close_mount_handle(void*, void* handle) {
|
||||
|
||||
namespace {
|
||||
|
||||
struct Monitor {
|
||||
uint32_t generation;
|
||||
std::vector<uint64_t> tokens;
|
||||
};
|
||||
// Guarded by mount_mutex, like the mount handles. Tag 5 in bits 40-43 keeps these handles apart
|
||||
// from mount handles (tag 4) and XGameSave handles.
|
||||
std::unordered_map<void*, Monitor> monitors;
|
||||
constexpr uintptr_t kMonitorTag = 5;
|
||||
uint64_t token_counter = 0;
|
||||
|
||||
// Caller holds mount_mutex.
|
||||
Monitor* find_monitor(void* handle, uint32_t generation) {
|
||||
const auto found = monitors.find(handle);
|
||||
if (found == monitors.end() || generation == 0 || found->second.generation != generation) return nullptr;
|
||||
return &found->second;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT WINAPI create_installation_monitor(void*, const char* identifier, uint32_t, const void*, uint32_t, void*,
|
||||
void** monitor) {
|
||||
if (!monitor) return E_POINTER;
|
||||
*monitor = nullptr;
|
||||
if (!identifier) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
if (!generation) return kRuntimeNotInitialized;
|
||||
bool match = false;
|
||||
const auto hr = is_current_package(identifier, match);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (!match) return kNotFound;
|
||||
try {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
++handle_counter;
|
||||
void* handle = reinterpret_cast<void*>(kMonitorTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
|
||||
monitors.emplace(handle, Monitor{generation, {}});
|
||||
*monitor = handle;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageCreateInstallationMonitor",
|
||||
"monitor for the running package: fully installed, progress never changes (offline)");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
void WINAPI close_installation_monitor(void*, void* monitor) {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
monitors.erase(monitor); // an unknown or already closed handle is ignored
|
||||
}
|
||||
|
||||
void WINAPI get_installation_progress(void*, void* monitor, XPackageInstallationProgress* progress) {
|
||||
if (!progress) return;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
*progress = find_monitor(monitor, generation) ? XPackageInstallationProgress{1, 1, 1, true, true}
|
||||
: XPackageInstallationProgress{};
|
||||
}
|
||||
|
||||
bool WINAPI update_installation_monitor(void*, void*) {
|
||||
return false; // progress never changes offline
|
||||
}
|
||||
|
||||
HRESULT WINAPI register_installation_progress(void*, void* monitor, void*, void* callback, uint64_t* token) {
|
||||
if (!token) return E_POINTER;
|
||||
*token = 0;
|
||||
if (!callback) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
try {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
Monitor* open = find_monitor(monitor, generation);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
*token = ++token_counter;
|
||||
open->tokens.push_back(*token);
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "token=%llu accepted; offline progress never changes, so the callback is never called",
|
||||
static_cast<unsigned long long>(*token));
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageRegisterInstallationProgressChanged", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
bool WINAPI unregister_installation_progress(void*, void* monitor, uint64_t token, bool) {
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
Monitor* open = find_monitor(monitor, generation);
|
||||
if (!open) return false;
|
||||
for (auto it = open->tokens.begin(); it != open->tokens.end(); ++it) {
|
||||
if (*it == token) {
|
||||
open->tokens.erase(it);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct XVersionValue {
|
||||
uint16_t major, minor, build, revision;
|
||||
};
|
||||
struct XPackageDetails {
|
||||
const char* packageIdentifier;
|
||||
XVersionValue version;
|
||||
uint32_t kind;
|
||||
const char* displayName;
|
||||
const char* description;
|
||||
const char* publisher;
|
||||
const char* storeId;
|
||||
bool installing;
|
||||
uint32_t index;
|
||||
uint32_t count;
|
||||
bool ageRestricted;
|
||||
const char* titleId;
|
||||
};
|
||||
using EnumerationCallback = bool(CALLBACK*)(void* context, const XPackageDetails* details);
|
||||
constexpr uint32_t kKindGame = 0, kScopeThisPublisher = 2;
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT WINAPI enumerate_packages(void*, uint32_t kind, uint32_t scope, void* context, void* callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
if (!active_runtime_generation()) return kRuntimeNotInitialized;
|
||||
if (kind > 2 || scope > kScopeThisPublisher) return E_INVALIDARG;
|
||||
char detail[128];
|
||||
if (kind != kKindGame) {
|
||||
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: no content packages installed (offline)", kind, scope);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
|
||||
return S_OK;
|
||||
}
|
||||
char id[kIdBytes];
|
||||
const auto hr = current_identifier(id);
|
||||
if (FAILED(hr)) return hr;
|
||||
const XPackageDetails details{id, {}, kKindGame, "", "", "", "", false, 0, 1, false, ""};
|
||||
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: reported the running game only (offline)", kind, scope);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
|
||||
reinterpret_cast<EnumerationCallback>(callback)(context, &details);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// --- COM object ---
|
||||
|
||||
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
|
||||
@@ -453,7 +301,6 @@ const void* const package_object = &kObject;
|
||||
void release_package_state() {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
mounts.clear();
|
||||
monitors.clear();
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -85,6 +85,10 @@ HRESULT WINAPI create_container(void* self, void* provider, const char* name, vo
|
||||
void WINAPI close_container(void* self, void* container);
|
||||
HRESULT WINAPI enumerate_container_info(void* self, void* provider, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
HRESULT WINAPI get_container_info(void* self, void* provider, const char* name, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
HRESULT WINAPI enumerate_container_info_by_name(void* self, void* provider, const char* prefix, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
HRESULT WINAPI read_blob_data(void* self, void* container, const char** names, uint32_t* count, size_t size,
|
||||
void* blobs);
|
||||
HRESULT WINAPI read_blob_data_async(void* self, void* container, const char** names, uint32_t count, void* async);
|
||||
@@ -106,23 +110,4 @@ HRESULT WINAPI get_mount_path_size(void* self, void* handle, size_t* size);
|
||||
HRESULT WINAPI get_mount_path(void* self, void* handle, size_t size, char* path);
|
||||
void WINAPI close_mount_handle(void* self, void* handle);
|
||||
|
||||
// Installation monitors and enumeration (package.cpp), served on IXPackageImpl slots 5-10 and
|
||||
// the XPackageEnumeratePackages slots. Layouts follow the documented XPackage structures.
|
||||
struct XPackageInstallationProgress {
|
||||
uint64_t totalBytes;
|
||||
uint64_t installedBytes;
|
||||
uint64_t launchBytes;
|
||||
bool launchable;
|
||||
bool completed;
|
||||
};
|
||||
HRESULT WINAPI create_installation_monitor(void* self, const char* identifier, uint32_t selector_count,
|
||||
const void* selectors, uint32_t interval_ms, void* queue, void** monitor);
|
||||
void WINAPI close_installation_monitor(void* self, void* monitor);
|
||||
void WINAPI get_installation_progress(void* self, void* monitor, XPackageInstallationProgress* progress);
|
||||
bool WINAPI update_installation_monitor(void* self, void* monitor);
|
||||
HRESULT WINAPI register_installation_progress(void* self, void* monitor, void* context, void* callback,
|
||||
uint64_t* token);
|
||||
bool WINAPI unregister_installation_progress(void* self, void* monitor, uint64_t token, bool wait);
|
||||
HRESULT WINAPI enumerate_packages(void* self, uint32_t kind, uint32_t scope, void* context, void* callback);
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -185,13 +185,31 @@ public:
|
||||
Queue(DispatchMode work, DispatchMode completion) : lanes{{this, work}, {this, completion}} {}
|
||||
|
||||
Lane lanes[2];
|
||||
// A composite queue (XTaskQueueCreateComposite) has no lanes of its own in use: each port
|
||||
// forwards to a port of another queue.
|
||||
QueueRef forward[2];
|
||||
Port forward_port[2] = {Port::work, Port::completion};
|
||||
};
|
||||
|
||||
// Follows composite forwarding to the queue and port that hold the lane.
|
||||
static void resolve_lane(QueueRef& queue, Port& port) {
|
||||
for (int depth = 0; depth < 8 && queue; ++depth) {
|
||||
const auto index = static_cast<uint32_t>(port);
|
||||
if (!queue->forward[index]) return;
|
||||
const Port next_port = queue->forward_port[index];
|
||||
queue = queue->forward[index];
|
||||
port = next_port;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::mutex queues_mutex;
|
||||
std::unordered_map<uintptr_t, QueueRef> handles;
|
||||
uintptr_t next_handle = 1;
|
||||
// XTaskQueuePortHandle values (even numbers, so they never collide with queue handles).
|
||||
std::unordered_map<uintptr_t, std::pair<QueueRef, Port>> port_handles;
|
||||
uintptr_t next_port_handle = 2;
|
||||
QueueRef process_queue;
|
||||
|
||||
HRESULT make_queue(DispatchMode work, DispatchMode completion, QueueRef& queue) {
|
||||
@@ -238,7 +256,9 @@ QueueRef acquire_queue(void* handle) {
|
||||
}
|
||||
|
||||
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion) {
|
||||
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
QueueRef target = queue;
|
||||
resolve_lane(target, port);
|
||||
return target->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
}
|
||||
|
||||
|
||||
@@ -275,6 +295,10 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
|
||||
queue = std::move(it->second);
|
||||
close_queue = queue != process_queue;
|
||||
handles.erase(it);
|
||||
// Duplicated handles share the queue: only the last close shuts its lanes down.
|
||||
for (const auto& other : handles) {
|
||||
if (other.second == queue) close_queue = false;
|
||||
}
|
||||
}
|
||||
// The frozen ABI exposes no termination or duplicate-handle API. Drain manual
|
||||
// completion callbacks on close and let accepted pool work finish normally.
|
||||
@@ -285,8 +309,64 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
|
||||
|
||||
bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
|
||||
if (!handle || port > Port::completion) return false;
|
||||
auto queue = acquire_queue(handle);
|
||||
if (!queue) return false;
|
||||
resolve_lane(queue, port);
|
||||
return queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
}
|
||||
|
||||
// Not exported: reached through IXGameRuntimeCore (com_dispatch.cpp).
|
||||
HRESULT WINAPI bx_xtq_duplicate_handle(void* handle, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
const auto queue = acquire_queue(handle);
|
||||
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
if (!queue) return E_HANDLE;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
*out = add_handle(queue);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI bx_xtq_get_port(void* handle, Port port, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (port > Port::completion) return E_INVALIDARG;
|
||||
const auto queue = acquire_queue(handle);
|
||||
if (!queue) return E_HANDLE;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
const auto id = next_port_handle;
|
||||
next_port_handle += 2;
|
||||
port_handles.emplace(id, std::make_pair(queue, port));
|
||||
*out = reinterpret_cast<void*>(id);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI bx_xtq_create_composite(void* work_port, void* completion_port, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
const auto work = port_handles.find(reinterpret_cast<uintptr_t>(work_port));
|
||||
const auto completion = port_handles.find(reinterpret_cast<uintptr_t>(completion_port));
|
||||
if (work == port_handles.end() || completion == port_handles.end()) return E_HANDLE;
|
||||
// Immediate lanes: never used, every submit and dispatch is forwarded.
|
||||
auto queue = std::make_shared<Queue>(DispatchMode::immediate, DispatchMode::immediate);
|
||||
queue->forward[0] = work->second.first;
|
||||
queue->forward_port[0] = work->second.second;
|
||||
queue->forward[1] = completion->second.first;
|
||||
queue->forward_port[1] = completion->second.second;
|
||||
*out = add_handle(queue);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
||||
|
||||
@@ -643,6 +643,21 @@ HRESULT WINAPI XUserAddResult(AsyncBlock* block, void** out) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Not exported: XUserDuplicateHandle is reached through IXUser (com_dispatch.cpp). A duplicate is
|
||||
// a new handle to the same (single, offline) user; each handle is closed separately.
|
||||
HRESULT WINAPI bx_xuser_duplicate_handle(void* user, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
std::lock_guard lock(state_mutex);
|
||||
if (!users.contains(user)) return runtime_invalid_handle;
|
||||
return create_handle(users, out);
|
||||
}
|
||||
|
||||
bool WINAPI bx_xuser_is_handle(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
return users.contains(user);
|
||||
}
|
||||
|
||||
void WINAPI XUserCloseHandle(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
users.erase(user);
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
add_executable(test_acphal_default_heap main.cpp)
|
||||
target_link_libraries(test_acphal_default_heap PRIVATE acphal kernel32)
|
||||
@@ -1,90 +0,0 @@
|
||||
// AcpHal's default APU heap, in a fresh process: a title that allocates shape contexts before
|
||||
// any ApuCreateHeap gets a 64 MB default heap (BetterXen's stand-in for the console's default
|
||||
// non-cached APU heap). test_audio_input creates its own heap first, so this branch needs a
|
||||
// process of its own.
|
||||
//
|
||||
// Expected values come from this file: 64 MiB is the documented-in-CHANGELOG default, so shape
|
||||
// contexts of exactly 64 MiB must fit and 64 MiB + 64 bytes must not.
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*);
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void);
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
|
||||
void* WINAPI ApuMapApuAddress(uint32_t);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
int g_failures = 0;
|
||||
void check(bool ok, const char* what) {
|
||||
if (!ok) {
|
||||
++g_failures;
|
||||
std::printf("FAIL: test_acphal_default_heap: %s\n", what);
|
||||
}
|
||||
}
|
||||
|
||||
struct ShapeContexts {
|
||||
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
|
||||
void* arrays[6];
|
||||
uint32_t apu[6];
|
||||
};
|
||||
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS");
|
||||
|
||||
constexpr uint32_t kXmaBytes = 64;
|
||||
constexpr uint32_t kDefaultHeap = 64u << 20;
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
std::string text;
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return text;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return text;
|
||||
char buf[65536];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
|
||||
size_t count_of(const std::string& text, const char* needle) {
|
||||
size_t n = 0;
|
||||
for (size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
char probe[8];
|
||||
if (GetEnvironmentVariableA("BX_LOG_FILE", probe, sizeof(probe)) == 0) {
|
||||
std::printf("FAIL: test_acphal_default_heap: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
// No ApuCreateHeap. One XMA element more than 64 MiB holds does not fit the default heap...
|
||||
ShapeContexts too_big{};
|
||||
too_big.counts[4] = kDefaultHeap / kXmaBytes + 1;
|
||||
check(AcpHalAllocateShapeContexts(&too_big) == E_OUTOFMEMORY, "64 MiB + 64 bytes exceeds the default heap");
|
||||
// ...and exactly 64 MiB does (the failed attempt above left nothing allocated).
|
||||
ShapeContexts exact{};
|
||||
exact.counts[4] = kDefaultHeap / kXmaBytes;
|
||||
check(AcpHalAllocateShapeContexts(&exact) == S_OK && exact.arrays[4] && exact.apu[4],
|
||||
"exactly 64 MiB of shape contexts fits the default heap");
|
||||
check(exact.apu[4] && ApuMapApuAddress(exact.apu[4]) == exact.arrays[4], "the shape array is an APU heap allocation");
|
||||
// The default heap is the heap: a later ApuCreateHeap finds one already created.
|
||||
check(ApuCreateHeap(64, 64) == HRESULT_FROM_WIN32(ERROR_BUSY), "ApuCreateHeap after the default heap reports busy");
|
||||
check(AcpHalReleaseShapeContexts() == S_OK, "release");
|
||||
const std::string log = read_log();
|
||||
check(count_of(log, "\"event\":\"apu_default_heap\"") == 1, "the default heap is created once and logged");
|
||||
if (g_failures) {
|
||||
std::printf("FAIL: test_acphal_default_heap (%d failed)\n", g_failures);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_acphal_default_heap\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -118,10 +118,7 @@ int main() {
|
||||
PVOID handler = AddVectoredExceptionHandler(0, resume);
|
||||
check(handler != nullptr, "AddVectoredExceptionHandler");
|
||||
|
||||
// A recorded breakpoint leaves the guest thread's last-error value as it was.
|
||||
SetLastError(0x12345678);
|
||||
bx_breakpoint_site();
|
||||
check(GetLastError() == 0x12345678, "a recorded breakpoint preserves the thread's last-error value");
|
||||
RaiseException(kStatusAssertionFailure, 0, 0, nullptr);
|
||||
for (int i = 0; i < kRecordLimit + 4; ++i) bx_breakpoint_site();
|
||||
RemoveVectoredExceptionHandler(handler);
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
add_executable(test_veh_diagnostics main.cpp)
|
||||
target_include_directories(test_veh_diagnostics PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_veh_diagnostics PRIVATE bx_runtime_veh kernel32)
|
||||
# A fixed image base: the parent passes its own code address to the child's BX_VEH_HIT, which is
|
||||
# armed before the child's main runs.
|
||||
target_link_options(test_veh_diagnostics PRIVATE -Wl,--disable-dynamicbase)
|
||||
@@ -1,389 +0,0 @@
|
||||
// Conformance test for bx_runtime_veh.dll's opt-in diagnostics (BX_VEH_AV_CONTEXT, BX_VEH_AV_ALL,
|
||||
// BX_VEH_WATCH, BX_VEH_HIT, BX_VEH_SAMPLE).
|
||||
//
|
||||
// The switches are read when runtime_veh attaches, before main, so the parent starts this same
|
||||
// executable as a child once per mode with that mode's environment, then reads the shared JSONL
|
||||
// log (BX_LOG_FILE) for the records the child produced. Expected values come from what each child
|
||||
// does, not from runtime_veh. Every record must be valid JSON and valid UTF-8.
|
||||
//
|
||||
// Run under `bx-cli run --log`. Exit 0: all checks passed. Exit 1: a check failed. Exit 77: the
|
||||
// host cannot run a mode (logged as SKIP).
|
||||
#include <windows.h>
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" __declspec(dllimport) uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
|
||||
// A store whose length the child's handler knows (mov [rcx], rdx = 48 89 11), used to make a
|
||||
// write fault the child can step over.
|
||||
extern "C" void store_qword(volatile uint64_t* at, uint64_t value);
|
||||
asm(".globl store_qword\n"
|
||||
"store_qword:\n"
|
||||
" movq %rdx, (%rcx)\n"
|
||||
" ret\n");
|
||||
|
||||
// The code-breakpoint target. Not inlined, so the child calls the address the parent passes.
|
||||
extern "C" __attribute__((noinline)) int hit_target(const char* text) {
|
||||
volatile int sum = 0;
|
||||
for (const char* c = text; *c; ++c) sum += *c;
|
||||
return sum;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
int g_failures = 0;
|
||||
int g_checks = 0;
|
||||
|
||||
void check(bool ok, const char* what) {
|
||||
++g_checks;
|
||||
if (!ok) {
|
||||
++g_failures;
|
||||
std::printf("FAIL: test_veh_diagnostics: %s\n", what);
|
||||
}
|
||||
}
|
||||
|
||||
constexpr uintptr_t kWatchBase = 0x7A0000000ull; // the child's watched allocation
|
||||
|
||||
// --- Child side --------------------------------------------------------------------------------
|
||||
|
||||
volatile LONG g_child_avs = 0;
|
||||
|
||||
LONG CALLBACK child_handler(PEXCEPTION_POINTERS ep) {
|
||||
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return EXCEPTION_CONTINUE_SEARCH;
|
||||
InterlockedIncrement(&g_child_avs);
|
||||
// A real fault in store_qword: step over its 3-byte store.
|
||||
if (reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) == reinterpret_cast<uintptr_t>(&store_qword)) {
|
||||
ep->ContextRecord->Rip += 3;
|
||||
}
|
||||
return EXCEPTION_CONTINUE_EXECUTION; // a raised (continuable) one resumes after RaiseException
|
||||
}
|
||||
|
||||
void raise_av() {
|
||||
const ULONG_PTR info[2] = {1, 0x1234};
|
||||
RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 2, info);
|
||||
}
|
||||
|
||||
DWORD WINAPI raise_many(LPVOID) {
|
||||
for (int i = 0; i < 8; ++i) raise_av();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int child(const char* mode, const char* arg) {
|
||||
(void)bx_veh_get_clwb_trap_count(); // keeps the runtime_veh import
|
||||
AddVectoredExceptionHandler(0, child_handler); // after runtime_veh's own handler
|
||||
if (!std::strcmp(mode, "off")) {
|
||||
for (int i = 0; i < 4; ++i) raise_av();
|
||||
return g_child_avs == 4 ? 0 : 2;
|
||||
}
|
||||
if (!std::strcmp(mode, "av")) {
|
||||
HANDLE threads[4];
|
||||
for (auto& t : threads) t = CreateThread(nullptr, 0, raise_many, nullptr, 0, nullptr);
|
||||
WaitForMultipleObjects(4, threads, TRUE, 10000);
|
||||
for (auto t : threads) CloseHandle(t);
|
||||
return g_child_avs == 32 ? 0 : 2;
|
||||
}
|
||||
if (!std::strcmp(mode, "watch")) {
|
||||
auto* base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(kWatchBase), 0x10000,
|
||||
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
|
||||
if (base != reinterpret_cast<uint8_t*>(kWatchBase)) return 77;
|
||||
// The helper thread protects the page once it is committed.
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
for (int i = 0; i < 2000; ++i) {
|
||||
if (VirtualQuery(base, &mbi, sizeof(mbi)) && mbi.Protect == PAGE_READONLY) break;
|
||||
Sleep(1);
|
||||
}
|
||||
if (mbi.Protect != PAGE_READONLY) return 3;
|
||||
*reinterpret_cast<volatile uint64_t*>(base + 0x10) = 0x1122334455667788ull; // watched: logged
|
||||
*reinterpret_cast<volatile uint64_t*>(base + 0x200) = 7; // same page, not watched
|
||||
if (*reinterpret_cast<volatile uint64_t*>(base + 0x10) != 0x1122334455667788ull) return 4;
|
||||
// Decommit the watched page: the next write faults, and runtime_veh cannot unprotect the
|
||||
// page, so it must disarm and pass the fault on (to child_handler) rather than loop.
|
||||
if (!VirtualFree(base, 0x1000, MEM_DECOMMIT)) return 5;
|
||||
const LONG before = g_child_avs;
|
||||
store_qword(reinterpret_cast<volatile uint64_t*>(base + 0x10), 9);
|
||||
return g_child_avs == before + 1 ? 0 : 6;
|
||||
}
|
||||
if (!std::strcmp(mode, "hit")) {
|
||||
const uintptr_t expected = static_cast<uintptr_t>(std::strtoull(arg, nullptr, 16));
|
||||
if (expected != reinterpret_cast<uintptr_t>(&hit_target)) return 77; // image relocated
|
||||
hit_target("quote\" back\\ path");
|
||||
hit_target("second call");
|
||||
return 0;
|
||||
}
|
||||
if (!std::strcmp(mode, "sample")) {
|
||||
const DWORD until = GetTickCount() + 300;
|
||||
volatile uint64_t spin = 0;
|
||||
while (GetTickCount() < until) spin = spin + 1;
|
||||
return spin ? 0 : 2;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
|
||||
// --- Parent side -------------------------------------------------------------------------------
|
||||
|
||||
std::wstring widen(const char* s) {
|
||||
std::wstring out;
|
||||
while (*s) out.push_back(static_cast<wchar_t>(static_cast<unsigned char>(*s++)));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string read_log_from(const char* path, uint64_t offset) {
|
||||
std::string text;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return text;
|
||||
LARGE_INTEGER at;
|
||||
at.QuadPart = static_cast<LONGLONG>(offset);
|
||||
SetFilePointerEx(f, at, nullptr, FILE_BEGIN);
|
||||
char buf[65536];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
|
||||
uint64_t file_size(const char* path) {
|
||||
WIN32_FILE_ATTRIBUTE_DATA data{};
|
||||
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &data)) return 0;
|
||||
return (static_cast<uint64_t>(data.nFileSizeHigh) << 32) | data.nFileSizeLow;
|
||||
}
|
||||
|
||||
// A JSONL record: one object whose strings use only JSON escapes and no raw control characters,
|
||||
// in valid UTF-8.
|
||||
bool valid_record(const std::string& line) {
|
||||
if (line.size() < 2 || line.front() != '{' || line.back() != '}') return false;
|
||||
bool in_string = false;
|
||||
for (size_t i = 0; i < line.size(); ++i) {
|
||||
const unsigned char c = static_cast<unsigned char>(line[i]);
|
||||
if (c >= 0x80) { // UTF-8 sequence
|
||||
const int extra = (c & 0xE0) == 0xC0 ? 1 : (c & 0xF0) == 0xE0 ? 2 : (c & 0xF8) == 0xF0 ? 3 : -1;
|
||||
if (extra < 0 || i + extra >= line.size()) return false;
|
||||
for (int k = 1; k <= extra; ++k) {
|
||||
if ((static_cast<unsigned char>(line[i + k]) & 0xC0) != 0x80) return false;
|
||||
}
|
||||
i += extra;
|
||||
continue;
|
||||
}
|
||||
if (!in_string) {
|
||||
if (c == '"') in_string = true;
|
||||
continue;
|
||||
}
|
||||
if (c < 0x20) return false;
|
||||
if (c == '"') {
|
||||
in_string = false;
|
||||
} else if (c == '\\') {
|
||||
if (i + 1 >= line.size()) return false;
|
||||
const char e = line[++i];
|
||||
if (e == 'u') {
|
||||
if (i + 4 >= line.size()) return false;
|
||||
for (int k = 1; k <= 4; ++k) {
|
||||
if (!std::isxdigit(static_cast<unsigned char>(line[i + k]))) return false;
|
||||
}
|
||||
i += 4;
|
||||
} else if (!std::strchr("\"\\/bfnrt", e)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return !in_string;
|
||||
}
|
||||
|
||||
std::vector<std::string> records(const std::string& text, const char* event) {
|
||||
std::vector<std::string> out;
|
||||
const std::string needle = std::string("\"event\":\"") + event + "\"";
|
||||
size_t start = 0;
|
||||
while (start < text.size()) {
|
||||
size_t end = text.find('\n', start);
|
||||
if (end == std::string::npos) end = text.size();
|
||||
std::string line = text.substr(start, end - start);
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
if (line.find(needle) != std::string::npos) out.push_back(line);
|
||||
start = end + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
struct ChildRun {
|
||||
DWORD exit_code = 0xFFFFFFFF;
|
||||
std::string log;
|
||||
};
|
||||
|
||||
// Starts `exe` as a child in `mode` with the extra environment variables, waits for it, and
|
||||
// returns its exit code and the log lines it appended.
|
||||
ChildRun run_child(const std::wstring& exe, const char* mode, const char* arg,
|
||||
const std::vector<std::wstring>& extra_env, const char* log_path) {
|
||||
ChildRun run;
|
||||
std::wstring block;
|
||||
if (wchar_t* env = GetEnvironmentStringsW()) {
|
||||
for (const wchar_t* p = env; *p; p += std::wcslen(p) + 1) {
|
||||
std::wstring entry(p);
|
||||
if (entry.rfind(L"BX_VEH_", 0) == 0) continue; // only this mode's switches
|
||||
block += entry;
|
||||
block.push_back(L'\0');
|
||||
}
|
||||
FreeEnvironmentStringsW(env);
|
||||
}
|
||||
for (const auto& e : extra_env) {
|
||||
block += e;
|
||||
block.push_back(L'\0');
|
||||
}
|
||||
block.push_back(L'\0');
|
||||
std::wstring cmd = L"\"" + exe + L"\" child " + widen(mode) + L" " + widen(arg);
|
||||
STARTUPINFOW si{};
|
||||
si.cb = sizeof(si);
|
||||
PROCESS_INFORMATION pi{};
|
||||
const uint64_t before = file_size(log_path);
|
||||
if (!CreateProcessW(exe.c_str(), cmd.data(), nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT, block.data(),
|
||||
nullptr, &si, &pi)) {
|
||||
return run;
|
||||
}
|
||||
if (WaitForSingleObject(pi.hProcess, 60000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &run.exit_code);
|
||||
else TerminateProcess(pi.hProcess, 9);
|
||||
CloseHandle(pi.hThread);
|
||||
CloseHandle(pi.hProcess);
|
||||
run.log = read_log_from(log_path, before);
|
||||
return run;
|
||||
}
|
||||
|
||||
bool all_valid(const std::vector<std::string>& lines) {
|
||||
for (const auto& l : lines) {
|
||||
if (!valid_record(l)) {
|
||||
std::printf(" invalid record: %.200s\n", l.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int parent(const char* log_path) {
|
||||
wchar_t self[MAX_PATH];
|
||||
GetModuleFileNameW(nullptr, self, MAX_PATH);
|
||||
const std::wstring exe(self);
|
||||
int skipped = 0;
|
||||
|
||||
// Off: synthetic access violations produce no av_context record.
|
||||
{
|
||||
ChildRun r = run_child(exe, "off", "-", {}, log_path);
|
||||
check(r.exit_code == 0, "off: child handled its access violations (exit 0)");
|
||||
check(records(r.log, "av_context").empty(), "off: no av_context record without BX_VEH_AV_CONTEXT");
|
||||
}
|
||||
|
||||
// AV context from four threads at once, with a spec containing a quote, a backslash and a
|
||||
// control character and far too long for one line: 16 records (the cap), each valid JSON.
|
||||
std::wstring spec = L"BX_VEH_AV_CONTEXT=zz\"q\\b\x01,";
|
||||
for (int i = 0; i < 80; ++i) spec += L"*10+8,";
|
||||
{
|
||||
ChildRun r = run_child(exe, "av", "-", {spec, L"BX_VEH_AV_ALL=1"}, log_path);
|
||||
const auto lines = records(r.log, "av_context");
|
||||
check(r.exit_code == 0, "av: every access violation reached the child (exit 0)");
|
||||
check(lines.size() == 16, "av: 16 av_context records from 32 faults (the cap)");
|
||||
check(all_valid(lines), "av: every av_context record is valid JSON");
|
||||
bool escaped = false;
|
||||
for (const auto& l : lines) escaped = escaped || l.find("zz\\\"q\\\\b\\u0001") != std::string::npos;
|
||||
check(escaped, "av: the spec token is JSON-escaped");
|
||||
bool stack = true;
|
||||
for (const auto& l : lines) stack = stack && l.find("| stack:") != std::string::npos;
|
||||
check(stack, "av: a truncated spec still leaves room for the stack");
|
||||
}
|
||||
|
||||
// A non-ASCII module name in the stack must stay valid UTF-8.
|
||||
{
|
||||
std::wstring dir = exe.substr(0, exe.find_last_of(L'\\') + 1);
|
||||
const std::wstring copy = dir + L"veh_ünïcode.exe";
|
||||
if (CopyFileW(exe.c_str(), copy.c_str(), FALSE)) {
|
||||
ChildRun r = run_child(copy, "av", "-", {L"BX_VEH_AV_CONTEXT=1", L"BX_VEH_AV_ALL=1"}, log_path);
|
||||
const auto lines = records(r.log, "av_context");
|
||||
check(r.exit_code == 0 && !lines.empty(), "unicode: the renamed child logged av_context");
|
||||
check(all_valid(lines), "unicode: records with a non-ASCII module name are valid JSON and UTF-8");
|
||||
bool named = false;
|
||||
for (const auto& l : lines) named = named || l.find("veh_\xc3\xbc" "n\xc3\xaf" "code") != std::string::npos;
|
||||
check(named, "unicode: the module name is written in UTF-8");
|
||||
DeleteFileW(copy.c_str());
|
||||
} else {
|
||||
std::printf("SKIP: unicode mode: could not copy the executable\n");
|
||||
++skipped;
|
||||
}
|
||||
}
|
||||
|
||||
// Write watch: one logged write, a write outside the range not logged, and a protection
|
||||
// failure that disarms the watch and lets the fault reach the guest.
|
||||
{
|
||||
wchar_t watch[64];
|
||||
std::swprintf(watch, 64, L"BX_VEH_WATCH=%llx:8", static_cast<unsigned long long>(kWatchBase + 0x10));
|
||||
ChildRun r = run_child(exe, "watch", "-", {watch}, log_path);
|
||||
if (r.exit_code == 77) {
|
||||
std::printf("SKIP: watch mode: the fixed test address is not free in this process\n");
|
||||
++skipped;
|
||||
} else {
|
||||
const auto writes = records(r.log, "watched_write");
|
||||
const auto disarmed = records(r.log, "diagnostic_disarmed");
|
||||
check(r.exit_code == 0, "watch: the write to the decommitted page reached the child (exit 0)");
|
||||
check(writes.size() == 1 && writes[0].find("address=7a0000010") != std::string::npos &&
|
||||
writes[0].find("value_after=1122334455667788") != std::string::npos,
|
||||
"watch: exactly the watched write is logged, with its value");
|
||||
check(disarmed.size() == 1 && disarmed[0].find("watch: could not unprotect") != std::string::npos,
|
||||
"watch: a failed protection change disarms the watch and is logged");
|
||||
check(all_valid(writes) && all_valid(disarmed), "watch: records are valid JSON");
|
||||
}
|
||||
}
|
||||
|
||||
// Code breakpoint: two calls, two hits (the breakpoint is re-armed), the string argument safe.
|
||||
{
|
||||
char address[32];
|
||||
std::snprintf(address, sizeof(address), "%llx", static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(&hit_target)));
|
||||
std::wstring hit = L"BX_VEH_HIT=" + widen(address);
|
||||
ChildRun r = run_child(exe, "hit", address, {hit}, log_path);
|
||||
if (r.exit_code == 77) {
|
||||
std::printf("SKIP: hit mode: the child's image was relocated\n");
|
||||
++skipped;
|
||||
} else {
|
||||
const auto hits = records(r.log, "code_hit");
|
||||
check(r.exit_code == 0, "hit: the child ran through both breakpoint hits (exit 0)");
|
||||
check(hits.size() == 2, "hit: both calls are logged (the breakpoint is re-armed)");
|
||||
check(all_valid(hits), "hit: code_hit records are valid JSON");
|
||||
bool text = false;
|
||||
for (const auto& l : hits) text = text || l.find("[rcx]s=quote_ back_ path") != std::string::npos;
|
||||
check(text, "hit: a string argument is logged with quote and backslash made safe");
|
||||
}
|
||||
}
|
||||
|
||||
// Sampler: records while the child runs, valid JSON, and a clean exit.
|
||||
{
|
||||
ChildRun r = run_child(exe, "sample", "-", {L"BX_VEH_SAMPLE=5"}, log_path);
|
||||
const auto samples = records(r.log, "sample");
|
||||
check(r.exit_code == 0, "sample: the child exits normally with the sampler running");
|
||||
check(!samples.empty(), "sample: sample records are written");
|
||||
check(all_valid(samples), "sample: sample records are valid JSON");
|
||||
}
|
||||
|
||||
if (g_failures) {
|
||||
std::printf("FAIL: test_veh_diagnostics (%d of %d checks failed)\n", g_failures, g_checks);
|
||||
return 1;
|
||||
}
|
||||
if (skipped) {
|
||||
std::printf("SKIP: test_veh_diagnostics: %d mode(s) could not run on this host (%d checks passed)\n", skipped, g_checks);
|
||||
return 77;
|
||||
}
|
||||
std::printf("PASS: test_veh_diagnostics (%d checks: off, AV context, UTF-8 module names, write watch, code hit, sampler)\n",
|
||||
g_checks);
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc >= 4 && !std::strcmp(argv[1], "child")) return child(argv[2], argv[3]);
|
||||
char log_path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (n == 0 || n >= sizeof(log_path)) {
|
||||
std::printf("FAIL: test_veh_diagnostics: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
return parent(log_path);
|
||||
}
|
||||
@@ -422,63 +422,6 @@ int main() {
|
||||
q->Release();
|
||||
}
|
||||
|
||||
/* A full AutoSubmitDisabled queue stalls the enqueuer until Submit is called on another
|
||||
* thread; it must not submit by itself (documented DSTORAGE_QUEUE_OPTIONS behaviour). A
|
||||
* capacity-4 queue holds 3 requests (one slot stays free, as for the public queues). A
|
||||
* worker enqueues 5: the fourth waits, and no destination changes until this thread calls
|
||||
* Submit. */
|
||||
{
|
||||
XboxQueueDesc qd{};
|
||||
qd.source_type = 1;
|
||||
qd.capacity = 4;
|
||||
qd.priority = 1;
|
||||
qd.name = "xbox_full_held_queue";
|
||||
qd.flags = 1;
|
||||
IXboxDStorageQueue* q = nullptr;
|
||||
check(factory->CreateQueueX(&qd, kXboxQueueIid, reinterpret_cast<void**>(&q)) == S_OK && q,
|
||||
"CreateQueueX(capacity 4, AutoSubmitDisabled) must succeed");
|
||||
if (q) {
|
||||
static uint8_t full_dst[5][16];
|
||||
std::memset(full_dst, 0, sizeof(full_dst));
|
||||
struct Job {
|
||||
IXboxDStorageQueue* q;
|
||||
const uint8_t* src;
|
||||
volatile LONG enqueued;
|
||||
} job{q, payload + 32, 0};
|
||||
auto worker = [](void* arg) -> DWORD {
|
||||
auto* j = static_cast<Job*>(arg);
|
||||
for (auto& dst : full_dst) {
|
||||
XboxRequest r{};
|
||||
r.options = 0x400000ull;
|
||||
r.destination = dst;
|
||||
r.destination_size = sizeof(dst);
|
||||
r.source_ptr = const_cast<uint8_t*>(j->src);
|
||||
r.source_size = sizeof(dst);
|
||||
j->q->EnqueueRequest(&r);
|
||||
InterlockedIncrement(&j->enqueued);
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
HANDLE thread = CreateThread(nullptr, 0, worker, &job, 0, nullptr);
|
||||
Sleep(500);
|
||||
bool untouched = true;
|
||||
for (auto& dst : full_dst) untouched = untouched && !copied(dst, 0);
|
||||
check(untouched, "a full AutoSubmitDisabled queue must not run anything before Submit");
|
||||
check(job.enqueued == 3, "the enqueue past capacity must wait for Submit (enqueued=%ld)",
|
||||
static_cast<long>(job.enqueued));
|
||||
q->Submit(); // runs the three queued requests, freeing slots for the last two
|
||||
check(thread && WaitForSingleObject(thread, 5000) == WAIT_OBJECT_0,
|
||||
"Submit from another thread must release the waiting enqueue");
|
||||
q->Submit(); // the last two requests
|
||||
bool all = true;
|
||||
for (auto& dst : full_dst) all = all && copied(dst, 5000);
|
||||
check(all, "all five requests must run after Submit");
|
||||
if (thread) CloseHandle(thread);
|
||||
q->Close();
|
||||
q->Release();
|
||||
}
|
||||
}
|
||||
|
||||
/* A corrupted stream fails with the DirectStorage decompression error, not silently. */
|
||||
static uint8_t corrupted[sizeof(kZlibStream)];
|
||||
std::memcpy(corrupted, kZlibStream, sizeof(corrupted));
|
||||
|
||||
@@ -91,23 +91,6 @@ static_assert(sizeof(XgPlaneLayout) == 1736, "XG_PLANE_LAYOUT");
|
||||
static_assert(sizeof(XgResourceLayout) == 6976, "XG_RESOURCE_LAYOUT");
|
||||
|
||||
|
||||
struct XgPackedMipDesc {
|
||||
UINT8 NumStandardMips;
|
||||
UINT8 NumPackedMips;
|
||||
UINT32 NumTilesForPackedMips;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
struct XgTileShape {
|
||||
UINT32 Width, Height, Depth;
|
||||
};
|
||||
struct XgSubresourceTiling {
|
||||
UINT32 WidthInTiles;
|
||||
UINT16 HeightInTiles;
|
||||
UINT16 DepthInTiles;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
static_assert(sizeof(XgPackedMipDesc) == 12 && sizeof(XgSubresourceTiling) == 12, "tiling structures");
|
||||
|
||||
// The interface the DLL implements. It is declared, like the structures it uses, outside the anonymous namespace: with internal
|
||||
// linkage and no derived class in this file, GCC may treat calls through it as unreachable.
|
||||
class Computer {
|
||||
@@ -126,7 +109,7 @@ public:
|
||||
UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 sub, UINT32 sample, const void* base,
|
||||
UINT32 row_pitch, UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT GetResourceTiling(UINT32*, XgPackedMipDesc*, XgTileShape*, UINT32*, UINT32, XgSubresourceTiling*) = 0;
|
||||
virtual HRESULT GetResourceTiling(UINT32*, void*, void*, UINT32*, UINT32, void*) = 0;
|
||||
virtual HRESULT GetTextureViewDescriptor(UINT32, void*) = 0;
|
||||
virtual bool IsTiledResource() = 0;
|
||||
virtual HRESULT GetSwizzlePatternInfo(UINT32, void*) = 0;
|
||||
@@ -345,98 +328,6 @@ void test_refusals_and_suggest(SuggestFn suggest) {
|
||||
|
||||
} // namespace
|
||||
|
||||
// GetResourceTiling against the public D3D12 standard tile shapes, with BetterXen's linear mip
|
||||
// sizes for the packed tail. All expected numbers are worked out here by hand.
|
||||
bool tiling_is(const XgSubresourceTiling& t, UINT32 w, UINT16 h, UINT16 d, UINT32 start) {
|
||||
return t.WidthInTiles == w && t.HeightInTiles == h && t.DepthInTiles == d && t.StartTileIndexInOverallResource == start;
|
||||
}
|
||||
|
||||
void test_tiling_limits_and_methods() {
|
||||
// 2D RGBA8 1024x1024, 11 mips, 2 slices: 128x128 tiles. Mips 0-3 are standard
|
||||
// (8x8 + 4x4 + 2x2 + 1x1 = 85 tiles); mips 4-10 pack into one 64 KiB tile per slice
|
||||
// (pitches 256 bytes: 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 = 32512 bytes).
|
||||
auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 1024, 1024, 11, kLayoutLinear);
|
||||
d.DepthOrArraySize = 2;
|
||||
Computer* c = nullptr;
|
||||
check(g_create(&d, &c) == S_OK && c, "2D array for tiling created");
|
||||
if (c) {
|
||||
UINT32 total = 0, count = 22;
|
||||
XgPackedMipDesc packed{};
|
||||
XgTileShape shape{};
|
||||
XgSubresourceTiling t[22]{};
|
||||
check(c->GetResourceTiling(&total, &packed, &shape, &count, 0, t) == S_OK, "GetResourceTiling 2D");
|
||||
check(total == 172 && count == 22, "2D: 86 tiles per slice, 172 in all, 22 subresources");
|
||||
check(shape.Width == 128 && shape.Height == 128 && shape.Depth == 1, "2D RGBA8 tile shape 128x128x1");
|
||||
check(packed.NumStandardMips == 4 && packed.NumPackedMips == 7 && packed.NumTilesForPackedMips == 1 &&
|
||||
packed.StartTileIndexInOverallResource == 85,
|
||||
"2D packed mips: 4 standard, 7 packed into 1 tile starting at 85");
|
||||
check(tiling_is(t[0], 8, 8, 1, 0) && tiling_is(t[1], 4, 4, 1, 64) && tiling_is(t[2], 2, 2, 1, 80) &&
|
||||
tiling_is(t[3], 1, 1, 1, 84),
|
||||
"2D standard mip tilings of slice 0");
|
||||
check(tiling_is(t[4], 0, 0, 0, 0xFFFFFFFFu) && tiling_is(t[10], 0, 0, 0, 0xFFFFFFFFu),
|
||||
"2D packed mips have no tiling of their own");
|
||||
check(tiling_is(t[11], 8, 8, 1, 86) && tiling_is(t[14], 1, 1, 1, 170), "2D slice 1 starts after slice 0's 86 tiles");
|
||||
check(c->AddRef() == 2 && c->Release() == 1, "AddRef and Release count references");
|
||||
check(!c->IsTiledResource(), "a linear layout is not a tiled resource");
|
||||
unsigned char scratch[256]{};
|
||||
check(c->GetTextureViewDescriptor(0, scratch) == E_NOTIMPL && c->GetSwizzlePatternInfo(0, scratch) == E_NOTIMPL,
|
||||
"unimplemented methods report E_NOTIMPL (and are logged)");
|
||||
c->Release();
|
||||
}
|
||||
|
||||
// 3D R8 256x256x64, 2 mips: 64x32x32 tiles. Mip 0: 4x8x2 = 64 tiles; mip 1 (128x128x32): 2x4x1 = 8.
|
||||
XgResourceDesc v = tex2d(DXGI_FORMAT_R8_UNORM, 256, 256, 2, kLayoutLinear);
|
||||
v.Dimension = 4; // XG_RESOURCE_DIMENSION_TEXTURE3D
|
||||
v.DepthOrArraySize = 64;
|
||||
c = nullptr;
|
||||
check(g_create(&v, &c) == S_OK && c, "3D texture created");
|
||||
if (c) {
|
||||
UINT32 total = 0, count = 2;
|
||||
XgPackedMipDesc packed{};
|
||||
XgTileShape shape{};
|
||||
XgSubresourceTiling t[2]{};
|
||||
check(c->GetResourceTiling(&total, &packed, &shape, &count, 0, t) == S_OK, "GetResourceTiling 3D");
|
||||
check(shape.Width == 64 && shape.Height == 32 && shape.Depth == 32, "3D one-byte tile shape 64x32x32");
|
||||
check(total == 72 && packed.NumStandardMips == 2 && packed.NumPackedMips == 0, "3D: 72 tiles, no packed mips");
|
||||
check(tiling_is(t[0], 4, 8, 2, 0) && tiling_is(t[1], 2, 4, 1, 64), "3D mip tilings count depth tiles");
|
||||
std::vector<uint8_t> tiled(1 << 20), linear(1 << 20);
|
||||
check(c->CopyIntoSubresource(tiled.data(), 0, 2, linear.data(), 256, 65536) == E_INVALIDARG &&
|
||||
c->CopyFromSubresource(linear.data(), 0, 2, 0, tiled.data(), 256, 65536) == E_INVALIDARG,
|
||||
"3D subresource past the mip count is refused, not aliased onto mip 0");
|
||||
c->Release();
|
||||
}
|
||||
|
||||
// 1D RGBA8 16384 wide: one 64 KiB row of 16384 elements is one tile.
|
||||
XgResourceDesc line = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 16384, 1, 1, kLayoutLinear);
|
||||
line.Dimension = 2; // XG_RESOURCE_DIMENSION_TEXTURE1D
|
||||
c = nullptr;
|
||||
check(g_create(&line, &c) == S_OK && c, "1D texture created");
|
||||
if (c) {
|
||||
UINT32 total = 0;
|
||||
XgTileShape shape{};
|
||||
check(c->GetResourceTiling(&total, nullptr, &shape, nullptr, 0, nullptr) == S_OK && total == 1 &&
|
||||
shape.Width == 16384 && shape.Height == 1 && shape.Depth == 1,
|
||||
"1D RGBA8: one 16384x1x1 tile");
|
||||
c->Release();
|
||||
}
|
||||
|
||||
// The public D3D12 limits: 16384 for 1D/2D, 2048 for 3D and array sizes.
|
||||
auto refused = [](XgResourceDesc desc) {
|
||||
Computer* r = nullptr;
|
||||
const bool no = g_create(&desc, &r) == E_INVALIDARG && !r;
|
||||
if (r) r->Release();
|
||||
return no;
|
||||
};
|
||||
check(refused(tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 16385, 16, 1, kLayoutLinear)), "2D width 16385 refused");
|
||||
check(refused(tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 1ull << 32, 16, 1, kLayoutLinear)), "2D width 2^32 refused, not truncated");
|
||||
XgResourceDesc deep = v;
|
||||
deep.DepthOrArraySize = 2049;
|
||||
check(refused(deep), "3D depth 2049 refused");
|
||||
XgResourceDesc arr = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 16, 16, 1, kLayoutLinear);
|
||||
arr.DepthOrArraySize = 2049;
|
||||
check(refused(arr), "array size 2049 refused");
|
||||
}
|
||||
|
||||
int main() {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
HMODULE xg = LoadLibraryA("xg_xs.dll");
|
||||
@@ -455,13 +346,12 @@ int main() {
|
||||
test_64kb_s_32bpp();
|
||||
test_64kb_s_bc1();
|
||||
test_64kb_s_128bpp();
|
||||
test_tiling_limits_and_methods();
|
||||
test_refusals_and_suggest(suggest);
|
||||
if (g_failures) {
|
||||
std::printf("FAIL: test_xg_xbox: %d of %d checks failed\n", g_failures, g_checks);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_xg_xbox (%d checks: linear mips, depth/stencil planes, BC1, buffer, tiling, limits, SW_64KB_S vs D3D12 "
|
||||
std::printf("PASS: test_xg_xbox (%d checks: linear mips, depth/stencil planes, BC1, buffer, SW_64KB_S vs D3D12 "
|
||||
"standard swizzle, linear fallbacks)\n",
|
||||
g_checks);
|
||||
return 0;
|
||||
|
||||
@@ -1021,107 +1021,6 @@ int main() {
|
||||
slot<CloseFn>(package, kCloseMount)(package, mount);
|
||||
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == kInvalidHandle);
|
||||
|
||||
// Installation monitors (documented XPackage functions; IXPackageImpl slots 5-10). Offline the
|
||||
// running package is fully installed and its inst never changes.
|
||||
struct Progress {
|
||||
uint64_t totalBytes, installedBytes, launchBytes;
|
||||
bool launchable, completed;
|
||||
};
|
||||
using CreateMonitorFn = HRESULT(WINAPI*)(void*, const char*, uint32_t, const void*, uint32_t, void*, void**);
|
||||
using MonitorVoidFn = void(WINAPI*)(void*, void*);
|
||||
using ProgressFn = void(WINAPI*)(void*, void*, Progress*);
|
||||
using UpdateFn = bool(WINAPI*)(void*, void*);
|
||||
using RegisterFn = HRESULT(WINAPI*)(void*, void*, void*, void*, uint64_t*);
|
||||
using UnregisterFn = bool(WINAPI*)(void*, void*, uint64_t, bool);
|
||||
struct Details {
|
||||
const char* packageIdentifier;
|
||||
uint16_t version[4];
|
||||
uint32_t kind;
|
||||
const char *displayName, *description, *publisher, *storeId;
|
||||
bool installing;
|
||||
uint32_t index, count;
|
||||
bool ageRestricted;
|
||||
const char* titleId;
|
||||
};
|
||||
using EnumCallback = bool(CALLBACK*)(void*, const Details*);
|
||||
using EnumFn = HRESULT(WINAPI*)(void*, uint32_t, uint32_t, void*, EnumCallback);
|
||||
auto progress_cb = [](void*, void*) {};
|
||||
void* pk = nullptr; // the public IXPackageImpl object (QueryApiImpl, IXPackageImpl4)
|
||||
{
|
||||
const GUID cls = guid_bytes(0xAF406016, 0xE850, 0x4AA8, 0xA8, 0x8D, 0x2F, 0x3D, 0xCB, 0x9D, 0xAC, 0x7E);
|
||||
const GUID iid4 = guid_bytes(0x0B9D556E, 0xAB70, 0x43F4, 0xBA, 0xA0, 0x99, 0x99, 0xAC, 0x4C, 0xB0, 0x40);
|
||||
CHECK(QueryApiImpl(&cls, &iid4, &pk) == S_OK && pk);
|
||||
}
|
||||
void* monitor = nullptr;
|
||||
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, id, 0, nullptr, 0, nullptr, nullptr) == E_POINTER);
|
||||
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, nullptr, 0, nullptr, 0, nullptr, &monitor) == E_INVALIDARG);
|
||||
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, "BXPKG0000000000000000", 0, nullptr, 0, nullptr,
|
||||
&monitor) == kNotFound && !monitor);
|
||||
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, id, 0, nullptr, 0, nullptr, &monitor) == S_OK && monitor);
|
||||
Progress inst{};
|
||||
slot<ProgressFn>(pk, kPkGetProgress)(pk, monitor, &inst);
|
||||
CHECK(inst.totalBytes == 1 && inst.installedBytes == 1 && inst.launchBytes == 1 && inst.launchable &&
|
||||
inst.completed);
|
||||
CHECK(!slot<UpdateFn>(pk, kPkUpdateMonitor)(pk, monitor));
|
||||
uint64_t token = 0, token2 = 0;
|
||||
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, nullptr, &token) == E_INVALIDARG);
|
||||
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
|
||||
nullptr) == E_POINTER);
|
||||
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
|
||||
&token) == S_OK && token);
|
||||
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
|
||||
&token2) == S_OK && token2 != token);
|
||||
CHECK(slot<UnregisterFn>(pk, kPkUnregisterProgress)(pk, monitor, token, true));
|
||||
CHECK(!slot<UnregisterFn>(pk, kPkUnregisterProgress)(pk, monitor, token, true)); // already removed
|
||||
slot<MonitorVoidFn>(pk, kPkCloseMonitor)(pk, monitor);
|
||||
slot<MonitorVoidFn>(pk, kPkCloseMonitor)(pk, monitor); // a second close is harmless
|
||||
inst = {7, 7, 7, true, true};
|
||||
slot<ProgressFn>(pk, kPkGetProgress)(pk, monitor, &inst);
|
||||
CHECK(inst.totalBytes == 0 && !inst.completed); // a closed handle reports nothing
|
||||
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
|
||||
&token) == kInvalidHandle);
|
||||
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, id, 0, nullptr, 0, nullptr, &monitor) == S_OK);
|
||||
void* survivor = monitor; // checked stale after the uninitialize below
|
||||
|
||||
// XPackageEnumeratePackages (slots 28, 35, 39): this game for Game (documented for ThisOnly),
|
||||
// no packages for Content.
|
||||
struct Seen {
|
||||
int count = 0;
|
||||
std::string id;
|
||||
uint32_t kind = 99;
|
||||
} seen;
|
||||
EnumCallback collect = [](void* ctx, const Details* d) {
|
||||
auto* out = static_cast<Seen*>(ctx);
|
||||
++out->count;
|
||||
out->id = d->packageIdentifier;
|
||||
out->kind = d->kind;
|
||||
return true;
|
||||
};
|
||||
for (int s : {kPkEnumPackages, kPkEnumPackages2, kPkEnumPackages3}) {
|
||||
seen = {};
|
||||
CHECK(slot<EnumFn>(pk, s)(pk, 0, 0, &seen, collect) == S_OK); // Game, ThisOnly
|
||||
CHECK(seen.count == 1 && seen.id == id && seen.kind == 0);
|
||||
seen = {};
|
||||
CHECK(slot<EnumFn>(pk, s)(pk, 1, 0, &seen, collect) == S_OK && seen.count == 0); // Content
|
||||
CHECK(slot<EnumFn>(pk, s)(pk, 0, 0, &seen, nullptr) == E_INVALIDARG);
|
||||
}
|
||||
{
|
||||
// The accepted, never-fired registration is visible in the JSONL log (bx-cli trace).
|
||||
char log_path[MAX_PATH]{};
|
||||
std::string log;
|
||||
if (GetEnvironmentVariableA("BX_LOG_FILE", log_path, MAX_PATH)) {
|
||||
HANDLE f = CreateFileA(log_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
if (f != INVALID_HANDLE_VALUE) {
|
||||
char buf[65536];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) log.append(buf, got);
|
||||
CloseHandle(f);
|
||||
}
|
||||
}
|
||||
CHECK(log.find("\"event\":\"XPackageRegisterInstallationProgressChanged\"") != std::string::npos &&
|
||||
log.find("callback is never called") != std::string::npos);
|
||||
}
|
||||
|
||||
// --- Uninitialize then reinitialize: old handles stay dead, queued work does not run ---
|
||||
{
|
||||
void* old_container = saves.container(provider, "profiles/main");
|
||||
@@ -1172,11 +1071,6 @@ int main() {
|
||||
CHECK(saves.read_status(old_container, {}) == kInvalidHandle);
|
||||
CHECK(saves.write(old_update, "x", "x", 1) == kInvalidHandle);
|
||||
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, old_mount, &path_size) == kInvalidHandle);
|
||||
Progress stale_progress{7, 7, 7, true, true};
|
||||
slot<ProgressFn>(pk, kPkGetProgress)(pk, survivor, &stale_progress);
|
||||
CHECK(stale_progress.totalBytes == 0); // uninitialize closed every monitor
|
||||
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, survivor, nullptr,
|
||||
reinterpret_cast<void*>(+progress_cb), &token) == kInvalidHandle);
|
||||
|
||||
void* fresh_user = add_user(queue);
|
||||
void* fresh = saves.provider(fresh_user);
|
||||
|
||||
Reference in new issue
Block a user