mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-12-03 03:22:28 +00:00
Compare commits
68
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cb858e6f5 | ||
|
|
b36e397681 | ||
|
|
5bc4ff5cf4 | ||
|
|
5e204bd883 | ||
|
|
5c2e2c9b63 | ||
|
|
77dd9ffef3 | ||
|
|
abecde1c39 | ||
|
|
e532fc56ba | ||
|
|
4c5cd55884 | ||
|
|
ec3dea9942 | ||
|
|
1fed04a80c | ||
|
|
a9efeffc6f | ||
|
|
365b411fed | ||
|
|
1b4b1bf7d7 | ||
|
|
aeac1892c1 | ||
|
|
a9674bf9c7 | ||
|
|
eee9a4fcdc | ||
|
|
fe28c5c2af | ||
|
|
e21f41ae24 | ||
|
|
506defdd45 | ||
|
|
64141e9ae6 | ||
|
|
04148f77f8 | ||
|
|
5a6e786850 | ||
|
|
34f744aa5d | ||
|
|
afc093ee54 | ||
|
|
224586917f | ||
|
|
2af3e7d10a | ||
|
|
17e2e2a835 | ||
|
|
3ec40ba7fb | ||
|
|
b3aad0d948 | ||
|
|
277edd592a | ||
|
|
d4996ba9fd | ||
|
|
ca2b48ef83 | ||
|
|
dc41f00cb3 | ||
|
|
1b04d6e237 | ||
|
|
9116c0a39e | ||
|
|
b96a9b5978 | ||
|
|
dcec248837 | ||
|
|
40b5ee7a8e | ||
|
|
b975e6335b | ||
|
|
8f4786e436 | ||
|
|
0c398214fa | ||
|
|
78b56747fb | ||
|
|
63bd059182 | ||
|
|
24b124e144 | ||
|
|
cff3e754a9 | ||
|
|
27bfa17cb1 | ||
|
|
261d71d8d1 | ||
|
|
2cc64bd617 | ||
|
|
d99e35ad42 | ||
|
|
f7748387da | ||
|
|
28a9c868e6 | ||
|
|
6cfade83fe | ||
|
|
c963b9bc1a | ||
|
|
30197aa236 | ||
|
|
957b8efb21 | ||
|
|
e04a3b3f62 | ||
|
|
ea29d3fc56 | ||
|
|
d724c6c013 | ||
|
|
43cb1aab54 | ||
|
|
af869008a0 | ||
|
|
84f4370227 | ||
|
|
79e1906c27 | ||
|
|
d65c12f6a9 | ||
|
|
3f2f2732ed | ||
|
|
7c807d8b3a | ||
|
|
ca2ad143f9 | ||
|
|
0b474941f0 |
No files matched your search
@@ -4,46 +4,59 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
## 0. What to Do When Told "Work"
|
||||
|
||||
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:
|
||||
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **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.
|
||||
**"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.
|
||||
|
||||
---
|
||||
|
||||
@@ -121,7 +134,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; 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 (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
|
||||
### Merge eligibility
|
||||
|
||||
@@ -10,15 +10,67 @@ 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.
|
||||
|
||||
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`.
|
||||
- **Samplers and page pools.**
|
||||
- **Pipelines** through the shader gate.
|
||||
- **Opt-in null rendering** (`BX_NULL_RENDER=1`): pipelines that cannot be built become null pipelines, and their draws and dispatches are skipped and logged.
|
||||
- **Fences** at GPU addresses and GPU value writes.
|
||||
- **`PresentX`** onto a DXGI swapchain.
|
||||
- **Console page mappings:** `CopyPageMappingsX`, `CopyPageMappingsBatchX` and `ClearPageMappingsX`.
|
||||
- **The full 1,384-byte Xbox command-list area.**
|
||||
- **Opt-in dumps of presented frames** (`BX_PRESENT_DUMP`).
|
||||
|
||||
`test_d3d12_xbox_layout` checks the page mappings and the command-list area.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
|
||||
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
|
||||
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
|
||||
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
|
||||
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
|
||||
- `d3d12_xs.dll` gives titles Xbox-layout D3D12 objects ([ADR 0009](docs/adr/0009-xbox-layout-d3d12-objects.md)). A title built against the Xbox Series D3D12 header calls through function tables whose order differs from PC D3D12. `ID3D12Device` matches only up to slot 43, and `ID3D12Device11` has 139 slots. So before, every call past those slots reached the wrong PC method, and on a project-authorized target build the first such call jumped to address 0.
|
||||
- **Objects and tables:** `BxXboxObject` (`shims/d3d12_xs/xbox_facade.{h,cpp}`) has the Xbox object layout and sets `m_OutOfLineFlags`. Its Xbox-order table forwards to the PC proxies. `shims/d3d12_xs/tools/gen_xbox_tables.py` generates the tables (`xbox_tables_generated.cpp`) from the Xbox header, used under Microsoft's authorization, and the toolchain's `<d3d12.h>`. It takes only slot order, names, IIDs and parameter types, and the header is not committed.
|
||||
- **Slots:** a slot with an equivalent PC signature forwards with the PC types, unwrapping interface parameters and wrapping created objects. Every other slot logs `BX_VTABLE_STUB_LOG`.
|
||||
- **Coverage:** the device chain up to `ID3D12Device11`, plus resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues. Command lists are not covered yet.
|
||||
- **`CreateCommandQueueX`:** maps the Xbox queue description onto PC `CreateCommandQueue`.
|
||||
- **Layout choice:** titles set `Version` in the device parameter block and get the Xbox layout. BetterXen's PC-layout fixtures pass a zeroed block and keep the PC proxy. The choice is logged as `xbox_layout`.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, created through `CreateCommandListX` or `CreateCommandList`. Their zeroed put-buffer fields force the five inline fast paths through the table.
|
||||
- **Embedded interface pointers:** `ResourceBarrier` and `CopyTextureRegion` unwrap the interface pointers inside their structures.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` are emulated by a host timer (`frame_pacing.cpp`).
|
||||
- **Generator fixes:** CRLF lines, a table-boundary overrun that hid `ID3D12GraphicsCommandList1`, nested SAL, and `FLOAT`.
|
||||
- **Resources at title-chosen addresses:** `CreatePlacedResourceX`/`X1` create host shadow resources (`placed_x.cpp`), with buffer contents copied from the title's memory at creation. The resource reports the title's address from `GetGPUVirtualAddress`. Ongoing synchronisation, GPU-to-CPU copies, title-address translation in GPU calls and texture contents are not implemented yet.
|
||||
- **Test:** `tests/conformance/test_d3d12_xbox_layout/` calls Xbox slots by number, with the slot numbers and offsets written out by hand from the header and the expected values taken from a PC-layout device. It also records a buffer copy through Xbox command objects, runs it on the GPU and reads the result back, and checks frame pacing. It fails against the previous DLL (8 checks against the Phase 1 build).
|
||||
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
|
||||
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
|
||||
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
|
||||
@@ -30,7 +82,27 @@ 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`.
|
||||
- `xmem.dll` follows the documented signatures of five exports (source: the authorized GDK documentation). Before, a title calling them as documented had its arguments misread: on a project-authorized target build, `XMemAllocatePhysicalPages` failed and the title's check broke into its crash reporter. `XMemAllocatePhysicalPages` accepts `MEM_64K_PAGES` (`MEM_2MB_PAGES | MEM_PHYSICAL`) as 64 KB pages, as Microsoft's public samples pass it; the `MEM_2MB_PAGES` bit alone is `XMEM_2MB_CLUSTERS`, still unimplemented and logged. `test_xmem_physical` adds the samples' shape: a `MEM_64K_PAGES` page mapped into a mappable reservation made with protection `0x2404`.
|
||||
- **Signatures:** `XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray)`, `XMemFreePhysicalPages(NumberOfPages, PageArray)` (count by value), `XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray)` and `XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)` (parallel arrays, returns `BOOL`). `XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection)` takes five arguments, which supersedes the closed #518.
|
||||
- **Pages and flags:** physical pages are always 64 KB. The four memory-bandwidth values are accepted. `XMEM_2MB_CLUSTERS` and mapping into `MEM_2MB_PAGES` reservations are not implemented: they log `BX_STUB_LOG` and fail with `ERROR_NOT_SUPPORTED`. Other flag bits fail with `ERROR_INVALID_PARAMETER`.
|
||||
- **Mapping:** `XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)` reserves a placeholder, and `XMemMapPhysicalPages` maps into it. It replaces pages already mapped there, a NULL page array unmaps, and an unmapped range stays reserved and can be mapped again. Scatter checks every entry before changing any, and a 0 tag unmaps its slot. Mapping outside a mappable reservation is refused. A NULL address remains a BetterXen extension for synthetic fixtures: the shim picks the span, and unmapping it frees it.
|
||||
- **Title-managed placeholders:**
|
||||
- `XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)` reserves a placeholder the title splits itself with `VirtualFree(MEM_PRESERVE_PLACEHOLDER)`.
|
||||
- `MEM_REPLACE_PLACEHOLDER` with `XMEM_MAPPABLE` turns a split part into a mappable range without a new reservation. It is refused unless the part is still a placeholder.
|
||||
- `XMEM_GRAPHICS_32BIT_ADDRESS` keeps new reservations below 4 GB.
|
||||
- The `PAGE_GRAPHICS_*` protection bits set a GPU view the host does not have, so mapped views use the low-byte CPU protection.
|
||||
- Replacing a placeholder with committed memory is not implemented and logs `BX_STUB_LOG`.
|
||||
- A project-authorized target build lays out its descriptor memory this way.
|
||||
- **Tests:** `test_xmem_physical` is rewritten against the documented contracts, with constants written out from the documentation, and fails against the previous `xmem.dll`. `test_xmem`, `test_xmem_external_charge`, `test_d3d12_placed`, `test_d3d12_vmem_xbox`, `test_m2_first_frame` and `test_integration_boot` use the documented signatures.
|
||||
- **Not covered:** `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` still differ from their documented signatures (#642).
|
||||
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
|
||||
- `d3d12_xs.dll!D3D12XboxCreateDevice` takes the documented four parameters `(pAdapter, pParameters, riid, ppDevice)`. Before, it took three `(params, riid, ppv)`, so a title calling it as documented had its interface ID treated as the out pointer, and the shim wrote through it. On a project-authorized target build that faulted on a write into read-only data. Source: the authorized GDK documentation of the function and of `D3D12XBOX_CREATE_DEVICE_PARAMETERS`. A NULL parameter block now fails with `E_INVALIDARG`, as documented. A non-NULL adapter is logged and the default host adapter is used, which is an inference, since BetterXen has no adapter objects. Of the parameter block only `Version` is read and logged. All fixtures that create a device pass a zeroed 80-byte parameter block. `test_d3d12_xs` checks the NULL-parameter refusal and that it clears the out pointer.
|
||||
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
|
||||
|
||||
+5
-1
@@ -3,7 +3,8 @@
|
||||
## Getting Started & Architecture
|
||||
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
|
||||
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
@@ -16,15 +17,18 @@
|
||||
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
|
||||
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
|
||||
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
|
||||
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
|
||||
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [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
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# ADR 0009: Xbox-layout D3D12 objects in d3d12_xs
|
||||
|
||||
Status: **Proposed** (2026-11-28). Phase 1 is implemented with this ADR; the maintainers decide whether the direction stands. The evidence is from local Apple Silicon runs by the implementer and has not been independently reproduced.
|
||||
|
||||
## Context
|
||||
|
||||
`d3d12_xs.dll` handed titles PC D3D12 objects: C++ proxies (`proxy.h`, `proxy_generated.cpp`) whose vtables follow the PC `<d3d12.h>` order. A title built against the Xbox Series D3D12 header (`d3d12_xs.h`, part of the GDK material Microsoft authorized the project to use) calls through each object's **function table**, and that order is different:
|
||||
|
||||
| Interface | Xbox slots | PC slots | Orders agree up to |
|
||||
| --- | --- | --- | --- |
|
||||
| `ID3D12Device` | 83 | 44 | slot 43. Xbox then adds 39 methods (`CreatePlacedResourceX`, `CreateCommandQueueX`, ...) before `ID3D12Device1`. |
|
||||
| `ID3D12Device11` (chain) | 139 | — | `ID3D12Device11` is the interface a project-authorized target build asks for. |
|
||||
| `ID3D12GraphicsCommandList` | 107 | 60 | slot 27 |
|
||||
| `ID3D12CommandQueue` | 38 | 19 | slot 13 |
|
||||
|
||||
So every call past those slots reached the wrong PC method. On the target build, the first call on the device after `QueryInterface(ID3D12Device11)` jumped to address 0.
|
||||
|
||||
From the same header:
|
||||
- **Base layout:** every object starts with the table pointer, a 32-bit flags word and `m_RefCount`, 16 bytes in all.
|
||||
- **`ID3D12Device` fields:** a 64-bit null constant-buffer address at +16 and a 64-byte union at +24. The union's first byte, `m_OutOfLineFlags`, makes the two inline device helpers (`CopyDescriptorsSimple`, `CreateConstantBufferView`) call out through the table when it is non-zero. That holds unless a title is compiled with `D3DCOMPILE_NO_DEBUG`, in which case they write descriptors inline.
|
||||
- **Command lists:** they add a put buffer and CPU state. Of their 76 inline methods, 71 call the table. The other five write command packets directly when the next write fits below `m_Putter`'s limits, and call the table otherwise.
|
||||
- **IIDs:** the interface IDs of shared interfaces are the PC ones (`ID3D12Device` `189819f1-…`, `ID3D12Resource` `696442be-…`).
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Xbox-layout objects:** titles get `BxXboxObject`s (`xbox_facade.h`). They have the Xbox object layout, with `m_OutOfLineFlags` set, and an Xbox-order function table. Each object hosts a PC object, normally one of the existing proxies, so their logging, shader gate, heap hooks and wrapping stay in force.
|
||||
2. **Generated tables:** `tools/gen_xbox_tables.py` reads the Xbox header locally and the toolchain's `<d3d12.h>`, and writes `xbox_tables_generated.cpp`. It takes only slot order, names, IIDs and parameter types from the Xbox header. The header is never committed.
|
||||
- **Forwarders:** a slot whose Xbox and PC signatures are equivalent gets a typed forwarder written with the PC types. That includes the free-function versus member struct-return difference, so the compiler produces the right calling convention. Interface pointers passed in are unwrapped, and `(REFIID, void**)` results are wrapped.
|
||||
- **Stubs:** every other slot is a `BX_VTABLE_STUB_LOG` stub.
|
||||
- **Hand-written slots:** Xbox-only methods are implemented in `xbox_facade.cpp` as titles need them.
|
||||
3. **Who gets which layout:** titles set `Version` in the `D3D12XBOX_CREATE_DEVICE_PARAMETERS` block they pass to `D3D12XboxCreateDevice`, and the documentation requires it. Those calls get the Xbox layout. BetterXen's synthetic fixtures are PC-layout clients built against `<d3d12.h>`, pass a zeroed block, and keep the PC proxy. The log records which layout was chosen (`xbox_layout`).
|
||||
4. **Command lists (Phase 2):** command lists get an Xbox object whose zeroed put-buffer pointers fail every inline room check, so every call reaches the table.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Phase 1 (this change):**
|
||||
- The device chain up to `ID3D12Device11` is covered: 139 slots, 75 forwarded, 4 shared or hand-written, 60 stubs.
|
||||
- So are the objects it creates: resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues.
|
||||
- `CreateCommandQueueX` maps the Xbox queue description onto PC `CreateCommandQueue`. The engine and queue indices are logged and not used.
|
||||
- On the target build, the title now creates its device and four compute queues, and stops at `CreateCommandListX`, which is Phase 2.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, 150 slots: 75 forwarded, 6 shared or hand-written, 69 stubs. They are created through `CreateCommandListX` and the PC `CreateCommandList`, and their Xbox field area is zeroed, so the five inline fast paths call through the table.
|
||||
- **Interface pointers inside structures:** `ResourceBarrier` and `CopyTextureRegion` unwrap them before the host call. The Xbox `ResourceBarrier` returns 0 actions.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` (`frame_pacing.cpp`) are emulated from the recorded interval by a host timer. It signals the origin, vblank and flip events and their ancillary handles, and gives out frame-pipeline tokens as documented.
|
||||
- **Generator fixes:** CRLF lines in parts of the header, a table definition whose end the boundary pattern ran past (it hid `ID3D12GraphicsCommandList1`), SAL annotations with nested parentheses, and `FLOAT`/`float`.
|
||||
- **Resources at title-chosen addresses** (`placed_x.cpp`), translation by copy:
|
||||
- `CreatePlacedResourceX` and `CreatePlacedResourceX1` create a host shadow resource. A buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's memory at creation; a texture gets a committed texture whose contents are not filled, which is logged.
|
||||
- The resource reports the title's address from `GetGPUVirtualAddress`.
|
||||
- Not yet done: keeping shadows in step with later CPU writes (planned: page-protection dirty tracking, copying at submit), copying GPU writes back, and translating title addresses in GPU calls.
|
||||
- **On the target build:** the title creates 581 command lists, sets a 30 Hz interval and schedules its origin and flip events. It then lays out its own descriptor memory with `xmem` placeholders (#643) and creates a 174 MB buffer at a title-chosen address through `CreatePlacedResourceX1`, now served by a shadow.
|
||||
- **Where it stops:** the title creates a descriptor heap and requires `GetCPUDescriptorHandleForHeapStart` to equal an address in its own descriptor memory. D3DMetal returns an opaque handle.
|
||||
- **What that needs:** BetterXen-owned descriptor heaps whose handles are addresses, translated to host descriptors when used. That is the descriptor-heap item under Consequences.
|
||||
- **Fixtures:** the existing fixtures are unaffected, since they use the PC layout. `tests/conformance/test_d3d12_xbox_layout` calls Xbox slots by number, with the expected results taken from a PC-layout device. It fails against the previous `d3d12_xs.dll`.
|
||||
- **What the fixture can and cannot show:** its slot numbers and object offsets are written by hand, but from the same header the generator reads. It shows that the generator and the fixture agree. It cannot show that either read the header correctly; only an independent re-derivation from the header, or a title running further, can.
|
||||
- **On a host without the forwarded interface** (vkd3d stops at `ID3D12Device9`): the Xbox-layout device is refused with `E_NOINTERFACE` and logged. The fixture verifies the refusal and skips (exit 77). `bx_xbox_wrap` refuses the same way for every wrapped family, so a title never gets a PC object where it expects an Xbox one.
|
||||
- **Frame pacing:** the emulated frame interval follows host `Sleep` and is not synchronised to the display. The pacing thread is detached and never exits, which is safe only while `d3d12_xs.dll` stays loaded for the life of the process.
|
||||
- **Descriptor heaps:** a title compiled with `D3DCOMPILE_NO_DEBUG` writes console-format descriptors straight into descriptor-heap memory and computes handles with Xbox descriptor sizes. Supporting that needs BetterXen-owned descriptor heaps translated at bind time, which is not part of this ADR.
|
||||
- **Identity:** QueryInterface on an Xbox object for another wrapped family returns that family's Xbox object over the same host. A host reached through another path, such as `GetDevice` returning the raw host device, may get a second Xbox object.
|
||||
- **Replacing the PC proxy:** this ADR supersedes the PC proxy for titles. Whether the PC proxy is eventually removed in favour of fixtures that use the Xbox layout is left open.
|
||||
@@ -268,3 +268,13 @@ retrieved = "2026-11-22"
|
||||
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
|
||||
test = "Read slides 12 and 13. No console execution."
|
||||
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
|
||||
|
||||
[[claim]]
|
||||
id = "CLAIM-XBOX-CS-ENTRY-ABI"
|
||||
class = "U"
|
||||
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
|
||||
sources = ["docs/research/console-shader-abi.md"]
|
||||
retrieved = "2026-11-28"
|
||||
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
|
||||
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
|
||||
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
|
||||
@@ -0,0 +1,200 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,75 @@
|
||||
# Console compute shader entry ABI (probe results)
|
||||
|
||||
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
|
||||
|
||||
What this is:
|
||||
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
|
||||
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
|
||||
|
||||
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
|
||||
|
||||
## Method
|
||||
|
||||
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
|
||||
|
||||
| Probe | Root signature | Shader |
|
||||
| --- | --- | --- |
|
||||
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
|
||||
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
|
||||
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
|
||||
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
|
||||
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
|
||||
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
|
||||
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
|
||||
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
|
||||
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
|
||||
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
|
||||
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
|
||||
|
||||
## Observations
|
||||
|
||||
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
|
||||
|
||||
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
|
||||
- A root constant takes one SGPR (p01: `s4`–`s7`).
|
||||
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
|
||||
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
|
||||
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
|
||||
|
||||
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
|
||||
|
||||
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
|
||||
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
|
||||
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
|
||||
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
|
||||
|
||||
**Descriptor tables.** Descriptors are loaded from the table address:
|
||||
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
|
||||
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
|
||||
|
||||
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
|
||||
|
||||
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
|
||||
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
|
||||
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
|
||||
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
|
||||
|
||||
## Open
|
||||
|
||||
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
|
||||
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
|
||||
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
|
||||
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
|
||||
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
|
||||
- **`s0`–`s3`:** what they hold when root data fits in registers.
|
||||
- **One compiler build, one host:** a different GDK version may differ.
|
||||
|
||||
## Provenance
|
||||
|
||||
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
|
||||
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
|
||||
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
|
||||
+15
-9
@@ -137,8 +137,10 @@ not define the patterns.
|
||||
|
||||
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
|
||||
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
|
||||
not public, so BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are **local** constants,
|
||||
not the console's.
|
||||
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
|
||||
interface have been retired: `xg_xs.dll` now follows the documented XG contract
|
||||
titles call, with values from the authorized GDK documentation recorded as derived
|
||||
facts in `shims/xg_xs/xg_xbox.cpp`.
|
||||
|
||||
### Element sizes and the derived masks
|
||||
|
||||
@@ -164,11 +166,15 @@ distinct offsets, each block-aligned and inside the tile).
|
||||
### Verification
|
||||
|
||||
The three masks above were expanded and their bijectivity checked against an
|
||||
independently written `pdep` reference, outside the shim. `test_xg_xs.exe`
|
||||
re-derives its expected offsets from those masks (and, at 32 bpp, from the
|
||||
D3D12 page) rather than reading them back from the shim: one test per block
|
||||
size, covering intra-block offsets (the 16 texels of a BC block share one byte
|
||||
offset), independently derived absolute offsets, and an offset -> texel -> offset
|
||||
round trip. It keeps asserting `E_NOTIMPL` for `SW_64KB_D`, `SW_64KB_R`, 1D/3D,
|
||||
MSAA, and every multi-mip or multi-slice case. Synthetic evidence only; no
|
||||
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
|
||||
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
|
||||
back from the shim:
|
||||
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
|
||||
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
|
||||
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
|
||||
the offsets are a bijection of aligned slots inside the 64 KiB tile;
|
||||
- it checks that the 16 texels of a BC block share one byte offset.
|
||||
|
||||
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
|
||||
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
|
||||
Xbox-hardware claim.
|
||||
+81
-20
@@ -1,6 +1,6 @@
|
||||
# BetterXen Roadmap
|
||||
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
|
||||
## Direction
|
||||
|
||||
@@ -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**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
|
||||
|
||||
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
|
||||
|
||||
@@ -35,34 +35,95 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
---
|
||||
|
||||
## Milestones (M0 → M6)
|
||||
## Foundation and stages
|
||||
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
|
||||
|
||||
### Foundation (history)
|
||||
|
||||
| Milestone | What it established | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
|
||||
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
|
||||
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
|
||||
|
||||
### The stages
|
||||
|
||||
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
|
||||
|
||||
| Stage | The target build… | Exit gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 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 |
|
||||
| **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 |
|
||||
|
||||
### Startup diagnosis
|
||||
"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)).
|
||||
|
||||
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.
|
||||
### Boot
|
||||
|
||||
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.
|
||||
**Known work, all found by running the target build:**
|
||||
|
||||
### M2 first-frame acceptance and parallel memory work
|
||||
| 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/` |
|
||||
|
||||
- **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.
|
||||
**Not needed for the gate:** audio output, correct pictures, performance.
|
||||
|
||||
### Picture
|
||||
|
||||
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
|
||||
|
||||
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
|
||||
2. **The translator.** Vendor a pinned copy of the authorized upstream GFX10-to-DXIL translator into `shader-transpiler/` (per-file licence check, upstream registry and reuse matrix entries, ADR 0008 amendment), and expose it through `bx_shader_bridge.dll`. BetterXen owns its copy and fixes it.
|
||||
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
|
||||
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
|
||||
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
|
||||
|
||||
### Menus to Playable — known work and unknowns
|
||||
|
||||
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
|
||||
|
||||
| Stage | Known work | Main unknown |
|
||||
| --- | --- | --- |
|
||||
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
|
||||
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
|
||||
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
|
||||
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
|
||||
|
||||
### Decision gates
|
||||
|
||||
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
|
||||
|
||||
| Gate | When | Question | If the answer is no |
|
||||
| --- | --- | --- | --- |
|
||||
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
|
||||
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
|
||||
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
|
||||
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
|
||||
|
||||
### What counts as progress
|
||||
|
||||
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
|
||||
|
||||
1. remove a blocker of the current stage (shown by the run report before and after);
|
||||
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
|
||||
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
|
||||
4. retire a risk at a decision gate.
|
||||
|
||||
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
|
||||
|
||||
---
|
||||
|
||||
## How Progress Is Reported
|
||||
|
||||
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
|
||||
|
||||
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
|
||||
@@ -0,0 +1,137 @@
|
||||
# Target-Build Bring-Up: Development Cycle and Review
|
||||
|
||||
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
|
||||
|
||||
## Authorization is recorded, not assumed
|
||||
|
||||
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
|
||||
|
||||
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
|
||||
- the build;
|
||||
- the evidence class: target-build observation, or authorized SDK documentation;
|
||||
- the maintainer who approved it;
|
||||
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
|
||||
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
|
||||
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
|
||||
- **The note's ID goes into every PR and every review** that relies on that evidence.
|
||||
|
||||
## Roles
|
||||
|
||||
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
|
||||
- **Author.** Turns one finding into one single-track PR.
|
||||
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
|
||||
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
|
||||
|
||||
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
|
||||
|
||||
## Cycle
|
||||
|
||||
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
|
||||
2. **Record the evidence privately,** under an evidence note ID.
|
||||
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
|
||||
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
|
||||
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
|
||||
6. **Review independently** (see "What a reviewer does").
|
||||
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
|
||||
|
||||
### Bring-up checkpoints
|
||||
|
||||
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
|
||||
|
||||
1. **Starts:** reaches its first graphics device.
|
||||
2. **Presents:** presents its first frame, whatever it contains.
|
||||
3. **Frame loop:** keeps presenting for a recorded duration.
|
||||
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
|
||||
5. **Interactive:** reaches a menu that accepts input.
|
||||
|
||||
Each PR states which checkpoint it affects, and the measured result before and after.
|
||||
|
||||
## PR description template
|
||||
|
||||
```text
|
||||
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
|
||||
Source: "authorized SDK documentation" and/or "target-build observation";
|
||||
never quote header or documentation text, never name the title or build
|
||||
Authorization: authorization note ID
|
||||
Evidence: evidence note ID(s)
|
||||
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
|
||||
Test: the conformance test that asserts the contract, and how its expected
|
||||
values were derived independently of the implementation
|
||||
Checkpoint: the checkpoint this affects, with the measured result before and after
|
||||
```
|
||||
|
||||
## What a reviewer does
|
||||
|
||||
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
|
||||
|
||||
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
|
||||
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
|
||||
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
|
||||
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
|
||||
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
|
||||
|
||||
## Offline-run procedure
|
||||
|
||||
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
|
||||
|
||||
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
|
||||
|
||||
```sh
|
||||
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
|
||||
BOTTLE=<bottle name>
|
||||
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
|
||||
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
|
||||
|
||||
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
|
||||
# serve the title outside it.
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
|
||||
|
||||
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
|
||||
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
|
||||
&& echo REACHABLE || echo BLOCKED
|
||||
|
||||
# 3. Run the title inside the same profile. Every process it starts, including the new
|
||||
# wineserver, inherits the sandbox.
|
||||
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
|
||||
BX_TRACE_D3D=0 BX_NULL_RENDER=1 \
|
||||
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
|
||||
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
|
||||
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
|
||||
```
|
||||
|
||||
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
|
||||
|
||||
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
|
||||
|
||||
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
|
||||
|
||||
| Switch | Where | Effect |
|
||||
| --- | --- | --- |
|
||||
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
|
||||
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
|
||||
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
|
||||
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
|
||||
|
||||
Their output can contain title addresses and file names, so it goes only into the private evidence store.
|
||||
|
||||
## Evidence
|
||||
|
||||
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
|
||||
|
||||
## What never enters the repository
|
||||
|
||||
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
|
||||
|
||||
- SDK header or documentation text;
|
||||
- the title's name or file names;
|
||||
- identifiers derived from the title or build: its hashes, addresses or raw logs;
|
||||
- decompiled code or disassembly;
|
||||
- screenshots of the title;
|
||||
- personal paths.
|
||||
|
||||
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
|
||||
@@ -41,6 +41,21 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
|
||||
"XPC_SERVICE_NAME",
|
||||
];
|
||||
|
||||
/// Opt-in `bx_runtime_veh.dll` diagnostic switches. They carry addresses and counts, never
|
||||
/// credentials, so the isolated guest environment lets them through by name; every other
|
||||
/// variable is still stripped.
|
||||
const DIAGNOSTIC_ENV_ALLOWLIST: &[&str] = &[
|
||||
"BX_VEH_AV_CONTEXT",
|
||||
"BX_VEH_AV_ALL",
|
||||
"BX_VEH_WATCH",
|
||||
"BX_VEH_WATCH_RANGE",
|
||||
"BX_VEH_WATCH_RANGE_MAX",
|
||||
"BX_VEH_HIT",
|
||||
"BX_VEH_HIT_ALL",
|
||||
"BX_VEH_HIT_RDX",
|
||||
"BX_VEH_SAMPLE",
|
||||
];
|
||||
|
||||
fn usage_text() -> &'static str {
|
||||
"BetterXen Hybrid CLI (bx-cli)\n\
|
||||
\n\
|
||||
@@ -375,6 +390,40 @@ fn render_trace(text: &str) -> String {
|
||||
);
|
||||
}
|
||||
}
|
||||
if !summary.breakpoint_exceptions.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nBreakpoint/assert exceptions, first chance ({}):",
|
||||
summary.breakpoint_exceptions.len()
|
||||
);
|
||||
for hit in &summary.breakpoint_exceptions {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" code={} {} + RVA={} (module_base={} address={})",
|
||||
hit.exception_code.as_deref().unwrap_or("unknown"),
|
||||
hit.module.as_deref().unwrap_or("?"),
|
||||
hit.rva.as_deref().unwrap_or("unknown"),
|
||||
hit.module_base.as_deref().unwrap_or("unknown"),
|
||||
hit.address.as_deref().unwrap_or("unknown"),
|
||||
);
|
||||
}
|
||||
// Any record at the cap counts: concurrent threads, or several processes appending to one
|
||||
// log, can write the capped record before a lower-numbered one.
|
||||
if let Some(limit) =
|
||||
summary
|
||||
.breakpoint_exceptions
|
||||
.iter()
|
||||
.find_map(|hit| match (hit.record, hit.limit) {
|
||||
(Some(record), Some(limit)) if limit > 0 && record >= limit => Some(limit),
|
||||
_ => None,
|
||||
})
|
||||
{
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" cap of {limit} records reached; later breakpoints were not recorded"
|
||||
);
|
||||
}
|
||||
}
|
||||
if !summary.unimpl_apis.is_empty() {
|
||||
let _ = writeln!(out, "\nUnimplemented APIs:");
|
||||
for (api, count) in &summary.unimpl_apis {
|
||||
@@ -402,7 +451,7 @@ where
|
||||
{
|
||||
let mut env_map = BTreeMap::new();
|
||||
env_map.insert("PATH".to_string(), SAFE_CHILD_PATH.to_string());
|
||||
for &key in HOST_ENV_ALLOWLIST {
|
||||
for &key in HOST_ENV_ALLOWLIST.iter().chain(DIAGNOSTIC_ENV_ALLOWLIST) {
|
||||
if let Some(val) = lookup(key) {
|
||||
env_map.insert(key.to_string(), val);
|
||||
}
|
||||
@@ -1657,6 +1706,26 @@ sub setup_bottle_wineprefix {
|
||||
assert!(!child.contains_key("CX_GRAPHICS_BACKEND"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_env_passes_only_the_named_veh_diagnostics() {
|
||||
let host = BTreeMap::from([
|
||||
("BX_VEH_AV_CONTEXT", "1"),
|
||||
("BX_VEH_SAMPLE", "5"),
|
||||
("BX_VEH_UNKNOWN", "x"),
|
||||
("BX_LOG_FILE", "/tmp/elsewhere.jsonl"),
|
||||
("GH_TOKEN", "secret_token"),
|
||||
]);
|
||||
let child = collect_isolated_host_env(|k| host.get(k).map(|s| (*s).to_string()));
|
||||
assert_eq!(
|
||||
child.get("BX_VEH_AV_CONTEXT").map(String::as_str),
|
||||
Some("1")
|
||||
);
|
||||
assert_eq!(child.get("BX_VEH_SAMPLE").map(String::as_str), Some("5"));
|
||||
assert!(!child.contains_key("BX_VEH_UNKNOWN"));
|
||||
assert!(!child.contains_key("BX_LOG_FILE"));
|
||||
assert!(!child.contains_key("GH_TOKEN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_unix_path_to_wine_z_drive() {
|
||||
assert_eq!(
|
||||
@@ -1723,6 +1792,62 @@ sub setup_bottle_wineprefix {
|
||||
assert_eq!(format_shader_gate_section(&summarize_jsonl(log)), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_breakpoint_exceptions_with_module_and_rva() {
|
||||
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(
|
||||
rendered.contains(
|
||||
"\nBreakpoint/assert exceptions, first chance (1):\n code=0x80000003 \
|
||||
title.exe + RVA=0x0000000002236178 (module_base=0x0000000140000000 \
|
||||
address=0x0000000142236178)\n"
|
||||
),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(!rendered.contains("Unhandled exceptions"), "{rendered}");
|
||||
assert!(
|
||||
!rendered.contains("cap of"),
|
||||
"one of 16 records is not the cap: {rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_when_the_breakpoint_record_cap_is_reached() {
|
||||
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
|
||||
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(
|
||||
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_the_cap_when_a_capped_record_is_not_the_last_line() {
|
||||
// Two threads (or processes) appending: the capped record lands before record 15.
|
||||
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
|
||||
{"ts_ms":6,"tid":8,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(
|
||||
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_the_address_of_a_breakpoint_outside_any_image() {
|
||||
let log = r#"{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(
|
||||
rendered.contains("address=0x0000000000410000"),
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_decisions_kinds_stages_gaps_and_missing_bridge() {
|
||||
// Realistic records, matching the emitter in shims/d3d12_xs/shader_gate.cpp.
|
||||
|
||||
@@ -18,6 +18,9 @@ pub struct TraceSummary {
|
||||
pub amd_traps: BTreeMap<String, TrapCount>,
|
||||
pub adx_errors: usize,
|
||||
pub unhandled_exceptions: Vec<UnhandledException>,
|
||||
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
|
||||
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
|
||||
pub breakpoint_exceptions: Vec<BreakpointException>,
|
||||
pub unimpl_apis: BTreeMap<String, usize>,
|
||||
pub unimpl_vtables: BTreeMap<String, usize>,
|
||||
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
|
||||
@@ -182,6 +185,30 @@ pub struct UnhandledException {
|
||||
pub rip: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct BreakpointException {
|
||||
pub exception_code: Option<String>,
|
||||
pub module: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
/// The faulting address, which locates a breakpoint outside any image (module `?`).
|
||||
pub address: Option<String>,
|
||||
/// 1-based index of this record and the per-process cap, so a reader can tell a run
|
||||
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
|
||||
pub record: Option<u32>,
|
||||
pub limit: Option<u32>,
|
||||
}
|
||||
|
||||
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let digits: &str = &line[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
@@ -344,6 +371,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
|
||||
});
|
||||
}
|
||||
"breakpoint_exception" => {
|
||||
summary.breakpoint_exceptions.push(BreakpointException {
|
||||
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
|
||||
module: extract_json_str(trimmed, "module").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
address: extract_json_str(trimmed, "address").map(str::to_owned),
|
||||
record: extract_json_u32(trimmed, "record"),
|
||||
limit: extract_json_u32(trimmed, "limit"),
|
||||
});
|
||||
}
|
||||
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
|
||||
"unimpl_vtable" => {
|
||||
*summary
|
||||
@@ -420,6 +458,39 @@ mod tests {
|
||||
assert_eq!(summary.clwb_trap_lower_bound, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_breakpoint_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
|
||||
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
|
||||
"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert!(summary.unhandled_exceptions.is_empty());
|
||||
assert_eq!(
|
||||
summary.breakpoint_exceptions,
|
||||
[
|
||||
BreakpointException {
|
||||
exception_code: Some("0x80000003".into()),
|
||||
module: Some("title.exe".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000002236178".into()),
|
||||
address: Some("0x0000000142236178".into()),
|
||||
record: Some(1),
|
||||
limit: Some(16),
|
||||
},
|
||||
BreakpointException {
|
||||
exception_code: Some("0xc0000420".into()),
|
||||
module: Some("?".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
address: Some("0x0000000000410000".into()),
|
||||
record: Some(2),
|
||||
limit: Some(16),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_unhandled_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
|
||||
+104
-23
@@ -1,29 +1,52 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
class AcpHal final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
// 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.
|
||||
class AcpHal {
|
||||
UINT32 commands_ = 0, messages_ = 0;
|
||||
bool connected_ = false;
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
|
||||
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
|
||||
commands_ = num_commands;
|
||||
messages_ = num_messages;
|
||||
connected_ = true;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
ULONG left = InterlockedDecrement(&refs);
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
virtual HRESULT WINAPI Disconnect() {
|
||||
connected_ = false;
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
|
||||
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);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
virtual bool WINAPI PopMessage(void*) { return false; }
|
||||
virtual UINT32 WINAPI GetNumMessages() { return 0; }
|
||||
virtual void WINAPI Release() { delete this; }
|
||||
virtual ~AcpHal() = default;
|
||||
};
|
||||
|
||||
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
|
||||
@@ -47,19 +70,77 @@ HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
// NDA constraint: the public Microsoft Learn page for AcpHal is gated behind
|
||||
// an Xbox developer NDA, so the true signatures and context layout are unknown
|
||||
// from public sources. BetterXen therefore returns E_NOTIMPL (not the console's
|
||||
// behaviour) and keeps the stub log so bx-cli trace still surfaces the call.
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* context) {
|
||||
(void)context;
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
|
||||
return E_NOTIMPL;
|
||||
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment);
|
||||
HRESULT WINAPI ApuFree(void* va);
|
||||
|
||||
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) / AcpHalReleaseShapeContexts() (authorized GDK
|
||||
// documentation; layout and element sizes derived from it, no header text): the caller fills six
|
||||
// counts, the call allocates each array from the APU heap and returns its CPU pointer and APU
|
||||
// address. Allocating twice without a release fails with ACP_E_ALREADY_ALLOCATED.
|
||||
struct ShapeContexts {
|
||||
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
|
||||
void* arrays[6]; // CPU pointers, same order
|
||||
uint32_t apu[6]; // APU addresses, same order
|
||||
};
|
||||
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS is 96 bytes");
|
||||
static_assert(offsetof(ShapeContexts, arrays) == 24 && offsetof(ShapeContexts, apu) == 72, "SHAPE_CONTEXTS layout");
|
||||
constexpr uint32_t kShapeElementBytes[6] = {32, 160, 32, 16, 64, 32};
|
||||
constexpr HRESULT kAcpAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
|
||||
constexpr uint32_t kDefaultApuHeapBytes = 64u << 20;
|
||||
|
||||
void* shape_arrays[6];
|
||||
bool shape_allocated = false;
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* argument) {
|
||||
auto* contexts = static_cast<ShapeContexts*>(argument);
|
||||
if (!contexts) return E_INVALIDARG;
|
||||
if (shape_allocated) return kAcpAlreadyAllocated;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
if (contexts->counts[i] > (0xFFFFFFFFu / kShapeElementBytes[i])) return E_INVALIDARG;
|
||||
}
|
||||
{
|
||||
// The console has a default non-cached APU heap; create one when the title made none.
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (!heap_created) {
|
||||
capacity = kDefaultApuHeapBytes;
|
||||
used = 0;
|
||||
heap_created = true;
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "apu_default_heap", "no ApuCreateHeap before shape contexts: 64 MB default heap");
|
||||
}
|
||||
}
|
||||
void* arrays[6] = {};
|
||||
uint32_t apu[6] = {};
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
if (!contexts->counts[i]) continue;
|
||||
const uint32_t bytes = contexts->counts[i] * kShapeElementBytes[i];
|
||||
const HRESULT hr = ApuAlloc(&arrays[i], &apu[i], bytes, 64);
|
||||
if (FAILED(hr)) {
|
||||
for (int j = 0; j < i; ++j) ApuFree(arrays[j]);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
std::memset(arrays[i], 0, bytes);
|
||||
}
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
contexts->arrays[i] = arrays[i];
|
||||
contexts->apu[i] = apu[i];
|
||||
shape_arrays[i] = arrays[i];
|
||||
}
|
||||
shape_allocated = true;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "src=%u eqcomp=%u filtvol=%u dma=%u xma=%u pcm=%u", contexts->counts[0],
|
||||
contexts->counts[1], contexts->counts[2], contexts->counts[3], contexts->counts[4], contexts->counts[5]);
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "shape_contexts_allocated", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
|
||||
return E_NOTIMPL;
|
||||
if (!shape_allocated) return S_OK;
|
||||
for (void*& array : shape_arrays) {
|
||||
ApuFree(array);
|
||||
array = nullptr;
|
||||
}
|
||||
shape_allocated = false;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
|
||||
|
||||
@@ -5,5 +5,16 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
proxy.cpp
|
||||
proxy_generated.cpp
|
||||
shader_gate.cpp
|
||||
xbox_facade.cpp
|
||||
frame_pacing.cpp
|
||||
placed_x.cpp
|
||||
descriptor_heaps.cpp
|
||||
committed.cpp
|
||||
pipelines.cpp
|
||||
gpu_writes.cpp
|
||||
fences.cpp
|
||||
presentx_xbox.cpp
|
||||
page_mappings.cpp
|
||||
xbox_tables_generated.cpp
|
||||
)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32 user32 dxguid)
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Committed resources with title-visible memory (ADR 0009).
|
||||
*
|
||||
* On the console the D3D12 runtime allocates a committed resource's memory through XMemAlloc
|
||||
* with AllocatorId eXALLOCAllocatorId_D3D (128) and ObjectType Resource (4) (authorized GDK
|
||||
* documentation, "Direct3D 12 XMemAlloc object types"). Titles hook XMemAlloc to place that
|
||||
* memory themselves, and some check afterwards how much of their own pool those requests used.
|
||||
*
|
||||
* Here the host committed resource holds the contents. The resource also gets the same
|
||||
* XMemAlloc request, and its GPU virtual address is the address that request returned, so title
|
||||
* hooks and title address checks see what they would see on the console. The page size the
|
||||
* console runtime requests is not documented: this layer asks for 2 MB pages for allocations of
|
||||
* at least 2 MB and 64 KB pages otherwise (measured against one title; logged per resource).
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kObjectTypeResource = 4;
|
||||
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
|
||||
constexpr ULONGLONG kPageSize64K = 1ull << 14; // XALLOC_ATTRIBUTES.PageSize, bits 14-15
|
||||
constexpr ULONGLONG kPageSize2M = 2ull << 14;
|
||||
constexpr UINT64 k2M = 2ull << 20;
|
||||
|
||||
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method) {
|
||||
if (FAILED(hr) || !ppv || !*ppv) return hr;
|
||||
// *ppv is the host resource as `riid`; every ID3D12Resource* interface pointer is the object.
|
||||
auto* resource = static_cast<ID3D12Resource*>(*ppv);
|
||||
const D3D12_RESOURCE_DESC desc = resource->GetDesc();
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
|
||||
const UINT64 size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
|
||||
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D | (size >= k2M ? kPageSize2M : kPageSize64K);
|
||||
void* title = XMemAlloc(static_cast<SIZE_T>(size), attributes);
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu page=%s title_va=%p", method,
|
||||
static_cast<int>(desc.Dimension), static_cast<unsigned long long>(size),
|
||||
size >= k2M ? "2MB" : "64KB", title);
|
||||
bx_log_emit(title ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "committed_title_memory", detail);
|
||||
if (!title || !bx_xbox_title_memory_attach(resource, reinterpret_cast<uint64_t>(title), size, attributes)) {
|
||||
resource->Release();
|
||||
*ppv = nullptr;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource");
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
return finish(device, device->CreateCommittedResource(heap, flags, desc, state, clear, riid, ppv), riid, ppv,
|
||||
"CreateCommittedResource");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource1");
|
||||
auto* device = bx_xbox_host<ID3D12Device4>(self);
|
||||
return finish(device, device->CreateCommittedResource1(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource1");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource2");
|
||||
auto* device = bx_xbox_host<ID3D12Device8>(self);
|
||||
return finish(device, device->CreateCommittedResource2(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource2");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, UINT32 formats,
|
||||
DXGI_FORMAT* castable, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource3");
|
||||
auto* device = bx_xbox_host<ID3D12Device10>(self);
|
||||
return finish(device,
|
||||
device->CreateCommittedResource3(heap, flags, desc, layout, clear, bx_xbox_unwrap_as(session), formats,
|
||||
castable, riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource3");
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
@@ -21,6 +23,38 @@ HMODULE get_host_d3d12() {
|
||||
return mod;
|
||||
}
|
||||
|
||||
// A failed host serialization is the title's error to handle, but it is logged with the host's
|
||||
// message and the shape of the description so the rejected feature can be found.
|
||||
void log_serialize_failure(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, HRESULT hr, ID3DBlob* errors) {
|
||||
static std::atomic<uint32_t> logged{0};
|
||||
if (logged.fetch_add(1) >= 32) return;
|
||||
char shape[160] = "desc=null";
|
||||
if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_1) {
|
||||
const auto& d = desc->Desc_1_1;
|
||||
std::snprintf(shape, sizeof(shape), "version=1.1 params=%u samplers=%u flags=0x%x", d.NumParameters,
|
||||
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
|
||||
} else if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_0) {
|
||||
const auto& d = desc->Desc_1_0;
|
||||
std::snprintf(shape, sizeof(shape), "version=1.0 params=%u samplers=%u flags=0x%x", d.NumParameters,
|
||||
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
|
||||
} else if (desc) {
|
||||
std::snprintf(shape, sizeof(shape), "version=%u", static_cast<unsigned>(desc->Version));
|
||||
}
|
||||
char message[160] = "";
|
||||
if (errors && errors->GetBufferPointer() && errors->GetBufferSize()) {
|
||||
const size_t n = errors->GetBufferSize() < sizeof(message) - 1 ? errors->GetBufferSize() : sizeof(message) - 1;
|
||||
std::memcpy(message, errors->GetBufferPointer(), n);
|
||||
message[n] = '\0';
|
||||
for (char& ch : message) {
|
||||
if (ch == '"' || ch == '\\' || static_cast<unsigned char>(ch) < 0x20) ch = ' ';
|
||||
}
|
||||
}
|
||||
char detail[384];
|
||||
std::snprintf(detail, sizeof(detail), "hr=0x%08lx %s host_error=%s", static_cast<unsigned long>(hr), shape,
|
||||
message[0] ? message : "(none)");
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "root_signature_serialize_failed", detail);
|
||||
}
|
||||
|
||||
void initialize_trace_flag() {
|
||||
static std::once_flag initialized;
|
||||
std::call_once(initialized, [] {
|
||||
@@ -117,8 +151,34 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID r
|
||||
adapter ? "non-null (ignored, default host adapter)" : "default", g_bx_trace_d3d);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
|
||||
|
||||
/*
|
||||
* ADR 0009: a title built against the Xbox header calls through Xbox-order function tables,
|
||||
* so it gets an Xbox-layout device over the PC proxy. The documentation requires titles to
|
||||
* set Version (D3D12_SDK_VERSION); BetterXen's synthetic fixtures, which are PC-layout
|
||||
* clients built against <d3d12.h>, pass a zeroed block and keep the PC proxy.
|
||||
*/
|
||||
if (version != 0 && bx_xbox_iface_for(riid) == &bx_xbox_Device) {
|
||||
void* pc = nullptr;
|
||||
hr = proxy->QueryInterface(riid, &pc);
|
||||
proxy->Release();
|
||||
if (FAILED(hr) || !pc) return FAILED(hr) ? hr : E_NOINTERFACE;
|
||||
// The wrap fails (E_NOINTERFACE, logged) when the host device lacks the interface the Xbox
|
||||
// table forwards to: a title must not get a PC-layout device reported as an Xbox one.
|
||||
HRESULT failure = E_OUTOFMEMORY;
|
||||
*ppv = bx_xbox_wrap(riid, pc, &failure);
|
||||
bx_log_emit(*ppv ? BX_LOG_INFO : BX_LOG_ERROR, "d3d12_xs", "xbox_layout",
|
||||
*ppv ? "device=xbox_function_tables"
|
||||
: "device=refused: the host device lacks the interface the Xbox device table forwards to "
|
||||
"(the D3DMetal backend provides it)");
|
||||
return *ppv ? S_OK : failure;
|
||||
}
|
||||
hr = proxy->QueryInterface(riid, ppv);
|
||||
proxy->Release();
|
||||
if (SUCCEEDED(hr)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "xbox_layout",
|
||||
version == 0 ? "device=pc_layout (params Version 0: synthetic PC-layout client)"
|
||||
: "device=pc_layout (interface has no Xbox table)");
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
@@ -137,7 +197,12 @@ HRESULT WINAPI D3D12SerializeVersionedRootSignature(
|
||||
auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(
|
||||
GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")));
|
||||
if (fn) {
|
||||
return fn(desc, blob, error_blob);
|
||||
ID3DBlob* local_error = nullptr;
|
||||
ID3DBlob** errors = error_blob ? error_blob : &local_error;
|
||||
const HRESULT hr = fn(desc, blob, errors);
|
||||
if (FAILED(hr)) log_serialize_failure(desc, hr, *errors);
|
||||
if (local_error) local_error->Release();
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12SerializeVersionedRootSignature");
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
* Descriptor heaps at title-visible addresses (ADR 0009).
|
||||
*
|
||||
* On the console a descriptor handle is an address: the runtime allocates a heap's storage as a
|
||||
* GPU allocation through XMemAlloc (object type Resource, allocator D3D), so a title's allocation
|
||||
* hooks can place it in the title's own memory, and handles are base + index * descriptor size,
|
||||
* with the console's sizes (32 bytes CBV/SRV/UAV, 16 sampler, 112 RTV, 128 DSV).
|
||||
*
|
||||
* Here each heap has that title-visible storage (allocated the same way, so the title's hooks
|
||||
* see the same request) and a host D3D12 heap. Title handles are translated to host handles by
|
||||
* index. The storage is not interpreted: descriptors a title writes there inline (titles built
|
||||
* with D3DCOMPILE_NO_DEBUG) are not translated, and ID3D12Device's m_OutOfLineFlags keeps the
|
||||
* other titles' descriptor writes on the out-of-line path, which reaches the host heap.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kObjectTypeResource = 4; // D3D12 XMemAlloc object types: GPU "Resource"
|
||||
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
|
||||
|
||||
struct Heap {
|
||||
uintptr_t base;
|
||||
UINT count;
|
||||
UINT xbox_size;
|
||||
ID3D12DescriptorHeap* host; // not owned: the Xbox object owns the reference
|
||||
SIZE_T host_cpu;
|
||||
UINT64 host_gpu;
|
||||
UINT host_increment;
|
||||
ULONGLONG attributes;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
Heap* g_heaps = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
bool add(const Heap& heap) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (g_count == g_capacity) {
|
||||
const size_t capacity = g_capacity ? g_capacity * 2 : 32;
|
||||
auto* grown = new (std::nothrow) Heap[capacity];
|
||||
if (!grown) return false;
|
||||
for (size_t i = 0; i < g_count; ++i) grown[i] = g_heaps[i];
|
||||
delete[] g_heaps;
|
||||
g_heaps = grown;
|
||||
g_capacity = capacity;
|
||||
}
|
||||
g_heaps[g_count++] = heap;
|
||||
return true;
|
||||
}
|
||||
|
||||
const Heap* find_locked(uintptr_t address) {
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Heap& h = g_heaps[i];
|
||||
if (address >= h.base && address < h.base + static_cast<uintptr_t>(h.count) * h.xbox_size) return &h;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void log_untranslated(const char* what, uint64_t value) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) >= 8) return; // the first few are enough to see the pattern
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s 0x%llx is in no title descriptor heap", what,
|
||||
static_cast<unsigned long long>(value));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "descriptor_untranslated", detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
switch (type) {
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV: return 32;
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER: return 16;
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_RTV: return 112;
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_DSV: return 128;
|
||||
default: return 32;
|
||||
}
|
||||
}
|
||||
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title) {
|
||||
if (!title.ptr) return title;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (const Heap* h = find_locked(title.ptr)) {
|
||||
return {h->host_cpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
|
||||
}
|
||||
log_untranslated("CPU descriptor handle", title.ptr);
|
||||
return title;
|
||||
}
|
||||
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title) {
|
||||
if (!title.ptr) return title;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (const Heap* h = find_locked(static_cast<uintptr_t>(title.ptr))) {
|
||||
if (h->host_gpu) return {h->host_gpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
|
||||
}
|
||||
log_untranslated("GPU descriptor handle", title.ptr);
|
||||
return title;
|
||||
}
|
||||
|
||||
void bx_xbox_descriptor_heap_forget(IUnknown* host) {
|
||||
Heap gone{};
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (static_cast<IUnknown*>(g_heaps[i].host) == host) {
|
||||
gone = g_heaps[i];
|
||||
g_heaps[i] = g_heaps[--g_count];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (gone.base) XMemFree(reinterpret_cast<void*>(gone.base), gone.attributes);
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDescriptorHeap");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12DescriptorHeap* host = nullptr;
|
||||
HRESULT hr = device->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr) || !host) return FAILED(hr) ? hr : E_FAIL;
|
||||
|
||||
const UINT size = bx_xbox_descriptor_size(desc->Type);
|
||||
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D;
|
||||
void* storage = XMemAlloc(static_cast<SIZE_T>(desc->NumDescriptors) * size, attributes);
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "type=%d count=%u xbox_size=%u flags=0x%x title_base=%p",
|
||||
static_cast<int>(desc->Type), desc->NumDescriptors, size, static_cast<unsigned>(desc->Flags), storage);
|
||||
bx_log_emit(storage ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "descriptor_heap", detail);
|
||||
if (!storage) {
|
||||
host->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE cpu{};
|
||||
host->GetCPUDescriptorHandleForHeapStart(&cpu);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE gpu{};
|
||||
if (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) host->GetGPUDescriptorHandleForHeapStart(&gpu);
|
||||
const Heap heap{reinterpret_cast<uintptr_t>(storage), desc->NumDescriptors, size, host, cpu.ptr, gpu.ptr,
|
||||
device->GetDescriptorHandleIncrementSize(desc->Type), attributes};
|
||||
if (!add(heap)) {
|
||||
XMemFree(storage, attributes);
|
||||
host->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*ppv = host;
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void*, D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
return bx_xbox_descriptor_size(type);
|
||||
}
|
||||
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self) {
|
||||
auto* host = bx_xbox_host<ID3D12DescriptorHeap>(self);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_heaps[i].host == host) return {g_heaps[i].base};
|
||||
}
|
||||
return {0};
|
||||
}
|
||||
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self) {
|
||||
// On the console the GPU handle of a heap is the same address as its CPU handle.
|
||||
return {bx_xbox_heap_cpu_start(self).ptr};
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateConstantBufferView");
|
||||
D3D12_CONSTANT_BUFFER_VIEW_DESC host_desc{};
|
||||
if (desc) {
|
||||
host_desc = *desc;
|
||||
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));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
|
||||
const UINT* dest_sizes, UINT src_ranges,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
BX_D3D_TRACE("XboxDevice", "CopyDescriptors");
|
||||
auto* dst = new (std::nothrow) D3D12_CPU_DESCRIPTOR_HANDLE[dest_ranges + src_ranges + 1];
|
||||
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]);
|
||||
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;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "OMSetRenderTargets");
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE host_rtvs[8] = {};
|
||||
const UINT n = count > 8 ? 8 : count;
|
||||
for (UINT i = 0; rtvs && i < (single_range ? 1u : n); ++i) host_rtvs[i] = bx_xbox_host_cpu_handle(rtvs[i]);
|
||||
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);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
|
||||
D3D12_VERTEX_BUFFER_VIEW host[32] = {};
|
||||
const UINT n = count > 32 ? 32 : count;
|
||||
for (UINT i = 0; views && i < n; ++i) {
|
||||
host[i] = views[i];
|
||||
host[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetIndexBuffer");
|
||||
D3D12_INDEX_BUFFER_VIEW host{};
|
||||
if (view) {
|
||||
host = *view;
|
||||
host.BufferLocation = bx_xbox_host_gpu_va(view->BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetIndexBuffer(view ? &host : nullptr);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace {
|
||||
|
||||
/* The leading fields of D3D12XBOX_SAMPLER_DESC (authorized GDK header; every field is 4 bytes). */
|
||||
struct XboxSamplerPrefix {
|
||||
UINT flags;
|
||||
UINT filter_mag; // D3D12XBOX_TEXTURE_XY_FILTER: 0 point, 1 bilinear, 2 aniso point, 3 aniso bilinear
|
||||
UINT filter_min;
|
||||
UINT filter_mip; // D3D12XBOX_TEXTURE_MIP_FILTER: 0 none, 1 point, 2 linear
|
||||
UINT filter_z;
|
||||
UINT filter_mode; // D3D12XBOX_TEXTURE_FILTER_MODE: 0 lerp, 1 min, 2 max
|
||||
D3D12_TEXTURE_ADDRESS_MODE address_u, address_v, address_w;
|
||||
FLOAT min_lod, max_lod, mip_lod_bias, mip_lod_bias_secondary;
|
||||
UINT max_anisotropy;
|
||||
FLOAT anisotropy_bias;
|
||||
UINT anisotropy_threshold;
|
||||
D3D12_COMPARISON_FUNC comparison;
|
||||
FLOAT border_color[4];
|
||||
};
|
||||
static_assert(sizeof(XboxSamplerPrefix) == 21 * 4, "D3D12XBOX_SAMPLER_DESC prefix layout");
|
||||
|
||||
D3D12_FILTER_TYPE xy_type(UINT filter) { return (filter & 1) ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT; }
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateSamplerX");
|
||||
if (!xbox_desc) return;
|
||||
XboxSamplerPrefix x{};
|
||||
std::memcpy(&x, xbox_desc, sizeof(x));
|
||||
// A comparison function other than NEVER selects comparison filtering (inference: the console
|
||||
// description has no separate comparison filter, so the function is the only signal).
|
||||
const bool compare = x.comparison > D3D12_COMPARISON_FUNC_NEVER;
|
||||
const D3D12_FILTER_REDUCTION_TYPE reduction = compare ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON
|
||||
: x.filter_mode == 1 ? D3D12_FILTER_REDUCTION_TYPE_MINIMUM
|
||||
: x.filter_mode == 2 ? D3D12_FILTER_REDUCTION_TYPE_MAXIMUM
|
||||
: D3D12_FILTER_REDUCTION_TYPE_STANDARD;
|
||||
D3D12_SAMPLER_DESC pc{};
|
||||
const bool aniso = x.filter_mag >= 2 || x.filter_min >= 2;
|
||||
pc.Filter = aniso ? D3D12_ENCODE_ANISOTROPIC_FILTER(reduction)
|
||||
: D3D12_ENCODE_BASIC_FILTER(xy_type(x.filter_min), xy_type(x.filter_mag),
|
||||
x.filter_mip == 2 ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT,
|
||||
reduction);
|
||||
pc.AddressU = x.address_u;
|
||||
pc.AddressV = x.address_v;
|
||||
pc.AddressW = x.address_w;
|
||||
pc.MipLODBias = x.mip_lod_bias;
|
||||
pc.MaxAnisotropy = aniso ? (x.max_anisotropy < 1 ? 1 : x.max_anisotropy > 16 ? 16 : x.max_anisotropy) : 1;
|
||||
pc.ComparisonFunc = compare ? x.comparison : D3D12_COMPARISON_FUNC_NEVER;
|
||||
for (int i = 0; i < 4; ++i) pc.BorderColor[i] = x.border_color[i];
|
||||
pc.MinLOD = x.min_lod;
|
||||
pc.MaxLOD = x.filter_mip == 0 ? x.min_lod : x.max_lod; // no mip filter: the base level only
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateSampler(&pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Fences with a title-visible value (ADR 0009). ID3D12Fence1::GetGpuAddressX returns the GPU
|
||||
* address of a fence's 64-bit value (authorized GDK documentation); titles read it from the CPU
|
||||
* and target it with Write*BitValue*X and Wait*BitValueX. Each fence that is asked for its
|
||||
* address gets an 8-byte slot in memory this layer owns, kept equal to the host fence's value:
|
||||
* - a CPU Signal stores the value at once;
|
||||
* - a queue Signal stores it when the host fence completes (a one-shot threadpool wait);
|
||||
* - a GPU value write to the slot (gpu_writes.cpp) also signals the host fence.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Slot {
|
||||
ID3D12Fence* host;
|
||||
std::atomic<uint64_t>* value;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
std::vector<Slot> g_slots;
|
||||
std::atomic<uint64_t>* g_page = nullptr;
|
||||
size_t g_used = 0;
|
||||
constexpr size_t kSlotsPerPage = 4096 / sizeof(uint64_t);
|
||||
|
||||
std::atomic<uint64_t>* allocate_locked() {
|
||||
if (!g_page || g_used == kSlotsPerPage) {
|
||||
g_page = static_cast<std::atomic<uint64_t>*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
g_used = 0;
|
||||
if (!g_page) return nullptr;
|
||||
}
|
||||
return &g_page[g_used++];
|
||||
}
|
||||
|
||||
std::atomic<uint64_t>* slot_of(ID3D12Fence* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (const Slot& s : g_slots) {
|
||||
if (s.host == host) return s.value;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void store_max(std::atomic<uint64_t>* slot, uint64_t value) {
|
||||
uint64_t current = slot->load();
|
||||
while (current < value && !slot->compare_exchange_weak(current, value)) {
|
||||
}
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
std::atomic<uint64_t>* slot;
|
||||
uint64_t value;
|
||||
HANDLE event;
|
||||
HANDLE wait;
|
||||
};
|
||||
|
||||
void CALLBACK on_completed(void* context, BOOLEAN) {
|
||||
auto* p = static_cast<Pending*>(context);
|
||||
store_max(p->slot, p->value);
|
||||
// The wait cannot be unregistered from its own callback with a blocking call; hand it off.
|
||||
UnregisterWaitEx(p->wait, nullptr);
|
||||
CloseHandle(p->event);
|
||||
delete p;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (const Slot& s : g_slots) {
|
||||
if (reinterpret_cast<uint64_t>(s.value) == address) {
|
||||
if (host) *host = s.host;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void bx_xbox_fence_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_slots.size(); ++i) {
|
||||
if (static_cast<IUnknown*>(g_slots[i].host) == host) { // the slot memory is not reused
|
||||
g_slots[i] = g_slots.back();
|
||||
g_slots.pop_back();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self) {
|
||||
BX_D3D_TRACE("XboxFence", "GetGpuAddressX");
|
||||
auto* host = bx_xbox_host<ID3D12Fence>(self);
|
||||
if (auto* existing = slot_of(host)) return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(existing);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
std::atomic<uint64_t>* slot = allocate_locked();
|
||||
if (!slot) return 0;
|
||||
slot->store(host->GetCompletedValue());
|
||||
g_slots.push_back({host, slot});
|
||||
return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(slot);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value) {
|
||||
BX_D3D_TRACE("XboxFence", "Signal");
|
||||
auto* host = bx_xbox_host<ID3D12Fence>(self);
|
||||
const HRESULT hr = host->Signal(value);
|
||||
if (SUCCEEDED(hr)) {
|
||||
if (auto* slot = slot_of(host)) slot->store(value);
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "Signal");
|
||||
ID3D12Fence* host_fence = bx_xbox_unwrap_as(fence);
|
||||
const HRESULT hr = bx_xbox_host<ID3D12CommandQueue>(self)->Signal(host_fence, value);
|
||||
std::atomic<uint64_t>* slot = SUCCEEDED(hr) && host_fence ? slot_of(host_fence) : nullptr;
|
||||
if (!slot) return hr;
|
||||
if (host_fence->GetCompletedValue() >= value) {
|
||||
store_max(slot, value);
|
||||
return hr;
|
||||
}
|
||||
auto* p = new (std::nothrow) Pending{slot, value, CreateEventW(nullptr, TRUE, FALSE, nullptr), nullptr};
|
||||
if (!p || !p->event) {
|
||||
delete p;
|
||||
return hr;
|
||||
}
|
||||
if (FAILED(host_fence->SetEventOnCompletion(value, p->event)) ||
|
||||
!RegisterWaitForSingleObject(&p->wait, p->event, on_completed, p, INFINITE, WT_EXECUTEONLYONCE)) {
|
||||
CloseHandle(p->event);
|
||||
delete p;
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "fence_slot", "could not arm the completion mirror for a queue Signal");
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "Wait");
|
||||
return bx_xbox_host<ID3D12CommandQueue>(self)->Wait(bx_xbox_unwrap_as(fence), value);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Xbox frame pacing on the host (ADR 0009): ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX
|
||||
* and WaitFrameEventX, as the authorized GDK documentation describes them.
|
||||
*
|
||||
* On the console, display hardware signals the frame events. Here one thread emulates them
|
||||
* from the recorded frame interval: at the start of each interval it signals the VBLANK and
|
||||
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
|
||||
* new frame pipeline token. Each signal also sets the ancillary events given to
|
||||
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr UINT kEventTypes = 3; // ORIGIN, DISPLAY_VBLANK, DISPLAY_FLIP
|
||||
constexpr UINT kOrigin = 0;
|
||||
constexpr UINT kMaxAncillarySignals = 7;
|
||||
constexpr UINT kMaxAncillaryWaits = 63;
|
||||
constexpr UINT kScheduleDisableSignal = 0x1;
|
||||
constexpr UINT kWaitAll = 0x1;
|
||||
constexpr UINT kWaitProcessTokenOnTimeout = 0x2;
|
||||
constexpr UINT kIntervalFlag60FpsPlus = 0x1;
|
||||
constexpr UINT kSignaledNone = 0xFFFFFFFF;
|
||||
constexpr UINT kInfinite = 0xFFFFFFFF;
|
||||
|
||||
struct Scheduled {
|
||||
bool active = false;
|
||||
UINT offset_us = 0;
|
||||
HANDLE ancillary[kMaxAncillarySignals] = {};
|
||||
UINT ancillary_count = 0;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
UINT g_interval_us = 0;
|
||||
UINT g_period = 0;
|
||||
Scheduled g_events[kEventTypes];
|
||||
HANDLE g_signal[kEventTypes] = {}; // auto-reset, set at each occurrence
|
||||
UINT64 g_next_token = 1;
|
||||
UINT64 g_last_origin_token = 0;
|
||||
bool g_thread_started = false;
|
||||
|
||||
void close_ancillary(Scheduled& e) {
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
|
||||
e.ancillary_count = 0;
|
||||
}
|
||||
|
||||
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++;
|
||||
SetEvent(g_signal[type]);
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
|
||||
}
|
||||
|
||||
void pacing_thread() {
|
||||
LARGE_INTEGER frequency, start;
|
||||
QueryPerformanceFrequency(&frequency);
|
||||
QueryPerformanceCounter(&start);
|
||||
const auto now_us = [&] {
|
||||
LARGE_INTEGER t;
|
||||
QueryPerformanceCounter(&t);
|
||||
return static_cast<UINT64>((t.QuadPart - start.QuadPart) * 1000000 / frequency.QuadPart);
|
||||
};
|
||||
const auto sleep_until = [&](UINT64 target_us) {
|
||||
for (UINT64 t = now_us(); t < target_us; t = now_us()) {
|
||||
const UINT64 ms = (target_us - t) / 1000;
|
||||
Sleep(ms ? static_cast<DWORD>(ms) : 0);
|
||||
}
|
||||
};
|
||||
UINT64 interval_start = 0;
|
||||
for (;;) {
|
||||
UINT interval, origin_offset;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
interval = g_interval_us;
|
||||
origin_offset = g_events[kOrigin].offset_us;
|
||||
}
|
||||
signal(1);
|
||||
signal(2);
|
||||
sleep_until(interval_start + (origin_offset < interval ? origin_offset : 0));
|
||||
signal(kOrigin);
|
||||
interval_start += interval;
|
||||
sleep_until(interval_start);
|
||||
}
|
||||
}
|
||||
|
||||
void log_pacing(const char* event, const char* fmt, UINT a, UINT b, UINT c) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), fmt, a, b, c);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void*, IDXGIOutput*, UINT length_us, UINT period,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxDevice", "SetFrameIntervalX");
|
||||
if (length_us == 0 || period < 1 || period > 4 || (flags & ~kIntervalFlag60FpsPlus) != 0) return E_INVALIDARG;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_interval_us = length_us;
|
||||
g_period = period;
|
||||
log_pacing("frame_interval", "length_us=%u period=%u flags=0x%x (host timer, no display sync)", length_us, period, flags);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void*, UINT type, UINT offset_us,
|
||||
const BxXboxFrameObjectList* signals, UINT flags) {
|
||||
BX_D3D_TRACE("XboxDevice", "ScheduleFrameEventX");
|
||||
if (type >= kEventTypes || (flags & ~kScheduleDisableSignal) != 0) return E_INVALIDARG;
|
||||
if (signals && (signals->Count > kMaxAncillarySignals || (signals->Count && !signals->pObjects))) return E_INVALIDARG;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (g_interval_us == 0) return E_INVALIDARG; // documented: an interval must be established first
|
||||
if (offset_us >= g_interval_us) return E_INVALIDARG;
|
||||
for (UINT i = 0; i < kEventTypes; ++i) {
|
||||
if (!g_signal[i] && !(g_signal[i] = CreateEventW(nullptr, FALSE, FALSE, nullptr))) return E_OUTOFMEMORY;
|
||||
}
|
||||
Scheduled& e = g_events[type];
|
||||
close_ancillary(e);
|
||||
e.active = !(flags & kScheduleDisableSignal);
|
||||
e.offset_us = offset_us;
|
||||
for (UINT i = 0; signals && i < signals->Count; ++i) {
|
||||
// The title may close its handle; the scheduled signal keeps its own copy.
|
||||
if (!DuplicateHandle(GetCurrentProcess(), signals->pObjects[i], GetCurrentProcess(), &e.ancillary[e.ancillary_count],
|
||||
0, FALSE, DUPLICATE_SAME_ACCESS)) {
|
||||
close_ancillary(e);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
++e.ancillary_count;
|
||||
}
|
||||
log_pacing("frame_event_scheduled", "type=%u offset_us=%u ancillary=%u", type, offset_us, e.ancillary_count);
|
||||
if (!g_thread_started) {
|
||||
std::thread(pacing_thread).detach();
|
||||
g_thread_started = true;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UINT timeout_ms,
|
||||
const BxXboxFrameWaitList* waits, UINT flags,
|
||||
UINT64* token) {
|
||||
BX_D3D_TRACE("XboxDevice", "WaitFrameEventX");
|
||||
if (type >= kEventTypes || (flags & ~(kWaitAll | kWaitProcessTokenOnTimeout)) != 0) return E_INVALIDARG;
|
||||
if (waits && (waits->Count > kMaxAncillaryWaits || (waits->Count && !waits->pObjects))) return E_INVALIDARG;
|
||||
HANDLE handles[1 + kMaxAncillaryWaits];
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!g_events[type].active) return E_INVALIDARG; // documented: the event must be scheduled
|
||||
handles[0] = g_signal[type];
|
||||
}
|
||||
const UINT ancillary = waits ? waits->Count : 0;
|
||||
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
|
||||
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;
|
||||
if (waits && waits->pSignaledObjectIndex) {
|
||||
*waits->pSignaledObjectIndex = satisfied && !(flags & kWaitAll) && result > WAIT_OBJECT_0
|
||||
? result - WAIT_OBJECT_0 - 1 : kSignaledNone;
|
||||
}
|
||||
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
*token = satisfied ? g_last_origin_token : g_next_token++;
|
||||
}
|
||||
return satisfied ? S_OK : S_FALSE;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,267 @@
|
||||
/*
|
||||
* GPU value writes into title memory (ADR 0009): Write32/64BitValueBottomOfPipeX and
|
||||
* ...TopOfPipeX record "when the GPU reaches this point, store this value at this address".
|
||||
* On the console the address is title memory that the CPU polls. The host GPU cannot write
|
||||
* title memory, so each command list keeps its writes in recording order, and when a queue
|
||||
* executes lists that carry writes, it waits for the host GPU (an internal fence) and stores the
|
||||
* values from the CPU, in submission order, before the Execute call returns. Executes with
|
||||
* writes are therefore synchronous (logged once); executes without writes are not changed.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Write {
|
||||
uint64_t address;
|
||||
uint64_t value;
|
||||
bool wide;
|
||||
bool wait = false; // Wait*BitValueX: value is the reference
|
||||
D3D12_COMPARISON_FUNC compare = D3D12_COMPARISON_FUNC_GREATER_EQUAL;
|
||||
uint64_t mask = ~0ull;
|
||||
};
|
||||
|
||||
struct ListWrites {
|
||||
ID3D12GraphicsCommandList* list;
|
||||
std::vector<Write> writes;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
std::vector<ListWrites> g_lists;
|
||||
|
||||
ListWrites* find_locked(ID3D12GraphicsCommandList* list) {
|
||||
for (ListWrites& entry : g_lists) {
|
||||
if (entry.list == list) return &entry;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool writable(uint64_t address, size_t size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) || region.State != MEM_COMMIT) return false;
|
||||
constexpr DWORD kWritable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
return (region.Protect & kWritable) && address + size <= reinterpret_cast<uint64_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
|
||||
void record(void* self, const Write& op) {
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
ListWrites* entry = find_locked(list);
|
||||
if (!entry) {
|
||||
g_lists.push_back({list, {}});
|
||||
entry = &g_lists.back();
|
||||
}
|
||||
entry->writes.push_back(op);
|
||||
}
|
||||
|
||||
void record(void* self, uint64_t address, uint64_t value, bool wide) { record(self, Write{address, value, wide}); }
|
||||
|
||||
bool satisfied(const Write& w) {
|
||||
const uint64_t raw = w.wide ? reinterpret_cast<const std::atomic<uint64_t>*>(w.address)->load()
|
||||
: reinterpret_cast<const std::atomic<uint32_t>*>(w.address)->load();
|
||||
const uint64_t v = raw & w.mask;
|
||||
switch (w.compare) {
|
||||
case D3D12_COMPARISON_FUNC_NEVER: return false;
|
||||
case D3D12_COMPARISON_FUNC_LESS: return v < w.value;
|
||||
case D3D12_COMPARISON_FUNC_EQUAL: return v == w.value;
|
||||
case D3D12_COMPARISON_FUNC_LESS_EQUAL: return v <= w.value;
|
||||
case D3D12_COMPARISON_FUNC_GREATER: return v > w.value;
|
||||
case D3D12_COMPARISON_FUNC_NOT_EQUAL: return v != w.value;
|
||||
case D3D12_COMPARISON_FUNC_GREATER_EQUAL: return v >= w.value;
|
||||
default: return true;
|
||||
}
|
||||
}
|
||||
|
||||
// A GPU wait on memory becomes a host queue Wait when the memory is a fence slot and the
|
||||
// comparison is >=; otherwise the CPU polls the memory before submitting (10 s limit, logged).
|
||||
void apply_wait(ID3D12CommandQueue* queue, const Write& w) {
|
||||
ID3D12Fence* fence = nullptr;
|
||||
if (w.wide && w.compare == D3D12_COMPARISON_FUNC_GREATER_EQUAL && w.mask == ~0ull && bx_xbox_fence_slot(w.address, &fence)) {
|
||||
queue->Wait(fence, w.value);
|
||||
return;
|
||||
}
|
||||
if (!writable(w.address, w.wide ? 8 : 4)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", "wait address is not title memory; wait skipped");
|
||||
return;
|
||||
}
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
while (!satisfied(w)) {
|
||||
if (GetTickCount64() - start > 10000) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "wait on 0x%llx not satisfied after 10 s; submitting anyway",
|
||||
static_cast<unsigned long long>(w.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", detail);
|
||||
return;
|
||||
}
|
||||
SwitchToThread();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct QueueFence {
|
||||
ID3D12CommandQueue* queue;
|
||||
ID3D12Fence* fence;
|
||||
uint64_t value;
|
||||
};
|
||||
std::vector<QueueFence> g_fences; // guarded by g_lock
|
||||
|
||||
HRESULT wait_for_queue(ID3D12CommandQueue* queue) {
|
||||
ID3D12Fence* fence = nullptr;
|
||||
uint64_t value = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (QueueFence& q : g_fences) {
|
||||
if (q.queue == queue) {
|
||||
fence = q.fence;
|
||||
value = ++q.value;
|
||||
}
|
||||
}
|
||||
if (!fence) {
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return E_FAIL;
|
||||
const HRESULT hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
|
||||
device->Release();
|
||||
if (FAILED(hr)) return hr;
|
||||
value = 1;
|
||||
g_fences.push_back({queue, fence, value});
|
||||
}
|
||||
}
|
||||
HRESULT hr = queue->Signal(fence, value);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (fence->GetCompletedValue() >= value) return S_OK;
|
||||
HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event) return E_OUTOFMEMORY;
|
||||
hr = fence->SetEventOnCompletion(value, event);
|
||||
if (SUCCEEDED(hr) && WaitForSingleObject(event, 10000) != WAIT_OBJECT_0) hr = HRESULT_FROM_WIN32(WAIT_TIMEOUT);
|
||||
CloseHandle(event);
|
||||
return hr;
|
||||
}
|
||||
|
||||
void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
|
||||
BxXboxUnwrapArray<ID3D12CommandList> host(lists, count);
|
||||
if (!host.ok()) return;
|
||||
std::vector<Write> pending;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
if (ListWrites* entry = find_locked(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host.data()[i])))) {
|
||||
pending.insert(pending.end(), entry->writes.begin(), entry->writes.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
bx_xbox_sync_mapped_buffers();
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) apply_wait(queue, w);
|
||||
}
|
||||
queue->ExecuteCommandLists(count, host.data());
|
||||
bool any_write = false;
|
||||
for (const Write& w : pending) any_write = any_write || !w.wait;
|
||||
if (!any_write) return;
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "gpu_value_writes",
|
||||
"executes carrying Write*BitValue*X wait for the host GPU, then store the values in title memory");
|
||||
}
|
||||
const HRESULT hr = wait_for_queue(queue);
|
||||
if (FAILED(hr)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "waiting for the host GPU failed hr=0x%08lx; values still written",
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
|
||||
}
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) continue;
|
||||
if (!writable(w.address, w.wide ? 8 : 4)) {
|
||||
static std::atomic<int> bad{0};
|
||||
if (bad.fetch_add(1) < 8) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "address 0x%llx is not writable title memory; value dropped",
|
||||
static_cast<unsigned long long>(w.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (w.wide) {
|
||||
reinterpret_cast<std::atomic<uint64_t>*>(w.address)->store(w.value, std::memory_order_release);
|
||||
} else {
|
||||
reinterpret_cast<std::atomic<uint32_t>*>(w.address)->store(static_cast<uint32_t>(w.value), std::memory_order_release);
|
||||
}
|
||||
ID3D12Fence* fence = nullptr;
|
||||
if (w.wide && bx_xbox_fence_slot(w.address, &fence)) fence->Signal(w.value);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_xbox_gpu_writes_reset(IUnknown* host_list) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_lists.size(); ++i) {
|
||||
if (static_cast<IUnknown*>(g_lists[i].list) == host_list) {
|
||||
g_lists[i] = std::move(g_lists.back());
|
||||
g_lists.pop_back();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueBottomOfPipeX");
|
||||
record(self, address, value, false);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueBottomOfPipeX");
|
||||
record(self, address, value, true);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueTopOfPipeX");
|
||||
record(self, address, value, false);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueTopOfPipeX");
|
||||
record(self, address, value, true);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT64 reference, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait64BitValueX");
|
||||
Write op{address, reference, true};
|
||||
op.wait = true;
|
||||
op.compare = compare;
|
||||
record(self, op);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT reference, UINT mask, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait32BitValueX");
|
||||
Write op{address, reference, false};
|
||||
op.wait = true;
|
||||
op.compare = compare;
|
||||
op.mask = mask;
|
||||
record(self, op);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists");
|
||||
execute(self, count, lists);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
|
||||
UINT64 token, UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists2X");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "frame token and kickoff flags (first: token=%llu flags=0x%x) not used by the host",
|
||||
static_cast<unsigned long long>(token), flags);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "execute_command_lists2_x", detail);
|
||||
}
|
||||
execute(self, count, lists);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,193 @@
|
||||
// Console GPU page mappings: ID3D12CommandQueue CopyPageMappingsX, ClearPageMappingsX and
|
||||
// CopyPageMappingsBatchX (authorized GDK documentation; layouts and semantics derived from it).
|
||||
//
|
||||
// A page pool is title memory registered with RegisterPagePoolX; these calls make the 64 KiB (or,
|
||||
// with D3D12XBOX_PAGE_MAPPING_FLAG_2MB_PAGES, 2 MiB) pages at a destination GPU address show pool
|
||||
// pages. GPU addresses are title addresses in BetterXen and pool pages are xmem physical pages, so
|
||||
// each destination page is mapped onto the pool page's physical page with
|
||||
// XMemMapPhysicalPagesScatter; xmem reports the physical page behind a pool address. Range types:
|
||||
// incrementing pool pages, one constant pool page, null pages (unmapped) and skipped pages (left as
|
||||
// they are). The remapping happens when the call is made, not in queue order.
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
namespace {
|
||||
|
||||
struct PageMappingRange {
|
||||
UINT RangeType;
|
||||
UINT StartPageIndexInPool;
|
||||
UINT PageCount;
|
||||
};
|
||||
struct PageMappingBatch {
|
||||
D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress;
|
||||
UINT RangeCount;
|
||||
const PageMappingRange* pRanges;
|
||||
};
|
||||
static_assert(sizeof(PageMappingRange) == 12, "D3D12XBOX_PAGE_MAPPING_RANGE");
|
||||
static_assert(sizeof(PageMappingBatch) == 24, "D3D12XBOX_PAGE_MAPPING_BATCH");
|
||||
|
||||
enum : UINT { kIncrementing = 0, kConstant = 1, kNullPages = 2, kSkip = 3 };
|
||||
constexpr UINT kFlag2MbPages = 2;
|
||||
constexpr uint64_t kSmallPage = 64 * 1024;
|
||||
|
||||
using ScatterFn = BOOL(WINAPI*)(PVOID*, ULONG_PTR, PULONG_PTR);
|
||||
using QueryFn = int (*)(uint64_t, bx_xmem_region_info_t*);
|
||||
|
||||
struct Xmem {
|
||||
ScatterFn scatter = nullptr;
|
||||
QueryFn query = nullptr;
|
||||
Xmem() {
|
||||
if (HMODULE m = GetModuleHandleA("xmem.dll")) {
|
||||
scatter = reinterpret_cast<ScatterFn>(reinterpret_cast<void*>(GetProcAddress(m, "XMemMapPhysicalPagesScatter")));
|
||||
query = reinterpret_cast<QueryFn>(reinterpret_cast<void*>(GetProcAddress(m, "bx_xmem_query_region")));
|
||||
}
|
||||
}
|
||||
};
|
||||
const Xmem& xmem() {
|
||||
static const Xmem api;
|
||||
return api;
|
||||
}
|
||||
|
||||
void log_mapping(const char* what, const char* detail) {
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) <= 64) bx_log_emit(BX_LOG_INFO, "d3d12_xs", what, detail);
|
||||
}
|
||||
|
||||
void log_failure(const char* detail) {
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) <= 32) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "page_mapping_failed", detail);
|
||||
}
|
||||
|
||||
// Collects destination slots and physical pages (0: unmap), then maps them in one scatter call.
|
||||
class Mapper {
|
||||
public:
|
||||
Mapper(uint64_t pool, UINT pool_pages, UINT flags)
|
||||
: pool_(pool), pool_pages_(pool_pages), page_(flags & kFlag2MbPages ? 32 * kSmallPage : kSmallPage) {}
|
||||
|
||||
// One destination page `dst_page` (index from `dst`) showing pool page `pool_page`, or none.
|
||||
bool add(uint64_t dst, uint64_t dst_page, bool null_page, UINT pool_page) {
|
||||
for (uint64_t sub = 0; sub < page_ / kSmallPage; ++sub) {
|
||||
ULONG_PTR tag = 0;
|
||||
if (!null_page) {
|
||||
if (pool_page >= pool_pages_) return fail("pool page index past the pool", dst, pool_page);
|
||||
bx_xmem_region_info_t info{};
|
||||
const uint64_t src = pool_ + uint64_t(pool_page) * page_ + sub * kSmallPage;
|
||||
if (!xmem().query || !xmem().query(src, &info) || !info.physical_tag) {
|
||||
return fail("pool address has no xmem physical page", dst, pool_page);
|
||||
}
|
||||
tag = static_cast<ULONG_PTR>(info.physical_tag);
|
||||
}
|
||||
slots_.push_back(reinterpret_cast<PVOID>(static_cast<uintptr_t>(dst + dst_page * page_ + sub * kSmallPage)));
|
||||
tags_.push_back(tag);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool add_range(uint64_t dst, uint64_t& cursor, const PageMappingRange& range) {
|
||||
switch (range.RangeType) {
|
||||
case kSkip:
|
||||
cursor += range.PageCount;
|
||||
return true;
|
||||
case kIncrementing:
|
||||
case kConstant:
|
||||
case kNullPages:
|
||||
for (UINT i = 0; i < range.PageCount; ++i) {
|
||||
const UINT pool_page = range.RangeType == kIncrementing ? range.StartPageIndexInPool + i
|
||||
: range.StartPageIndexInPool;
|
||||
if (!add(dst, cursor + i, range.RangeType == kNullPages, pool_page)) return false;
|
||||
}
|
||||
cursor += range.PageCount;
|
||||
return true;
|
||||
default:
|
||||
return fail("unknown range type", dst, range.RangeType);
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT commit() {
|
||||
if (slots_.empty()) return S_OK;
|
||||
if (!xmem().scatter) {
|
||||
log_failure("xmem.dll!XMemMapPhysicalPagesScatter not available");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
if (!xmem().scatter(slots_.data(), slots_.size(), tags_.data())) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "XMemMapPhysicalPagesScatter of %zu pages at %p failed error=%lu",
|
||||
slots_.size(), slots_.front(), static_cast<unsigned long>(GetLastError()));
|
||||
log_failure(detail);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
size_t pages() const { return slots_.size(); }
|
||||
|
||||
private:
|
||||
bool fail(const char* why, uint64_t dst, UINT value) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s (destination 0x%llx, value %u)", why,
|
||||
static_cast<unsigned long long>(dst), value);
|
||||
log_failure(detail);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t pool_;
|
||||
UINT pool_pages_;
|
||||
uint64_t page_;
|
||||
std::vector<PVOID> slots_;
|
||||
std::vector<ULONG_PTR> tags_;
|
||||
};
|
||||
|
||||
HRESULT map_batches(UINT count, const PageMappingBatch* batches, uint64_t pool, UINT pool_pages, UINT flags,
|
||||
const char* method) {
|
||||
if (count && !batches) return E_INVALIDARG;
|
||||
Mapper mapper(pool, pool_pages, flags);
|
||||
for (UINT b = 0; b < count; ++b) {
|
||||
if (batches[b].RangeCount && !batches[b].pRanges) return E_INVALIDARG;
|
||||
uint64_t cursor = 0;
|
||||
for (UINT r = 0; r < batches[b].RangeCount; ++r) {
|
||||
if (!mapper.add_range(batches[b].DestinationAddress, cursor, batches[b].pRanges[r])) return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
const HRESULT hr = mapper.commit();
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "%s batches=%u first_destination=0x%llx pool=0x%llx pool_pages=%u flags=0x%x pages=%zu hr=0x%08lx",
|
||||
method, count, count ? static_cast<unsigned long long>(batches[0].DestinationAddress) : 0ull,
|
||||
static_cast<unsigned long long>(pool), pool_pages, flags, mapper.pages(), static_cast<unsigned long>(hr));
|
||||
log_mapping("page_mappings", detail);
|
||||
return hr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void*, UINT batch_count, const void* batches,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsBatchX");
|
||||
return map_batches(batch_count, static_cast<const PageMappingBatch*>(batches), pool, pool_pages, flags,
|
||||
"CopyPageMappingsBatchX");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT range_count, const void* ranges,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsX");
|
||||
const PageMappingBatch batch{destination, range_count, static_cast<const PageMappingRange*>(ranges)};
|
||||
return map_batches(1, &batch, pool, pool_pages, flags, "CopyPageMappingsX");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT page_count, UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "ClearPageMappingsX");
|
||||
const PageMappingRange range{kNullPages, 0, page_count};
|
||||
const PageMappingBatch batch{destination, 1, &range};
|
||||
return map_batches(1, &batch, 0, 0, flags, "ClearPageMappingsX");
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
/*
|
||||
* Pipeline states on the Xbox-layout device (ADR 0009), and the opt-in null-render mode.
|
||||
*
|
||||
* Every pipeline creation goes through the M2 shader format gate (shader_gate.h, ADR 0008), so
|
||||
* each stage writes a `shader_gate` record, and the title's root signature is unwrapped before
|
||||
* the description reaches the host. The Xbox *X variants take extended descriptions
|
||||
* (D3D12XBOX_EXTENDED_*_PIPELINE_STATE_DESC) that have no host equivalent; their count is logged
|
||||
* and the base description is created.
|
||||
*
|
||||
* Null-render mode (BX_NULL_RENDER=1, off by default): a pipeline the host refuses, for example
|
||||
* one whose shaders are console-only, becomes a BetterXen null pipeline instead of a failure.
|
||||
* Binding it is recorded per command list, and draws and dispatches recorded while it is bound
|
||||
* are skipped. Everything else still runs, so fences complete and frames present, with the
|
||||
* skipped work missing from them. Each refusal and each skip is logged: the mode exists to see
|
||||
* how far a title gets, not to hide what it cannot run.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "proxy.h"
|
||||
#include "shader_gate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
namespace {
|
||||
|
||||
bool null_render_enabled() {
|
||||
static const bool enabled = [] {
|
||||
char value[8] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_NULL_RENDER", value, sizeof(value));
|
||||
const bool on = n > 0 && n < sizeof(value) && value[0] == '1';
|
||||
if (on) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render", "enabled: refused pipelines become null pipelines");
|
||||
return on;
|
||||
}();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/* A pipeline-state object with no host pipeline behind it. */
|
||||
class NullPipelineState final : public ID3D12PipelineState {
|
||||
public:
|
||||
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
|
||||
riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12PipelineState)) {
|
||||
*ppv = static_cast<ID3D12PipelineState*>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
const ULONG left = --refs_;
|
||||
if (!left) {
|
||||
device_->Release();
|
||||
delete this;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT* size, void*) override {
|
||||
if (size) *size = 0;
|
||||
return DXGI_ERROR_NOT_FOUND;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override { return device_->QueryInterface(riid, ppv); }
|
||||
HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override {
|
||||
if (blob) *blob = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
ID3D12Device* device_;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
NullPipelineState** g_nulls = nullptr; // live null pipelines, so they can be recognised
|
||||
size_t g_null_count = 0;
|
||||
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;
|
||||
|
||||
template <typename T>
|
||||
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
|
||||
if (count == capacity) {
|
||||
const size_t grown_capacity = capacity ? capacity * 2 : 16;
|
||||
auto** grown = new (std::nothrow) T*[grown_capacity];
|
||||
if (!grown) return false;
|
||||
for (size_t i = 0; i < count; ++i) grown[i] = items[i];
|
||||
delete[] items;
|
||||
items = grown;
|
||||
capacity = grown_capacity;
|
||||
}
|
||||
items[count++] = item;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool erase(T** items, size_t& count, const T* item) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (items[i] == item) {
|
||||
items[i] = items[--count];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool contains(T* const* items, size_t count, const T* item) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (items[i] == item) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
|
||||
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
|
||||
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)));
|
||||
return *is_null ? nullptr : host;
|
||||
}
|
||||
|
||||
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
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) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!contains(g_lists, g_list_count, list)) return false;
|
||||
}
|
||||
static std::atomic<uint64_t> skipped{0};
|
||||
const uint64_t n = ++skipped;
|
||||
if ((n & (n - 1)) == 0) { // 1, 2, 4, 8, ...: enough to follow without flooding the log
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s with a null pipeline bound; total skipped=%llu", what,
|
||||
static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render_skip", detail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx%s", kind, static_cast<unsigned long>(hr),
|
||||
null_render_enabled() ? "; null pipeline returned" : "");
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
|
||||
if (!null_render_enabled() || !ppv) return hr;
|
||||
auto* null_pso = new (std::nothrow) NullPipelineState(device);
|
||||
if (!null_pso) return E_OUTOFMEMORY;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!push(g_nulls, g_null_count, g_null_capacity, null_pso)) {
|
||||
null_pso->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
*ppv = static_cast<ID3D12PipelineState*>(null_pso);
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
void log_extended(const char* kind, UINT count) {
|
||||
if (!count) return;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s: %u extended description(s) not applied", kind, count);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_extended_desc", detail);
|
||||
}
|
||||
|
||||
HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
BxShaderGate gate;
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
|
||||
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
|
||||
HRESULT hr = gate.admit("compute", "CS", desc->CS, admitted.CS);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateComputePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
BxShaderGate gate;
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
|
||||
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
|
||||
HRESULT hr = gate.admit("graphics", "VS", desc->VS, admitted.VS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "PS", desc->PS, admitted.PS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device2>(self);
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
size_t root_offset = SIZE_MAX;
|
||||
HRESULT hr = copy_stream(*desc, stream, offsets, names, &root_offset);
|
||||
if (FAILED(hr)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "stream of %llu bytes not parsed (unknown or console subobject?)",
|
||||
static_cast<unsigned long long>(desc->SizeInBytes));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pso_stream", detail);
|
||||
return refused(device, hr, "stream", riid, ppv);
|
||||
}
|
||||
if (root_offset != SIZE_MAX) {
|
||||
ID3D12RootSignature* root = nullptr;
|
||||
std::memcpy(&root, &stream[root_offset], sizeof(root));
|
||||
root = bx_xbox_unwrap_as(root);
|
||||
std::memcpy(&stream[root_offset], &root, sizeof(root));
|
||||
}
|
||||
BxShaderGate gate;
|
||||
for (size_t i = 0; i < offsets.size() && SUCCEEDED(hr); ++i) {
|
||||
D3D12_SHADER_BYTECODE in{};
|
||||
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
|
||||
D3D12_SHADER_BYTECODE out = in;
|
||||
hr = gate.admit("stream", names[i], in, out);
|
||||
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePipelineState");
|
||||
return create_stream(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title) {
|
||||
bool is_null = false;
|
||||
host_pipeline(title, &is_null);
|
||||
return is_null;
|
||||
}
|
||||
|
||||
void bx_xbox_pipeline_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
erase(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
void bx_xbox_list_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
|
||||
return create_compute(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineState");
|
||||
return create_graphics(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineStateX");
|
||||
log_extended("CreateComputePipelineStateX", extended_count);
|
||||
return create_compute(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineStateX");
|
||||
log_extended("CreateGraphicsPipelineStateX", extended_count);
|
||||
return create_graphics(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso) {
|
||||
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);
|
||||
if (!is_null) list->SetPipelineState(host);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso) {
|
||||
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);
|
||||
bx_xbox_gpu_writes_reset(list);
|
||||
return list->Reset(bx_xbox_unwrap_as(allocator), host);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
|
||||
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);
|
||||
}
|
||||
|
||||
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")) {
|
||||
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Dispatch");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "Dispatch")) list->Dispatch(x, y, z);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
|
||||
ID3D12Resource* arguments, UINT64 arguments_offset,
|
||||
ID3D12Resource* count, UINT64 count_offset) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ExecuteIndirect");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (list_skips(list, "ExecuteIndirect")) return;
|
||||
list->ExecuteIndirect(bx_xbox_unwrap_as(signature), max_commands, bx_xbox_unwrap_as(arguments), arguments_offset,
|
||||
bx_xbox_unwrap_as(count), count_offset);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
|
||||
ID3D12RootSignature* root, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandSignature");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
// D3D12XBOX_INDIRECT_ARGUMENT_TYPE_* values start at 100 and have no PC equivalent, except
|
||||
// DISPATCH_SINGLE / DISPATCH_L2 (105): a dispatch whose arguments are D3D12_DISPATCH_ARGUMENTS
|
||||
// and whose D3D12XBOX_DISPATCH_FLAGS are a direct parameter (authorized GDK documentation), so
|
||||
// the host gets D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. The flags are cache hints and are dropped.
|
||||
constexpr int kFirstXboxArgument = 100;
|
||||
constexpr int kXboxDispatchSingle = 105;
|
||||
constexpr UINT kMaxArguments = 32;
|
||||
D3D12_INDIRECT_ARGUMENT_DESC host_args[kMaxArguments] = {};
|
||||
char types[160] = {};
|
||||
size_t used = 0;
|
||||
bool console_only = desc->NumArgumentDescs > kMaxArguments;
|
||||
for (UINT i = 0; i < desc->NumArgumentDescs && i < kMaxArguments && desc->pArgumentDescs; ++i) {
|
||||
const int type = static_cast<int>(desc->pArgumentDescs[i].Type);
|
||||
host_args[i] = desc->pArgumentDescs[i];
|
||||
if (type == kXboxDispatchSingle) {
|
||||
host_args[i] = {};
|
||||
host_args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
|
||||
} else if (type >= kFirstXboxArgument) {
|
||||
console_only = true;
|
||||
}
|
||||
if (used < sizeof(types) - 8) used += std::snprintf(types + used, sizeof(types) - used, "%s%d", i ? "," : "", type);
|
||||
}
|
||||
D3D12_COMMAND_SIGNATURE_DESC host_desc = *desc;
|
||||
host_desc.pArgumentDescs = host_args;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
HRESULT hr = console_only ? E_NOTIMPL
|
||||
: device->CreateCommandSignature(&host_desc, bx_xbox_unwrap_as(root), riid, ppv);
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail), "stride=%u args=[%s] root_signature=%d hr=0x%08lx%s", desc->ByteStride, types,
|
||||
root ? 1 : 0, static_cast<unsigned long>(hr), console_only ? " (console argument types)" : "");
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "command_signature", detail);
|
||||
return SUCCEEDED(hr) ? bx_xbox_wrap_result(hr, riid, ppv) : hr;
|
||||
}
|
||||
|
||||
namespace {
|
||||
void log_once(std::atomic<bool>& flag, const char* event, const char* detail) {
|
||||
if (!flag.exchange(true)) bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ResetX");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (flags) log_once(logged, "reset_x_flags", "D3D12XBOX_COMMAND_LIST_RESET_FLAGS have no host meaning; ignored");
|
||||
return bx_xbox_list_reset(self, allocator, pso);
|
||||
}
|
||||
|
||||
// Console cache synchronisation points. The closest host D3D12 operation is a global UAV
|
||||
// barrier: all prior UAV work completes before later work starts.
|
||||
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT, UINT, D3D12_GPU_VIRTUAL_ADDRESS, SIZE_T) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SyncTopOfPipeX/SyncBottomOfPipeX");
|
||||
static std::atomic<bool> logged{false};
|
||||
log_once(logged, "sync_x", "SyncTopOfPipeX/SyncBottomOfPipeX recorded as a global UAV barrier");
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, UINT64) {
|
||||
BX_D3D_TRACE("XboxCommandAllocator", "SetAllocatorCallbackX");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (callback) {
|
||||
log_once(logged, "allocator_callback_x",
|
||||
"SetAllocatorCallbackX accepted; host command lists do not allocate from title memory, so it is never called");
|
||||
}
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* 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) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
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) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
|
||||
}
|
||||
|
||||
/*
|
||||
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
|
||||
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
|
||||
* from a host pipeline needs its creation description, which this layer does not keep yet: that
|
||||
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
|
||||
*/
|
||||
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);
|
||||
if (!from_null) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_derived",
|
||||
"deriving from a host pipeline is not implemented (its creation description is not kept)");
|
||||
}
|
||||
}
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived graphics");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived compute");
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
/*
|
||||
* Resources placed at a title-chosen GPU virtual address (ADR 0009, "translation by copy").
|
||||
*
|
||||
* On the console a title maps its own physical pages at an address and places resources there
|
||||
* with ID3D12Device::CreatePlacedResourceX / CreatePlacedResourceX1; CPU and GPU see the same
|
||||
* memory. D3DMetal cannot create a resource over existing memory (the existing-memory imports
|
||||
* measured for #473 return E_NOTIMPL), so each such resource gets a shadow resource on the host:
|
||||
*
|
||||
* - a buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's
|
||||
* memory when it is created;
|
||||
* - a texture gets a committed texture whose contents are not filled (logged); texture
|
||||
* contents need the console tiling translation (xg_xs) first.
|
||||
*
|
||||
* The title's address and the shadow are recorded, and the resource reports the title's address
|
||||
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
|
||||
* title addresses in GPU calls, are not done yet; both are logged when reached.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
struct Shadow {
|
||||
ID3D12Resource* host; // owned by the Xbox object, or (implicit shadows) by this table
|
||||
uint64_t title_va;
|
||||
uint64_t size;
|
||||
bool buffer;
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
|
||||
int mapped = 0; // outstanding Map calls on title memory (buffers)
|
||||
};
|
||||
|
||||
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
|
||||
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
|
||||
if (!s.buffer || end <= begin || end > s.size) return false;
|
||||
void* mapped = nullptr;
|
||||
const D3D12_RANGE none{0, 0};
|
||||
if (FAILED(s.host->Map(0, to_host ? &none : nullptr, &mapped)) || !mapped) return false;
|
||||
auto* host = static_cast<uint8_t*>(mapped) + begin;
|
||||
auto* title = reinterpret_cast<uint8_t*>(s.title_va) + begin;
|
||||
if (to_host) std::memcpy(host, title, static_cast<size_t>(end - begin));
|
||||
else std::memcpy(title, host, static_cast<size_t>(end - begin));
|
||||
const D3D12_RANGE written{static_cast<SIZE_T>(begin), static_cast<SIZE_T>(end)};
|
||||
s.host->Unmap(0, to_host ? &written : &none);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::mutex g_lock;
|
||||
Shadow* g_shadows = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
bool remember(const Shadow& shadow) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (g_count == g_capacity) {
|
||||
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
|
||||
auto* grown = new (std::nothrow) Shadow[capacity];
|
||||
if (!grown) return false;
|
||||
if (g_count) std::memcpy(grown, g_shadows, g_count * sizeof(Shadow));
|
||||
delete[] g_shadows;
|
||||
g_shadows = grown;
|
||||
g_capacity = capacity;
|
||||
}
|
||||
g_shadows[g_count++] = shadow;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool readable(const void* p, uint64_t size) {
|
||||
auto cursor = reinterpret_cast<uintptr_t>(p);
|
||||
const uintptr_t end = cursor + size;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT
|
||||
|| (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, const char* method,
|
||||
ID3D12Resource** out) {
|
||||
*out = nullptr;
|
||||
const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
if (buffer) {
|
||||
heap.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
} else {
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
}
|
||||
D3D12_RESOURCE_DESC host_desc = desc;
|
||||
// Console tiling layouts and D3D12XBOX_RESOURCE_FLAG_* bits have no PC meaning.
|
||||
constexpr UINT kPcResourceFlags = 0x1FF;
|
||||
host_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc.Flags & kPcResourceFlags);
|
||||
ID3D12Resource* resource = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
char detail[224];
|
||||
std::snprintf(detail, sizeof(detail), "%s title_va=0x%llx dim=%d width=%llu height=%u format=%d hr=0x%08lx",
|
||||
method, static_cast<unsigned long long>(title_va), static_cast<int>(desc.Dimension),
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format),
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", detail);
|
||||
if (FAILED(hr) || !resource) return FAILED(hr) ? hr : E_FAIL;
|
||||
|
||||
const auto* title = reinterpret_cast<const void*>(title_va);
|
||||
if (buffer) {
|
||||
void* mapped = nullptr;
|
||||
if (SUCCEEDED(resource->Map(0, nullptr, &mapped)) && mapped) {
|
||||
if (readable(title, desc.Width)) {
|
||||
std::memcpy(mapped, title, static_cast<size_t>(desc.Width));
|
||||
} else {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "title memory not readable; shadow left zeroed");
|
||||
}
|
||||
resource->Unmap(0, nullptr);
|
||||
}
|
||||
} else {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
|
||||
}
|
||||
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
|
||||
resource->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*out = resource;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT create_shadow(void* self, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** ppv,
|
||||
const char* method) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
const HRESULT hr = make_shadow(bx_xbox_host<ID3D12Device>(self), title_va, desc, method, &resource);
|
||||
if (FAILED(hr)) return hr;
|
||||
*ppv = resource;
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
|
||||
return a.Dimension == b.Dimension && a.Width == b.Width && a.Height == b.Height &&
|
||||
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
|
||||
}
|
||||
|
||||
// A view of placed memory with no resource object: reuse the shadow made for the same address
|
||||
// and shape, or make one. These shadows live for the rest of the process (logged).
|
||||
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
|
||||
}
|
||||
}
|
||||
ID3D12Resource* resource = nullptr;
|
||||
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
|
||||
}
|
||||
|
||||
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
|
||||
constexpr size_t kPcViewDescBytes = 40;
|
||||
static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == kPcViewDescBytes, "PC SRV description size");
|
||||
static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == kPcViewDescBytes, "PC UAV description size");
|
||||
|
||||
uint64_t view_location(const void* xbox_desc) {
|
||||
uint64_t va = 0;
|
||||
std::memcpy(&va, static_cast<const char*>(xbox_desc) + kPcViewDescBytes, sizeof(va));
|
||||
return va;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX");
|
||||
if (!desc || !location) return E_INVALIDARG;
|
||||
return create_shadow(self, location, *desc, riid, ppv, "CreatePlacedResourceX");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC1* desc1, UINT,
|
||||
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX1");
|
||||
if (!desc1 || !location) return E_INVALIDARG;
|
||||
// D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC followed by SamplerFeedbackMipRegion.
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
std::memcpy(&desc, desc1, sizeof(desc));
|
||||
return create_shadow(self, location, desc, riid, ppv, "CreatePlacedResourceX1");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawShaderResourceViewX");
|
||||
if (!resource_desc || !xbox_desc) return;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
|
||||
if (!resource) return;
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawUnorderedAccessViewX");
|
||||
if (!resource_desc || !xbox_desc) return;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
|
||||
if (!resource) return;
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateUnorderedAccessView(resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedShaderResourceViewX");
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
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));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedUnorderedAccessViewX");
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as(resource), nullptr,
|
||||
xbox_desc ? &pc : nullptr, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
|
||||
if (!title) return title;
|
||||
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 >= s.title_va && title < s.title_va + s.size) return s.host->GetGPUVirtualAddress() + (title - s.title_va);
|
||||
}
|
||||
return title; // not a title address this layer knows: a host address already, or untranslated
|
||||
}
|
||||
|
||||
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});
|
||||
}
|
||||
|
||||
void bx_xbox_placed_forget(IUnknown* host) {
|
||||
Shadow gone{};
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (static_cast<IUnknown*>(g_shadows[i].host) == host) {
|
||||
gone = g_shadows[i];
|
||||
g_shadows[i] = g_shadows[--g_count];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
|
||||
}
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self) {
|
||||
BX_D3D_TRACE("XboxResource", "GetGPUVirtualAddress");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
{
|
||||
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 host->GetGPUVirtualAddress();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* Page pools (RegisterPagePoolX / UnregisterPagePoolX, authorized GDK documentation): a title
|
||||
* registers a 64 KB-aligned, fully mapped range of its graphics memory as the source of later
|
||||
* CopyPageMappingsX calls. Registration is validated and recorded; the handle is the record.
|
||||
* CopyPageMappingsX itself (a queue method) is not implemented yet and stays a logged stub.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
struct PagePool {
|
||||
uint64_t address;
|
||||
UINT pages;
|
||||
PagePool* next;
|
||||
};
|
||||
|
||||
PagePool* g_pools = nullptr; // guarded by g_lock
|
||||
|
||||
bool fully_mapped(uint64_t address, uint64_t size) {
|
||||
auto cursor = static_cast<uintptr_t>(address);
|
||||
const uintptr_t end = cursor + static_cast<uintptr_t>(size);
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void*, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
|
||||
HANDLE* handle) {
|
||||
BX_D3D_TRACE("XboxDevice", "RegisterPagePoolX");
|
||||
constexpr uint64_t kPage = 64 * 1024;
|
||||
const bool valid = handle && pages && address && (address % kPage) == 0 && fully_mapped(address, pages * kPage);
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "address=0x%llx pages=%u %s", static_cast<unsigned long long>(address), pages,
|
||||
valid ? "registered" : "rejected (unaligned, empty or not fully mapped)");
|
||||
bx_log_emit(valid ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "page_pool", detail);
|
||||
if (!valid) return E_INVALIDARG;
|
||||
auto* pool = new (std::nothrow) PagePool{address, pages, nullptr};
|
||||
if (!pool) return E_OUTOFMEMORY;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
pool->next = g_pools;
|
||||
g_pools = pool;
|
||||
}
|
||||
*handle = pool;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void*, HANDLE handle) {
|
||||
BX_D3D_TRACE("XboxDevice", "UnregisterPagePoolX");
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (PagePool** link = &g_pools; *link; link = &(*link)->next) {
|
||||
if (*link == handle) {
|
||||
PagePool* gone = *link;
|
||||
*link = gone->next;
|
||||
delete gone;
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* Map on a resource that has title-visible memory (placed at a title address, or committed with
|
||||
* XMemAlloc memory) returns that memory, as on the console, where CPU and GPU share it. Other
|
||||
* resources map their host resource. Writes through the title pointer reach the host resource
|
||||
* only where this layer copies them (buffers at creation; texture contents are not copied yet,
|
||||
* logged at creation).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data) {
|
||||
BX_D3D_TRACE("XboxResource", "Map");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
uint64_t title_va = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
Shadow& s = g_shadows[i];
|
||||
if (s.host != host) continue;
|
||||
title_va = s.title_va;
|
||||
// Make GPU results visible: refresh the read range of title memory from the host.
|
||||
const uint64_t begin = read ? read->Begin : 0, end = read ? read->End : s.size;
|
||||
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
|
||||
++s.mapped;
|
||||
}
|
||||
}
|
||||
if (!title_va) {
|
||||
const HRESULT hr = host->Map(subresource, read, data);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxResource", "Map", hr);
|
||||
return hr;
|
||||
}
|
||||
if (subresource != 0) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_map",
|
||||
"Map of a non-zero subresource of title memory returns the resource base");
|
||||
}
|
||||
}
|
||||
if (data) *data = reinterpret_cast<void*>(title_va);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written) {
|
||||
BX_D3D_TRACE("XboxResource", "Unmap");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
Shadow& s = g_shadows[i];
|
||||
if (s.host != host) continue;
|
||||
// Hand the CPU's writes to the host resource (a null range means all of it).
|
||||
const uint64_t begin = written ? written->Begin : 0, end = written ? written->End : s.size;
|
||||
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
|
||||
if (s.mapped > 0) --s.mapped;
|
||||
return;
|
||||
}
|
||||
}
|
||||
host->Unmap(subresource, written);
|
||||
}
|
||||
|
||||
/*
|
||||
* Before a submission, buffers the title keeps mapped (persistent maps) are copied from title
|
||||
* memory to their host resources, up to 16 MB each; larger ones are logged once and not copied.
|
||||
*/
|
||||
void bx_xbox_sync_mapped_buffers() {
|
||||
constexpr uint64_t kLimit = 16ull << 20;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (!s.mapped || !s.buffer) continue;
|
||||
if (s.size > kLimit) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "persistently mapped buffer of %llu bytes not copied to the host before submit",
|
||||
static_cast<unsigned long long>(s.size));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_sync", detail);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
copy_buffer(s, true, 0, s.size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
/*
|
||||
* ID3D12CommandQueue::PresentX as titles call it on the Xbox-layout queue (authorized GDK
|
||||
* documentation: PresentX(PlaneCount, const D3D12XBOX_PRESENT_PLANE_PARAMETERS*,
|
||||
* const D3D12XBOX_PRESENT_PARAMETERS*)). This is separate from presentx.h, BetterXen's own
|
||||
* swapchain bridge for synthetic fixtures.
|
||||
*
|
||||
* On the first present, a host DXGI flip-model swapchain is created on the title's top-level
|
||||
* window (the visible window owned by this process), sized to plane 0's first resource. Each
|
||||
* present copies that resource into the current back buffer when formats and sizes match, and
|
||||
* otherwise leaves the back buffer unchanged (logged once), then presents with sync interval 0: frame pacing
|
||||
* is the title's own, through the frame events (frame_pacing.cpp). Plane 1, source and
|
||||
* destination rectangles, colour spaces and scaling are not applied (logged once).
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <cstdlib>
|
||||
#include <cwchar>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
|
||||
UINT64 Token;
|
||||
UINT ResourceCount;
|
||||
ID3D12Resource** ppResources;
|
||||
D3D12_RECT* pSrcViewRects;
|
||||
void* pDestPlacementBase;
|
||||
UINT ColorSpace;
|
||||
UINT ScaleFilter;
|
||||
UINT ExtendedDescCount;
|
||||
void* pExtendedDescs;
|
||||
UINT Flags;
|
||||
};
|
||||
static_assert(sizeof(PlaneParameters) == 72, "D3D12XBOX_PRESENT_PLANE_PARAMETERS layout");
|
||||
|
||||
constexpr UINT kBuffers = 3;
|
||||
|
||||
struct Presenter {
|
||||
std::mutex lock;
|
||||
bool failed = false;
|
||||
ID3D12CommandQueue* queue = nullptr; // host queue the swapchain was made for
|
||||
IDXGISwapChain3* swapchain = nullptr;
|
||||
ID3D12CommandAllocator* allocators[kBuffers] = {};
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
UINT64 fence_values[kBuffers] = {};
|
||||
UINT64 next_value = 1;
|
||||
HANDLE event = nullptr;
|
||||
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
|
||||
UINT width = 0, height = 0;
|
||||
UINT64 presents = 0;
|
||||
};
|
||||
Presenter g;
|
||||
|
||||
struct FindWindow {
|
||||
DWORD pid;
|
||||
HWND found;
|
||||
};
|
||||
BOOL CALLBACK find_window(HWND window, LPARAM param) {
|
||||
auto* f = reinterpret_cast<FindWindow*>(param);
|
||||
DWORD pid = 0;
|
||||
GetWindowThreadProcessId(window, &pid);
|
||||
if (pid == f->pid && IsWindowVisible(window) && !GetWindow(window, GW_OWNER)) {
|
||||
f->found = window;
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void log_hr(const char* what, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
|
||||
DXGI_FORMAT swapchain_format(DXGI_FORMAT f) {
|
||||
switch (f) {
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM:
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM:
|
||||
case DXGI_FORMAT_R10G10B10A2_UNORM:
|
||||
case DXGI_FORMAT_R16G16B16A16_FLOAT: return f;
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
default: return DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
}
|
||||
}
|
||||
|
||||
bool create_locked(ID3D12CommandQueue* queue, const D3D12_RESOURCE_DESC& source) {
|
||||
FindWindow f{GetCurrentProcessId(), nullptr};
|
||||
EnumWindows(find_window, reinterpret_cast<LPARAM>(&f));
|
||||
if (!f.found) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", "no visible window owned by the title; frames not shown");
|
||||
return false;
|
||||
}
|
||||
using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
|
||||
HMODULE dxgi = LoadLibraryW(L"dxgi.dll");
|
||||
auto create_factory = dxgi ? reinterpret_cast<CreateFactory2>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory2"))) : nullptr;
|
||||
IDXGIFactory2* factory = nullptr;
|
||||
HRESULT hr = create_factory ? create_factory(0, __uuidof(IDXGIFactory2), reinterpret_cast<void**>(&factory)) : E_NOINTERFACE;
|
||||
if (FAILED(hr)) {
|
||||
log_hr("CreateDXGIFactory2", hr);
|
||||
return false;
|
||||
}
|
||||
g.width = static_cast<UINT>(source.Width);
|
||||
g.height = source.Height;
|
||||
g.format = swapchain_format(source.Format);
|
||||
DXGI_SWAP_CHAIN_DESC1 desc{};
|
||||
desc.Width = g.width;
|
||||
desc.Height = g.height;
|
||||
desc.Format = g.format;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
desc.BufferCount = kBuffers;
|
||||
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
IDXGISwapChain1* chain1 = nullptr;
|
||||
hr = factory->CreateSwapChainForHwnd(queue, f.found, &desc, nullptr, nullptr, &chain1);
|
||||
factory->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr("CreateSwapChainForHwnd", hr);
|
||||
return false;
|
||||
}
|
||||
hr = chain1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&g.swapchain));
|
||||
chain1->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr("IDXGISwapChain3", hr);
|
||||
return false;
|
||||
}
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
for (UINT i = 0; SUCCEEDED(hr) && i < kBuffers; ++i) {
|
||||
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
|
||||
reinterpret_cast<void**>(&g.allocators[i]));
|
||||
}
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.allocators[0], nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&g.list));
|
||||
}
|
||||
if (SUCCEEDED(hr)) hr = g.list->Close();
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g.fence));
|
||||
if (device) device->Release();
|
||||
g.event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (FAILED(hr) || !g.event) {
|
||||
log_hr("present resources", FAILED(hr) ? hr : E_OUTOFMEMORY);
|
||||
return false;
|
||||
}
|
||||
g.queue = queue;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "swapchain %ux%u format=%d on the title window (title buffer format=%d)", g.width,
|
||||
g.height, static_cast<int>(g.format), static_cast<int>(source.Format));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox", detail);
|
||||
return true;
|
||||
}
|
||||
|
||||
void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = r;
|
||||
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = before;
|
||||
b.Transition.StateAfter = after;
|
||||
list->ResourceBarrier(1, &b);
|
||||
}
|
||||
|
||||
|
||||
// Diagnostics (off unless BX_PRESENT_DUMP=<folder>): every BX_PRESENT_DUMP_EVERY-th present (default
|
||||
// 64, at most 32 files) the presented buffer is copied to a readback buffer and written as a BMP,
|
||||
// downscaled 4x, for looking at frames without screen-recording access.
|
||||
const wchar_t* dump_folder() {
|
||||
static wchar_t folder[MAX_PATH] = L"";
|
||||
static const bool on = GetEnvironmentVariableW(L"BX_PRESENT_DUMP", folder, MAX_PATH) > 0;
|
||||
return on ? folder : nullptr;
|
||||
}
|
||||
UINT64 dump_every() {
|
||||
static const UINT64 every = [] {
|
||||
char v[16];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_PRESENT_DUMP_EVERY", v, sizeof(v));
|
||||
const unsigned long k = (n > 0 && n < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
|
||||
return static_cast<UINT64>(k ? k : 64);
|
||||
}();
|
||||
return every;
|
||||
}
|
||||
|
||||
void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_RESOURCE_DESC& desc, UINT64 frame) {
|
||||
static int written = 0;
|
||||
if (written >= 32 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return;
|
||||
const DXGI_FORMAT f = desc.Format;
|
||||
const bool bgra = f == DXGI_FORMAT_B8G8R8A8_UNORM || f == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
|
||||
const bool rgba = f == DXGI_FORMAT_R8G8B8A8_UNORM || f == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
|
||||
if (!bgra && !rgba) return;
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return;
|
||||
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
|
||||
UINT rows = 0;
|
||||
UINT64 row_bytes = 0, total = 0;
|
||||
device->GetCopyableFootprints(&desc, 0, 1, 0, &fp, &rows, &row_bytes, &total);
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC buf{};
|
||||
buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buf.Width = total;
|
||||
buf.Height = 1;
|
||||
buf.DepthOrArraySize = 1;
|
||||
buf.MipLevels = 1;
|
||||
buf.SampleDesc.Count = 1;
|
||||
buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ID3D12Resource* readback = nullptr;
|
||||
ID3D12CommandAllocator* alloc = nullptr;
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&readback));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&alloc));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, __uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
|
||||
if (SUCCEEDED(hr)) {
|
||||
barrier(list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{readback, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
|
||||
dst.PlacedFootprint = fp;
|
||||
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
list->Close();
|
||||
ID3D12CommandList* lists[] = {list};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
queue->Signal(fence, 1);
|
||||
fence->SetEventOnCompletion(1, done);
|
||||
WaitForSingleObject(done, 5000);
|
||||
CloseHandle(done);
|
||||
const BYTE* data = nullptr;
|
||||
if (SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast<void**>(const_cast<BYTE**>(&data))))) {
|
||||
const UINT w = static_cast<UINT>(desc.Width) / 4, h = desc.Height / 4;
|
||||
const UINT stride = (w * 3 + 3) & ~3u;
|
||||
std::vector<BYTE> bmp(54 + static_cast<size_t>(stride) * h, 0);
|
||||
auto put32 = [&](size_t at, uint32_t v) { std::memcpy(&bmp[at], &v, 4); };
|
||||
bmp[0] = 'B'; bmp[1] = 'M';
|
||||
put32(2, static_cast<uint32_t>(bmp.size())); put32(10, 54); put32(14, 40);
|
||||
put32(18, w); put32(22, h); bmp[26] = 1; bmp[28] = 24; put32(34, static_cast<uint32_t>(stride * h));
|
||||
uint64_t sum = 0;
|
||||
for (UINT y = 0; y < h; ++y) {
|
||||
const BYTE* row = data + fp.Offset + static_cast<UINT64>(y * 4) * fp.Footprint.RowPitch;
|
||||
BYTE* out = &bmp[54 + static_cast<size_t>(h - 1 - y) * stride];
|
||||
for (UINT x = 0; x < w; ++x) {
|
||||
const BYTE* px = row + static_cast<size_t>(x) * 16;
|
||||
const BYTE r = bgra ? px[2] : px[0], g = px[1], b = bgra ? px[0] : px[2];
|
||||
out[x * 3 + 0] = b; out[x * 3 + 1] = g; out[x * 3 + 2] = r;
|
||||
sum += r + g + b;
|
||||
}
|
||||
}
|
||||
readback->Unmap(0, nullptr);
|
||||
wchar_t path[MAX_PATH];
|
||||
std::swprintf(path, MAX_PATH, L"%ls\\frame_%06llu.bmp", dump_folder(), static_cast<unsigned long long>(frame));
|
||||
HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file != INVALID_HANDLE_VALUE) {
|
||||
DWORD wrote = 0;
|
||||
WriteFile(file, bmp.data(), static_cast<DWORD>(bmp.size()), &wrote, nullptr);
|
||||
CloseHandle(file);
|
||||
++written;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "frame %llu dumped %ux%u, mean channel value %.1f",
|
||||
static_cast<unsigned long long>(frame), w, h, w && h ? double(sum) / (double(w) * h * 3) : 0.0);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_dump", detail);
|
||||
}
|
||||
}
|
||||
if (fence) fence->Release();
|
||||
if (list) list->Release();
|
||||
if (alloc) alloc->Release();
|
||||
if (readback) readback->Release();
|
||||
device->Release();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes_raw,
|
||||
const void* parameters) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
|
||||
(void)parameters;
|
||||
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
|
||||
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
|
||||
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
|
||||
if (!source) return E_INVALIDARG;
|
||||
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
|
||||
std::lock_guard<std::mutex> guard(g.lock);
|
||||
if (g.failed) return S_OK;
|
||||
const D3D12_RESOURCE_DESC desc = source->GetDesc();
|
||||
if (!g.swapchain && !create_locked(queue, desc)) {
|
||||
g.failed = true;
|
||||
return S_OK; // the title keeps running; frames are not shown (logged)
|
||||
}
|
||||
static std::atomic<bool> logged_extra{false};
|
||||
if ((plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase) && !logged_extra.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox",
|
||||
"plane 1, view rectangles, placement and scaling are not applied; plane 0 is copied as is");
|
||||
}
|
||||
const UINT index = g.swapchain->GetCurrentBackBufferIndex();
|
||||
if (g.fence->GetCompletedValue() < g.fence_values[index]) {
|
||||
g.fence->SetEventOnCompletion(g.fence_values[index], g.event);
|
||||
WaitForSingleObject(g.event, 2000);
|
||||
}
|
||||
ID3D12Resource* back = nullptr;
|
||||
HRESULT hr = g.swapchain->GetBuffer(index, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&back));
|
||||
if (FAILED(hr)) {
|
||||
log_hr("GetBuffer", hr);
|
||||
return S_OK;
|
||||
}
|
||||
g.allocators[index]->Reset();
|
||||
g.list->Reset(g.allocators[index], nullptr);
|
||||
const bool copyable = desc.Width == g.width && desc.Height == g.height && swapchain_format(desc.Format) == g.format &&
|
||||
desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1;
|
||||
if (copyable) {
|
||||
// The title's buffer is assumed to be presentable (PRESENT, i.e. COMMON) when PresentX is called.
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{back, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT);
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
} else {
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "title buffer %llux%u format=%d does not match the swapchain; not copied, the window shows the previous contents",
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
}
|
||||
g.list->Close();
|
||||
ID3D12CommandList* lists[] = {g.list};
|
||||
g.queue->ExecuteCommandLists(1, lists);
|
||||
back->Release();
|
||||
hr = g.swapchain->Present(0, 0);
|
||||
g.fence_values[index] = g.next_value++;
|
||||
g.queue->Signal(g.fence, g.fence_values[index]);
|
||||
const UINT64 n = ++g.presents;
|
||||
if (dump_folder() && copyable && n % dump_every() == 0) dump_frame(g.queue, source, desc, n);
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "frames presented=%llu last hr=0x%08lx", static_cast<unsigned long long>(n),
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_frames", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
@@ -513,10 +513,13 @@ const StreamSubobject* find_subobject(uint32_t type) {
|
||||
}
|
||||
|
||||
/* Copies the caller's stream into `copy` so the gate can substitute prepared bytecode without
|
||||
* touching memory it does not own, and records where each shader payload sits. An unknown tag,
|
||||
* touching memory it does not own, and records where each shader payload sits (and, when
|
||||
* `root_offset` is given, the root-signature payload, or SIZE_MAX without one). An unknown tag,
|
||||
* or a payload that overruns SizeInBytes, is rejected. */
|
||||
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
|
||||
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names) {
|
||||
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
|
||||
size_t* root_offset) {
|
||||
if (root_offset) *root_offset = SIZE_MAX;
|
||||
if (desc.SizeInBytes == 0 || !desc.pPipelineStateSubobjectStream) return E_INVALIDARG;
|
||||
const auto* source = static_cast<const uint8_t*>(desc.pPipelineStateSubobjectStream);
|
||||
copy.assign(source, source + desc.SizeInBytes);
|
||||
@@ -543,6 +546,7 @@ HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<ui
|
||||
const size_t payload = offset + entry->payload_offset;
|
||||
const size_t record = entry->record_size;
|
||||
if (copy.size() - offset < record) return E_INVALIDARG;
|
||||
if (root_offset && entry->type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) *root_offset = payload;
|
||||
if (entry->stage) {
|
||||
D3D12_SHADER_BYTECODE code{};
|
||||
std::memcpy(&code, ©[payload], sizeof(code));
|
||||
@@ -575,7 +579,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
const HRESULT copied = copy_stream(*desc, stream, offsets, names);
|
||||
const HRESULT copied = copy_stream(*desc, stream, offsets, names, nullptr);
|
||||
{
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=%d",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
@@ -117,3 +118,9 @@ using BxCommandAllocatorProxy = BxChildProxy<BxCommandAllocatorProxyGen>;
|
||||
using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_PROXY_H */
|
||||
|
||||
/* Validates and copies a pipeline-state stream (proxy.cpp, #576): shader payload offsets and
|
||||
* stage names, and the root-signature payload offset when `root_offset` is given. */
|
||||
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
|
||||
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
|
||||
size_t* root_offset);
|
||||
@@ -296,6 +296,13 @@ HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12
|
||||
return S_OK;
|
||||
}
|
||||
default:
|
||||
// A container with a DXIL part that the classifier cannot call executable DXIL:
|
||||
// the measured case is a header-only program (a `NOBC` payload, no bitcode), which
|
||||
// D3DMetal crashes on in CreatePipelineState instead of failing. Refuse it.
|
||||
if (info.dxil_chunk_size != 0) {
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "reject_unclassified_dxil", E_NOTIMPL);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "pass_original", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ public:
|
||||
* host gets: the bridge's prepared DXIL copy for DXIL and dual containers, or `in` unchanged
|
||||
* for legacy DXBC, unclassifiable input, or when the bridge is missing (logged once as
|
||||
* `shader_bridge_missing`). Returns E_NOTIMPL for an ACCC-only container, which has no
|
||||
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge. Copies live until this
|
||||
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge, and for a container whose
|
||||
* DXIL part the bridge cannot classify (a header-only program). Copies live until this
|
||||
* object is destroyed.
|
||||
*/
|
||||
HRESULT admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the Xbox-layout function tables of the d3d12_xs proxy objects.
|
||||
|
||||
A title built against the Xbox D3D12 headers calls every method through a function table whose
|
||||
order is not the PC D3D12 order (Xbox-only methods sit between and inside the PC ones). This
|
||||
script reads two headers:
|
||||
|
||||
* the Xbox Series header (d3d12_xs.h from the GDKX, used under Microsoft's authorization). Only
|
||||
facts are taken from it: interface names and IIDs, the slot order of each function table, and
|
||||
each method's name, return type and parameter types. Nothing from it is copied into the output
|
||||
verbatim beyond those names, and the header itself is never committed.
|
||||
* the toolchain's PC <d3d12.h>, which the shim is compiled against.
|
||||
|
||||
For every slot of the chosen Xbox interfaces it emits one of:
|
||||
* a typed forwarder to the PC method of the same name, when the Xbox and PC signatures are
|
||||
equivalent (the PC types are used, so the compiler handles struct returns and the calling
|
||||
convention); interface-pointer parameters are unwrapped and (REFIID, void**) results wrapped;
|
||||
* a shared IUnknown/GetDevice slot implemented in xbox_facade.cpp;
|
||||
* a stub that logs BX_VTABLE_STUB_LOG and returns a neutral value, for Xbox-only methods and for
|
||||
methods whose signatures differ.
|
||||
|
||||
Usage: python3 shims/d3d12_xs/tools/gen_xbox_tables.py /path/to/d3d12_xs.h [path/to/pc/d3d12.h]
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import gen_proxy # noqa: E402 (PC header parser shared with the PC proxy generator)
|
||||
|
||||
OUT_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
# Xbox leaf interface -> (PC interface the host object must provide, C++ family tag)
|
||||
FAMILIES = {
|
||||
"ID3D12Device11": ("ID3D12Device10", "Device"),
|
||||
"ID3D12Resource2": ("ID3D12Resource2", "Resource"),
|
||||
"ID3D12Heap1": ("ID3D12Heap1", "Heap"),
|
||||
"ID3D12Fence1": ("ID3D12Fence", "Fence"), # D3DMetal answers ID3D12Fence, not Fence1
|
||||
"ID3D12DescriptorHeap": ("ID3D12DescriptorHeap", "DescriptorHeap"),
|
||||
"ID3D12RootSignature": ("ID3D12RootSignature", "RootSignature"),
|
||||
"ID3D12PipelineState": ("ID3D12PipelineState", "PipelineState"),
|
||||
"ID3D12CommandAllocator": ("ID3D12CommandAllocator", "CommandAllocator"),
|
||||
"ID3D12QueryHeap": ("ID3D12QueryHeap", "QueryHeap"),
|
||||
"ID3D12CommandSignature": ("ID3D12CommandSignature", "CommandSignature"),
|
||||
"ID3D12CommandQueue": ("ID3D12CommandQueue", "CommandQueue"),
|
||||
"ID3D12GraphicsCommandList8": ("ID3D12GraphicsCommandList7", "GraphicsCommandList"),
|
||||
}
|
||||
# Xbox-only slots implemented by hand in xbox_facade.cpp: family -> {method: function}.
|
||||
CUSTOM = {
|
||||
"Device": {"CreateCommandQueueX": "bx_xbox_device_create_command_queue_x",
|
||||
"CreateCommandListX": "bx_xbox_device_create_command_list_x",
|
||||
"SetFrameIntervalX": "bx_xbox_device_set_frame_interval_x",
|
||||
"ScheduleFrameEventX": "bx_xbox_device_schedule_frame_event_x",
|
||||
"WaitFrameEventX": "bx_xbox_device_wait_frame_event_x",
|
||||
"CreatePlacedResourceX": "bx_xbox_device_create_placed_resource_x",
|
||||
"CreatePlacedResourceX1": "bx_xbox_device_create_placed_resource_x1",
|
||||
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
|
||||
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
|
||||
"CreateConstantBufferView": "bx_xbox_device_create_constant_buffer_view",
|
||||
"CopyDescriptors": "bx_xbox_device_copy_descriptors",
|
||||
"CreateCommandSignature": "bx_xbox_device_create_command_signature",
|
||||
"CreatePipelineState": "bx_xbox_device_create_pipeline_state",
|
||||
"DeserializeGraphicsPipelineStateX": "bx_xbox_device_deserialize_graphics_pipeline_state_x",
|
||||
"CreateDerivedGraphicsPipelineStateX": "bx_xbox_device_create_derived_graphics_pipeline_state_x",
|
||||
"CreateDerivedComputePipelineStateX": "bx_xbox_device_create_derived_compute_pipeline_state_x",
|
||||
"DeserializeComputePipelineStateX": "bx_xbox_device_deserialize_compute_pipeline_state_x",
|
||||
"CreateSamplerX": "bx_xbox_device_create_sampler_x",
|
||||
"RegisterPagePoolX": "bx_xbox_device_register_page_pool_x",
|
||||
"UnregisterPagePoolX": "bx_xbox_device_unregister_page_pool_x",
|
||||
"CreateComputePipelineState": "bx_xbox_device_create_compute_pipeline_state",
|
||||
"CreateGraphicsPipelineState": "bx_xbox_device_create_graphics_pipeline_state",
|
||||
"CreateComputePipelineStateX": "bx_xbox_device_create_compute_pipeline_state_x",
|
||||
"CreateGraphicsPipelineStateX": "bx_xbox_device_create_graphics_pipeline_state_x",
|
||||
"CreateCommittedResource": "bx_xbox_device_create_committed_resource",
|
||||
"CreateCommittedResource1": "bx_xbox_device_create_committed_resource1",
|
||||
"CreateCommittedResource2": "bx_xbox_device_create_committed_resource2",
|
||||
"CreateCommittedResource3": "bx_xbox_device_create_committed_resource3",
|
||||
"CreatePlacedRawShaderResourceViewX": "bx_xbox_device_create_placed_raw_srv_x",
|
||||
"CreatePlacedRawUnorderedAccessViewX": "bx_xbox_device_create_placed_raw_uav_x",
|
||||
"CreatePlacedShaderResourceViewX": "bx_xbox_device_create_placed_srv_x",
|
||||
"CreatePlacedUnorderedAccessViewX": "bx_xbox_device_create_placed_uav_x"},
|
||||
"Resource": {"GetGPUVirtualAddress": "bx_xbox_resource_get_gpu_virtual_address",
|
||||
"Map": "bx_xbox_resource_map", "Unmap": "bx_xbox_resource_unmap"},
|
||||
"Fence": {"GetGpuAddressX": "bx_xbox_fence_get_gpu_address_x", "Signal": "bx_xbox_fence_signal"},
|
||||
"CommandQueue": {"ExecuteCommandLists": "bx_xbox_queue_execute_command_lists",
|
||||
"Signal": "bx_xbox_queue_signal", "Wait": "bx_xbox_queue_wait",
|
||||
"PresentX": "bx_xbox_queue_present_x",
|
||||
"CopyPageMappingsBatchX": "bx_xbox_queue_copy_page_mappings_batch_x",
|
||||
"CopyPageMappingsX": "bx_xbox_queue_copy_page_mappings_x",
|
||||
"ClearPageMappingsX": "bx_xbox_queue_clear_page_mappings_x",
|
||||
"ExecuteCommandLists2X": "bx_xbox_queue_execute_command_lists2_x"},
|
||||
"CommandAllocator": {"SetAllocatorCallbackX": "bx_xbox_allocator_set_callback_x"},
|
||||
"DescriptorHeap": {"GetCPUDescriptorHandleForHeapStart": "bx_xbox_heap_cpu_start",
|
||||
"GetGPUDescriptorHandleForHeapStart": "bx_xbox_heap_gpu_start"},
|
||||
"GraphicsCommandList": {"ResourceBarrier": "bx_xbox_list_resource_barrier",
|
||||
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
|
||||
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
|
||||
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
|
||||
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
|
||||
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
|
||||
"Reset": "bx_xbox_list_reset",
|
||||
"ResetX": "bx_xbox_list_reset_x",
|
||||
"Wait64BitValueX": "bx_xbox_list_wait64_x",
|
||||
"Wait32BitValueX": "bx_xbox_list_wait32_x",
|
||||
"Write32BitValueBottomOfPipeX": "bx_xbox_list_write32_bop_x",
|
||||
"Write64BitValueBottomOfPipeX": "bx_xbox_list_write64_bop_x",
|
||||
"Write32BitValueTopOfPipeX": "bx_xbox_list_write32_top_x",
|
||||
"Write64BitValueTopOfPipeX": "bx_xbox_list_write64_top_x",
|
||||
"SyncTopOfPipeX": "bx_xbox_list_sync_x",
|
||||
"SyncBottomOfPipeX": "bx_xbox_list_sync_x",
|
||||
"DrawInstanced": "bx_xbox_list_draw_instanced",
|
||||
"DrawIndexedInstanced": "bx_xbox_list_draw_indexed_instanced",
|
||||
"Dispatch": "bx_xbox_list_dispatch",
|
||||
"ExecuteIndirect": "bx_xbox_list_execute_indirect"},
|
||||
}
|
||||
SHARED = {"QueryInterface": "bx_xbox_query_interface", "AddRef": "bx_xbox_add_ref",
|
||||
"Release": "bx_xbox_release", "GetDevice": "bx_xbox_get_device"}
|
||||
# Interfaces whose pointers a forwarded call must unwrap from an Xbox object to its host.
|
||||
WRAPPABLE = re.compile(r"^(const\s+)?(ID3D12\w+|IUnknown)\s*\*$")
|
||||
WRAPPABLE_ARRAY = re.compile(r"^(ID3D12\w+)\s*\*\s*const\s*\*$")
|
||||
|
||||
|
||||
def strip_sal(text):
|
||||
text = re.sub(r"//[^\n]*", "", text)
|
||||
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
|
||||
# SAL annotations, including arguments with nested parentheses such as sizeof(UINT).
|
||||
out, i = [], 0
|
||||
for m in re.finditer(r"\b_[A-Za-z]\w*_\b", text):
|
||||
if m.start() < i:
|
||||
continue
|
||||
out.append(text[i:m.start()])
|
||||
j = m.end()
|
||||
while j < len(text) and text[j] == " ":
|
||||
j += 1
|
||||
if j < len(text) and text[j] == "(":
|
||||
depth = 0
|
||||
while j < len(text):
|
||||
depth += {"(": 1, ")": -1}.get(text[j], 0)
|
||||
j += 1
|
||||
if depth == 0:
|
||||
break
|
||||
i = j
|
||||
out.append(text[i:])
|
||||
return " ".join("".join(out).split())
|
||||
|
||||
|
||||
def canon(t):
|
||||
"""Canonical spelling for comparing an Xbox and a PC parameter or return type."""
|
||||
t = " ".join(t.split())
|
||||
t = re.sub(r"\s*\*\s*", "*", t)
|
||||
t = re.sub(r"\s*&\s*", "&", t)
|
||||
t = t.replace("LPCWSTR", "const WCHAR*").replace("LPCSTR", "const char*")
|
||||
t = re.sub(r"\bWINBOOL\b", "BOOL", t)
|
||||
t = re.sub(r"\bFLOAT\b", "float", t)
|
||||
t = re.sub(r"^const IID&$", "REFIID", t)
|
||||
t = re.sub(r"^const GUID&$", "REFGUID", t)
|
||||
if "*" not in t and "&" not in t and "[" not in t:
|
||||
t = re.sub(r"^const ", "", t) # top-level const on a by-value parameter
|
||||
return t
|
||||
|
||||
|
||||
def xbox_param_type(p):
|
||||
p = " ".join(p.split())
|
||||
m = re.match(r"^(.*?)(\w+)(\[[^\]]*\])$", p)
|
||||
if m:
|
||||
return canon(m.group(1)) + m.group(3)
|
||||
m = re.match(r"^(.*[\s\*&])(\w+)$", p)
|
||||
return canon(m.group(1) if m else p)
|
||||
|
||||
|
||||
def parse_xbox(text):
|
||||
iids = {m.group(1): m.groups()[1:] for m in re.finditer(
|
||||
r"^D3DINTERFACE\((\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),"
|
||||
r"\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+)\)", text, re.M)}
|
||||
bases = {m.group(1): m.group(2) for m in re.finditer(
|
||||
r"^D3DINTERFACE\((\w+),[^)]*\)\s*:\s*public\s+(\w+)", text, re.M)}
|
||||
tables = {}
|
||||
for m in re.finditer(r"struct\s+(\w+)_Function_Table\s*\{((?:(?!struct\s+\w+_Function_Table\b).)*?)\n\s*\};", text, re.S):
|
||||
entries = []
|
||||
for decl in re.split(r";\s*\n", m.group(2) + "\n"):
|
||||
decl = strip_sal(decl).rstrip(";").strip()
|
||||
b = re.match(r"^(\w+)_Function_Table\s+\w+$", decl)
|
||||
if b:
|
||||
entries.append(("base", b.group(1)))
|
||||
continue
|
||||
f = re.match(r"^(.*?)\(\s*D3DAPI\s*\*\s*(\w+)\s*\)\s*\((.*)\)$", decl, re.S)
|
||||
if f:
|
||||
params = [x.strip() for x in f.group(3).split(",") if x.strip() and x.strip() != "void"]
|
||||
entries.append(("fn", (f.group(2), canon(f.group(1)), [xbox_param_type(p) for p in params])))
|
||||
tables[m.group(1)] = entries
|
||||
return iids, bases, tables
|
||||
|
||||
|
||||
def flatten(tables, name):
|
||||
out = []
|
||||
for kind, v in tables.get(name, []):
|
||||
out += flatten(tables, v) if kind == "base" else [v]
|
||||
return out
|
||||
|
||||
|
||||
def table_name(iface):
|
||||
return "D3D12" + iface[len("ID3D12"):] if iface.startswith("ID3D12") else iface
|
||||
|
||||
|
||||
def pc_methods(interfaces, leaf):
|
||||
methods = {}
|
||||
for iface in gen_proxy.chain_of(interfaces, leaf):
|
||||
for ret, name, params in interfaces[iface][1]:
|
||||
methods.setdefault(name, (iface, ret, params))
|
||||
return methods
|
||||
|
||||
|
||||
def classify(xret, xparams, pc):
|
||||
"""Returns ('forward', struct_return) when the Xbox slot can call the PC method, else None."""
|
||||
_, pret, pparams = pc
|
||||
pp = [canon(t) + a for t, a in pparams]
|
||||
xp = xparams[1:] # drop the explicit Xbox `this`
|
||||
pr = canon(pret)
|
||||
if xp == pp and (xret == pr or (xret == "void" and pr in ("void", "HRESULT"))):
|
||||
return ("forward", False)
|
||||
if pr.endswith("*") and pp and pp[0] == pr and pr[:-1] == xret and xp == pp[1:]:
|
||||
return ("forward", True) # Xbox returns by value, PC by pointer
|
||||
if xret == "void" and pr.endswith("*") and pp and pp[0] == pr and xp == pp:
|
||||
return ("forward", False) # Xbox out-pointer, PC returns that pointer
|
||||
return None
|
||||
|
||||
|
||||
def emit_forward(family, slot, name, pc, struct_return):
|
||||
iface, pret, pparams = pc
|
||||
params = list(pparams)
|
||||
ret = pret[:-1].strip() if struct_return else pret
|
||||
if struct_return:
|
||||
params = params[1:]
|
||||
decl, call, pre, post = [], [], [], []
|
||||
for i, (t, arr) in enumerate(params):
|
||||
decl.append(f"{t} a{i}{arr}")
|
||||
translate = {"D3D12_CPU_DESCRIPTOR_HANDLE": "bx_xbox_host_cpu_handle",
|
||||
"D3D12_GPU_DESCRIPTOR_HANDLE": "bx_xbox_host_gpu_handle",
|
||||
"D3D12_GPU_VIRTUAL_ADDRESS": "bx_xbox_host_gpu_va"}.get(canon(t)) if not arr else None
|
||||
if translate:
|
||||
call.append(f"{translate}(a{i})")
|
||||
elif WRAPPABLE.match(t) and not arr:
|
||||
call.append(f"bx_xbox_unwrap_as<{WRAPPABLE.match(t).group(2)}>(a{i})")
|
||||
elif WRAPPABLE_ARRAY.match(t) and not arr:
|
||||
elem = WRAPPABLE_ARRAY.match(t).group(1)
|
||||
pre.append(f"BxXboxUnwrapArray<{elem}> u{i}(a{i}, {find_count(params, i, name)});")
|
||||
pre.append(f"if (!u{i}.ok()) return {failure_value(ret)};")
|
||||
call.append(f"u{i}.data()")
|
||||
else:
|
||||
call.append(f"a{i}")
|
||||
wrap_out = len(params) >= 2 and canon(params[-2][0]) == "REFIID" and canon(params[-1][0]) == "void**"
|
||||
host = f"bx_xbox_host<{iface}>(self)"
|
||||
lines = [f"static {ret} STDMETHODCALLTYPE x_{family}_{slot}(void* self{''.join(', ' + d for d in decl)}) {{",
|
||||
f' BX_D3D_TRACE("Xbox{family}", "{name}");']
|
||||
lines += [" " + p for p in pre]
|
||||
if struct_return:
|
||||
lines += [f" {ret} result{{}};", f" {host}->{name}(&result{''.join(', ' + c for c in call)});",
|
||||
" return result;"]
|
||||
elif ret == "void":
|
||||
lines.append(f" {host}->{name}({', '.join(call)});")
|
||||
elif wrap_out and ret == "HRESULT":
|
||||
n = len(params)
|
||||
lines += [f" HRESULT hr = {host}->{name}({', '.join(call)});",
|
||||
f' if (FAILED(hr)) bx_xbox_log_host_failure("Xbox{family}", "{name}", hr);',
|
||||
f" return bx_xbox_wrap_result(hr, a{n - 2}, a{n - 1});"]
|
||||
elif ret == "HRESULT":
|
||||
lines += [f" HRESULT hr = {host}->{name}({', '.join(call)});",
|
||||
f' if (FAILED(hr)) bx_xbox_log_host_failure("Xbox{family}", "{name}", hr);',
|
||||
" return hr;"]
|
||||
else:
|
||||
lines.append(f" return {host}->{name}({', '.join(call)});")
|
||||
return lines + ["}"]
|
||||
|
||||
|
||||
def find_count(params, index, name=""):
|
||||
# The element count is the nearest UINT parameter, before the array or (as in
|
||||
# SetEventOnMultipleFenceCompletion) after it.
|
||||
for j in list(range(index - 1, -1, -1)) + list(range(index + 1, len(params))):
|
||||
if canon(params[j][0]) in ("UINT", "UINT32"):
|
||||
return f"a{j}"
|
||||
sys.exit(f"no element count before array parameter {index} of {name}: {params}")
|
||||
|
||||
|
||||
def failure_value(ret):
|
||||
return {"HRESULT": "E_OUTOFMEMORY", "void": ""}.get(ret, "{}")
|
||||
|
||||
|
||||
STRUCT_TYPES = set() # filled from the Xbox header's `typedef struct` names
|
||||
|
||||
|
||||
def emit_stub(family, slot, name, xret, reason):
|
||||
stub = f'BX_VTABLE_STUB_LOG("Xbox{family}", {slot}u, "{name}");'
|
||||
if xret == "HRESULT":
|
||||
return [f"/* {reason} */",
|
||||
f"static HRESULT STDMETHODCALLTYPE x_{family}_{slot}(void*) {{ {stub} return E_NOTIMPL; }}"]
|
||||
if xret in STRUCT_TYPES:
|
||||
# A struct returned by value comes back through a hidden pointer passed first; it is
|
||||
# handed back unfilled (the stub log says so). Structs of 8 bytes or less are returned in
|
||||
# RAX instead; none of the stubbed slots returns one today.
|
||||
return [f"/* {reason}; returns struct {xret} */",
|
||||
f"static void* STDMETHODCALLTYPE x_{family}_{slot}(void* result, void*) {{ {stub} return result; }}"]
|
||||
# Integers, enums, BOOL and pointers come back zero; a void slot ignores the value.
|
||||
return [f"/* {reason} */",
|
||||
f"static UINT64 STDMETHODCALLTYPE x_{family}_{slot}(void*) {{ {stub} return 0; }}"]
|
||||
|
||||
|
||||
def guid_literal(parts):
|
||||
g = [p.lower() for p in parts]
|
||||
return (f"{{0x{g[0]}, 0x{g[1]}, 0x{g[2]}, "
|
||||
f"{{0x{g[3]}, 0x{g[4]}, 0x{g[5]}, 0x{g[6]}, 0x{g[7]}, 0x{g[8]}, 0x{g[9]}, 0x{g[10]}}}}}")
|
||||
|
||||
|
||||
def chain(bases, leaf):
|
||||
out, cur = [], leaf
|
||||
while cur in bases:
|
||||
out.append(cur)
|
||||
cur = bases[cur]
|
||||
return out + [cur]
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
sys.exit(__doc__)
|
||||
xtext = Path(sys.argv[1]).read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n") # parts of the header use CRLF
|
||||
pc_header = sys.argv[2] if len(sys.argv) > 2 else gen_proxy.find_header()
|
||||
interfaces = gen_proxy.parse_interfaces(Path(pc_header).read_text(encoding="utf-8", errors="replace"))
|
||||
iids, bases, tables = parse_xbox(xtext)
|
||||
STRUCT_TYPES.update(re.findall(r"typedef\s+struct\s+(\w+)", xtext))
|
||||
STRUCT_TYPES.update(t for t in re.findall(r"^struct\s+(\w+)\s*$", xtext, re.M))
|
||||
|
||||
note = ("// Generated by shims/d3d12_xs/tools/gen_xbox_tables.py from the Xbox Series D3D12 header (slot\n"
|
||||
"// order, names and types only) and the toolchain's <d3d12.h>. Do not edit by hand.")
|
||||
h = [note, "#ifndef BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H",
|
||||
"#define BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H", "", '#include "xbox_facade.h"', ""]
|
||||
c = [note, '#include "xbox_tables_generated.h"', "", "namespace {", ""]
|
||||
summary = []
|
||||
for leaf, (pc_leaf, family) in FAMILIES.items():
|
||||
slots = flatten(tables, table_name(leaf))
|
||||
if not slots:
|
||||
sys.exit(f"no Xbox function table for {leaf}")
|
||||
pc = pc_methods(interfaces, pc_leaf)
|
||||
counts = {"forward": 0, "shared": 0, "stub": 0}
|
||||
names = []
|
||||
for slot, (name, xret, xparams) in enumerate(slots):
|
||||
if name in SHARED or name in CUSTOM.get(family, {}):
|
||||
fn = SHARED.get(name) or CUSTOM[family][name]
|
||||
names.append(f"reinterpret_cast<const void*>(&{fn})")
|
||||
counts["shared"] += 1
|
||||
continue
|
||||
kind = classify(xret, xparams, pc[name]) if name in pc else None
|
||||
if kind:
|
||||
c += emit_forward(family, slot, name, pc[name], kind[1])
|
||||
counts["forward"] += 1
|
||||
else:
|
||||
reason = "signature differs from the PC method" if name in pc else "Xbox-only method"
|
||||
c += emit_stub(family, slot, name, xret, reason)
|
||||
counts["stub"] += 1
|
||||
names.append(f"reinterpret_cast<const void*>(&x_{family}_{slot})")
|
||||
c += ["", f"const void* const k{family}Table[] = {{"] + [f" {n}," for n in names] + ["};", ""]
|
||||
family_iids = [i for i in chain(bases, leaf) if i in iids and i not in ("IGraphicsUnknown",)]
|
||||
c += [f"const IID k{family}Iids[] = {{"] + [f" {guid_literal(iids[i])}, /* {i} */" for i in family_iids]
|
||||
c += ["};", ""]
|
||||
h.append(f"extern const BxXboxIface bx_xbox_{family};")
|
||||
summary.append(f"{family}: {len(slots)} slots, {counts}")
|
||||
c.append(f"/* {leaf}: {len(slots)} slots ({counts['forward']} forwarded, {counts['shared']} shared, "
|
||||
f"{counts['stub']} stubs); hosted on {pc_leaf}. */")
|
||||
c += [f"const IID kHost{family} = __uuidof({pc_leaf});", ""]
|
||||
c += ["} // namespace", ""]
|
||||
for leaf, (pc_leaf, family) in FAMILIES.items():
|
||||
size = len(flatten(tables, table_name(leaf)))
|
||||
c.append(f'extern const BxXboxIface bx_xbox_{family} = {{"{leaf}", k{family}Iids, '
|
||||
f"sizeof(k{family}Iids) / sizeof(IID), &kHost{family}, k{family}Table, {size}}};")
|
||||
c += ["", "extern const BxXboxIface* const bx_xbox_ifaces[] = {"]
|
||||
c += [f" &bx_xbox_{family}," for _, family in FAMILIES.values()] + ["};",
|
||||
f"extern const size_t bx_xbox_iface_count = {len(FAMILIES)};"]
|
||||
h += ["", "extern const BxXboxIface* const bx_xbox_ifaces[];", "extern const size_t bx_xbox_iface_count;",
|
||||
"", "#endif"]
|
||||
(OUT_DIR / "xbox_tables_generated.h").write_text("\n".join(h) + "\n")
|
||||
(OUT_DIR / "xbox_tables_generated.cpp").write_text("\n".join(c) + "\n")
|
||||
print("\n".join(summary))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,316 @@
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
/*
|
||||
* ADR 0009: Xbox-layout objects over the PC proxies. See xbox_facade.h for the layout and
|
||||
* xbox_tables_generated.cpp (tools/gen_xbox_tables.py) for the slot order.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint8_t kOutOfLineCommon = 0x1; // Xbox OutOfLineFlags_Common
|
||||
|
||||
struct Entry {
|
||||
IUnknown* host;
|
||||
const BxXboxIface* iface;
|
||||
BxXboxObject* object;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
Entry* g_entries = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
bool same_iid(REFIID a, REFIID b) {
|
||||
return std::memcmp(&a, &b, sizeof(IID)) == 0;
|
||||
}
|
||||
|
||||
bool answers(const BxXboxIface* iface, REFIID riid) {
|
||||
for (size_t i = 0; i < iface->iid_count; ++i) {
|
||||
if (same_iid(iface->iids[i], riid)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const BxXboxIface* iface_of_object(const void* p) {
|
||||
if (!p) return nullptr;
|
||||
const void* table = *static_cast<const void* const*>(p);
|
||||
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
|
||||
if (bx_xbox_ifaces[i]->table == table) return bx_xbox_ifaces[i];
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void log_iid(const char* event, const char* what, REFIID riid, bx_log_level_t level = BX_LOG_WARN) {
|
||||
char guid[40];
|
||||
bx_format_guid(riid, guid, sizeof(guid));
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s iid=%s", what, guid);
|
||||
bx_log_emit(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
BxXboxObject* find_locked(IUnknown* host, const BxXboxIface* iface) {
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_entries[i].host == host && g_entries[i].iface == iface) return g_entries[i].object;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool insert_locked(Entry entry) {
|
||||
if (g_count == g_capacity) {
|
||||
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
|
||||
auto* grown = new (std::nothrow) Entry[capacity];
|
||||
if (!grown) return false;
|
||||
if (g_count) std::memcpy(grown, g_entries, g_count * sizeof(Entry));
|
||||
delete[] g_entries;
|
||||
g_entries = grown;
|
||||
g_capacity = capacity;
|
||||
}
|
||||
g_entries[g_count++] = entry;
|
||||
return true;
|
||||
}
|
||||
|
||||
void erase_locked(BxXboxObject* object) {
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_entries[i].object == object) {
|
||||
g_entries[i] = g_entries[--g_count];
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const BxXboxIface* bx_xbox_iface_for(REFIID riid) {
|
||||
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
|
||||
if (answers(bx_xbox_ifaces[i], riid)) return bx_xbox_ifaces[i];
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void* bx_xbox_wrap(REFIID riid, void* raw, HRESULT* failure) {
|
||||
if (failure) *failure = E_OUTOFMEMORY;
|
||||
if (!raw) return nullptr;
|
||||
auto* unknown = static_cast<IUnknown*>(raw);
|
||||
const BxXboxIface* iface = bx_xbox_iface_for(riid);
|
||||
if (!iface) {
|
||||
log_iid("xbox_unwrapped", "no Xbox table answers this interface; returning the PC object", riid);
|
||||
return raw;
|
||||
}
|
||||
void* typed = nullptr;
|
||||
if (FAILED(unknown->QueryInterface(*iface->host_iid, &typed)) || !typed) {
|
||||
// The Xbox table forwards to an interface this host object lacks. Handing back the PC
|
||||
// object would let a title call Xbox slot numbers on a PC table, so this fails instead.
|
||||
log_iid("xbox_wrap_refused", iface->name, *iface->host_iid, BX_LOG_ERROR);
|
||||
unknown->Release();
|
||||
if (failure) *failure = E_NOINTERFACE;
|
||||
return nullptr;
|
||||
}
|
||||
unknown->Release();
|
||||
auto* host = static_cast<IUnknown*>(typed);
|
||||
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (BxXboxObject* existing = find_locked(host, iface)) {
|
||||
ULONG refs = existing->refs.load();
|
||||
while (refs != 0 && !existing->refs.compare_exchange_weak(refs, refs + 1)) {
|
||||
}
|
||||
if (refs != 0) {
|
||||
existing->xbox_ref_count = refs + 1;
|
||||
host->Release();
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
auto* object = new (std::nothrow) BxXboxObject{};
|
||||
if (!object) {
|
||||
host->Release();
|
||||
return nullptr;
|
||||
}
|
||||
object->function_table = iface->table;
|
||||
object->xbox_ref_count = 1;
|
||||
if (iface == &bx_xbox_Device) {
|
||||
object->xbox_fields[kBxXboxDeviceOutOfLineOffset - offsetof(BxXboxObject, xbox_fields)] = kOutOfLineCommon;
|
||||
}
|
||||
object->host = host;
|
||||
object->iface = iface;
|
||||
object->refs.store(1);
|
||||
if (!insert_locked({host, iface, object})) {
|
||||
host->Release();
|
||||
delete object;
|
||||
return nullptr;
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv) {
|
||||
if (SUCCEEDED(hr) && ppv && *ppv) {
|
||||
HRESULT failure = E_OUTOFMEMORY;
|
||||
void* wrapped = bx_xbox_wrap(riid, *ppv, &failure);
|
||||
if (!wrapped) {
|
||||
*ppv = nullptr;
|
||||
return failure;
|
||||
}
|
||||
*ppv = wrapped;
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
IUnknown* bx_xbox_unwrap(const void* p) {
|
||||
if (iface_of_object(p)) return static_cast<const BxXboxObject*>(p)->host;
|
||||
return static_cast<IUnknown*>(const_cast<void*>(p));
|
||||
}
|
||||
|
||||
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s::%s hr=0x%08lx", iface, method, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "host_call_failed", detail);
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv) {
|
||||
auto* object = static_cast<BxXboxObject*>(self);
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (same_iid(riid, IID_BxProxyHost)) {
|
||||
*ppv = object->host; // by contract, no reference (see bx_unwrap_raw)
|
||||
return S_OK;
|
||||
}
|
||||
if (same_iid(riid, __uuidof(IUnknown)) || answers(object->iface, riid)) {
|
||||
bx_xbox_add_ref(self);
|
||||
*ppv = self;
|
||||
return S_OK;
|
||||
}
|
||||
void* raw = nullptr;
|
||||
HRESULT hr = object->host->QueryInterface(riid, &raw);
|
||||
if (FAILED(hr) || !raw) return hr;
|
||||
if (bx_xbox_iface_for(riid)) {
|
||||
HRESULT failure = E_OUTOFMEMORY;
|
||||
*ppv = bx_xbox_wrap(riid, raw, &failure);
|
||||
return *ppv ? S_OK : failure;
|
||||
}
|
||||
log_iid("xbox_qi_unwrapped", object->iface->name, riid);
|
||||
*ppv = raw;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self) {
|
||||
auto* object = static_cast<BxXboxObject*>(self);
|
||||
const ULONG refs = object->refs.fetch_add(1) + 1;
|
||||
object->xbox_ref_count = refs;
|
||||
return refs;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self) {
|
||||
auto* object = static_cast<BxXboxObject*>(self);
|
||||
std::unique_lock<std::mutex> guard(g_lock);
|
||||
const ULONG refs = object->refs.fetch_sub(1) - 1;
|
||||
object->xbox_ref_count = refs;
|
||||
if (refs != 0) return refs;
|
||||
erase_locked(object);
|
||||
guard.unlock();
|
||||
if (object->iface == &bx_xbox_Resource) bx_xbox_placed_forget(object->host);
|
||||
if (object->iface == &bx_xbox_DescriptorHeap) bx_xbox_descriptor_heap_forget(object->host);
|
||||
if (object->iface == &bx_xbox_Fence) bx_xbox_fence_forget(object->host);
|
||||
if (object->iface == &bx_xbox_PipelineState) bx_xbox_pipeline_forget(object->host);
|
||||
if (object->iface == &bx_xbox_GraphicsCommandList) {
|
||||
bx_xbox_list_forget(object->host);
|
||||
bx_xbox_gpu_writes_reset(object->host);
|
||||
}
|
||||
object->host->Release();
|
||||
delete object;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv) {
|
||||
if (!ppv) return;
|
||||
*ppv = nullptr;
|
||||
auto* child = bx_xbox_host<ID3D12DeviceChild>(self);
|
||||
void* device = nullptr;
|
||||
if (SUCCEEDED(child->GetDevice(riid, &device)) && device) *ppv = bx_xbox_wrap(riid, device);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandQueueX");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
D3D12_COMMAND_QUEUE_DESC pc{};
|
||||
pc.Type = desc->Type;
|
||||
pc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
|
||||
pc.Flags = desc->Flags;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "type=%d flags=0x%x engine_or_pipe=%u queue=%u (indices not used by the host)",
|
||||
static_cast<int>(desc->Type), static_cast<unsigned>(desc->Flags), desc->EngineOrPipeIndex,
|
||||
desc->QueueIndex);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandQueueX", detail);
|
||||
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandQueue(&pc, riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
|
||||
ID3D12CommandAllocator* allocator,
|
||||
ID3D12PipelineState* initial_state, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandListX");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "type=%d xbox_flags=0x%x node_mask=0x%x barrier_batch=%u (flags and batch not used by the host)",
|
||||
static_cast<int>(desc->Type), desc->Flags, desc->NodeMask, desc->ResourceBarrierBatchSize);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandListX", detail);
|
||||
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandList(
|
||||
desc->NodeMask, desc->Type, bx_xbox_unwrap_as(allocator),
|
||||
bx_xbox_pipeline_is_null(initial_state) ? nullptr : bx_xbox_unwrap_as(initial_state), riid, ppv);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateCommandListX", hr);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ResourceBarrier");
|
||||
if (!barriers || count == 0) return 0;
|
||||
constexpr UINT kInline = 32;
|
||||
D3D12_RESOURCE_BARRIER inline_copy[kInline];
|
||||
D3D12_RESOURCE_BARRIER* copy = count <= kInline ? inline_copy : new (std::nothrow) D3D12_RESOURCE_BARRIER[count];
|
||||
if (!copy) return 0;
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
copy[i] = barriers[i];
|
||||
switch (copy[i].Type) {
|
||||
case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION:
|
||||
copy[i].Transition.pResource = bx_xbox_unwrap_as(copy[i].Transition.pResource);
|
||||
break;
|
||||
case D3D12_RESOURCE_BARRIER_TYPE_ALIASING:
|
||||
copy[i].Aliasing.pResourceBefore = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceBefore);
|
||||
copy[i].Aliasing.pResourceAfter = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceAfter);
|
||||
break;
|
||||
case D3D12_RESOURCE_BARRIER_TYPE_UAV:
|
||||
copy[i].UAV.pResource = bx_xbox_unwrap_as(copy[i].UAV.pResource);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(count, copy);
|
||||
if (copy != inline_copy) delete[] copy;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
|
||||
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
|
||||
const D3D12_BOX* box) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyTextureRegion");
|
||||
D3D12_TEXTURE_COPY_LOCATION d{}, s{};
|
||||
if (dst) {
|
||||
d = *dst;
|
||||
d.pResource = bx_xbox_unwrap_as(d.pResource);
|
||||
}
|
||||
if (src) {
|
||||
s = *src;
|
||||
s.pResource = bx_xbox_unwrap_as(s.pResource);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,343 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_XBOX_FACADE_H
|
||||
#define BETTERXEN_D3D12_XS_XBOX_FACADE_H
|
||||
|
||||
/*
|
||||
* Xbox-layout objects in front of the PC proxies (ADR 0009).
|
||||
*
|
||||
* A title built against the Xbox Series D3D12 header calls every method through the object's
|
||||
* function table, whose slot order differs from PC D3D12. A BxXboxObject has the Xbox object
|
||||
* layout and an Xbox-order table (xbox_tables_generated.cpp); each slot forwards to the PC
|
||||
* object it hosts, which is usually one of the PC proxies in proxy.h.
|
||||
*
|
||||
* Layout (from the Xbox header): the function-table pointer, a 32-bit flags word and the
|
||||
* reference count make up every object's 16-byte base. ID3D12Device adds a 64-bit null constant
|
||||
* buffer address at +16 and a 64-byte union at +24 whose first byte, m_OutOfLineFlags, makes
|
||||
* inline helpers call out through the table when non-zero. The same layout is used for every
|
||||
* interface family; the fields after the base are ignored by the others. Command lists add a
|
||||
* put buffer and are not wrapped yet.
|
||||
*/
|
||||
#include "proxy.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <new>
|
||||
|
||||
struct BxXboxIface {
|
||||
const char* name; // Xbox leaf interface, for logs
|
||||
const IID* iids; // Xbox interface IDs this table answers
|
||||
size_t iid_count;
|
||||
const IID* host_iid; // PC interface the hosted object provides
|
||||
const void* const* table; // Xbox-order function table
|
||||
size_t slots;
|
||||
};
|
||||
|
||||
/*
|
||||
* Interface-specific Xbox fields follow the 16-byte base. ID3D12Device: null constant-buffer
|
||||
* address at +16, m_OutOfLineFlags at +24. ID3D12GraphicsCommandList: m_Putter at +16 (five
|
||||
* put-buffer pointers and 256 reserved bytes), CPU state at +312, the graphics and compute root
|
||||
* packet-header tables at +316 and +828 and the PSO shadow at +1340; the whole object is 1384
|
||||
* bytes (an 8-byte field at +1376 follows), which the title's inline code writes. Zero put
|
||||
* pointers make every inline fast path fail its room check and call through the table. The other
|
||||
* interfaces define no fields here. The area below is the largest Xbox object (the command list)
|
||||
* plus a margin, so title writes never reach BetterXen's state after it: with 1360 bytes the
|
||||
* list's last field was BetterXen's host pointer, and the title overwrote it.
|
||||
*/
|
||||
constexpr size_t kBxXboxCommandListBytes = 1384;
|
||||
constexpr size_t kBxXboxFieldBytes = kBxXboxCommandListBytes - 16 + 64;
|
||||
|
||||
struct BxXboxObject {
|
||||
const void* const* function_table;
|
||||
uint32_t xbox_flags;
|
||||
uint32_t xbox_ref_count; // kept equal to `refs` for anything reading the Xbox field
|
||||
uint8_t xbox_fields[kBxXboxFieldBytes];
|
||||
// BetterXen state, after every field the Xbox layout defines.
|
||||
IUnknown* host; // owns one reference; typed as iface->host_iid
|
||||
const BxXboxIface* iface;
|
||||
std::atomic<ULONG> refs;
|
||||
};
|
||||
static_assert(offsetof(BxXboxObject, xbox_ref_count) == 12, "Xbox m_RefCount offset");
|
||||
static_assert(offsetof(BxXboxObject, xbox_fields) == 16, "Xbox interface fields start after the base");
|
||||
static_assert(offsetof(BxXboxObject, host) >= kBxXboxCommandListBytes, "BetterXen state lies past every Xbox field");
|
||||
static_assert(offsetof(BxXboxObject, host) >= 1372, "BetterXen state follows the Xbox command-list fields");
|
||||
constexpr size_t kBxXboxDeviceOutOfLineOffset = 24;
|
||||
|
||||
/* The Xbox table for `riid`, or nullptr when none of the wrapped families answers it. */
|
||||
const BxXboxIface* bx_xbox_iface_for(REFIID riid);
|
||||
|
||||
/* Wraps `host` (consumes the caller's reference) in the Xbox object for `riid`. One Xbox object
|
||||
exists per host object and family. When no family answers `riid`, `host` is returned as is
|
||||
and that is logged. */
|
||||
void* bx_xbox_wrap(REFIID riid, void* host, HRESULT* failure = nullptr);
|
||||
|
||||
/* After a (REFIID, void**) creation call: wraps a successful result. */
|
||||
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv);
|
||||
|
||||
/* The hosted PC object when `p` is one of our Xbox objects, otherwise `p` itself. */
|
||||
IUnknown* bx_xbox_unwrap(const void* p);
|
||||
template <typename T>
|
||||
T* bx_xbox_unwrap_as(T* p) {
|
||||
return static_cast<T*>(static_cast<void*>(bx_xbox_unwrap(p)));
|
||||
}
|
||||
template <typename T>
|
||||
const T* bx_xbox_unwrap_as(const T* p) {
|
||||
return static_cast<const T*>(static_cast<void*>(bx_xbox_unwrap(p)));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T* bx_xbox_host(void* self) {
|
||||
return static_cast<T*>(static_cast<BxXboxObject*>(self)->host);
|
||||
}
|
||||
|
||||
/* Unwraps an array of interface pointers for one forwarded call. */
|
||||
template <typename T>
|
||||
class BxXboxUnwrapArray {
|
||||
public:
|
||||
BxXboxUnwrapArray(T* const* items, UINT count) : count_(count) {
|
||||
if (!items || count == 0) {
|
||||
ok_ = true;
|
||||
return;
|
||||
}
|
||||
data_ = count <= kInline ? inline_ : new (std::nothrow) T*[count];
|
||||
ok_ = data_ != nullptr;
|
||||
for (UINT i = 0; ok_ && i < count; ++i) data_[i] = bx_xbox_unwrap_as(items[i]);
|
||||
}
|
||||
~BxXboxUnwrapArray() {
|
||||
if (data_ && data_ != inline_) delete[] data_;
|
||||
}
|
||||
BxXboxUnwrapArray(const BxXboxUnwrapArray&) = delete;
|
||||
BxXboxUnwrapArray& operator=(const BxXboxUnwrapArray&) = delete;
|
||||
bool ok() const { return ok_; }
|
||||
T* const* data() const { return data_; }
|
||||
|
||||
private:
|
||||
static constexpr UINT kInline = 16;
|
||||
T* inline_[kInline] = {};
|
||||
T** data_ = nullptr;
|
||||
UINT count_ = 0;
|
||||
bool ok_ = false;
|
||||
};
|
||||
|
||||
extern "C" {
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv);
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self);
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self);
|
||||
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv);
|
||||
|
||||
/* Xbox ID3D12Device::CreateCommandQueueX: the Xbox queue description selects a hardware
|
||||
engine/pipe and queue index; the PC queue gets the same type and flags at normal priority. */
|
||||
struct BxXboxCommandQueueDesc {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
D3D12_COMMAND_QUEUE_FLAGS Flags;
|
||||
UINT EngineOrPipeIndex;
|
||||
UINT QueueIndex;
|
||||
};
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
|
||||
REFIID riid, void** ppv);
|
||||
|
||||
/* Xbox ID3D12Device::CreateCommandListX. ResourceBarrierBatchSize sizes an Xbox-side batch and is
|
||||
not used by the host. */
|
||||
struct BxXboxCommandListDesc {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags;
|
||||
UINT NodeMask;
|
||||
UINT ResourceBarrierBatchSize;
|
||||
};
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
|
||||
ID3D12CommandAllocator* allocator,
|
||||
ID3D12PipelineState* initial_state, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
/* Frame pacing (frame_pacing.cpp): Xbox ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX and
|
||||
WaitFrameEventX, emulated with a host timer. Event types: 0 origin, 1 display vblank, 2 flip. */
|
||||
struct BxXboxFrameObjectList {
|
||||
UINT Count;
|
||||
HANDLE* pObjects;
|
||||
};
|
||||
struct BxXboxFrameWaitList {
|
||||
UINT Count;
|
||||
HANDLE* pObjects;
|
||||
UINT* pSignaledObjectIndex;
|
||||
};
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void* self, IDXGIOutput* output, UINT length_us,
|
||||
UINT period, UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void* self, UINT type, UINT offset_us,
|
||||
const BxXboxFrameObjectList* signals, UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void* self, UINT type, UINT timeout_ms,
|
||||
const BxXboxFrameWaitList* waits, UINT flags,
|
||||
UINT64* token);
|
||||
|
||||
/*
|
||||
* Title memory and host objects (ADR 0009). Everything that maps title-visible GPU memory to
|
||||
* host objects goes through these functions, so the backend behind them (D3DMetal today) can be
|
||||
* replaced on its own: title descriptor handles to host handles (descriptor_heaps.cpp) and title
|
||||
* GPU addresses to host addresses (placed_x.cpp). Unknown values pass through unchanged.
|
||||
*/
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title);
|
||||
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
void bx_xbox_descriptor_heap_forget(IUnknown* host);
|
||||
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
|
||||
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes);
|
||||
|
||||
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
|
||||
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
|
||||
|
||||
/* Fences with a title-visible value (fences.cpp). */
|
||||
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host);
|
||||
void bx_xbox_fence_forget(IUnknown* host);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT64 reference, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT reference, UINT mask, UINT flags);
|
||||
|
||||
/* GPU value writes into title memory (gpu_writes.cpp). */
|
||||
void bx_xbox_gpu_writes_reset(IUnknown* host_list);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flush, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flush, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists);
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
|
||||
UINT64 token, UINT flags);
|
||||
|
||||
/* Pipelines and the opt-in null-render mode (pipelines.cpp). */
|
||||
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title);
|
||||
void bx_xbox_pipeline_forget(IUnknown* host);
|
||||
void bx_xbox_list_forget(IUnknown* host);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void* extended,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void* extended,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
|
||||
ID3D12RootSignature* root, REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void* state, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void* state, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT count, const void* descs, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT count, const void* descs, REFIID riid,
|
||||
void** ppv);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
|
||||
UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT sync_flags, UINT control_flags, D3D12_GPU_VIRTUAL_ADDRESS base,
|
||||
SIZE_T size);
|
||||
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void* self, void* callback, UINT64 context);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
|
||||
UINT 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);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
|
||||
ID3D12Resource* arguments, UINT64 arguments_offset,
|
||||
ID3D12Resource* count, UINT64 count_offset);
|
||||
|
||||
/* Map / Unmap: title memory for resources that have it (placed_x.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data);
|
||||
void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written);
|
||||
void bx_xbox_sync_mapped_buffers();
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes, const void* parameters);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void* self, UINT batch_count, const void* batches,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
|
||||
UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT range_count, const void* ranges,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages, UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT page_count, UINT flags);
|
||||
|
||||
/* Page pools (placed_x.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
|
||||
HANDLE* handle);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void* self, HANDLE handle);
|
||||
|
||||
/* Committed resources with title-visible memory (committed.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, UINT32 formats,
|
||||
DXGI_FORMAT* castable, REFIID riid, void** ppv);
|
||||
|
||||
/* Descriptor heaps with title-visible storage (descriptor_heaps.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void* self, D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
/* `xbox_desc` is a D3D12XBOX_SAMPLER_DESC. */
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
|
||||
const UINT* dest_sizes, UINT src_ranges,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view);
|
||||
|
||||
/* Resources at a title-chosen GPU address (placed_x.cpp): host shadow resources. */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC1* desc, UINT initial_layout,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self);
|
||||
/* Xbox views of placed memory; `xbox_desc` is a D3D12XBOX_SHADER/UNORDERED_ACCESS_VIEW_DESC. */
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
/* Drops the shadow record of a destroyed resource. */
|
||||
void bx_xbox_placed_forget(IUnknown* host);
|
||||
|
||||
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
|
||||
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
|
||||
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
|
||||
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
|
||||
const D3D12_BOX* box);
|
||||
}
|
||||
|
||||
#include "xbox_tables_generated.h"
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
// 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.
|
||||
#ifndef BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H
|
||||
#define BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H
|
||||
|
||||
#include "xbox_facade.h"
|
||||
|
||||
extern const BxXboxIface bx_xbox_Device;
|
||||
extern const BxXboxIface bx_xbox_Resource;
|
||||
extern const BxXboxIface bx_xbox_Heap;
|
||||
extern const BxXboxIface bx_xbox_Fence;
|
||||
extern const BxXboxIface bx_xbox_DescriptorHeap;
|
||||
extern const BxXboxIface bx_xbox_RootSignature;
|
||||
extern const BxXboxIface bx_xbox_PipelineState;
|
||||
extern const BxXboxIface bx_xbox_CommandAllocator;
|
||||
extern const BxXboxIface bx_xbox_QueryHeap;
|
||||
extern const BxXboxIface bx_xbox_CommandSignature;
|
||||
extern const BxXboxIface bx_xbox_CommandQueue;
|
||||
extern const BxXboxIface bx_xbox_GraphicsCommandList;
|
||||
|
||||
extern const BxXboxIface* const bx_xbox_ifaces[];
|
||||
extern const size_t bx_xbox_iface_count;
|
||||
|
||||
#endif
|
||||
@@ -1,8 +1,12 @@
|
||||
#include <windows.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstdarg>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <initializer_list>
|
||||
#include <intrin.h>
|
||||
|
||||
#include "bx_config.h"
|
||||
@@ -18,6 +22,12 @@ LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
|
||||
std::atomic_flag g_crash_logged{};
|
||||
std::atomic<bool> g_crash_in_flight{false};
|
||||
std::atomic<uint64_t> g_clwb_traps{0};
|
||||
std::atomic<uint32_t> g_breakpoint_records{0};
|
||||
|
||||
// Breakpoint and assertion-failure records per process, so a guest that uses int3 on purpose
|
||||
// cannot flood the log.
|
||||
constexpr uint32_t kMaxBreakpointRecords = 16;
|
||||
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
|
||||
|
||||
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
|
||||
// counts reach the JSONL trace only: the frozen .def has no export for them.
|
||||
@@ -354,11 +364,874 @@ LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
|
||||
return disposition;
|
||||
}
|
||||
|
||||
// A guest with its own crash reporter replaces the top-level filter installed at attach, so
|
||||
// log_unhandled_exception never sees its assertions. The vectored handler runs before the
|
||||
// guest's top-level filter and before any vectored handler the guest registers last; a handler
|
||||
// the guest registers first can resume the exception before this one sees it. It records
|
||||
// breakpoints and assertion failures with their module offset. They are first-chance, so the
|
||||
// guest may still handle them; handling is left unchanged.
|
||||
void log_breakpoint(const EXCEPTION_RECORD& record) {
|
||||
// Past the cap the counter is not advanced again, so it cannot wrap around to 1.
|
||||
if (g_breakpoint_records.load(std::memory_order_relaxed) >= kMaxBreakpointRecords) {
|
||||
return;
|
||||
}
|
||||
const uint32_t index = g_breakpoint_records.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
if (index > kMaxBreakpointRecords) {
|
||||
return;
|
||||
}
|
||||
// The calls below can change the thread's last-error value; a resumed first-chance exception
|
||||
// must leave the guest's error state as it was.
|
||||
const DWORD last_error = GetLastError();
|
||||
const uintptr_t address = reinterpret_cast<uintptr_t>(record.ExceptionAddress);
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t module_base = 0;
|
||||
char module[MAX_PATH] = "?";
|
||||
if (VirtualQuery(record.ExceptionAddress, ®ion, sizeof(region)) &&
|
||||
region.Type == MEM_IMAGE) {
|
||||
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
// Wide API plus an explicit UTF-8 conversion: the ANSI form returns the name in the
|
||||
// active code page, which would make a non-ASCII module name invalid UTF-8 in the JSON.
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD length =
|
||||
GetModuleFileNameW(reinterpret_cast<HMODULE>(module_base), path, MAX_PATH);
|
||||
if (length > 0 && length < MAX_PATH) {
|
||||
const wchar_t* slash = std::wcsrchr(path, L'\\');
|
||||
const wchar_t* name = slash ? slash + 1 : path;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, module, sizeof(module), nullptr, nullptr) == 0) {
|
||||
std::snprintf(module, sizeof(module), "?");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
char line[1024];
|
||||
const int length = std::snprintf(
|
||||
line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\","
|
||||
"\"event\":\"breakpoint_exception\",\"exception_code\":\"0x%08lx\","
|
||||
"\"module\":\"%s\",\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
|
||||
"\"address\":\"0x%016llx\",\"record\":%u,\"limit\":%u}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
record.ExceptionCode, module, static_cast<unsigned long long>(module_base),
|
||||
static_cast<unsigned long long>(module_base ? address - module_base : 0),
|
||||
static_cast<unsigned long long>(address), index, kMaxBreakpointRecords);
|
||||
if (length > 0 && length < static_cast<int>(sizeof(line))) {
|
||||
write_log_line(line, static_cast<size_t>(length));
|
||||
}
|
||||
SetLastError(last_error);
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_AV_CONTEXT is set): the first access violations in an image
|
||||
// are logged with the general registers and, for each address in the variable, 64 bytes of
|
||||
// memory. An entry "*ADDR+OFF" first reads the pointer at ADDR, then dumps at pointer + OFF.
|
||||
// Reads are guarded by VirtualQuery; handling is left unchanged (first chance, search continues).
|
||||
bool readable_bytes(uintptr_t address, size_t size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) || region.State != MEM_COMMIT ||
|
||||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
return address + size <= reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
|
||||
// A JSONL line built with bounded appends: an append that does not fit is dropped and marks the
|
||||
// line truncated, so the length never passes the buffer. Four bytes stay reserved for the closing
|
||||
// "\"}\n". Text from the environment or module names goes through add_escaped.
|
||||
class LineBuf {
|
||||
public:
|
||||
LineBuf(char* p, size_t cap) : p_(p), cap_(cap - 4) { p_[0] = '\0'; }
|
||||
void add(const char* fmt, ...) {
|
||||
if (truncated_) return;
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
const int n = std::vsnprintf(p_ + len_, cap_ - len_, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n < 0 || static_cast<size_t>(n) >= cap_ - len_) {
|
||||
p_[len_] = '\0'; // drop the partial append
|
||||
truncated_ = true;
|
||||
return;
|
||||
}
|
||||
len_ += static_cast<size_t>(n);
|
||||
}
|
||||
// JSON string escaping for " \ and control characters; other bytes (UTF-8) pass through.
|
||||
void add_escaped(const char* text, size_t max) {
|
||||
for (size_t i = 0; text[i] && i < max && !truncated_; ++i) {
|
||||
const unsigned char ch = static_cast<unsigned char>(text[i]);
|
||||
if (ch == '"' || ch == '\\') add("\\%c", ch);
|
||||
else if (ch < 0x20) add("\\u%04x", ch);
|
||||
else add("%c", ch);
|
||||
}
|
||||
}
|
||||
bool room(size_t n) const { return !truncated_ && cap_ - len_ > n; }
|
||||
// Closes the JSON string and object and writes the line.
|
||||
void finish() {
|
||||
std::memcpy(p_ + len_, "\"}\n", 4);
|
||||
write_log_line(p_, len_ + 3);
|
||||
}
|
||||
|
||||
private:
|
||||
char* p_;
|
||||
size_t cap_;
|
||||
size_t len_ = 0;
|
||||
bool truncated_ = false;
|
||||
};
|
||||
|
||||
// A module's file name (without the directory) in UTF-8, or "?" when it cannot be read.
|
||||
void module_name_utf8(uintptr_t base, char* out, size_t size) {
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD n = base ? GetModuleFileNameW(reinterpret_cast<HMODULE>(base), path, MAX_PATH) : 0;
|
||||
if (n == 0 || n >= MAX_PATH) {
|
||||
std::snprintf(out, size, "?");
|
||||
return;
|
||||
}
|
||||
const wchar_t* slash = std::wcsrchr(path, L'\\');
|
||||
const wchar_t* name = slash ? slash + 1 : path;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, out, static_cast<int>(size), nullptr, nullptr) == 0) {
|
||||
std::snprintf(out, size, "?");
|
||||
}
|
||||
}
|
||||
|
||||
// BX_VEH_AV_CONTEXT and BX_VEH_AV_ALL, read once when runtime_veh attaches. With the context
|
||||
// switch unset the access-violation path does nothing at all.
|
||||
char g_av_spec[512];
|
||||
bool g_av_context_on = false;
|
||||
bool g_av_all = false;
|
||||
|
||||
void read_av_switches() {
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_CONTEXT", g_av_spec, sizeof(g_av_spec));
|
||||
g_av_context_on = n > 0 && n < sizeof(g_av_spec);
|
||||
char v[4];
|
||||
const DWORD k = GetEnvironmentVariableA("BX_VEH_AV_ALL", v, sizeof(v));
|
||||
g_av_all = k > 0 && k < sizeof(v) && v[0] == '1';
|
||||
}
|
||||
|
||||
void log_av_context(const EXCEPTION_POINTERS& ep) {
|
||||
static std::atomic<uint32_t> logged{0};
|
||||
if (!g_av_context_on || logged.fetch_add(1) >= 16) return;
|
||||
const CONTEXT& c = *ep.ContextRecord;
|
||||
char line[1600];
|
||||
LineBuf out(line, sizeof(line));
|
||||
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"av_context\","
|
||||
"\"detail\":\"rip=%llx fault=%llx rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx "
|
||||
"rsp=%llx r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)c.Rip,
|
||||
(unsigned long long)(ep.ExceptionRecord->NumberParameters >= 2 ? ep.ExceptionRecord->ExceptionInformation[1] : 0),
|
||||
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx,
|
||||
(unsigned long long)c.Rdx, (unsigned long long)c.Rsi, (unsigned long long)c.Rdi,
|
||||
(unsigned long long)c.Rbp, (unsigned long long)c.Rsp, (unsigned long long)c.R8,
|
||||
(unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
|
||||
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14,
|
||||
(unsigned long long)c.R15);
|
||||
// The comma-separated spec, scanned without shared state (several threads can fault at once).
|
||||
for (const char* cursor = g_av_spec; *cursor && out.room(220);) {
|
||||
const char* comma = std::strchr(cursor, ',');
|
||||
const size_t length = comma ? static_cast<size_t>(comma - cursor) : std::strlen(cursor);
|
||||
char item[64];
|
||||
const size_t take = length < sizeof(item) - 1 ? length : sizeof(item) - 1;
|
||||
std::memcpy(item, cursor, take);
|
||||
item[take] = '\0';
|
||||
cursor += length + (comma ? 1 : 0);
|
||||
// "*A+O": dump at [A]+O. "**A+O1+O2": dump at [[A]+O1]+O2.
|
||||
const int derefs = item[0] == '*' ? (item[1] == '*' ? 2 : 1) : 0;
|
||||
char* rest = nullptr;
|
||||
uintptr_t address = static_cast<uintptr_t>(std::strtoull(item + derefs, &rest, 16));
|
||||
uintptr_t offsets[2] = {0, 0};
|
||||
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
|
||||
bool ok = true;
|
||||
for (int k = 0; k < derefs && ok; ++k) {
|
||||
ok = readable_bytes(address, 8);
|
||||
if (ok) address = *reinterpret_cast<const uintptr_t*>(address) + offsets[k];
|
||||
}
|
||||
out.add(" | ");
|
||||
out.add_escaped(item, sizeof(item));
|
||||
if (!ok) {
|
||||
out.add(" unresolved");
|
||||
continue;
|
||||
}
|
||||
if (derefs == 0) address += offsets[0];
|
||||
out.add(" @%llx:", (unsigned long long)address);
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
if (VirtualQuery(reinterpret_cast<void*>(address), &mbi, sizeof(mbi))) {
|
||||
out.add(" [type=%lx prot=%lx alloc=%llx region=%llx+%llx]", static_cast<unsigned long>(mbi.Type),
|
||||
static_cast<unsigned long>(mbi.Protect), (unsigned long long)reinterpret_cast<uintptr_t>(mbi.AllocationBase),
|
||||
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.BaseAddress), (unsigned long long)mbi.RegionSize);
|
||||
}
|
||||
if (!readable_bytes(address, 64)) {
|
||||
out.add(" unreadable");
|
||||
continue;
|
||||
}
|
||||
const auto* q = reinterpret_cast<const uint64_t*>(address);
|
||||
for (int i = 0; i < 8; ++i) out.add(" %llx", (unsigned long long)q[i]);
|
||||
}
|
||||
// The faulting thread's stack: up to eight frames, unwound from its context, as module+offset.
|
||||
out.add(" | stack:");
|
||||
CONTEXT walk = c;
|
||||
for (int i = 0; i < 8 && walk.Rip && out.room(64); ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(walk.Rip), ®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));
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
|
||||
if (!fn) {
|
||||
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) break;
|
||||
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
|
||||
walk.Rsp += 8;
|
||||
continue;
|
||||
}
|
||||
PVOID handler_data = nullptr;
|
||||
DWORD64 frame = 0;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
out.finish();
|
||||
}
|
||||
|
||||
// A diagnostic that had to stop (a protection change failed): logged once per kind.
|
||||
void log_disarmed(const char* what, uintptr_t address) {
|
||||
char line[256];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"diagnostic_disarmed\","
|
||||
"\"detail\":\"%s address=%llx error=%lu\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), what,
|
||||
(unsigned long long)address, GetLastError());
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
|
||||
// Set when runtime_veh detaches: helper threads stop at their next step and log nothing more.
|
||||
std::atomic<bool> g_diag_stop{false};
|
||||
std::atomic<int> g_diag_threads{0};
|
||||
|
||||
// Diagnostics (off unless BX_VEH_WATCH=ADDR:LEN, hex): a software write watch. A helper thread
|
||||
// makes the page holding [ADDR, ADDR+LEN) read-only as soon as that page is committed. Each
|
||||
// write fault in the page is allowed by restoring write access and single-stepping the writing
|
||||
// instruction; writes inside the range are logged with the instruction's module offset and the
|
||||
// value after the write, then the page is protected again. Writes by other threads while the
|
||||
// page is briefly writable are not seen, and system calls that write into the page fail while
|
||||
// it is protected, so this is for diagnosis only.
|
||||
uintptr_t g_watch_begin = 0, g_watch_end = 0, g_watch_page = 0;
|
||||
std::atomic<bool> g_watch_armed{false};
|
||||
std::atomic<uint32_t> g_watch_logged{0};
|
||||
DWORD g_watch_tls = TLS_OUT_OF_INDEXES;
|
||||
|
||||
// The watched address: "A:LEN", or a pointer chain "*A+O:LEN" / "**A+O1+O2:LEN" that the helper
|
||||
// thread resolves once every pointer in it is non-null and readable.
|
||||
uintptr_t g_watch_root = 0, g_watch_offsets[2] = {0, 0}, g_watch_length = 8;
|
||||
int g_watch_derefs = 0;
|
||||
|
||||
bool resolve_watch(uintptr_t* out) {
|
||||
uintptr_t address = g_watch_root;
|
||||
for (int k = 0; k < g_watch_derefs; ++k) {
|
||||
if (!readable_bytes(address, 8)) return false;
|
||||
const uintptr_t next = *reinterpret_cast<const uintptr_t*>(address);
|
||||
if (!next) return false;
|
||||
address = next + g_watch_offsets[k];
|
||||
}
|
||||
if (g_watch_derefs == 0) address += g_watch_offsets[0];
|
||||
*out = address;
|
||||
return true;
|
||||
}
|
||||
|
||||
DWORD WINAPI watch_arm_thread(LPVOID) {
|
||||
for (int i = 0; i < 600000 && !g_watch_armed.load() && !g_diag_stop.load(); ++i) {
|
||||
uintptr_t begin = 0;
|
||||
DWORD old = 0;
|
||||
if (resolve_watch(&begin) && readable_bytes(begin, g_watch_length)) {
|
||||
g_watch_begin = begin;
|
||||
g_watch_end = begin + g_watch_length;
|
||||
g_watch_page = begin & ~static_cast<uintptr_t>(4095);
|
||||
char line[512];
|
||||
int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watch_armed\","
|
||||
"\"detail\":\"address=%llx contents:",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)begin);
|
||||
for (uintptr_t a = begin; a + 8 <= g_watch_end && len < static_cast<int>(sizeof(line)) - 24; a += 8) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %llx",
|
||||
(unsigned long long)*reinterpret_cast<const uint64_t*>(a));
|
||||
}
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
if (VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
|
||||
g_watch_armed = true;
|
||||
} else {
|
||||
log_disarmed("watch: could not protect the page", g_watch_page);
|
||||
}
|
||||
break;
|
||||
}
|
||||
Sleep(1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void start_write_watch() {
|
||||
char spec[96];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_watch_derefs = spec[0] == '*' ? (spec[1] == '*' ? 2 : 1) : 0;
|
||||
char* rest = nullptr;
|
||||
g_watch_root = static_cast<uintptr_t>(std::strtoull(spec + g_watch_derefs, &rest, 16));
|
||||
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) g_watch_offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
|
||||
if (rest && *rest == ':') g_watch_length = static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16));
|
||||
g_watch_tls = TlsAlloc();
|
||||
if (g_watch_tls == TLS_OUT_OF_INDEXES) return;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, watch_arm_thread, nullptr, 0, nullptr)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
}
|
||||
|
||||
void log_watched_write(uintptr_t rip, uintptr_t address, uint64_t value) {
|
||||
if (g_watch_logged.fetch_add(1) >= 64) return;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(rip), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
char line[256];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watched_write\","
|
||||
"\"detail\":\"rip=%llx module_base=%llx address=%llx value_after=%llx\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)rip, (unsigned long long)base, (unsigned long long)address,
|
||||
(unsigned long long)value);
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
|
||||
// Returns true when the exception belonged to the write watch and was handled.
|
||||
bool handle_write_watch(PEXCEPTION_POINTERS ep) {
|
||||
if (!g_watch_armed.load() || g_watch_tls == TLS_OUT_OF_INDEXES) return false;
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
|
||||
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
|
||||
if ((address & ~static_cast<uintptr_t>(4095)) != g_watch_page) return false;
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old)) {
|
||||
// Fail open: the write cannot be allowed, so the guest gets its access violation.
|
||||
g_watch_armed = false;
|
||||
log_disarmed("watch: could not unprotect the page", g_watch_page);
|
||||
return false;
|
||||
}
|
||||
// Remember the write for the single-step that follows it (+1 so 0 means "none").
|
||||
TlsSetValue(g_watch_tls, reinterpret_cast<void*>(address + 1));
|
||||
ep->ContextRecord->EFlags |= 0x100;
|
||||
return true;
|
||||
}
|
||||
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
|
||||
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_watch_tls));
|
||||
if (!pending) return false;
|
||||
TlsSetValue(g_watch_tls, nullptr);
|
||||
const uintptr_t address = pending - 1;
|
||||
if (address >= g_watch_begin && address < g_watch_end) {
|
||||
const uintptr_t slot = address & ~static_cast<uintptr_t>(7);
|
||||
log_watched_write(static_cast<uintptr_t>(reinterpret_cast<uintptr_t>(r.ExceptionAddress)), address,
|
||||
*reinterpret_cast<const uint64_t*>(slot));
|
||||
}
|
||||
DWORD old = 0;
|
||||
if (!g_watch_armed.load() || !VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
|
||||
if (g_watch_armed.exchange(false)) log_disarmed("watch: could not re-protect the page", g_watch_page);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_WATCH_RANGE=A:LEN, hex, at most 16 MiB): a write watch over a
|
||||
// range of pages, for data whose exact address moves between runs. A helper thread makes each
|
||||
// read-write page in the range read-only as soon as it is committed. A write fault is allowed by
|
||||
// restoring the page and single-stepping the instruction; the write is logged with its address,
|
||||
// the value after it and up to six frames of the writing thread, unwound from its context. After
|
||||
// 64 logged writes the whole range is made writable again and the watch stops.
|
||||
constexpr size_t kRangeWatchPages = 4096;
|
||||
uintptr_t g_rw_begin = 0, g_rw_end = 0;
|
||||
std::atomic<uint8_t> g_rw_armed[kRangeWatchPages];
|
||||
std::atomic<bool> g_rw_on{false};
|
||||
std::atomic<uint32_t> g_rw_logged{0};
|
||||
DWORD g_rw_tls = TLS_OUT_OF_INDEXES;
|
||||
|
||||
void range_watch_stop() {
|
||||
g_rw_on = false;
|
||||
for (size_t i = 0; i < kRangeWatchPages; ++i) {
|
||||
if (g_rw_armed[i].exchange(0)) {
|
||||
DWORD old = 0;
|
||||
VirtualProtect(reinterpret_cast<void*>(g_rw_begin + i * 4096), 4096, PAGE_READWRITE, &old);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "*A+O:LEN": the range starts at [A] + O, resolved once the pointer at A is readable and non-zero.
|
||||
uintptr_t g_rw_root = 0, g_rw_offset = 0, g_rw_length = 0;
|
||||
|
||||
DWORD WINAPI range_watch_thread(LPVOID) {
|
||||
if (g_rw_root) {
|
||||
for (int i = 0; i < 600000; ++i) {
|
||||
if (g_diag_stop.load()) return 0;
|
||||
if (readable_bytes(g_rw_root, 8) && *reinterpret_cast<const uintptr_t*>(g_rw_root)) break;
|
||||
Sleep(1);
|
||||
}
|
||||
if (!readable_bytes(g_rw_root, 8) || !*reinterpret_cast<const uintptr_t*>(g_rw_root)) return 0;
|
||||
const uintptr_t begin = (*reinterpret_cast<const uintptr_t*>(g_rw_root) + g_rw_offset) & ~static_cast<uintptr_t>(4095);
|
||||
g_rw_end = (begin + g_rw_length + 4095) & ~static_cast<uintptr_t>(4095);
|
||||
g_rw_begin = begin;
|
||||
char line[200];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_watch_resolved\","
|
||||
"\"detail\":\"begin=%llx end=%llx\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)g_rw_begin, (unsigned long long)g_rw_end);
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
const size_t pages = (g_rw_end - g_rw_begin) / 4096;
|
||||
for (int round = 0; round < 600000 && g_rw_on.load() && !g_diag_stop.load(); ++round) {
|
||||
bool all = true;
|
||||
for (size_t i = 0; i < pages && g_rw_on.load(); ++i) {
|
||||
if (g_rw_armed[i].load()) continue;
|
||||
all = false;
|
||||
const uintptr_t page = g_rw_begin + i * 4096;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(page), ®ion, sizeof(region)) || region.State != MEM_COMMIT ||
|
||||
region.Protect != PAGE_READWRITE) {
|
||||
continue;
|
||||
}
|
||||
DWORD old = 0;
|
||||
if (VirtualProtect(reinterpret_cast<void*>(page), 4096, PAGE_READONLY, &old)) g_rw_armed[i] = 1;
|
||||
}
|
||||
if (all) break;
|
||||
Sleep(1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void start_range_watch() {
|
||||
char spec[64];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
char* rest = nullptr;
|
||||
const bool chain = spec[0] == '*';
|
||||
const uintptr_t first = static_cast<uintptr_t>(std::strtoull(spec + (chain ? 1 : 0), &rest, 16));
|
||||
uintptr_t offset = 0;
|
||||
if (chain && rest && *rest == '+') offset = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
|
||||
const uintptr_t length = rest && *rest == ':' ? static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16)) : 0;
|
||||
if (!first || !length || length > kRangeWatchPages * 4096) return;
|
||||
g_rw_tls = TlsAlloc();
|
||||
if (g_rw_tls == TLS_OUT_OF_INDEXES) return;
|
||||
if (chain) {
|
||||
g_rw_root = first;
|
||||
g_rw_offset = offset;
|
||||
g_rw_length = length;
|
||||
} else {
|
||||
g_rw_begin = first & ~static_cast<uintptr_t>(4095);
|
||||
g_rw_end = (g_rw_begin + length + 4095) & ~static_cast<uintptr_t>(4095);
|
||||
}
|
||||
g_rw_on = true;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, range_watch_thread, nullptr, 0, nullptr)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
}
|
||||
|
||||
void log_range_write(const CONTEXT& c, uintptr_t address) {
|
||||
uintptr_t frames[6]{};
|
||||
int count = 0;
|
||||
CONTEXT walk = c;
|
||||
for (; count < 6 && walk.Rip; ++count) {
|
||||
frames[count] = static_cast<uintptr_t>(walk.Rip);
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
|
||||
if (!fn) {
|
||||
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) { ++count; break; }
|
||||
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
|
||||
walk.Rsp += 8;
|
||||
continue;
|
||||
}
|
||||
PVOID handler_data = nullptr;
|
||||
DWORD64 frame = 0;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
char line[640];
|
||||
int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_write\","
|
||||
"\"detail\":\"address=%llx value_after=%llx frames:",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)address,
|
||||
(unsigned long long)*reinterpret_cast<const uint64_t*>(address & ~static_cast<uintptr_t>(7)));
|
||||
for (int i = 0; i < count && len < static_cast<int>(sizeof(line)) - 48; ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %llx+%llx", (unsigned long long)base,
|
||||
(unsigned long long)(frames[i] - base));
|
||||
}
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true when the exception belonged to the range watch and was handled.
|
||||
bool handle_range_watch(PEXCEPTION_POINTERS ep) {
|
||||
if (g_rw_tls == TLS_OUT_OF_INDEXES) return false;
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
|
||||
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
|
||||
if (address < g_rw_begin || address >= g_rw_end) return false;
|
||||
const size_t index = (address - g_rw_begin) / 4096;
|
||||
if (!g_rw_armed[index].load()) return false;
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READWRITE, &old)) {
|
||||
g_rw_armed[index] = 0; // fail open: the guest gets its access violation
|
||||
log_disarmed("range watch: could not unprotect a page", g_rw_begin + index * 4096);
|
||||
return false;
|
||||
}
|
||||
TlsSetValue(g_rw_tls, reinterpret_cast<void*>(address + 1));
|
||||
ep->ContextRecord->EFlags |= 0x100;
|
||||
return true;
|
||||
}
|
||||
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
|
||||
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_rw_tls));
|
||||
if (!pending) return false;
|
||||
TlsSetValue(g_rw_tls, nullptr);
|
||||
const uintptr_t address = pending - 1;
|
||||
static const uint32_t cap = [] {
|
||||
char v[16];
|
||||
const DWORD k = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE_MAX", v, sizeof(v));
|
||||
const unsigned long want = (k > 0 && k < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
|
||||
return static_cast<uint32_t>(want == 0 ? 64 : (want > 200000 ? 200000 : want));
|
||||
}();
|
||||
const uint32_t n = g_rw_logged.fetch_add(1);
|
||||
if (n < cap) log_range_write(*ep->ContextRecord, address);
|
||||
if (n + 1 >= cap) {
|
||||
range_watch_stop();
|
||||
} else if (g_rw_on.load()) {
|
||||
DWORD old = 0;
|
||||
const size_t index = (address - g_rw_begin) / 4096;
|
||||
if (g_rw_armed[index].load() &&
|
||||
!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READONLY, &old)) {
|
||||
g_rw_armed[index] = 0;
|
||||
log_disarmed("range watch: could not re-protect a page", g_rw_begin + index * 4096);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_HIT=A1,A2,..., hex, at most 8): software code breakpoints in this
|
||||
// process. Each address gets an int3 when runtime_veh attaches; a hit logs the registers, puts the
|
||||
// original byte back, single-steps that instruction and re-inserts the int3. The first 16 hits per
|
||||
// address are logged, then every 256th. Other threads can pass an address unseen while its byte is
|
||||
// restored, so this is for diagnosis only.
|
||||
struct CodeHit {
|
||||
uintptr_t address;
|
||||
uint8_t original;
|
||||
std::atomic<uint32_t> hits;
|
||||
};
|
||||
CodeHit g_code_hits[8];
|
||||
int g_code_hit_count = 0;
|
||||
DWORD g_code_hit_tls = TLS_OUT_OF_INDEXES;
|
||||
|
||||
// False when the byte could not be written. A failure to restore the page's original protection
|
||||
// is logged: the page then stays writable, which the log record makes visible.
|
||||
bool write_code_byte(uintptr_t address, uint8_t value) {
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, PAGE_EXECUTE_READWRITE, &old)) return false;
|
||||
*reinterpret_cast<volatile uint8_t*>(address) = value;
|
||||
DWORD unused = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, old, &unused)) {
|
||||
log_disarmed("code hit: could not restore the page protection", address);
|
||||
}
|
||||
FlushInstructionCache(GetCurrentProcess(), reinterpret_cast<void*>(address), 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_SAMPLE=MS, decimal): a sampling profiler for every thread in the
|
||||
// process. Every MS milliseconds a helper thread visits each other thread: while it is suspended
|
||||
// only its context and up to 64 KiB of its stack are copied (no heap or loader calls, so a thread
|
||||
// suspended inside either cannot deadlock the sampler). After it resumes, up to eight frames are
|
||||
// unwound against the copy with the images' unwind data and logged as module base + offset, with
|
||||
// the thread id. At most 20000 samples are logged. For diagnosis only.
|
||||
DWORD g_sample_interval = 0;
|
||||
DWORD g_sample_self = 0;
|
||||
alignas(16) uint8_t g_sample_stack[64 * 1024];
|
||||
|
||||
void sample_thread(DWORD tid) {
|
||||
HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, tid);
|
||||
if (!h) return;
|
||||
CONTEXT c{};
|
||||
c.ContextFlags = CONTEXT_FULL;
|
||||
uintptr_t stack_lo = 0;
|
||||
size_t copied = 0;
|
||||
bool got = false;
|
||||
if (SuspendThread(h) != static_cast<DWORD>(-1)) {
|
||||
got = GetThreadContext(h, &c) != FALSE;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (got && VirtualQuery(reinterpret_cast<void*>(c.Rsp), ®ion, sizeof(region)) && region.State == MEM_COMMIT) {
|
||||
stack_lo = static_cast<uintptr_t>(c.Rsp);
|
||||
const uintptr_t end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
copied = end - stack_lo < sizeof(g_sample_stack) ? end - stack_lo : sizeof(g_sample_stack);
|
||||
std::memcpy(g_sample_stack, reinterpret_cast<const void*>(stack_lo), copied);
|
||||
}
|
||||
ResumeThread(h);
|
||||
}
|
||||
CloseHandle(h);
|
||||
if (!got) return;
|
||||
// Unwind against the copy: stack addresses (rsp, and rbp when it points into the stack) are
|
||||
// rebased into g_sample_stack; return addresses read from it are the thread's real ones.
|
||||
const uintptr_t copy = reinterpret_cast<uintptr_t>(g_sample_stack);
|
||||
auto in_stack = [&](DWORD64 a) { return a >= stack_lo && a < stack_lo + copied; };
|
||||
CONTEXT walk = c;
|
||||
walk.Rsp = copy;
|
||||
if (in_stack(c.Rbp)) walk.Rbp = copy + (c.Rbp - stack_lo);
|
||||
uintptr_t frames[8]{};
|
||||
int count = 0;
|
||||
for (; count < 8 && walk.Rip; ++count) {
|
||||
frames[count] = static_cast<uintptr_t>(walk.Rip);
|
||||
if (walk.Rsp < copy || walk.Rsp + 8 > copy + copied) { ++count; break; }
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
|
||||
if (!fn) { // leaf function: the return address is at rsp
|
||||
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
|
||||
walk.Rsp += 8;
|
||||
continue;
|
||||
}
|
||||
PVOID handler_data = nullptr;
|
||||
DWORD64 frame = 0;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
char line[760];
|
||||
LineBuf out(line, sizeof(line));
|
||||
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"sample\",\"detail\":\"thread=%lu",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), tid);
|
||||
for (int i = 0; i < count && out.room(64); ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), ®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));
|
||||
}
|
||||
if (!g_diag_stop.load()) out.finish();
|
||||
}
|
||||
|
||||
DWORD WINAPI sampler_main(LPVOID) {
|
||||
const DWORD pid = GetCurrentProcessId();
|
||||
for (int logged = 0; logged < 20000 && !g_diag_stop.load();) {
|
||||
Sleep(g_sample_interval);
|
||||
if (g_diag_stop.load()) break;
|
||||
DWORD tids[256];
|
||||
int n = 0;
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
if (snap == INVALID_HANDLE_VALUE) continue;
|
||||
THREADENTRY32 te{};
|
||||
te.dwSize = sizeof(te);
|
||||
for (BOOL ok = Thread32First(snap, &te); ok && n < 256; ok = Thread32Next(snap, &te)) {
|
||||
if (te.th32OwnerProcessID == pid && te.th32ThreadID != g_sample_self) tids[n++] = te.th32ThreadID;
|
||||
}
|
||||
CloseHandle(snap);
|
||||
for (int i = 0; i < n; ++i, ++logged) sample_thread(tids[i]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void start_sampler() {
|
||||
char spec[16];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_SAMPLE", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_sample_interval = static_cast<DWORD>(std::strtoul(spec, nullptr, 10));
|
||||
if (g_sample_interval == 0) return;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, sampler_main, nullptr, 0, &g_sample_self)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
}
|
||||
|
||||
void start_code_hits() {
|
||||
char spec[256];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_code_hit_tls = TlsAlloc();
|
||||
if (g_code_hit_tls == TLS_OUT_OF_INDEXES) return;
|
||||
for (const char* item = spec; *item && g_code_hit_count < 8;) {
|
||||
char* end = nullptr;
|
||||
const uintptr_t address = static_cast<uintptr_t>(std::strtoull(item, &end, 16));
|
||||
const char* comma = std::strchr(item, ',');
|
||||
item = comma ? comma + 1 : item + std::strlen(item);
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!address || !VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) ||
|
||||
region.Type != MEM_IMAGE || region.State != MEM_COMMIT) {
|
||||
continue;
|
||||
}
|
||||
CodeHit& hit = g_code_hits[g_code_hit_count];
|
||||
hit.address = address;
|
||||
hit.original = *reinterpret_cast<const uint8_t*>(address);
|
||||
if (write_code_byte(address, 0xCC)) ++g_code_hit_count;
|
||||
}
|
||||
char line[160];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hits_armed\","
|
||||
"\"detail\":\"count=%d\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), g_code_hit_count);
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
|
||||
void log_code_hit(const CodeHit& hit, uint32_t count, const CONTEXT& c) {
|
||||
char line[2048];
|
||||
int len = std::snprintf(
|
||||
line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hit\","
|
||||
"\"detail\":\"address=%llx hit=%u rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx rsp=%llx "
|
||||
"r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), (unsigned long long)hit.address, count,
|
||||
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx, (unsigned long long)c.Rdx,
|
||||
(unsigned long long)c.Rsi, (unsigned long long)c.Rdi, (unsigned long long)c.Rbp, (unsigned long long)c.Rsp,
|
||||
(unsigned long long)c.R8, (unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
|
||||
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14, (unsigned long long)c.R15);
|
||||
// The first 16 bytes behind the three argument registers, when they point at readable memory.
|
||||
const struct {
|
||||
const char* name;
|
||||
DWORD64 value;
|
||||
} args[] = {{"rcx", c.Rcx}, {"rdx", c.Rdx}, {"r8", c.R8}};
|
||||
for (const auto& a : args) {
|
||||
if (len <= 0 || len >= static_cast<int>(sizeof(line)) - 64 || !readable_bytes(static_cast<uintptr_t>(a.value), 16)) continue;
|
||||
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(a.value));
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " [%s]=%016llx %016llx", a.name, (unsigned long long)q[0],
|
||||
(unsigned long long)q[1]);
|
||||
// Printable text (a path or name argument): up to 96 characters of it.
|
||||
const auto* s = reinterpret_cast<const unsigned char*>(static_cast<uintptr_t>(a.value));
|
||||
if (s[0] >= 0x20 && s[0] < 0x7f && s[1] >= 0x20 && s[1] < 0x7f && readable_bytes(static_cast<uintptr_t>(a.value), 96)) {
|
||||
char text[97];
|
||||
int n = 0;
|
||||
while (n < 96 && s[n] >= 0x20 && s[n] < 0x7f) {
|
||||
text[n] = (s[n] == '"' || s[n] == '\\') ? '_' : static_cast<char>(s[n]);
|
||||
++n;
|
||||
}
|
||||
text[n] = '\0';
|
||||
if (len < static_cast<int>(sizeof(line)) - 120) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " [%s]s=%s", a.name, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
// BX_VEH_HIT_RDX=LEN (hex, at most 0x200): also dump LEN bytes of the object rdx points to.
|
||||
static const size_t rdx_len = [] {
|
||||
char v[16];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_RDX", v, sizeof(v));
|
||||
if (n == 0 || n >= sizeof(v)) return static_cast<size_t>(0);
|
||||
const size_t want = static_cast<size_t>(std::strtoull(v, nullptr, 16)) & ~static_cast<size_t>(7);
|
||||
return want > 0x200 ? static_cast<size_t>(0x200) : want;
|
||||
}();
|
||||
if (rdx_len && len > 0 && readable_bytes(static_cast<uintptr_t>(c.Rdx), rdx_len)) {
|
||||
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(c.Rdx));
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " rdx_obj:");
|
||||
for (size_t i = 0; i < rdx_len / 8 && len < static_cast<int>(sizeof(line)) - 24; ++i) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %llx", (unsigned long long)q[i]);
|
||||
}
|
||||
}
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true when the exception belonged to a code breakpoint and was handled.
|
||||
bool handle_code_hit(PEXCEPTION_POINTERS ep) {
|
||||
if (g_code_hit_count == 0) return false;
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
CONTEXT& c = *ep->ContextRecord;
|
||||
if (r.ExceptionCode == EXCEPTION_BREAKPOINT) {
|
||||
const uintptr_t at = reinterpret_cast<uintptr_t>(r.ExceptionAddress);
|
||||
for (int i = 0; i < g_code_hit_count; ++i) {
|
||||
CodeHit& hit = g_code_hits[i];
|
||||
if (at != hit.address && c.Rip - 1 != hit.address) continue;
|
||||
const uint32_t count = hit.hits.fetch_add(1) + 1;
|
||||
static const bool every = [] {
|
||||
char v[4];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_ALL", v, sizeof(v));
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
if (count <= 16 || count % 256 == 0 || (every && count <= 20000)) log_code_hit(hit, count, c);
|
||||
if (!write_code_byte(hit.address, hit.original)) {
|
||||
// The original instruction cannot be put back: stop handling this address and let
|
||||
// the breakpoint reach the guest instead of looping on it.
|
||||
log_disarmed("code hit: could not restore the original byte", hit.address);
|
||||
hit.address = 0;
|
||||
return false;
|
||||
}
|
||||
c.Rip = hit.address;
|
||||
c.EFlags |= 0x100;
|
||||
TlsSetValue(g_code_hit_tls, reinterpret_cast<void*>(static_cast<uintptr_t>(i + 1)));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
|
||||
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_code_hit_tls));
|
||||
if (!pending) return false;
|
||||
TlsSetValue(g_code_hit_tls, nullptr);
|
||||
CodeHit& hit = g_code_hits[pending - 1];
|
||||
if (hit.address && !g_diag_stop.load() && !write_code_byte(hit.address, 0xCC)) {
|
||||
log_disarmed("code hit: could not re-insert the breakpoint", hit.address);
|
||||
hit.address = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Restores every page and code byte the diagnostics changed (used at detach).
|
||||
void disarm_diagnostics() {
|
||||
if (g_watch_armed.exchange(false)) {
|
||||
DWORD old = 0;
|
||||
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old);
|
||||
}
|
||||
if (g_rw_on.load() || g_rw_begin) range_watch_stop();
|
||||
for (int i = 0; i < g_code_hit_count; ++i) {
|
||||
CodeHit& hit = g_code_hits[i];
|
||||
if (hit.address && *reinterpret_cast<const volatile uint8_t*>(hit.address) == 0xCC) {
|
||||
write_code_byte(hit.address, hit.original);
|
||||
}
|
||||
hit.address = 0;
|
||||
}
|
||||
for (DWORD* tls : {&g_watch_tls, &g_rw_tls, &g_code_hit_tls}) {
|
||||
if (*tls != TLS_OUT_OF_INDEXES) {
|
||||
TlsFree(*tls);
|
||||
*tls = TLS_OUT_OF_INDEXES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
|
||||
if (handle_code_hit(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (handle_range_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (handle_write_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
const DWORD code = ep->ExceptionRecord->ExceptionCode;
|
||||
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
|
||||
log_breakpoint(*ep->ExceptionRecord);
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (code == EXCEPTION_ACCESS_VIOLATION) {
|
||||
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, ®ion, sizeof(region)) && region.Type == MEM_IMAGE)) {
|
||||
log_av_context(*ep);
|
||||
}
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (code != EXCEPTION_ILLEGAL_INSTRUCTION) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
@@ -479,6 +1352,15 @@ const bx_runtime_config_t* bx_get_runtime_config(void) {
|
||||
int bx_veh_install(void) {
|
||||
if (!g_veh_handle) {
|
||||
g_veh_handle = AddVectoredExceptionHandler(1, bx_veh_handler);
|
||||
if (g_veh_handle) {
|
||||
read_av_switches();
|
||||
// The helper threads below start running only after the loader lock is released; nothing
|
||||
// here waits for them. They check g_diag_stop and stop at detach.
|
||||
start_write_watch();
|
||||
start_code_hits();
|
||||
start_sampler();
|
||||
start_range_watch();
|
||||
}
|
||||
}
|
||||
return g_veh_handle != nullptr ? 1 : 0;
|
||||
}
|
||||
@@ -503,15 +1385,23 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
|
||||
if (current_filter != log_unhandled_exception) {
|
||||
SetUnhandledExceptionFilter(current_filter);
|
||||
}
|
||||
// Stop the diagnostics and take them out of the guest's memory: restore watched pages and
|
||||
// original code bytes. Nothing waits for the helper threads (that would deadlock on the
|
||||
// loader lock); they stop at their next step.
|
||||
g_diag_stop = true;
|
||||
disarm_diagnostics();
|
||||
if (g_veh_handle) {
|
||||
RemoveVectoredExceptionHandler(g_veh_handle);
|
||||
g_veh_handle = nullptr;
|
||||
}
|
||||
if (g_log_handle != INVALID_HANDLE_VALUE) {
|
||||
// A helper thread may still be inside write_log_line when this runs. While any helper was
|
||||
// started, the log handle and its lock are left alive (the process is ending, or the DLL is
|
||||
// being unloaded with threads that only touch them); otherwise they are released.
|
||||
if (g_diag_threads.load() == 0 && g_log_handle != INVALID_HANDLE_VALUE) {
|
||||
CloseHandle(g_log_handle);
|
||||
g_log_handle = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
if (g_log_lock_ready) {
|
||||
if (g_diag_threads.load() == 0 && g_log_lock_ready) {
|
||||
DeleteCriticalSection(&g_log_lock);
|
||||
g_log_lock_ready = false;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
|
||||
xcrdapi.cpp
|
||||
zlib_inflate.cpp
|
||||
)
|
||||
target_include_directories(xcrdapi PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/dstorage")
|
||||
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32 uuid)
|
||||
|
||||
@@ -55,12 +55,15 @@ struct Request {
|
||||
UINT compression;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
UINT64 resource_offset = 0;
|
||||
DWORD output_size = 0; // compression_zlib: bytes the stream inflates to at `destination`
|
||||
};
|
||||
|
||||
inline constexpr UINT compression_none = 0;
|
||||
inline constexpr UINT compression_lz = 1;
|
||||
inline constexpr UINT compression_bcpack = 2;
|
||||
inline constexpr UINT compression_gdeflate = 3;
|
||||
// RFC 1950 zlib streams (Xbox DSTORAGE_REQUEST_OPTIONS.ZlibDecompress); decoded by zlib_inflate.cpp.
|
||||
inline constexpr UINT compression_zlib = 4;
|
||||
|
||||
struct ErrorRecord {
|
||||
HRESULT first_error;
|
||||
|
||||
+135
-11
@@ -1,4 +1,5 @@
|
||||
#include "synthetic_storage.h"
|
||||
#include "zlib_inflate.h"
|
||||
|
||||
// Public PC DirectStorage contract: Microsoft.Direct3D.DirectStorage 1.4.0,
|
||||
// MIT per file, vendored unmodified under dstorage/ (see dstorage/README.md).
|
||||
@@ -8,6 +9,8 @@
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -415,7 +418,65 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
|
||||
return staged.finish(win32_error());
|
||||
}
|
||||
|
||||
HRESULT inflate_request(HANDLE file, const Request& request) {
|
||||
if (!request.destination || !request.output_size || request.size >= request.output_size) return E_INVALIDARG;
|
||||
auto* compressed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
|
||||
if (!compressed) return E_OUTOFMEMORY;
|
||||
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
|
||||
if (SUCCEEDED(hr)) {
|
||||
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
|
||||
request.output_size);
|
||||
if (r != BxInflateResult::ok) {
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 16) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes to %lu bytes: %s", request.size,
|
||||
request.output_size, bx_inflate_result_name(r));
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_zlib_failed", detail);
|
||||
}
|
||||
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
|
||||
}
|
||||
}
|
||||
HeapFree(GetProcessHeap(), 0, compressed);
|
||||
return hr;
|
||||
}
|
||||
|
||||
CopyResult fulfill_request(HANDLE file, const Request& request);
|
||||
|
||||
// Diagnostics (off unless BX_DSTORAGE_TRACE=1): one line per memory-destination request with its
|
||||
// destination range, sizes, file offset, result and the first 16 bytes written, up to 20000.
|
||||
bool dstorage_trace_enabled() {
|
||||
static const bool on = [] {
|
||||
char value[8];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_DSTORAGE_TRACE", value, sizeof(value));
|
||||
return n > 0 && n < sizeof(value) && value[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
CopyResult fulfill(HANDLE file, const Request& request) {
|
||||
const CopyResult result = fulfill_request(file, request);
|
||||
if (!dstorage_trace_enabled() || request.resource) return result;
|
||||
static std::atomic<UINT> traced{0};
|
||||
if (traced.fetch_add(1) >= 20000) return result;
|
||||
const DWORD out = request.compression == compression_zlib ? request.output_size : request.size;
|
||||
uint64_t head[2] = {0, 0};
|
||||
if (SUCCEEDED(result.hr) && request.destination && out >= 16) std::memcpy(head, request.destination, 16);
|
||||
char detail[220];
|
||||
std::snprintf(detail, sizeof(detail), "dst=%p..%p out=%lu src=%lu offset=0x%llx compression=%u hr=0x%08lx head=%016llx %016llx",
|
||||
request.destination, static_cast<const uint8_t*>(request.destination) + out, out, request.size,
|
||||
static_cast<unsigned long long>(request.file_offset), request.compression,
|
||||
static_cast<unsigned long>(result.hr), static_cast<unsigned long long>(head[0]),
|
||||
static_cast<unsigned long long>(head[1]));
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request", detail);
|
||||
return result;
|
||||
}
|
||||
|
||||
CopyResult fulfill_request(HANDLE file, const Request& request) {
|
||||
if (request.compression == compression_zlib) {
|
||||
if (request.resource) return {E_NOTIMPL, false};
|
||||
return {inflate_request(file, request), false};
|
||||
}
|
||||
if (request.compression) {
|
||||
log_compression(request.compression);
|
||||
return {E_NOTIMPL, false};
|
||||
@@ -443,9 +504,12 @@ CopyResult fulfill(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 (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
|
||||
// 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
|
||||
// both; the BetterXen synthetic queues use neither.
|
||||
class WorkQueue final : public Object<Queue, queue_iid> {
|
||||
public:
|
||||
@@ -471,7 +535,8 @@ public:
|
||||
}
|
||||
Entry entry{Kind::request, *request};
|
||||
if (request->resource) request->resource->AddRef();
|
||||
if (request->file && !request->compression) {
|
||||
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
|
||||
if (request->file && (request->compression == compression_none || request->compression == compression_zlib)) {
|
||||
const HRESULT result = request->file->GetHandle(&entry.handle);
|
||||
if (FAILED(result)) {
|
||||
if (request->resource) request->resource->Release();
|
||||
@@ -613,7 +678,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 (submitted_ < size_) submit();
|
||||
if (auto_submit_ && submitted_ < size_) submit();
|
||||
SleepConditionVariableSRW(&space_, &mutex_, INFINITE, 0);
|
||||
}
|
||||
}
|
||||
@@ -1314,8 +1379,39 @@ static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
|
||||
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
|
||||
static_assert(offsetof(XboxRequest, source_size) == 0x30, "source_size offset");
|
||||
|
||||
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull;
|
||||
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull;
|
||||
// DSTORAGE_REQUEST_OPTIONS (authorized GDK documentation): ZlibDecompress:1, BcpackMode:4,
|
||||
// SwizzleMode:16, DestinationIsPhysicalPages:1, SourceType:1, SourceIsPhysicalPages:1.
|
||||
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull; // SourceType, bit 22
|
||||
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull; // ZlibDecompress, bit 0
|
||||
constexpr UINT64 kXboxRequestBcpackMask = 0xFull << 1;
|
||||
constexpr UINT64 kXboxRequestSwizzleMask = 0xFFFFull << 5;
|
||||
constexpr UINT64 kXboxRequestDestinationPagesBit = 1ull << 21;
|
||||
constexpr UINT64 kXboxRequestSourcePagesBit = 1ull << 23;
|
||||
|
||||
// Logs each distinct option combination once, so a run shows which MDU stages a title uses.
|
||||
void log_request_options(UINT64 options, UINT32 source_size, UINT32 destination_size, UINT32 intermediate_size) {
|
||||
static std::mutex lock;
|
||||
static UINT64 seen[64];
|
||||
static size_t count = 0;
|
||||
const UINT64 key = options & ~kXboxRequestSourceMemoryBit;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (seen[i] == key) return;
|
||||
}
|
||||
if (count < 64) seen[count++] = key;
|
||||
}
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"options=0x%llx zlib=%d bcpack_mode=%llu swizzle_mode=%llu dest_pages=%d source_memory=%d source_pages=%d "
|
||||
"first sizes: source=%u destination=%u intermediate=%u",
|
||||
static_cast<unsigned long long>(options), static_cast<int>(options & 1),
|
||||
static_cast<unsigned long long>((options & kXboxRequestBcpackMask) >> 1),
|
||||
static_cast<unsigned long long>((options & kXboxRequestSwizzleMask) >> 5),
|
||||
(options & kXboxRequestDestinationPagesBit) ? 1 : 0, (options & kXboxRequestSourceMemoryBit) ? 1 : 0,
|
||||
(options & kXboxRequestSourcePagesBit) ? 1 : 0, source_size, destination_size, intermediate_size);
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request_options", detail);
|
||||
}
|
||||
|
||||
struct IXboxDStorageFile : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
@@ -1424,12 +1520,25 @@ public:
|
||||
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if ((request->options & kXboxRequestCompressedBit) != 0) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_compressed");
|
||||
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
|
||||
if (request->options & kXboxRequestBcpackMask) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if (!request->destination || request->source_size != request->destination_size) {
|
||||
if (request->options & kXboxRequestSwizzleMask) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_swizzle");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if (request->options & (kXboxRequestDestinationPagesBit | kXboxRequestSourcePagesBit)) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_pages");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
|
||||
if (!request->destination || (zlib ? request->source_size >= request->destination_size
|
||||
: request->source_size != request->destination_size)) {
|
||||
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
@@ -1437,6 +1546,10 @@ public:
|
||||
Request translated{};
|
||||
translated.destination = request->destination;
|
||||
translated.size = request->source_size;
|
||||
if (zlib) {
|
||||
translated.compression = compression_zlib;
|
||||
translated.output_size = request->destination_size;
|
||||
}
|
||||
if (is_memory) {
|
||||
if (!request->source_ptr) {
|
||||
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
|
||||
@@ -1623,11 +1736,22 @@ public:
|
||||
const UINT slots = desc->capacity - 1u;
|
||||
auto* entries = new (std::nothrow) Entry[slots];
|
||||
if (!entries) return E_OUTOFMEMORY;
|
||||
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, desc->capacity / 2u);
|
||||
// desc->flags is DSTORAGE_QUEUE_OPTIONS (authorized GDK documentation): bit 0,
|
||||
// AutoSubmitDisabled, makes the queue wait for Submit. A title maps a request's
|
||||
// destination pages after enqueueing it and before submitting, so starting work at half
|
||||
// capacity wrote into pages that were not mapped yet.
|
||||
constexpr UINT64 kAutoSubmitDisabled = 1;
|
||||
const UINT auto_submit = (desc->flags & kAutoSubmitDisabled) ? 0u : desc->capacity / 2u;
|
||||
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, auto_submit);
|
||||
if (!queue) {
|
||||
delete[] entries;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "xbox queue '%s' capacity=%u source=%llu auto_submit=%s",
|
||||
desc->name ? desc->name : "", static_cast<unsigned>(desc->capacity),
|
||||
static_cast<unsigned long long>(desc->source_type), auto_submit ? "half capacity" : "disabled");
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_queue", detail);
|
||||
if (!queue->create_work()) {
|
||||
const HRESULT error = win32_error();
|
||||
queue->Release();
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
/* zlib (RFC 1950) / deflate (RFC 1951) decoder; see zlib_inflate.h. */
|
||||
#include "zlib_inflate.h"
|
||||
|
||||
namespace {
|
||||
|
||||
struct Bits {
|
||||
const uint8_t* data;
|
||||
size_t size;
|
||||
size_t pos = 0; // next byte
|
||||
uint32_t buffer = 0;
|
||||
int count = 0; // valid bits in buffer
|
||||
bool overrun = false;
|
||||
|
||||
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
|
||||
uint32_t get(int n) {
|
||||
while (count < n) {
|
||||
if (pos >= size) {
|
||||
overrun = true;
|
||||
return 0;
|
||||
}
|
||||
buffer |= static_cast<uint32_t>(data[pos++]) << count;
|
||||
count += 8;
|
||||
}
|
||||
const uint32_t value = buffer & ((n == 32) ? 0xFFFFFFFFu : ((1u << n) - 1u));
|
||||
buffer >>= n;
|
||||
count -= n;
|
||||
return value;
|
||||
}
|
||||
void align_to_byte() {
|
||||
buffer >>= (count & 7);
|
||||
count -= (count & 7);
|
||||
}
|
||||
};
|
||||
|
||||
constexpr int kMaxBits = 15;
|
||||
|
||||
// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length and symbols sorted by code.
|
||||
struct Huffman {
|
||||
uint16_t counts[kMaxBits + 1] = {};
|
||||
uint16_t symbols[320] = {};
|
||||
|
||||
// Returns false for an over-subscribed set of lengths. An incomplete set is allowed (a
|
||||
// single distance code is legal), and decoding an unassigned code then fails.
|
||||
bool build(const uint8_t* lengths, int n) {
|
||||
for (int i = 0; i <= kMaxBits; ++i) counts[i] = 0;
|
||||
for (int i = 0; i < n; ++i) ++counts[lengths[i]];
|
||||
counts[0] = 0;
|
||||
int left = 1;
|
||||
for (int len = 1; len <= kMaxBits; ++len) {
|
||||
left <<= 1;
|
||||
left -= counts[len];
|
||||
if (left < 0) return false;
|
||||
}
|
||||
uint16_t offsets[kMaxBits + 2] = {};
|
||||
for (int len = 1; len <= kMaxBits; ++len) offsets[len + 1] = offsets[len] + counts[len];
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (lengths[i]) symbols[offsets[lengths[i]]++] = static_cast<uint16_t>(i);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Huffman codes are packed most significant bit first, one bit at a time.
|
||||
int decode(Bits& in) const {
|
||||
int code = 0, first = 0, index = 0;
|
||||
for (int len = 1; len <= kMaxBits; ++len) {
|
||||
code |= static_cast<int>(in.get(1));
|
||||
if (in.overrun) return -1;
|
||||
const int count = counts[len];
|
||||
if (code - first < count) return symbols[index + (code - first)];
|
||||
index += count;
|
||||
first += count;
|
||||
first <<= 1;
|
||||
code <<= 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
// RFC 1951 3.2.5 length and distance tables.
|
||||
constexpr uint16_t kLengthBase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
|
||||
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
|
||||
constexpr uint8_t kLengthExtra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
|
||||
constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
|
||||
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
|
||||
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
|
||||
|
||||
struct Output {
|
||||
uint8_t* data;
|
||||
size_t size;
|
||||
size_t pos = 0;
|
||||
};
|
||||
|
||||
BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman& dist) {
|
||||
for (;;) {
|
||||
const int symbol = lit.decode(in);
|
||||
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (symbol < 256) {
|
||||
if (out.pos >= out.size) return BxInflateResult::output_mismatch;
|
||||
out.data[out.pos++] = static_cast<uint8_t>(symbol);
|
||||
continue;
|
||||
}
|
||||
if (symbol == 256) return BxInflateResult::ok;
|
||||
const int li = symbol - 257;
|
||||
if (li >= 29) return BxInflateResult::bad_data;
|
||||
const size_t length = kLengthBase[li] + in.get(kLengthExtra[li]);
|
||||
const int ds = dist.decode(in);
|
||||
if (ds < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (ds >= 30) return BxInflateResult::bad_data;
|
||||
const size_t distance = kDistBase[ds] + in.get(kDistExtra[ds]);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (distance > out.pos) return BxInflateResult::bad_data;
|
||||
if (length > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (size_t i = 0; i < length; ++i, ++out.pos) out.data[out.pos] = out.data[out.pos - distance];
|
||||
}
|
||||
}
|
||||
|
||||
BxInflateResult fixed_block(Bits& in, Output& out) {
|
||||
static Huffman lit, dist;
|
||||
static bool built = [] {
|
||||
uint8_t lengths[288];
|
||||
int i = 0;
|
||||
for (; i < 144; ++i) lengths[i] = 8;
|
||||
for (; i < 256; ++i) lengths[i] = 9;
|
||||
for (; i < 280; ++i) lengths[i] = 7;
|
||||
for (; i < 288; ++i) lengths[i] = 8;
|
||||
lit.build(lengths, 288);
|
||||
uint8_t dl[30];
|
||||
for (int d = 0; d < 30; ++d) dl[d] = 5;
|
||||
dist.build(dl, 30);
|
||||
return true;
|
||||
}();
|
||||
(void)built;
|
||||
return codes(in, out, lit, dist);
|
||||
}
|
||||
|
||||
BxInflateResult dynamic_block(Bits& in, Output& out) {
|
||||
const int hlit = static_cast<int>(in.get(5)) + 257;
|
||||
const int hdist = static_cast<int>(in.get(5)) + 1;
|
||||
const int hclen = static_cast<int>(in.get(4)) + 4;
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (hlit > 286 || hdist > 30) return BxInflateResult::bad_data;
|
||||
static constexpr uint8_t kOrder[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
|
||||
uint8_t lengths[320] = {};
|
||||
for (int i = 0; i < hclen; ++i) lengths[kOrder[i]] = static_cast<uint8_t>(in.get(3));
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
Huffman code_lengths;
|
||||
if (!code_lengths.build(lengths, 19)) return BxInflateResult::bad_data;
|
||||
int index = 0;
|
||||
while (index < hlit + hdist) {
|
||||
int symbol = code_lengths.decode(in);
|
||||
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (symbol < 16) {
|
||||
lengths[index++] = static_cast<uint8_t>(symbol);
|
||||
continue;
|
||||
}
|
||||
uint8_t value = 0;
|
||||
int repeat;
|
||||
if (symbol == 16) {
|
||||
if (index == 0) return BxInflateResult::bad_data;
|
||||
value = lengths[index - 1];
|
||||
repeat = 3 + static_cast<int>(in.get(2));
|
||||
} else if (symbol == 17) {
|
||||
repeat = 3 + static_cast<int>(in.get(3));
|
||||
} else {
|
||||
repeat = 11 + static_cast<int>(in.get(7));
|
||||
}
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (index + repeat > hlit + hdist) return BxInflateResult::bad_data;
|
||||
while (repeat--) lengths[index++] = value;
|
||||
}
|
||||
if (lengths[256] == 0) return BxInflateResult::bad_data; // no end-of-block code
|
||||
Huffman lit, dist;
|
||||
if (!lit.build(lengths, hlit) || !dist.build(lengths + hlit, hdist)) return BxInflateResult::bad_data;
|
||||
return codes(in, out, lit, dist);
|
||||
}
|
||||
|
||||
uint32_t adler32(const uint8_t* data, size_t size) {
|
||||
uint32_t a = 1, b = 0;
|
||||
while (size) {
|
||||
size_t chunk = size < 5552 ? size : 5552; // largest n with no 32-bit overflow before the modulo
|
||||
size -= chunk;
|
||||
while (chunk--) {
|
||||
a += *data++;
|
||||
b += a;
|
||||
}
|
||||
a %= 65521u;
|
||||
b %= 65521u;
|
||||
}
|
||||
return (b << 16) | a;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
|
||||
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
|
||||
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
|
||||
const uint8_t cmf = input[0], flg = input[1];
|
||||
if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) {
|
||||
return BxInflateResult::bad_header;
|
||||
}
|
||||
Bits in{input + 2, input_size - 2};
|
||||
Output out{output, output_size};
|
||||
for (;;) {
|
||||
const uint32_t final_block = in.get(1);
|
||||
const uint32_t type = in.get(2);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
BxInflateResult r;
|
||||
if (type == 0) {
|
||||
in.align_to_byte();
|
||||
const uint32_t len = in.get(16), nlen = in.get(16);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if ((len ^ 0xFFFFu) != nlen) return BxInflateResult::bad_data;
|
||||
// After aligning, the bit buffer is empty: copy straight from the byte stream.
|
||||
if (len > in.size - in.pos) return BxInflateResult::truncated;
|
||||
if (len > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (uint32_t i = 0; i < len; ++i) out.data[out.pos++] = in.data[in.pos++];
|
||||
r = BxInflateResult::ok;
|
||||
} else if (type == 1) {
|
||||
r = fixed_block(in, out);
|
||||
} else if (type == 2) {
|
||||
r = dynamic_block(in, out);
|
||||
} else {
|
||||
return BxInflateResult::bad_data;
|
||||
}
|
||||
if (r != BxInflateResult::ok) return r;
|
||||
if (final_block) break;
|
||||
}
|
||||
if (out.pos != out.size) return BxInflateResult::output_mismatch;
|
||||
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
|
||||
in.align_to_byte();
|
||||
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
|
||||
if (input_size - 2 - trailer < 4) return BxInflateResult::truncated;
|
||||
const uint8_t* t = in.data + trailer;
|
||||
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
|
||||
(static_cast<uint32_t>(t[2]) << 8) | t[3];
|
||||
return adler32(output, output_size) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
|
||||
}
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result) {
|
||||
switch (result) {
|
||||
case BxInflateResult::ok: return "ok";
|
||||
case BxInflateResult::bad_header: return "bad_header";
|
||||
case BxInflateResult::bad_data: return "bad_data";
|
||||
case BxInflateResult::truncated: return "truncated";
|
||||
case BxInflateResult::output_mismatch: return "output_mismatch";
|
||||
case BxInflateResult::bad_checksum: return "bad_checksum";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* A zlib stream decoder written from the public specifications: IETF RFC 1950 (the zlib
|
||||
* wrapper and its Adler-32 check) and RFC 1951 (deflate: stored, fixed-Huffman and
|
||||
* dynamic-Huffman blocks, 32 KiB window). No third-party code.
|
||||
*
|
||||
* Used for DirectStorage requests whose DSTORAGE_REQUEST_OPTIONS.ZlibDecompress bit is set
|
||||
* (authorized GDK documentation: RFC 1950 streams, full 32 KiB window, compressed size smaller
|
||||
* than the decompressed size).
|
||||
*/
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
enum class BxInflateResult {
|
||||
ok,
|
||||
bad_header, // not an RFC 1950 header, or a preset dictionary is required
|
||||
bad_data, // malformed deflate data
|
||||
truncated, // the input ended before the final block
|
||||
output_mismatch, // the stream does not produce exactly `output_size` bytes
|
||||
bad_checksum, // Adler-32 of the output does not match the stream trailer
|
||||
};
|
||||
|
||||
/* Decodes `input` into exactly `output_size` bytes at `output`. */
|
||||
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size);
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result);
|
||||
@@ -1,4 +1,4 @@
|
||||
bx_add_shim_dll(xg_xs xg_xs xg_xs.def
|
||||
xg_xs.cpp
|
||||
xg_xbox.cpp
|
||||
)
|
||||
target_link_libraries(xg_xs PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -1,195 +0,0 @@
|
||||
#ifndef BETTERXEN_XG_TEXTURE_H
|
||||
#define BETTERXEN_XG_TEXTURE_H
|
||||
|
||||
/*
|
||||
* BetterXen M1 linear texture-address contract for xg_xs.dll.
|
||||
*
|
||||
* Field meanings follow the public D3D12 resource and footprint documents
|
||||
* (D3D12_RESOURCE_DIMENSION, D3D12_SUBRESOURCE_FOOTPRINT, and
|
||||
* D3D12_TEXTURE_DATA_PITCH_ALIGNMENT / D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT).
|
||||
* Block-compressed footprint width and height are texels rounded up to the
|
||||
* 4x4 block, the same rounding D3D12 uses for a copyable footprint.
|
||||
* Format numbers are the public DXGI_FORMAT values. This is not the Xbox
|
||||
* GDK XG interface and it is not an Xbox hardware result.
|
||||
*/
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <dxgiformat.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Public D3D12_RESOURCE_DIMENSION values used by this shim. */
|
||||
#define BX_XG_DIMENSION_BUFFER 1u
|
||||
#define BX_XG_DIMENSION_TEXTURE1D 2u
|
||||
#define BX_XG_DIMENSION_TEXTURE2D 3u
|
||||
#define BX_XG_DIMENSION_TEXTURE3D 4u
|
||||
|
||||
/* Public D3D12 texture copy alignments, in bytes. */
|
||||
#define BX_XG_LINEAR_PITCH_ALIGNMENT 256u
|
||||
#define BX_XG_LINEAR_PLACEMENT_ALIGNMENT 512u
|
||||
|
||||
/* Public D3D12 texture size limits used as the acceptance cap. */
|
||||
#define BX_XG_MAX_TEXTURE_EDGE 16384u
|
||||
#define BX_XG_MAX_ARRAY_SLICES 2048u
|
||||
|
||||
/*
|
||||
* Layout selectors for this shim. LINEAR is computed exactly.
|
||||
* SW_64KB_S / D / R are named RDNA 2 tile modes reserved for M3. They are
|
||||
* accepted by XGCreateTextureComputer and every layout or copy call on them
|
||||
* returns E_NOTIMPL without writing an address.
|
||||
* XGSuggestSwizzleMode never returns a tile mode. It returns LINEAR or NONE.
|
||||
*/
|
||||
typedef enum bx_xg_layout_mode {
|
||||
BX_XG_LAYOUT_LINEAR = 0,
|
||||
BX_XG_LAYOUT_SW_64KB_S = 1,
|
||||
BX_XG_LAYOUT_SW_64KB_D = 2,
|
||||
BX_XG_LAYOUT_SW_64KB_R = 3,
|
||||
BX_XG_LAYOUT_NONE = 0xFFFFFFFFu
|
||||
} bx_xg_layout_mode;
|
||||
|
||||
typedef struct bx_xg_sample_desc {
|
||||
uint32_t count;
|
||||
uint32_t quality;
|
||||
} bx_xg_sample_desc;
|
||||
|
||||
typedef struct bx_xg_resource_desc {
|
||||
uint32_t dimension;
|
||||
uint32_t alignment; /* 0 or BX_XG_LINEAR_PLACEMENT_ALIGNMENT */
|
||||
uint64_t width; /* texels */
|
||||
uint32_t height; /* texels */
|
||||
uint16_t depth_or_array_size;
|
||||
uint16_t mip_levels; /* 0 selects the full chain, down to 1x1 */
|
||||
uint32_t format; /* DXGI_FORMAT */
|
||||
bx_xg_sample_desc sample_desc;
|
||||
uint32_t layout; /* bx_xg_layout_mode */
|
||||
uint32_t flags; /* must be 0 */
|
||||
} bx_xg_resource_desc;
|
||||
|
||||
typedef struct bx_xg_subresource_footprint {
|
||||
uint32_t format;
|
||||
uint32_t width; /* texels, rounded up to the format block width */
|
||||
uint32_t height; /* texels, rounded up to the format block height */
|
||||
uint32_t depth;
|
||||
uint32_t row_pitch; /* bytes, multiple of BX_XG_LINEAR_PITCH_ALIGNMENT */
|
||||
} bx_xg_subresource_footprint;
|
||||
|
||||
typedef struct bx_xg_placed_footprint {
|
||||
uint64_t offset;
|
||||
bx_xg_subresource_footprint footprint;
|
||||
/*
|
||||
* Absolute byte just past this subresource's last payload byte:
|
||||
* offset + (row_count - 1) * row_pitch + row_bytes.
|
||||
* That is the D3D12 GetCopyableFootprints end. It does not include the
|
||||
* last row's pitch padding or the 512-byte tail. The copy span of a
|
||||
* GetResourceLayout call is layouts[last].copy_end - base_offset.
|
||||
*/
|
||||
uint64_t copy_end;
|
||||
} bx_xg_placed_footprint;
|
||||
|
||||
/* {B7E4C8A1-6F2D-4C55-8A19-3D0E5F7B91C4} BetterXen IXGTextureAddressComputer */
|
||||
static const GUID BX_IID_IXGTextureAddressComputer = {
|
||||
0xB7E4C8A1u, 0x6F2Du, 0x4C55u, {0x8Au, 0x19u, 0x3Du, 0x0Eu, 0x5Fu, 0x7Bu, 0x91u, 0xC4u}};
|
||||
|
||||
/* Public COM IUnknown IID. */
|
||||
static const GUID BX_IID_IUnknown = {
|
||||
0x00000000u, 0x0000u, 0x0000u, {0xC0u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x46u}};
|
||||
|
||||
/*
|
||||
* GetResourceLayout places every subresource at its absolute offset from
|
||||
* base_offset, including subresources before first_subresource. total_bytes
|
||||
* is the BetterXen allocation span: the 512-aligned end of the last requested
|
||||
* subresource, measured from base_offset, so a partial range still covers the
|
||||
* earlier subresources and a 1x1 RGBA8 texture reports 512. copy_end on each
|
||||
* footprint is the separate D3D12-style copy span end described above.
|
||||
*/
|
||||
typedef struct bx_xg_texture_computer bx_xg_texture_computer;
|
||||
|
||||
typedef struct bx_xg_texture_computer_vtbl {
|
||||
HRESULT(WINAPI* QueryInterface)(bx_xg_texture_computer* self, const GUID* riid, void** object);
|
||||
ULONG(WINAPI* AddRef)(bx_xg_texture_computer* self);
|
||||
ULONG(WINAPI* Release)(bx_xg_texture_computer* self);
|
||||
HRESULT(WINAPI* GetResourceLayout)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t first_subresource,
|
||||
uint32_t subresource_count,
|
||||
uint64_t base_offset,
|
||||
bx_xg_placed_footprint* layouts,
|
||||
uint32_t* row_counts,
|
||||
uint64_t* row_sizes_in_bytes,
|
||||
uint64_t* total_bytes);
|
||||
HRESULT(WINAPI* GetResourceSizeBytes)(bx_xg_texture_computer* self, uint64_t* size_bytes);
|
||||
HRESULT(WINAPI* GetResourceBaseAlignmentBytes)(bx_xg_texture_computer* self, uint64_t* alignment_bytes);
|
||||
HRESULT(WINAPI* GetMipLevelOffsetBytes)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t array_slice,
|
||||
uint32_t mip_level,
|
||||
uint64_t* offset_bytes);
|
||||
HRESULT(WINAPI* GetTexelElementOffsetBytes)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t array_slice,
|
||||
uint32_t mip_level,
|
||||
uint32_t x,
|
||||
uint32_t y,
|
||||
uint32_t z,
|
||||
uint64_t* offset_bytes);
|
||||
HRESULT(WINAPI* CopyIntoSubresource)(
|
||||
bx_xg_texture_computer* self,
|
||||
void* destination,
|
||||
uint64_t destination_size,
|
||||
uint32_t subresource,
|
||||
const void* source,
|
||||
uint64_t source_size,
|
||||
uint32_t source_row_pitch,
|
||||
uint32_t source_depth_pitch);
|
||||
HRESULT(WINAPI* CopyFromSubresource)(
|
||||
bx_xg_texture_computer* self,
|
||||
void* destination,
|
||||
uint64_t destination_size,
|
||||
uint32_t destination_row_pitch,
|
||||
uint32_t destination_depth_pitch,
|
||||
const void* source,
|
||||
uint64_t source_size,
|
||||
uint32_t subresource);
|
||||
} bx_xg_texture_computer_vtbl;
|
||||
|
||||
struct bx_xg_texture_computer {
|
||||
const bx_xg_texture_computer_vtbl* lpVtbl;
|
||||
};
|
||||
|
||||
/*
|
||||
* On success, *computer is an IXGTextureAddressComputer with a reference
|
||||
* count of 1. On failure, *computer is NULL when computer itself is non-NULL.
|
||||
* Subresource index is mip_level + array_slice * mip_levels.
|
||||
* A row pitch of 0 on a copy selects the tight logical row size.
|
||||
*/
|
||||
HRESULT WINAPI XGCreateTextureComputer(const bx_xg_resource_desc* desc, void** computer);
|
||||
|
||||
/*
|
||||
* Returns BX_XG_LAYOUT_LINEAR when this shim can lay the texture out, and
|
||||
* BX_XG_LAYOUT_NONE otherwise. The same arguments always return the same mode.
|
||||
*/
|
||||
uint32_t WINAPI XGSuggestSwizzleMode(
|
||||
uint32_t resource_type,
|
||||
uint32_t format,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
uint32_t depth,
|
||||
uint32_t mip_levels,
|
||||
uint32_t sample_count,
|
||||
uint32_t flags);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* BETTERXEN_XG_TEXTURE_H */
|
||||
@@ -0,0 +1,683 @@
|
||||
/*
|
||||
* The XG texture-address contract as titles call it (authorized GDK documentation, xg_xs.h):
|
||||
* XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**) and
|
||||
* XGSuggestSwizzleMode(const XG_RESOURCE_DESC*, flags, XG_TEXTURE_LAYOUT*). Only the structure
|
||||
* layouts, enum values and the method order are taken from there; no header text is reproduced.
|
||||
*
|
||||
* The layout this computer reports is BetterXen's, not the console's: every texture is laid out
|
||||
* linearly (swizzle mode LINEAR), mip-major (each mip holds all of its array or depth slices),
|
||||
* rows aligned to 256 bytes, mips to 512 bytes, the resource to 64 KB. Depth-stencil formats
|
||||
* get a separate depth plane and stencil plane. Every method uses the same layout, so sizes,
|
||||
* offsets, texel addresses and copies agree with each other. Data a title stores pre-tiled for
|
||||
* the console's swizzle modes is not detiled by this layer.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <dxgiformat.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// --- XG types (layouts from xg_xs.h) -------------------------------------------------------
|
||||
enum : uint32_t {
|
||||
kDimBuffer = 1,
|
||||
kDimTexture1D = 2,
|
||||
kDimTexture2D = 3,
|
||||
kDimTexture3D = 4,
|
||||
};
|
||||
// XG_TEXTURE_LAYOUT: 0 default (XG chooses), 1 row major, 2 64 KB with an undefined swizzle, or
|
||||
// 0x100 | XG_SWIZZLE_MODE to request one swizzle mode.
|
||||
constexpr uint32_t kLayoutSwizzleFlag = 0x100;
|
||||
constexpr uint32_t kLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
|
||||
constexpr uint32_t kSwizzleModeLinear = 0;
|
||||
constexpr uint32_t kSwizzleMode64KbS = 9; // XG_SWIZZLE_MODE_64KB_S
|
||||
enum : uint32_t { kPlaneUnused = 0, kPlaneDefault = 1, kPlaneDepth = 7, kPlaneStencil = 8 };
|
||||
|
||||
// --- RDNA 2 SW_64KB_S (clean-room, ported from the earlier xg_xs.cpp) ---------------------
|
||||
// Within one 64 KiB tile, the byte offset of element (x, y) is pdep(x, x_mask) | pdep(y, y_mask),
|
||||
// x and y in elements (texels, or 4x4 blocks for BC). The masks come from the public AddrLib RB+
|
||||
// pattern tables (GFX10_SW_64K_S_RBPLUS_PATINFO, MIT); at 4 bytes per element the x mask equals
|
||||
// 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.
|
||||
struct Sw64kbS {
|
||||
uint32_t bytes;
|
||||
uint32_t x_mask;
|
||||
uint32_t y_mask;
|
||||
uint32_t tile_x; // elements per tile row
|
||||
uint32_t tile_y; // element rows per tile
|
||||
};
|
||||
bool sw64kb_s_params(uint32_t bytes, Sw64kbS* out) {
|
||||
switch (bytes) {
|
||||
case 4: *out = {4, 0xAA8Cu, 0x5570u, 128, 128}; return true;
|
||||
case 8: *out = {8, 0xAAC8u, 0x5530u, 128, 64}; return true;
|
||||
case 16: *out = {16, 0xAAC0u, 0x5530u, 64, 64}; return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
uint32_t pdep(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; mask; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & bit) out |= lowest;
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
uint32_t pext(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; mask; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & lowest) out |= bit;
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
constexpr uint64_t kTileBytes = 64 * 1024;
|
||||
|
||||
struct XgSampleDesc {
|
||||
UINT Count;
|
||||
UINT Quality;
|
||||
};
|
||||
|
||||
struct XgResourceDesc {
|
||||
uint32_t Dimension;
|
||||
UINT64 Alignment;
|
||||
UINT64 Width;
|
||||
UINT Height;
|
||||
UINT16 DepthOrArraySize;
|
||||
UINT16 MipLevels;
|
||||
uint32_t Format;
|
||||
XgSampleDesc SampleDesc;
|
||||
uint32_t Layout;
|
||||
uint32_t MiscFlags;
|
||||
};
|
||||
|
||||
struct XgMipLevelLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 OffsetBytes;
|
||||
UINT64 Slice2DSizeBytes;
|
||||
UINT32 PitchPixels;
|
||||
UINT32 PitchBytes;
|
||||
UINT32 AlignmentBytes;
|
||||
UINT32 PaddedWidthElements;
|
||||
UINT32 PaddedHeightElements;
|
||||
UINT32 PaddedDepthOrArraySize;
|
||||
UINT32 WidthElements;
|
||||
UINT32 HeightElements;
|
||||
UINT32 WidthPixels;
|
||||
UINT32 HeightPixels;
|
||||
UINT32 DepthOrArraySize;
|
||||
UINT32 SampleCount;
|
||||
uint32_t SwizzleMode;
|
||||
UINT64 BankRotationAddressBitMask;
|
||||
UINT64 BankRotationBytesPerSlice;
|
||||
UINT32 SliceDepthElements;
|
||||
UINT32 IsMipTail;
|
||||
UINT32 MipTailOffsetElementsX : 11;
|
||||
UINT32 MipTailOffsetElementsY : 11;
|
||||
UINT32 MipTailOffsetElementsZ : 10;
|
||||
};
|
||||
|
||||
constexpr int kMaxMips = 15;
|
||||
constexpr int kMaxPlanes = 4;
|
||||
|
||||
struct XgPlaneLayout {
|
||||
uint32_t Usage;
|
||||
UINT64 SizeBytes;
|
||||
UINT64 SliceSizeBytes;
|
||||
UINT64 BaseOffsetBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 BytesPerElement;
|
||||
UINT32 StandardMipCount;
|
||||
UINT32 MipTailMipCount;
|
||||
XgMipLevelLayout MipLayout[kMaxMips];
|
||||
};
|
||||
|
||||
struct XgResourceLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 MipLevels;
|
||||
UINT32 Planes;
|
||||
XgPlaneLayout Plane[kMaxPlanes];
|
||||
uint32_t Dimension;
|
||||
};
|
||||
|
||||
// Pinned against the layouts derived from the GDK header (natural x64 alignment).
|
||||
static_assert(sizeof(XgResourceDesc) == 56, "XG_RESOURCE_DESC size");
|
||||
static_assert(offsetof(XgResourceDesc, Alignment) == 8 && offsetof(XgResourceDesc, Width) == 16, "XG_RESOURCE_DESC");
|
||||
static_assert(sizeof(XgMipLevelLayout) == 112, "XG_MIPLEVEL_LAYOUT size");
|
||||
static_assert(offsetof(XgPlaneLayout, MipLayout) == 56 && sizeof(XgPlaneLayout) == 1736, "XG_PLANE_LAYOUT size");
|
||||
static_assert(offsetof(XgResourceLayout, Plane) == 24 && sizeof(XgResourceLayout) == 6976, "XG_RESOURCE_LAYOUT size");
|
||||
|
||||
struct XgPackedMipDesc {
|
||||
UINT8 NumStandardMips;
|
||||
UINT8 NumPackedMips;
|
||||
UINT32 NumTilesForPackedMips;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
struct XgTileShape {
|
||||
UINT32 WidthInTexels;
|
||||
UINT32 HeightInTexels;
|
||||
UINT32 DepthInTexels;
|
||||
};
|
||||
struct XgSubresourceTiling {
|
||||
UINT32 WidthInTiles;
|
||||
UINT16 HeightInTiles;
|
||||
UINT16 DepthInTiles;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
|
||||
// --- Formats -------------------------------------------------------------------------------
|
||||
struct FormatInfo {
|
||||
uint32_t block; // texels per element edge: 1, or 4 for block compression
|
||||
uint32_t bytes; // bytes per element
|
||||
uint32_t stencil; // 1 when the format carries a stencil plane
|
||||
};
|
||||
|
||||
bool format_info(uint32_t f, FormatInfo* out) {
|
||||
auto set = [&](uint32_t block, uint32_t bytes, uint32_t stencil = 0) {
|
||||
*out = {block, bytes, stencil};
|
||||
return true;
|
||||
};
|
||||
if (f >= DXGI_FORMAT_R32G32B32A32_TYPELESS && f <= DXGI_FORMAT_R32G32B32A32_SINT) return set(1, 16);
|
||||
if (f >= DXGI_FORMAT_R32G32B32_TYPELESS && f <= DXGI_FORMAT_R32G32B32_SINT) return set(1, 12);
|
||||
if (f >= DXGI_FORMAT_R16G16B16A16_TYPELESS && f <= DXGI_FORMAT_R32G32_SINT) return set(1, 8);
|
||||
if (f >= DXGI_FORMAT_R32G8X24_TYPELESS && f <= DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) return set(1, 4, 1);
|
||||
if (f >= DXGI_FORMAT_R10G10B10A2_TYPELESS && f <= DXGI_FORMAT_R32_SINT) return set(1, 4);
|
||||
if (f >= DXGI_FORMAT_R24G8_TYPELESS && f <= DXGI_FORMAT_X24_TYPELESS_G8_UINT) return set(1, 4, 1);
|
||||
if (f >= DXGI_FORMAT_R8G8_TYPELESS && f <= DXGI_FORMAT_R16_SINT) return set(1, 2);
|
||||
if (f >= DXGI_FORMAT_R8_TYPELESS && f <= DXGI_FORMAT_A8_UNORM) return set(1, 1);
|
||||
if (f == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || f == DXGI_FORMAT_R8G8_B8G8_UNORM || f == DXGI_FORMAT_G8R8_G8B8_UNORM) return set(1, 4);
|
||||
if ((f >= DXGI_FORMAT_BC1_TYPELESS && f <= DXGI_FORMAT_BC1_UNORM_SRGB) ||
|
||||
(f >= DXGI_FORMAT_BC4_TYPELESS && f <= DXGI_FORMAT_BC4_SNORM)) {
|
||||
return set(4, 8);
|
||||
}
|
||||
if ((f >= DXGI_FORMAT_BC2_TYPELESS && f <= DXGI_FORMAT_BC3_UNORM_SRGB) ||
|
||||
(f >= DXGI_FORMAT_BC5_TYPELESS && f <= DXGI_FORMAT_BC5_SNORM) ||
|
||||
(f >= DXGI_FORMAT_BC6H_TYPELESS && f <= DXGI_FORMAT_BC7_UNORM_SRGB)) {
|
||||
return set(4, 16);
|
||||
}
|
||||
if (f >= DXGI_FORMAT_B5G6R5_UNORM && f <= DXGI_FORMAT_B5G5R5A1_UNORM) return set(1, 2);
|
||||
if (f >= DXGI_FORMAT_B8G8R8A8_UNORM && f <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return set(1, 4);
|
||||
if (f == DXGI_FORMAT_B4G4R4A4_UNORM) return set(1, 2);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t align_up(uint64_t v, uint64_t a) { return (v + a - 1) / a * a; }
|
||||
uint32_t mip_extent(uint64_t base, uint32_t mip) {
|
||||
const uint64_t v = base >> mip;
|
||||
return v ? static_cast<uint32_t>(v) : 1u;
|
||||
}
|
||||
|
||||
constexpr uint64_t kRowAlign = 256;
|
||||
constexpr uint64_t kMipAlign = 512;
|
||||
constexpr uint64_t kResourceAlign = 64 * 1024;
|
||||
|
||||
void log_rejected(const XgResourceDesc* d, const char* why) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s: dim=%u width=%llu height=%u depth_or_array=%u mips=%u format=%u samples=%u layout=0x%x",
|
||||
why, d->Dimension, static_cast<unsigned long long>(d->Width), d->Height, d->DepthOrArraySize,
|
||||
d->MipLevels, d->Format, d->SampleDesc.Count, d->Layout);
|
||||
bx_log_emit(BX_LOG_WARN, "xg_xs", "texture_computer_rejected", detail);
|
||||
}
|
||||
|
||||
// A requested swizzle mode this layer does not implement: laid out (and reported) linearly; the
|
||||
// first request for each mode is logged, with the description.
|
||||
void log_linear_instead(const XgResourceDesc* d) {
|
||||
static std::atomic<uint32_t> seen[32];
|
||||
const uint32_t mode = d->Layout & 0x1F;
|
||||
if (seen[mode].exchange(1)) return;
|
||||
log_rejected(d, "requested swizzle mode is not implemented; laid out and reported as LINEAR");
|
||||
}
|
||||
|
||||
// --- The computer ---------------------------------------------------------------------------
|
||||
class XGTextureAddressComputer {
|
||||
public:
|
||||
virtual ULONG AddRef() = 0;
|
||||
virtual ULONG Release() = 0;
|
||||
virtual HRESULT GetResourceLayout(XgResourceLayout* layout) = 0;
|
||||
virtual UINT64 GetResourceSizeBytes() = 0;
|
||||
virtual UINT64 GetResourceBaseAlignmentBytes() = 0;
|
||||
virtual UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) = 0;
|
||||
virtual UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z_or_slice,
|
||||
UINT32 sample, UINT32* bit_position) = 0;
|
||||
virtual HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y,
|
||||
UINT32* z_or_slice, UINT32* sample) = 0;
|
||||
virtual HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear,
|
||||
UINT32 row_pitch, UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
|
||||
const void* base, UINT32 row_pitch, UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape,
|
||||
UINT32* subresource_count, UINT32 first_subresource,
|
||||
XgSubresourceTiling* tilings) = 0;
|
||||
virtual HRESULT GetTextureViewDescriptor(UINT32 plane, void* descriptor) = 0;
|
||||
virtual bool IsTiledResource() = 0;
|
||||
virtual HRESULT GetSwizzlePatternInfo(UINT32 plane, void* info) = 0;
|
||||
};
|
||||
|
||||
class LayoutComputer final : public XGTextureAddressComputer {
|
||||
public:
|
||||
static HRESULT create(const XgResourceDesc& desc, XGTextureAddressComputer** out);
|
||||
|
||||
ULONG AddRef() override { return ++refs_; }
|
||||
ULONG Release() override {
|
||||
const ULONG left = --refs_;
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
}
|
||||
HRESULT GetResourceLayout(XgResourceLayout* layout) override {
|
||||
if (!layout) return E_POINTER;
|
||||
*layout = layout_;
|
||||
return S_OK;
|
||||
}
|
||||
UINT64 GetResourceSizeBytes() override { return layout_.SizeBytes; }
|
||||
UINT64 GetResourceBaseAlignmentBytes() override { return layout_.BaseAlignmentBytes; }
|
||||
UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) override {
|
||||
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
|
||||
return layout_.Plane[plane].MipLayout[mip].OffsetBytes;
|
||||
}
|
||||
UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z, UINT32 sample,
|
||||
UINT32* bit_position) override {
|
||||
if (bit_position) *bit_position = 0;
|
||||
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
|
||||
const XgPlaneLayout& p = layout_.Plane[plane];
|
||||
const XgMipLevelLayout& m = p.MipLayout[mip];
|
||||
const uint64_t ex = x / block_, ey = y / block_;
|
||||
if (swizzled_) {
|
||||
if (ex >= sw_.tile_x || ey >= sw_.tile_y) return 0;
|
||||
return m.OffsetBytes + element_offset(static_cast<uint32_t>(ex), static_cast<uint32_t>(ey));
|
||||
}
|
||||
return m.OffsetBytes + z * m.Slice2DSizeBytes + ey * m.PitchBytes +
|
||||
(ex * m.SampleCount + sample) * p.BytesPerElement;
|
||||
}
|
||||
HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y, UINT32* z,
|
||||
UINT32* sample) override {
|
||||
for (UINT32 pi = 0; pi < layout_.Planes; ++pi) {
|
||||
const XgPlaneLayout& p = layout_.Plane[pi];
|
||||
for (UINT32 mi = 0; mi < layout_.MipLevels; ++mi) {
|
||||
const XgMipLevelLayout& m = p.MipLayout[mi];
|
||||
if (offset < m.OffsetBytes || offset >= m.OffsetBytes + m.SizeBytes) continue;
|
||||
const uint64_t rel = offset - m.OffsetBytes;
|
||||
if (swizzled_) {
|
||||
const uint32_t in_tile = static_cast<uint32_t>(rel);
|
||||
if (plane) *plane = pi;
|
||||
if (mip) *mip = mi;
|
||||
if (z) *z = 0;
|
||||
if (y) *y = pext(in_tile, sw_.y_mask) * block_;
|
||||
if (x) *x = static_cast<UINT64>(pext(in_tile, sw_.x_mask)) * block_;
|
||||
if (sample) *sample = 0;
|
||||
return S_OK;
|
||||
}
|
||||
const uint64_t in_slice = rel % m.Slice2DSizeBytes;
|
||||
const uint64_t element = (in_slice % m.PitchBytes) / p.BytesPerElement;
|
||||
if (plane) *plane = pi;
|
||||
if (mip) *mip = mi;
|
||||
if (z) *z = static_cast<UINT32>(rel / m.Slice2DSizeBytes);
|
||||
if (y) *y = static_cast<UINT32>(in_slice / m.PitchBytes * block_);
|
||||
if (x) *x = element / m.SampleCount * block_;
|
||||
if (sample) *sample = static_cast<UINT32>(element % m.SampleCount);
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear, UINT32 row_pitch,
|
||||
UINT32 slice_pitch) override {
|
||||
return copy(static_cast<uint8_t*>(base), plane, subresource, static_cast<const uint8_t*>(linear), row_pitch,
|
||||
slice_pitch, true);
|
||||
}
|
||||
HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32, const void* base,
|
||||
UINT32 row_pitch, UINT32 slice_pitch) override {
|
||||
return copy(static_cast<uint8_t*>(const_cast<void*>(base)), plane, subresource, static_cast<uint8_t*>(linear),
|
||||
row_pitch, slice_pitch, false);
|
||||
}
|
||||
HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape, UINT32* count,
|
||||
UINT32 first, XgSubresourceTiling* tilings) override {
|
||||
// D3D12 standard 64 KB tiles (the public D3D12 tiled-resource rules): the tile shape follows
|
||||
// the element size (256x256 one-byte elements down to 64x64 sixteen-byte ones, in blocks for
|
||||
// block-compressed formats). Leading mips at least one tile wide and high are standard; the
|
||||
// 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_;
|
||||
}
|
||||
auto depth_of = [&](UINT32 m) { return volume ? layout_.Plane[0].MipLayout[m].DepthOrArraySize : 1u; };
|
||||
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) {
|
||||
++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;
|
||||
}
|
||||
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);
|
||||
};
|
||||
UINT32 per_slice = tail_tiles;
|
||||
for (UINT32 m = 0; m < standard; ++m) per_slice += tiles_of(m);
|
||||
if (total_tiles) *total_tiles = per_slice * slices_;
|
||||
UINT32 standard_tiles = 0;
|
||||
for (UINT32 m = 0; m < standard; ++m) standard_tiles += tiles_of(m);
|
||||
if (packed) {
|
||||
*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 (count) {
|
||||
const UINT32 total = mips * slices_;
|
||||
UINT32 written = 0;
|
||||
for (UINT32 i = first; i < total && written < *count && tilings; ++i, ++written) {
|
||||
const UINT32 m = i % mips, slice = i / mips;
|
||||
if (m >= standard) {
|
||||
tilings[written] = {0, 0, 0, 0xFFFFFFFFu}; // packed: no tiling of its own
|
||||
continue;
|
||||
}
|
||||
UINT32 start = slice * per_slice;
|
||||
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};
|
||||
}
|
||||
*count = written;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT GetTextureViewDescriptor(UINT32, void*) override {
|
||||
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetTextureViewDescriptor");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
bool IsTiledResource() override { return false; }
|
||||
HRESULT GetSwizzlePatternInfo(UINT32, void*) override {
|
||||
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetSwizzlePatternInfo");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, uint8_t* linear_rw, UINT32 row_pitch,
|
||||
UINT32 slice_pitch, bool into) {
|
||||
return copy(tiled, plane, subresource, static_cast<const uint8_t*>(linear_rw), row_pitch, slice_pitch, into,
|
||||
linear_rw);
|
||||
}
|
||||
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, const uint8_t* linear, UINT32 row_pitch,
|
||||
UINT32 slice_pitch, bool into, uint8_t* linear_out = nullptr) {
|
||||
if (!tiled || !linear || plane >= layout_.Planes) return E_INVALIDARG;
|
||||
const UINT32 mip = subresource % layout_.MipLevels;
|
||||
const UINT32 slice = subresource / layout_.MipLevels;
|
||||
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
|
||||
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;
|
||||
for (UINT32 row = 0; row < m.HeightElements; ++row) {
|
||||
for (UINT32 col = 0; col < m.WidthElements; ++col) {
|
||||
uint8_t* t = tiled + m.OffsetBytes + element_offset(col, row);
|
||||
const uint64_t lin = static_cast<uint64_t>(row) * row_pitch + static_cast<uint64_t>(col) * sw_.bytes;
|
||||
if (into) std::memcpy(t, linear + lin, sw_.bytes);
|
||||
else std::memcpy(linear_out + lin, t, sw_.bytes);
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
const uint64_t row_bytes = static_cast<uint64_t>(m.WidthElements) * m.SampleCount * p.BytesPerElement;
|
||||
for (UINT32 z = 0; z < depth; ++z) {
|
||||
uint8_t* dst_slice = tiled + m.OffsetBytes + (volume ? z : slice) * m.Slice2DSizeBytes;
|
||||
for (UINT32 row = 0; row < m.HeightElements; ++row) {
|
||||
uint8_t* t = dst_slice + static_cast<uint64_t>(row) * m.PitchBytes;
|
||||
const uint64_t lin = static_cast<uint64_t>(z) * slice_pitch + static_cast<uint64_t>(row) * row_pitch;
|
||||
if (into) std::memcpy(t, linear + lin, row_bytes);
|
||||
else std::memcpy(linear_out + lin, t, row_bytes);
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
uint32_t element_offset(uint32_t ex, uint32_t ey) const { return pdep(ex, sw_.x_mask) | pdep(ey, sw_.y_mask); }
|
||||
|
||||
XgResourceLayout layout_{};
|
||||
uint32_t block_ = 1;
|
||||
uint32_t slices_ = 1;
|
||||
bool swizzled_ = false; // SW_64KB_S, one tile (see Sw64kbS)
|
||||
Sw64kbS sw_{};
|
||||
std::atomic<ULONG> refs_{1};
|
||||
};
|
||||
|
||||
HRESULT LayoutComputer::create(const XgResourceDesc& d, XGTextureAddressComputer** out) {
|
||||
FormatInfo fi{1, 1, 0};
|
||||
const bool buffer = d.Dimension == kDimBuffer;
|
||||
if (!buffer && !format_info(d.Format, &fi)) {
|
||||
log_rejected(&d, "format not in the BetterXen XG table");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (d.Dimension < kDimBuffer || d.Dimension > kDimTexture3D || d.Width == 0) {
|
||||
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_;
|
||||
L.Dimension = d.Dimension;
|
||||
L.BaseAlignmentBytes = d.Alignment > kResourceAlign ? d.Alignment : kResourceAlign;
|
||||
if (buffer) {
|
||||
L.MipLevels = 1;
|
||||
L.Planes = 1;
|
||||
XgPlaneLayout& p = L.Plane[0];
|
||||
p.Usage = kPlaneDefault;
|
||||
p.BytesPerElement = 1;
|
||||
p.StandardMipCount = 1;
|
||||
p.SizeBytes = p.SliceSizeBytes = d.Width;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
XgMipLevelLayout& m = p.MipLayout[0];
|
||||
m.SizeBytes = m.Slice2DSizeBytes = d.Width;
|
||||
m.PitchBytes = static_cast<UINT32>(d.Width > UINT32_MAX ? UINT32_MAX : d.Width);
|
||||
m.WidthElements = m.WidthPixels = m.PitchPixels = m.PaddedWidthElements = m.PitchBytes;
|
||||
m.HeightElements = m.HeightPixels = m.PaddedHeightElements = 1;
|
||||
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kRowAlign);
|
||||
L.SizeBytes = align_up(d.Width, kResourceAlign);
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : (d.Height ? d.Height : 1);
|
||||
const uint32_t depth_or_array = d.DepthOrArraySize ? d.DepthOrArraySize : 1;
|
||||
uint32_t full = 1;
|
||||
for (uint64_t w = d.Width, h = height, z = d.Dimension == kDimTexture3D ? depth_or_array : 1; w > 1 || h > 1 || z > 1;
|
||||
w >>= 1, h >>= 1, z >>= 1) {
|
||||
++full;
|
||||
}
|
||||
uint32_t mips = d.MipLevels ? d.MipLevels : full;
|
||||
if (mips > full) mips = full;
|
||||
if (mips > kMaxMips) {
|
||||
log_rejected(&d, "more than 15 mip levels");
|
||||
delete c;
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
const uint32_t samples = d.SampleDesc.Count ? d.SampleDesc.Count : 1;
|
||||
c->block_ = fi.block;
|
||||
c->slices_ = d.Dimension == kDimTexture3D ? 1 : depth_or_array;
|
||||
// Default, row-major and undefined-swizzle requests leave the choice to XG: BetterXen picks
|
||||
// linear and reports it. A request for SW_64KB_S on one 2D tile gets that layout. Any other
|
||||
// requested swizzle mode is laid out linearly and reported as LINEAR (titles do not expect
|
||||
// XGCreateTextureComputer to fail for a mode they ask for); each such mode is logged once.
|
||||
const uint32_t width_el = static_cast<uint32_t>((d.Width + fi.block - 1) / fi.block);
|
||||
const uint32_t height_el = (height + fi.block - 1) / fi.block;
|
||||
Sw64kbS sw{};
|
||||
const bool requested = (d.Layout & kLayoutSwizzleFlag) && d.Layout != kLayoutSwizzleLinear;
|
||||
const bool single_tile_s = d.Layout == (kLayoutSwizzleFlag | kSwizzleMode64KbS) && d.Dimension == kDimTexture2D &&
|
||||
mips == 1 && depth_or_array == 1 && samples == 1 && !fi.stencil &&
|
||||
sw64kb_s_params(fi.bytes, &sw) && width_el <= sw.tile_x && height_el <= sw.tile_y;
|
||||
if (requested && !single_tile_s) log_linear_instead(&d);
|
||||
if (single_tile_s) {
|
||||
c->swizzled_ = true;
|
||||
c->sw_ = sw;
|
||||
L.MipLevels = 1;
|
||||
L.Planes = 1;
|
||||
L.BaseAlignmentBytes = d.Alignment > kTileBytes ? d.Alignment : kTileBytes;
|
||||
XgPlaneLayout& p = L.Plane[0];
|
||||
p.Usage = kPlaneDefault;
|
||||
p.BytesPerElement = fi.bytes;
|
||||
p.StandardMipCount = 1;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
p.SizeBytes = p.SliceSizeBytes = kTileBytes;
|
||||
XgMipLevelLayout& m = p.MipLayout[0];
|
||||
m.WidthPixels = static_cast<UINT32>(d.Width);
|
||||
m.HeightPixels = height;
|
||||
m.WidthElements = width_el;
|
||||
m.HeightElements = height_el;
|
||||
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
|
||||
m.PitchBytes = sw.tile_x * sw.bytes;
|
||||
m.PitchPixels = sw.tile_x * fi.block;
|
||||
m.PaddedWidthElements = sw.tile_x;
|
||||
m.PaddedHeightElements = sw.tile_y;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kTileBytes);
|
||||
m.SwizzleMode = kSwizzleMode64KbS;
|
||||
m.SizeBytes = m.Slice2DSizeBytes = kTileBytes;
|
||||
L.SizeBytes = kTileBytes;
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
L.MipLevels = mips;
|
||||
L.Planes = fi.stencil ? 2 : 1;
|
||||
uint64_t cursor = 0;
|
||||
for (uint32_t pi = 0; pi < L.Planes; ++pi) {
|
||||
XgPlaneLayout& p = L.Plane[pi];
|
||||
p.Usage = fi.stencil ? (pi == 0 ? kPlaneDepth : kPlaneStencil) : kPlaneDefault;
|
||||
p.BytesPerElement = fi.stencil && pi == 1 ? 1 : fi.bytes;
|
||||
p.StandardMipCount = mips;
|
||||
p.MipTailMipCount = 0;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
cursor = align_up(cursor, kResourceAlign);
|
||||
p.BaseOffsetBytes = cursor;
|
||||
for (uint32_t mi = 0; mi < mips; ++mi) {
|
||||
XgMipLevelLayout& m = p.MipLayout[mi];
|
||||
m.WidthPixels = mip_extent(d.Width, mi);
|
||||
m.HeightPixels = mip_extent(height, mi);
|
||||
m.DepthOrArraySize = d.Dimension == kDimTexture3D ? mip_extent(depth_or_array, mi) : depth_or_array;
|
||||
m.WidthElements = (m.WidthPixels + fi.block - 1) / fi.block;
|
||||
m.HeightElements = (m.HeightPixels + fi.block - 1) / fi.block;
|
||||
m.SampleCount = samples;
|
||||
m.PitchBytes = static_cast<UINT32>(align_up(static_cast<uint64_t>(m.WidthElements) * samples * p.BytesPerElement, kRowAlign));
|
||||
m.PitchPixels = m.PitchBytes / (p.BytesPerElement * samples) * fi.block;
|
||||
m.PaddedWidthElements = m.PitchBytes / (p.BytesPerElement * samples);
|
||||
m.PaddedHeightElements = m.HeightElements;
|
||||
m.PaddedDepthOrArraySize = m.DepthOrArraySize;
|
||||
m.SliceDepthElements = 1;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kMipAlign);
|
||||
m.SwizzleMode = kSwizzleModeLinear;
|
||||
m.Slice2DSizeBytes = static_cast<uint64_t>(m.PitchBytes) * m.HeightElements;
|
||||
m.SizeBytes = m.Slice2DSizeBytes * m.DepthOrArraySize;
|
||||
cursor = align_up(cursor, kMipAlign);
|
||||
m.OffsetBytes = cursor;
|
||||
cursor += m.SizeBytes;
|
||||
}
|
||||
p.SizeBytes = cursor - p.BaseOffsetBytes;
|
||||
p.SliceSizeBytes = p.MipLayout[0].Slice2DSizeBytes;
|
||||
}
|
||||
L.SizeBytes = align_up(cursor, kResourceAlign);
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
__declspec(dllexport) HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, XGTextureAddressComputer** out) {
|
||||
if (!desc || !out) return E_INVALIDARG;
|
||||
*out = nullptr;
|
||||
const HRESULT hr = LayoutComputer::create(*desc, out);
|
||||
if (SUCCEEDED(hr)) {
|
||||
static std::atomic<uint64_t> created{0};
|
||||
const uint64_t n = ++created;
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"BetterXen linear layout (not console tiling): dim=%u %llux%u x%u mips=%u format=%u layout=0x%x size=%llu; total created=%llu",
|
||||
desc->Dimension, static_cast<unsigned long long>(desc->Width), desc->Height,
|
||||
desc->DepthOrArraySize, desc->MipLevels, desc->Format, desc->Layout,
|
||||
static_cast<unsigned long long>((*out)->GetResourceSizeBytes()), static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_INFO, "xg_xs", "texture_computer", detail);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
__declspec(dllexport) HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t, uint32_t* layout) {
|
||||
if (!desc || !layout) return E_INVALIDARG;
|
||||
*layout = kLayoutSwizzleLinear; // this layer lays every texture out linearly
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -751,12 +751,6 @@ BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWith
|
||||
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
|
||||
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
|
||||
|
||||
BX_HR(pk_create_monitor, "IXPackageImpl", 5, "XPackageCreateInstallationMonitor")
|
||||
BX_VOID(pk_close_monitor, "IXPackageImpl", 6, "XPackageCloseInstallationMonitorHandle")
|
||||
BX_VOID(pk_get_progress, "IXPackageImpl", 7, "XPackageGetInstallationProgress")
|
||||
BX_BOOL(pk_update_monitor, "IXPackageImpl", 8, "XPackageUpdateInstallationMonitor")
|
||||
BX_HR(pk_reg_progress, "IXPackageImpl", 9, "XPackageRegisterInstallationProgressChanged")
|
||||
BX_BOOL(pk_unreg_progress, "IXPackageImpl", 10, "XPackageUnregisterInstallationProgressChanged")
|
||||
BX_HR(pk_locale, "IXPackageImpl", 11, "XPackageGetUserLocale")
|
||||
BX_HR(pk_find_chunk, "IXPackageImpl", 12, "XPackageFindChunkAvailability")
|
||||
BX_HR(pk_enum_chunk, "IXPackageImpl", 13, "XPackageEnumerateChunkAvailability")
|
||||
@@ -770,16 +764,13 @@ BX_HR(pk_unknown_20, "IXPackageImpl", 20, "unknown")
|
||||
BX_HR(pk_unknown_21, "IXPackageImpl", 21, "unknown")
|
||||
BX_BOOL(pk_unreg_installed, "IXPackageImpl", 22, "XPackageUnregisterPackageInstalled")
|
||||
BX_HR(pk_unknown_27, "IXPackageImpl", 27, "unknown")
|
||||
BX_HR(pk_enum_packages, "IXPackageImpl", 28, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed, "IXPackageImpl", 29, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_write_stats, "IXPackageImpl", 30, "XPackageGetWriteStats")
|
||||
BX_HR(pk_unknown_31, "IXPackageImpl", 31, "unknown")
|
||||
BX_HR(pk_uninstall_uwp, "IXPackageImpl", 32, "XPackageUninstallUWPInstance")
|
||||
BX_HR(pk_enum_features, "IXPackageImpl", 33, "XPackageEnumerateFeatures")
|
||||
BX_HR(pk_uninstall, "IXPackageImpl", 34, "XPackageUninstallPackage")
|
||||
BX_HR(pk_enum_packages_2, "IXPackageImpl2", 35, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_enum_packages_3, "IXPackageImpl3", 39, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalled")
|
||||
#undef BX_HR
|
||||
#undef BX_VOID
|
||||
@@ -827,12 +818,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*>(&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[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[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);
|
||||
@@ -850,18 +841,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*>(&pk_enum_packages);
|
||||
v[28] = reinterpret_cast<const void*>(&enumerate_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*>(&pk_enum_packages_2);
|
||||
v[35] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
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*>(&pk_enum_packages_3);
|
||||
v[39] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
|
||||
v[41] = reinterpret_cast<const void*>(&get_package_kind);
|
||||
return v;
|
||||
|
||||
@@ -22,9 +22,18 @@
|
||||
* 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.
|
||||
* - 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.
|
||||
* - 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"
|
||||
|
||||
@@ -37,6 +46,7 @@
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
@@ -250,6 +260,148 @@ 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) {
|
||||
@@ -301,6 +453,7 @@ const void* const package_object = &kObject;
|
||||
void release_package_state() {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
mounts.clear();
|
||||
monitors.clear();
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -106,4 +106,23 @@ 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
|
||||
+598
-122
@@ -1,6 +1,7 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
@@ -10,35 +11,86 @@
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T small_page = 64 * 1024;
|
||||
constexpr SIZE_T large_page = 2 * 1024 * 1024;
|
||||
|
||||
struct PageBlock;
|
||||
|
||||
struct Page {
|
||||
PageBlock* block;
|
||||
HANDLE section;
|
||||
bool allocated;
|
||||
bool releasing;
|
||||
};
|
||||
|
||||
// One XMemAllocatePhysicalPages call: a single pagefile-backed section holding all its pages,
|
||||
// page i at offset i * 64 KB. One section per call, not per page, keeps a title that asks for
|
||||
// gigabytes at once (about 100,000 pages) within the host's open-file limit. A freed page stays
|
||||
// backed by the section until every page of its block is freed.
|
||||
struct PageBlock {
|
||||
ULONG_PTR first_tag;
|
||||
SIZE_T count;
|
||||
SIZE_T size;
|
||||
SIZE_T live;
|
||||
HANDLE section;
|
||||
Page* entries;
|
||||
PageBlock* next;
|
||||
};
|
||||
|
||||
ULONG64 page_offset(const Page* page) {
|
||||
return static_cast<ULONG64>(page - page->block->entries) * small_page;
|
||||
}
|
||||
|
||||
// A run of `pages` consecutive pages of one block (offsets page..page+pages-1), mapped as one view
|
||||
// at `address`. A title maps its page pool in long runs; one view per run keeps the number of
|
||||
// placeholder splits and MapViewOfFile3 calls (each a Wine server round trip) proportional to the
|
||||
// runs, not the pages. Unmapping part of a run unmaps the view and maps the remaining sub-runs again.
|
||||
struct View {
|
||||
Page* page;
|
||||
SIZE_T pages;
|
||||
BYTE* address;
|
||||
View* next;
|
||||
// Mapped into an XMEM_MAPPABLE reservation: unmapping restores the placeholder so the
|
||||
// range stays reserved and can be mapped again.
|
||||
bool preserve;
|
||||
};
|
||||
|
||||
uintptr_t view_begin(const View* view) { return reinterpret_cast<uintptr_t>(view->address); }
|
||||
uintptr_t view_end(const View* view) { return view_begin(view) + view->pages * small_page; }
|
||||
bool follows(const Page* before, const Page* after) {
|
||||
return after->block == before->block && after == before + 1;
|
||||
}
|
||||
|
||||
// An XMemVirtualAlloc(MEM_RESERVE, XMEM_MAPPABLE) range, held as a placeholder.
|
||||
struct Reservation {
|
||||
uintptr_t begin;
|
||||
uintptr_t end;
|
||||
SIZE_T page;
|
||||
DWORD protect;
|
||||
Reservation* next;
|
||||
};
|
||||
|
||||
SRWLOCK memory_lock = SRWLOCK_INIT;
|
||||
PageBlock* blocks = nullptr;
|
||||
View* views = nullptr;
|
||||
ULONG_PTR next_tag = 1;
|
||||
Reservation* reservations = nullptr;
|
||||
// Page tags are physical page numbers, which count 4 KiB frames: a 64 KiB page's number is a
|
||||
// multiple of 16. Titles rely on that: the target build keeps a page as the 21-bit `number >> 4`
|
||||
// and rebuilds it with `<< 4`, so consecutive numbers per 64 KiB page made sixteen pages collapse
|
||||
// into one. Each allocation also starts on a kTagAlignment boundary, so a title rounding its first
|
||||
// number down to a large page stays inside it; 0 stays unused, and every number fits the 25 bits
|
||||
// (21 + 4) the title keeps.
|
||||
constexpr ULONG_PTR kFramesPerPage = small_page / 4096; // 16
|
||||
constexpr ULONG_PTR kTagAlignment = 0x1000; // 256 pages = 16 MB, in frames
|
||||
constexpr ULONG_PTR kTagLimit = ULONG_PTR{1} << 25;
|
||||
ULONG_PTR next_tag = kTagAlignment;
|
||||
|
||||
// XMemAllocatePhysicalPages flags (authorized GDK documentation): 2 MB clusters, and the four
|
||||
// memory-bandwidth values, which only the Series X Advanced memory mode uses.
|
||||
// XMEM_2MB_CLUSTERS is MEM_2MB_PAGES; MEM_64K_PAGES is MEM_2MB_PAGES | MEM_PHYSICAL (authorized GDK
|
||||
// headers). Public samples pass MEM_64K_PAGES for 64 KB pages, so both bits together mean 64 KB
|
||||
// pages, and the 2 MB bit alone means 2 MB clusters.
|
||||
constexpr uint64_t xmem_2mb_clusters = 0x20000000;
|
||||
constexpr uint64_t mem_physical = 0x00400000;
|
||||
constexpr uint64_t mem_64k_pages = xmem_2mb_clusters | mem_physical;
|
||||
constexpr uint64_t xmem_bandwidth_bits = 0x380;
|
||||
|
||||
struct Lock {
|
||||
Lock() { AcquireSRWLockExclusive(&memory_lock); }
|
||||
@@ -49,11 +101,13 @@ using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
|
||||
MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
|
||||
ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using UnmapPreserving = BOOL (WINAPI*)(HANDLE, PVOID, ULONG);
|
||||
|
||||
struct PlaceholderApi {
|
||||
HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
|
||||
ReservePlaceholder reserve = resolve<ReservePlaceholder>("VirtualAlloc2");
|
||||
ReplacePlaceholder replace = resolve<ReplacePlaceholder>("MapViewOfFile3");
|
||||
UnmapPreserving unmap = resolve<UnmapPreserving>("UnmapViewOfFile2");
|
||||
|
||||
template<class Function>
|
||||
Function resolve(const char* name) const {
|
||||
@@ -61,35 +115,36 @@ struct PlaceholderApi {
|
||||
}
|
||||
};
|
||||
|
||||
// The public backlog defines the supported sizes. The flags accepted here
|
||||
// belong to BetterXen's synthetic fixtures, pending a public console flags ABI.
|
||||
SIZE_T page_size(uint64_t flags) {
|
||||
switch (flags) {
|
||||
case 0:
|
||||
case small_page: return small_page;
|
||||
case large_page: return large_page;
|
||||
default: return 0;
|
||||
const PlaceholderApi& placeholder_api() {
|
||||
static const PlaceholderApi api;
|
||||
return api;
|
||||
}
|
||||
|
||||
// The reservation holding all of [begin, end), or nullptr.
|
||||
Reservation* find_reservation(uintptr_t begin, uintptr_t end) {
|
||||
for (Reservation* r = reservations; r; r = r->next) {
|
||||
if (begin >= r->begin && end <= r->end && begin < end) return r;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Page* find_page(ULONG_PTR tag) {
|
||||
for (PageBlock* block = blocks; block; block = block->next) {
|
||||
if (tag >= block->first_tag && tag - block->first_tag < block->count) {
|
||||
Page* page = &block->entries[tag - block->first_tag];
|
||||
return page->section ? page : nullptr;
|
||||
if (tag >= block->first_tag && (tag - block->first_tag) % kFramesPerPage == 0 &&
|
||||
(tag - block->first_tag) / kFramesPerPage < block->count) {
|
||||
Page* page = &block->entries[(tag - block->first_tag) / kFramesPerPage];
|
||||
return page->allocated ? page : nullptr;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ULONG_PTR page_tag(const Page* page) {
|
||||
return page->block->first_tag + (page - page->block->entries);
|
||||
return page->block->first_tag + static_cast<ULONG_PTR>(page - page->block->entries) * kFramesPerPage;
|
||||
}
|
||||
|
||||
void delete_block(PageBlock* block) {
|
||||
for (SIZE_T i = 0; i < block->count; ++i) {
|
||||
if (block->entries[i].section) CloseHandle(block->entries[i].section);
|
||||
}
|
||||
if (block->section) CloseHandle(block->section);
|
||||
delete[] block->entries;
|
||||
delete block;
|
||||
}
|
||||
@@ -110,7 +165,11 @@ bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
|
||||
|
||||
bool remove_view(View** link) {
|
||||
View* view = *link;
|
||||
if (!UnmapViewOfFile(view->address)) return false;
|
||||
const bool unmapped = view->preserve
|
||||
? placeholder_api().unmap && placeholder_api().unmap(GetCurrentProcess(), view->address,
|
||||
MEM_PRESERVE_PLACEHOLDER)
|
||||
: UnmapViewOfFile(view->address) != 0;
|
||||
if (!unmapped) return false;
|
||||
*link = view->next;
|
||||
delete view;
|
||||
return true;
|
||||
@@ -129,9 +188,8 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
|
||||
SIZE_T matched = 0;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
++matched;
|
||||
if (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
|
||||
matched += view->pages;
|
||||
}
|
||||
}
|
||||
if (matched != count) {
|
||||
@@ -141,8 +199,7 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
View* view = *link;
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
if (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
|
||||
if (!remove_view(link)) return nullptr;
|
||||
} else {
|
||||
link = &view->next;
|
||||
@@ -151,50 +208,236 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
return base;
|
||||
}
|
||||
|
||||
// Duplicate tags in `tags` are intentionally permitted so a single virtual span
|
||||
// can alias one physical page at multiple offsets (e.g. ring buffers / tiles).
|
||||
PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* tags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!valid_span(address, count, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
if (!tags) return unmap_span(static_cast<BYTE*>(address), count, size);
|
||||
|
||||
static const PlaceholderApi api;
|
||||
if (!api.reserve || !api.replace) {
|
||||
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
View* pending = nullptr;
|
||||
for (SIZE_T i = count; i > 0; --i) {
|
||||
Page* page = find_page(tags[i - 1]);
|
||||
if (!page || page->block->size != size) {
|
||||
destroy_views(pending);
|
||||
// Builds one unlinked View per tag, in order, after checking that every tag names a live page.
|
||||
bool build_views(const ULONG_PTR* tags, SIZE_T count, bool preserve, View** out) {
|
||||
View* first = nullptr;
|
||||
View** tail = &first;
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
Page* page = find_page(tags[i]);
|
||||
if (!page) {
|
||||
destroy_views(first);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return false;
|
||||
}
|
||||
auto* view = new (std::nothrow) View{page, 1, nullptr, nullptr, preserve};
|
||||
if (!view) {
|
||||
destroy_views(first);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return false;
|
||||
}
|
||||
*tail = view;
|
||||
tail = &view->next;
|
||||
}
|
||||
*out = first;
|
||||
return true;
|
||||
}
|
||||
|
||||
void publish(View* pending) {
|
||||
while (pending) {
|
||||
View* next = pending->next;
|
||||
pending->next = views;
|
||||
views = pending;
|
||||
pending = next;
|
||||
}
|
||||
}
|
||||
|
||||
// Maps the run [first, first + pages) at `address` inside a reservation. The range may cover one
|
||||
// placeholder or several (left by earlier mappings); each placeholder piece inside it is split out
|
||||
// where it extends past the range and replaced with one view, so a range inside one placeholder
|
||||
// becomes one view. Returns the unlinked chain of views (through `next`) and its tail in *tail,
|
||||
// or nullptr with the error set and nothing mapped.
|
||||
View* map_run(Page* first, SIZE_T pages, BYTE* address, DWORD protect, View** tail = nullptr) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
const uintptr_t begin = reinterpret_cast<uintptr_t>(address);
|
||||
const uintptr_t end = begin + pages * small_page;
|
||||
View* head = nullptr;
|
||||
View** link = &head;
|
||||
View* last = nullptr;
|
||||
for (uintptr_t at = begin; at < end;) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t piece_end = end;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(at), ®ion, sizeof(region)) && region.State == MEM_RESERVE) {
|
||||
const uintptr_t region_end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
if (region_end < piece_end) piece_end = region_end;
|
||||
}
|
||||
const SIZE_T piece_pages = (piece_end - at) / small_page;
|
||||
Page* piece_first = first + (at - begin) / small_page;
|
||||
auto* view = new (std::nothrow) View{piece_first, piece_pages, reinterpret_cast<BYTE*>(at), nullptr, true};
|
||||
if (!view) SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
if (view) VirtualFree(reinterpret_cast<void*>(at), piece_end - at, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
|
||||
if (!view || !api.replace(first->block->section, GetCurrentProcess(), reinterpret_cast<void*>(at),
|
||||
page_offset(piece_first), piece_end - at, MEM_REPLACE_PLACEHOLDER, protect,
|
||||
nullptr, 0)) {
|
||||
const DWORD error = GetLastError();
|
||||
delete view;
|
||||
while (head) {
|
||||
View* next = head->next;
|
||||
api.unmap(GetCurrentProcess(), head->address, MEM_PRESERVE_PLACEHOLDER);
|
||||
delete head;
|
||||
head = next;
|
||||
}
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
auto* view = new (std::nothrow) View{page, nullptr, pending};
|
||||
*link = view;
|
||||
link = &view->next;
|
||||
last = view;
|
||||
at = piece_end;
|
||||
}
|
||||
if (tail) *tail = last;
|
||||
return head;
|
||||
}
|
||||
|
||||
// The protection of the reservation holding `view` (the view was mapped with it).
|
||||
DWORD view_protect(const View* view) {
|
||||
const Reservation* r = find_reservation(view_begin(view), view_end(view));
|
||||
return r ? r->protect : PAGE_READWRITE;
|
||||
}
|
||||
|
||||
// Unmaps the pages of *link for which removed(page, page_address) is true. A view losing every
|
||||
// page is removed; one losing some (only in a reservation) is unmapped and its remaining sub-runs
|
||||
// are mapped again in its place. On return *link is the first view after the ones handled.
|
||||
template <class Removed>
|
||||
bool drop_pages(View**& link, Removed removed) {
|
||||
View* view = *link;
|
||||
SIZE_T gone = 0;
|
||||
for (SIZE_T i = 0; i < view->pages; ++i) gone += removed(view->page + i, view_begin(view) + i * small_page);
|
||||
if (gone == 0) {
|
||||
link = &view->next;
|
||||
return true;
|
||||
}
|
||||
if (gone == view->pages) return remove_view(link);
|
||||
if (!view->preserve) { // a span mapped without a reservation is unmapped as a whole
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return false;
|
||||
}
|
||||
const DWORD protect = view_protect(view);
|
||||
Page* first = view->page;
|
||||
const SIZE_T pages = view->pages;
|
||||
BYTE* address = view->address;
|
||||
if (!remove_view(link)) return false;
|
||||
for (SIZE_T i = 0; i < pages;) {
|
||||
if (removed(first + i, reinterpret_cast<uintptr_t>(address) + i * small_page)) {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
SIZE_T j = i + 1;
|
||||
while (j < pages && !removed(first + j, reinterpret_cast<uintptr_t>(address) + j * small_page)) ++j;
|
||||
View* kept_tail = nullptr;
|
||||
View* kept = map_run(first + i, j - i, address + i * small_page, protect, &kept_tail);
|
||||
if (!kept) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "remapping %llu kept pages after a partial unmap failed error=%lu",
|
||||
static_cast<unsigned long long>(j - i), static_cast<unsigned long>(GetLastError()));
|
||||
bx_log_emit(BX_LOG_ERROR, "xmem", "physical_remap_failed", detail);
|
||||
return false;
|
||||
}
|
||||
kept_tail->next = *link;
|
||||
*link = kept;
|
||||
link = &kept_tail->next;
|
||||
i = j;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Unmaps every mapped page in [begin, end). Views in a reservation keep its placeholder.
|
||||
bool unmap_range(uintptr_t begin, uintptr_t end) {
|
||||
for (View** link = &views; *link;) {
|
||||
View* view = *link;
|
||||
if (view_end(view) <= begin || view_begin(view) >= end) {
|
||||
link = &view->next;
|
||||
continue;
|
||||
}
|
||||
if (!drop_pages(link, [&](const Page*, uintptr_t at) { return at >= begin && at < end; })) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Maps `count` pages (any order, duplicates allowed) at consecutive slots from `address`, one view
|
||||
// per run of consecutive pages of one block. On failure nothing stays mapped and the error is set.
|
||||
bool map_pages(Page* const* pages, SIZE_T count, BYTE* address, DWORD protect) {
|
||||
View* done = nullptr;
|
||||
for (SIZE_T i = 0; i < count;) {
|
||||
SIZE_T j = i + 1;
|
||||
while (j < count && follows(pages[j - 1], pages[j])) ++j;
|
||||
View* view_tail = nullptr;
|
||||
View* view = map_run(pages[i], j - i, address + i * small_page, protect, &view_tail);
|
||||
if (!view) {
|
||||
destroy_views(pending);
|
||||
const DWORD error = GetLastError();
|
||||
while (done) {
|
||||
View* next = done->next;
|
||||
placeholder_api().unmap(GetCurrentProcess(), done->address, MEM_PRESERVE_PLACEHOLDER);
|
||||
delete done;
|
||||
done = next;
|
||||
}
|
||||
SetLastError(error);
|
||||
return false;
|
||||
}
|
||||
view_tail->next = done;
|
||||
done = view;
|
||||
i = j;
|
||||
}
|
||||
publish(done);
|
||||
return true;
|
||||
}
|
||||
|
||||
// XMemMapPhysicalPages into an XMEM_MAPPABLE reservation. Pages already mapped in the range are
|
||||
// unmapped first; a NULL `tags` only unmaps. Duplicate tags alias one page at several offsets.
|
||||
PVOID map_reserved(Reservation* reservation, BYTE* base, SIZE_T count, const ULONG_PTR* tags) {
|
||||
if (reservation->page != small_page) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPages(MEM_2MB_PAGES)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return nullptr;
|
||||
}
|
||||
const auto begin = reinterpret_cast<uintptr_t>(base);
|
||||
Page** pages = nullptr;
|
||||
if (tags) {
|
||||
pages = new (std::nothrow) Page*[count];
|
||||
if (!pages) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
pending = view;
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
pages[i] = find_page(tags[i]);
|
||||
if (!pages[i]) {
|
||||
delete[] pages;
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!unmap_range(begin, begin + count * small_page)) {
|
||||
const DWORD error = GetLastError();
|
||||
delete[] pages;
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
if (pages) {
|
||||
const bool mapped = map_pages(pages, count, base, reservation->protect);
|
||||
const DWORD error = GetLastError();
|
||||
delete[] pages;
|
||||
if (!mapped) {
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
// BetterXen extension, used by synthetic fixtures: with no address, reserve a fresh
|
||||
// placeholder of `count` pages and map `tags` into it. Unmapping such a span frees it.
|
||||
PVOID map_unreserved(SIZE_T count, const ULONG_PTR* tags) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
View* pending = nullptr;
|
||||
if (!build_views(tags, count, false, &pending)) return nullptr;
|
||||
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = size;
|
||||
requirements.Alignment = small_page;
|
||||
MEM_EXTENDED_PARAMETER alignment{};
|
||||
alignment.Type = MemExtendedParameterAddressRequirements;
|
||||
alignment.Pointer = &requirements;
|
||||
auto* base = static_cast<BYTE*>(api.reserve(nullptr, address, count * size,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
|
||||
address ? nullptr : &alignment, address ? 0 : 1));
|
||||
auto* base = static_cast<BYTE*>(api.reserve(nullptr, nullptr, count * small_page,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, &alignment, 1));
|
||||
if (!base) {
|
||||
const DWORD error = GetLastError();
|
||||
destroy_views(pending);
|
||||
@@ -205,13 +448,13 @@ PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* ta
|
||||
BYTE* cursor = base;
|
||||
SIZE_T remaining = count;
|
||||
View* view = pending;
|
||||
for (; view; view = view->next, cursor += size, --remaining) {
|
||||
for (; view; view = view->next, cursor += small_page, --remaining) {
|
||||
const bool split = remaining > 1;
|
||||
if (split && !VirtualFree(cursor, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
|
||||
if (!api.replace(view->page->section, nullptr, cursor, 0, size,
|
||||
if (split && !VirtualFree(cursor, small_page, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
|
||||
if (!api.replace(view->page->block->section, GetCurrentProcess(), cursor, page_offset(view->page), small_page,
|
||||
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
|
||||
if (split) VirtualFree(cursor + small_page, 0, MEM_RELEASE);
|
||||
SetLastError(error);
|
||||
break;
|
||||
}
|
||||
@@ -228,31 +471,151 @@ PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* ta
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
while (pending) {
|
||||
View* next = pending->next;
|
||||
pending->next = views;
|
||||
views = pending;
|
||||
pending = next;
|
||||
}
|
||||
publish(pending);
|
||||
return base;
|
||||
}
|
||||
|
||||
bool have_placeholder_api() {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
if (api.reserve && api.replace && api.unmap) return true;
|
||||
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Clean-room synthetic signatures modeled after public Win32 AWE
|
||||
// AllocateUserPhysicalPages / FreeUserPhysicalPages (memoryapi.h, [in, out]
|
||||
// page count pointer), pending a public console flags/signature ABI.
|
||||
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
namespace bx_xmem {
|
||||
|
||||
PVOID reserve_placeholder(PVOID address, SIZE_T size, uintptr_t highest) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
const auto requested = reinterpret_cast<uintptr_t>(address);
|
||||
const uintptr_t begin = requested - requested % small_page;
|
||||
if (!size || size > std::numeric_limits<uintptr_t>::max() - requested - small_page) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
return nullptr;
|
||||
}
|
||||
const uintptr_t end = (requested + size + small_page - 1) / small_page * small_page;
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = small_page;
|
||||
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
|
||||
MEM_EXTENDED_PARAMETER parameter{};
|
||||
parameter.Type = MemExtendedParameterAddressRequirements;
|
||||
parameter.Pointer = &requirements;
|
||||
return api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr, end - begin,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, begin ? nullptr : ¶meter,
|
||||
begin ? 0 : 1);
|
||||
}
|
||||
|
||||
PVOID reserve_mappable(PVOID address, SIZE_T size, SIZE_T page, DWORD protect, bool adopt, uintptr_t highest) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
const auto requested = reinterpret_cast<uintptr_t>(address);
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
if (adopt && (!address || requested % page != 0 || size % page != 0)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
if (!size || size > std::numeric_limits<uintptr_t>::max() - requested - page) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
// A reservation's base rounds down to its page size and its end rounds up.
|
||||
const uintptr_t begin = requested - requested % page;
|
||||
const uintptr_t end = (requested + size + page - 1) / page * page;
|
||||
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = page;
|
||||
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
|
||||
MEM_EXTENDED_PARAMETER alignment{};
|
||||
alignment.Type = MemExtendedParameterAddressRequirements;
|
||||
alignment.Pointer = &requirements;
|
||||
auto* reservation = new (std::nothrow) Reservation{};
|
||||
if (!reservation) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
PVOID base = nullptr;
|
||||
if (adopt) {
|
||||
// MEM_REPLACE_PLACEHOLDER: the title split this range out of its own placeholder; it
|
||||
// stays as it is and becomes mappable.
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(address, ®ion, sizeof(region)) || region.State != MEM_RESERVE
|
||||
|| reinterpret_cast<uintptr_t>(region.BaseAddress) != requested || region.RegionSize < size) {
|
||||
delete reservation;
|
||||
SetLastError(ERROR_INVALID_ADDRESS);
|
||||
return nullptr;
|
||||
}
|
||||
base = address;
|
||||
} else {
|
||||
base = api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr,
|
||||
end - begin, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
|
||||
begin ? nullptr : &alignment, begin ? 0 : 1);
|
||||
}
|
||||
if (!base) {
|
||||
delete reservation;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const auto b = reinterpret_cast<uintptr_t>(base);
|
||||
// A range the title released with VirtualFree may come back: drop stale records over it.
|
||||
for (Reservation** link = &reservations; *link;) {
|
||||
if ((*link)->begin < b + (end - begin) && b < (*link)->end) {
|
||||
Reservation* stale = *link;
|
||||
*link = stale->next;
|
||||
delete stale;
|
||||
} else {
|
||||
link = &(*link)->next;
|
||||
}
|
||||
}
|
||||
*reservation = {b, b + (end - begin), page, protect, reservations};
|
||||
reservations = reservation;
|
||||
return base;
|
||||
}
|
||||
|
||||
} // namespace bx_xmem
|
||||
|
||||
// Diagnostics (off unless BX_XMEM_TRACE=1): one line per map call (address, count, first and last
|
||||
// tag; Scatter: first and last slot too), up to 4000 calls.
|
||||
bool xmem_trace_on() {
|
||||
static const bool on = [] {
|
||||
char v[4];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_XMEM_TRACE", v, sizeof(v));
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
void trace_map(const char* kind, const void* first_address, const void* last_address, ULONG_PTR count,
|
||||
const ULONG_PTR* tags) {
|
||||
static LONG traced = 0;
|
||||
if (!xmem_trace_on() || InterlockedIncrement(&traced) > 4000) return;
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s va=%p..%p count=%llu tags=%llx..%llx", kind, first_address, last_address,
|
||||
static_cast<unsigned long long>(count), tags ? static_cast<unsigned long long>(tags[0]) : 0ull,
|
||||
tags ? static_cast<unsigned long long>(tags[count - 1]) : 0ull);
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "map_trace", detail);
|
||||
}
|
||||
|
||||
// Authorized GDK documentation: XMemAllocatePhysicalPages(XMemFlags, NumberOfPages,
|
||||
// PageArray), in 64 KB pages. XMEM_2MB_CLUSTERS is not implemented.
|
||||
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR num_pages,
|
||||
PULONG_PTR page_array) {
|
||||
if ((flags & mem_64k_pages) == mem_64k_pages) flags &= ~mem_64k_pages; // 64 KB pages: the default
|
||||
if ((flags & ~(xmem_2mb_clusters | xmem_bandwidth_bits)) != 0 || !num_pages || !page_array
|
||||
|| !valid_span(nullptr, *num_pages, small_page)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
if (flags & xmem_2mb_clusters) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemAllocatePhysicalPages(XMEM_2MB_CLUSTERS)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return FALSE;
|
||||
}
|
||||
const SIZE_T size = small_page;
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
|
||||
if (count > (kTagLimit - next_tag) / kFramesPerPage
|
||||
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|
||||
|| count > std::numeric_limits<uint64_t>::max() / size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
@@ -260,6 +623,10 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR p
|
||||
}
|
||||
const uint64_t total_bytes = static_cast<uint64_t>(count) * size;
|
||||
if (!bx_xmem::try_reserve_physical(total_bytes)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "XMemAllocatePhysicalPages flags=0x%llx pages=%llu exceeds the physical budget",
|
||||
static_cast<unsigned long long>(flags), static_cast<unsigned long long>(count));
|
||||
bx_log_emit(BX_LOG_WARN, "xmem", "physical_budget_exceeded", detail);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
@@ -270,49 +637,64 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR p
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, entries, blocks};
|
||||
const HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
|
||||
static_cast<DWORD>(total_bytes >> 32),
|
||||
static_cast<DWORD>(total_bytes & 0xFFFFFFFFu), nullptr);
|
||||
if (!section) {
|
||||
const DWORD error = GetLastError();
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "CreateFileMappingW for %llu pages failed error=%lu",
|
||||
static_cast<unsigned long long>(count), static_cast<unsigned long>(error));
|
||||
bx_log_emit(BX_LOG_WARN, "xmem", "physical_pages_failed", detail);
|
||||
delete[] entries;
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, section, entries, blocks};
|
||||
if (!block) {
|
||||
CloseHandle(section);
|
||||
delete[] entries;
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
|
||||
0, static_cast<DWORD>(size), nullptr);
|
||||
if (!section) {
|
||||
const DWORD error = GetLastError();
|
||||
delete_block(block);
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
entries[i] = {block, section, false};
|
||||
}
|
||||
for (SIZE_T i = 0; i < count; ++i) entries[i] = {block, true, false};
|
||||
|
||||
blocks = block;
|
||||
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
|
||||
next_tag += count;
|
||||
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i * kFramesPerPage;
|
||||
if (xmem_trace_on()) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "allocate flags=0x%llx count=%llu tags=%llx..%llx",
|
||||
static_cast<unsigned long long>(flags), static_cast<unsigned long long>(count),
|
||||
static_cast<unsigned long long>(next_tag),
|
||||
static_cast<unsigned long long>(next_tag + (count - 1) * kFramesPerPage));
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "alloc_trace", detail);
|
||||
}
|
||||
next_tag += count * kFramesPerPage;
|
||||
next_tag = (next_tag + kTagAlignment - 1) & ~(kTagAlignment - 1);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Rejects unknown, wrong-size, or duplicate tags in `page_array` with
|
||||
// ERROR_INVALID_PARAMETER without mutating `page_array` or live views.
|
||||
extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
// XMemFreePhysicalPages(NumberOfPages, PageArray). Unknown or duplicate tags in `page_array`
|
||||
// fail with ERROR_INVALID_PARAMETER without changing `page_array` or live views.
|
||||
extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_array) {
|
||||
if (xmem_trace_on() && page_array && count) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "free count=%llu tags=%llx..%llx", static_cast<unsigned long long>(count),
|
||||
static_cast<unsigned long long>(page_array[0]), static_cast<unsigned long long>(page_array[count - 1]));
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "free_trace", detail);
|
||||
}
|
||||
if (!page_array || !valid_span(nullptr, count, small_page)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
SIZE_T validated = 0;
|
||||
for (; validated < count; ++validated) {
|
||||
Page* page = find_page(page_array[validated]);
|
||||
if (!page || page->block->size != size || page->releasing) break;
|
||||
if (!page || page->releasing) break;
|
||||
page->releasing = true;
|
||||
}
|
||||
if (validated != count) {
|
||||
@@ -322,22 +704,17 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
if ((*link)->page->releasing) {
|
||||
if (!remove_view(link)) {
|
||||
const DWORD error = GetLastError();
|
||||
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
} else {
|
||||
link = &(*link)->next;
|
||||
if (!drop_pages(link, [](const Page* page, uintptr_t) { return page->releasing; })) {
|
||||
const DWORD error = GetLastError();
|
||||
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
Page* page = find_page(page_array[i]);
|
||||
CloseHandle(page->section);
|
||||
page->section = nullptr;
|
||||
page->allocated = false;
|
||||
--page->block->live;
|
||||
page_array[i] = 0;
|
||||
}
|
||||
@@ -350,18 +727,115 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_
|
||||
delete_block(block);
|
||||
}
|
||||
}
|
||||
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
|
||||
bx_xmem::release_physical(static_cast<uint64_t>(count) * small_page);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
// XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray). The address must lie in an
|
||||
// XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE) reservation. A NULL address is a
|
||||
// BetterXen extension (see map_unreserved); a span mapped that way is unmapped as a whole.
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PULONG_PTR page_array) {
|
||||
if (count) trace_map("map", address, static_cast<BYTE*>(address) + (count - 1) * small_page, count, page_array);
|
||||
if (!valid_span(address, count, small_page)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
Lock lock;
|
||||
auto* base = static_cast<BYTE*>(address);
|
||||
const auto begin = reinterpret_cast<uintptr_t>(address);
|
||||
if (address) {
|
||||
if (Reservation* reservation = find_reservation(begin, begin + count * small_page)) {
|
||||
return map_reserved(reservation, base, count, page_array);
|
||||
}
|
||||
if (!page_array) return unmap_span(base, count, small_page);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
if (!page_array) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
return map_unreserved(count, page_array);
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
// XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray): parallel arrays of
|
||||
// 64 KB slots in XMEM_MAPPABLE reservations and page tags. A NULL `page_array`, or a 0 tag,
|
||||
// unmaps the slot. All entries are checked before any is changed.
|
||||
static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_array);
|
||||
|
||||
extern "C" BOOL WINAPI XMemMapPhysicalPagesScatter(PVOID* addresses, ULONG_PTR count,
|
||||
PULONG_PTR page_array) {
|
||||
const BOOL ok = scatter_impl(addresses, count, page_array);
|
||||
if (!ok) {
|
||||
const DWORD error = GetLastError();
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) <= 32) {
|
||||
// The first entry that is not a mappable 64 KB slot or names an unknown page.
|
||||
ULONG_PTR bad = count;
|
||||
for (ULONG_PTR k = 0; addresses && k < count; ++k) {
|
||||
const auto slot = reinterpret_cast<uintptr_t>(addresses[k]);
|
||||
Lock lock;
|
||||
const bool slot_ok = slot % small_page == 0 && find_reservation(slot, slot + small_page);
|
||||
const bool page_ok = !page_array || !page_array[k] || find_page(page_array[k]);
|
||||
if (!slot_ok || !page_ok) { bad = k; break; }
|
||||
}
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "scatter of %llu slots failed error=%lu; first bad entry %llu: slot %p tag 0x%llx",
|
||||
static_cast<unsigned long long>(count), static_cast<unsigned long>(error),
|
||||
static_cast<unsigned long long>(bad), bad < count ? addresses[bad] : nullptr,
|
||||
bad < count && page_array ? static_cast<unsigned long long>(page_array[bad]) : 0ull);
|
||||
bx_log_emit(BX_LOG_WARN, "xmem", "scatter_failed", detail);
|
||||
}
|
||||
SetLastError(error);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_array) {
|
||||
if (addresses && count) trace_map("scatter", addresses[0], addresses[count - 1], count, page_array);
|
||||
if (!addresses || !count) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
if (!have_placeholder_api()) return FALSE;
|
||||
Lock lock;
|
||||
for (ULONG_PTR i = 0; i < count; ++i) {
|
||||
const auto slot = reinterpret_cast<uintptr_t>(addresses[i]);
|
||||
Reservation* reservation = slot % small_page == 0 ? find_reservation(slot, slot + small_page) : nullptr;
|
||||
if (!reservation || (page_array && page_array[i] && !find_page(page_array[i]))) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
if (reservation->page != small_page) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPagesScatter(MEM_2MB_PAGES)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
// Entries whose slots and pages both advance by one form a run, unmapped and mapped at once.
|
||||
for (ULONG_PTR i = 0; i < count;) {
|
||||
auto* slot = static_cast<BYTE*>(addresses[i]);
|
||||
const auto begin = reinterpret_cast<uintptr_t>(slot);
|
||||
const ULONG_PTR tag = page_array ? page_array[i] : 0;
|
||||
const Reservation* reservation = find_reservation(begin, begin + small_page);
|
||||
ULONG_PTR j = i + 1;
|
||||
while (j < count && reinterpret_cast<uintptr_t>(addresses[j]) == begin + (j - i) * small_page &&
|
||||
find_reservation(begin, begin + (j - i + 1) * small_page) == reservation &&
|
||||
(tag ? page_array[j] == tag + (j - i) * kFramesPerPage && find_page(page_array[j]) &&
|
||||
follows(find_page(page_array[j - 1]), find_page(page_array[j]))
|
||||
: !(page_array && page_array[j]))) {
|
||||
++j;
|
||||
}
|
||||
if (!unmap_range(begin, begin + (j - i) * small_page)) return FALSE;
|
||||
if (tag) {
|
||||
View* view = map_run(find_page(tag), j - i, slot, reservation->protect);
|
||||
if (!view) return FALSE;
|
||||
publish(view);
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
|
||||
@@ -369,15 +843,17 @@ extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info
|
||||
|
||||
Lock lock;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto base = reinterpret_cast<uintptr_t>(view->address);
|
||||
const SIZE_T size = view->page->block->size;
|
||||
if (va >= base && va - base < size) {
|
||||
if (va >= view_begin(view) && va < view_end(view)) {
|
||||
// Reported per 64 KB page, as when every page had its own view.
|
||||
const SIZE_T index = (va - view_begin(view)) / small_page;
|
||||
const uintptr_t base = view_begin(view) + index * small_page;
|
||||
const SIZE_T size = view->page->block->size;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(view->address, ®ion, sizeof(region))
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(base), ®ion, sizeof(region))
|
||||
|| region.AllocationBase != view->address || region.Type != MEM_MAPPED) {
|
||||
return 0;
|
||||
}
|
||||
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page)};
|
||||
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page + index)};
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
+97
-16
@@ -2,6 +2,7 @@
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
@@ -114,14 +115,29 @@ bool refresh_virtual_commits() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void report_unsupported_host_hooks() {
|
||||
static const bool reported = [] {
|
||||
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
|
||||
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
|
||||
// XMEM_SET_ALLOCATION_HOOKS (xmem.h, authorized GDK documentation): the title exports
|
||||
// `__XMemAllocationHooks__ = { AllocRoutine, FreeRoutine }`, and XMemAlloc / XMemFree call those
|
||||
// routines instead of the default allocator. A hook usually handles the allocations it cares
|
||||
// about and passes the rest to XMemAllocDefault / XMemFreeDefault.
|
||||
struct AllocationHooks {
|
||||
PVOID (WINAPI* alloc)(SIZE_T size, ULONGLONG attributes);
|
||||
VOID (WINAPI* free)(PVOID address, ULONGLONG attributes);
|
||||
};
|
||||
|
||||
const AllocationHooks& title_hooks() {
|
||||
static const AllocationHooks hooks = [] {
|
||||
AllocationHooks found{};
|
||||
const auto* exported = reinterpret_cast<const AllocationHooks*>(
|
||||
reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")));
|
||||
if (exported) found = *exported;
|
||||
if (found.alloc || found.free) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "alloc=%d free=%d", found.alloc ? 1 : 0, found.free ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "allocation_hooks", detail);
|
||||
}
|
||||
return true;
|
||||
return found;
|
||||
}();
|
||||
(void)reported;
|
||||
return hooks;
|
||||
}
|
||||
|
||||
SIZE_T page_size() {
|
||||
@@ -172,29 +188,94 @@ VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
|
||||
report_unsupported_host_hooks();
|
||||
if (const auto alloc = title_hooks().alloc) return alloc(size, attributes);
|
||||
return XMemAllocDefault(size, attributes);
|
||||
}
|
||||
|
||||
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
|
||||
report_unsupported_host_hooks();
|
||||
if (const auto free_routine = title_hooks().free) {
|
||||
free_routine(address, attributes);
|
||||
return;
|
||||
}
|
||||
XMemFreeDefault(address, attributes);
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect) {
|
||||
/*
|
||||
* XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection), as the
|
||||
* authorized GDK documentation gives it. AllocationType may carry MEM_64K_PAGES (0x20400000) or
|
||||
* MEM_2MB_PAGES (0x20000000). An XMEM_MAPPABLE (0x20) reservation is a placeholder for
|
||||
* XMemMapPhysicalPages. The other XMemFlags (CPU, graphics, address-width limits) select
|
||||
* console memory types the host does not distinguish, so plain reservations and commits
|
||||
* ignore them.
|
||||
*/
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
|
||||
DWORD protect) {
|
||||
constexpr DWORD mem_64k_pages = 0x20400000;
|
||||
constexpr DWORD mem_2mb_pages = 0x20000000;
|
||||
constexpr DWORD mem_reserve_placeholder = 0x00040000;
|
||||
constexpr DWORD mem_replace_placeholder = 0x00004000;
|
||||
constexpr uint64_t xmem_mappable = 0x20;
|
||||
constexpr uint64_t xmem_graphics_32bit_address = 0x7;
|
||||
// PAGE_GRAPHICS_* bits (0x800 and up) set the GPU view, which the host does not have; the
|
||||
// CPU protection is the low byte.
|
||||
const DWORD cpu_protect = protect & 0xFF;
|
||||
const uintptr_t highest = (xmem_flags & xmem_graphics_32bit_address) == xmem_graphics_32bit_address
|
||||
? 0xFFFFFFFFull : 0;
|
||||
if (xmem_flags & xmem_mappable) {
|
||||
const SIZE_T mappable_page = (alloc_type & mem_64k_pages) == mem_64k_pages ? 64 * 1024
|
||||
: (alloc_type & mem_2mb_pages) ? 2 * 1024 * 1024 : 0;
|
||||
if (!mappable_page || !(alloc_type & MEM_RESERVE) || (alloc_type & MEM_COMMIT)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
return bx_xmem::reserve_mappable(address, size, mappable_page, cpu_protect,
|
||||
(alloc_type & mem_replace_placeholder) != 0, highest);
|
||||
}
|
||||
// A GPU-only reservation of 64 KiB or 2 MiB pages (no CPU access, a PAGE_GRAPHICS_* bit set) is
|
||||
// a GPU address window the title fills with CopyPageMappingsX / CopyPageMappingsBatchX. It is
|
||||
// reserved as a mappable placeholder so the page-pool pages can be mapped into it; the views
|
||||
// are CPU readable and writable, since BetterXen works the GPU side through CPU addresses.
|
||||
const bool large_pages = (alloc_type & mem_64k_pages) == mem_64k_pages || (alloc_type & mem_2mb_pages);
|
||||
if (large_pages && (alloc_type & MEM_RESERVE) && !(alloc_type & (MEM_COMMIT | mem_replace_placeholder)) &&
|
||||
cpu_protect == PAGE_NOACCESS && (protect & ~0xFFu) != 0) {
|
||||
const SIZE_T window_page = (alloc_type & mem_64k_pages) == mem_64k_pages ? 64 * 1024 : 2 * 1024 * 1024;
|
||||
PVOID window = bx_xmem::reserve_mappable(address, size, window_page, PAGE_READWRITE, false, highest);
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "GPU window %p size=0x%llx page=0x%llx flags=0x%llx protect=0x%lx -> %p",
|
||||
address, static_cast<unsigned long long>(size), static_cast<unsigned long long>(window_page),
|
||||
static_cast<unsigned long long>(xmem_flags), static_cast<unsigned long>(protect), window);
|
||||
bx_log_emit(window ? BX_LOG_INFO : BX_LOG_WARN, "xmem", "gpu_window", detail);
|
||||
return window;
|
||||
}
|
||||
if (alloc_type & mem_reserve_placeholder) {
|
||||
if ((alloc_type & (MEM_COMMIT | mem_replace_placeholder)) || !(alloc_type & MEM_RESERVE)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
return bx_xmem::reserve_placeholder(address, size, highest);
|
||||
}
|
||||
if (alloc_type & mem_replace_placeholder) {
|
||||
// Committing over a title-managed placeholder is not implemented (no caller seen yet).
|
||||
BX_STUB_LOG("xmem.dll", "XMemVirtualAlloc(MEM_REPLACE_PLACEHOLDER)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return nullptr;
|
||||
}
|
||||
/* Strip console-only high bits before forwarding to standard Win32 VirtualAlloc. */
|
||||
DWORD win_alloc = alloc_type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN);
|
||||
if (win_alloc == 0) win_alloc = MEM_COMMIT | MEM_RESERVE;
|
||||
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
|
||||
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
|
||||
DWORD low_prot = protect & 0xFFu;
|
||||
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
|
||||
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
|
||||
: PAGE_READWRITE;
|
||||
const DWORD win_prot = protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE);
|
||||
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
|
||||
* early here cannot commit pages outside the working-set budget. */
|
||||
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
|
||||
return VirtualAlloc(address, size, win_alloc, win_prot);
|
||||
PVOID result = VirtualAlloc(address, size, win_alloc, win_prot);
|
||||
if (size >= (SIZE_T{256} << 20)) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "reserve %p size=0x%llx type=0x%lx flags=0x%llx protect=0x%lx -> %p",
|
||||
address, static_cast<unsigned long long>(size), static_cast<unsigned long>(alloc_type),
|
||||
static_cast<unsigned long long>(xmem_flags), static_cast<unsigned long>(protect), result);
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "large_reservation", detail);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bx_xmem {
|
||||
@@ -10,6 +12,18 @@ namespace bx_xmem {
|
||||
bool try_reserve_physical(uint64_t bytes);
|
||||
void release_physical(uint64_t bytes);
|
||||
|
||||
// Reserves an XMEM_MAPPABLE range as a placeholder that XMemMapPhysicalPages maps into, and
|
||||
// records its page size and the protection mapped views get. Returns the base, or NULL with
|
||||
// the Win32 error set.
|
||||
// With `adopt`, `address` is already a placeholder the title split out of its own
|
||||
// MEM_RESERVE_PLACEHOLDER reservation (MEM_REPLACE_PLACEHOLDER) and is only recorded. A non-zero
|
||||
// `highest` keeps a new reservation at or below that address (XMEM_GRAPHICS_32BIT_ADDRESS).
|
||||
PVOID reserve_mappable(PVOID address, SIZE_T size, SIZE_T page, DWORD protect, bool adopt, uintptr_t highest);
|
||||
|
||||
// A MEM_RESERVE_PLACEHOLDER reservation the title manages itself (split with VirtualFree and
|
||||
// MEM_PRESERVE_PLACEHOLDER). It is not recorded.
|
||||
PVOID reserve_placeholder(PVOID address, SIZE_T size, uintptr_t highest);
|
||||
|
||||
} // namespace bx_xmem
|
||||
|
||||
#endif // BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_acphal_default_heap main.cpp)
|
||||
target_link_libraries(test_acphal_default_heap PRIVATE acphal kernel32)
|
||||
@@ -0,0 +1,90 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -132,11 +133,27 @@ int main() {
|
||||
}
|
||||
const uint64_t log_start = log_file_size(dispatcher_log_path);
|
||||
|
||||
// IAcpHal is not a COM interface (authorized GDK documentation): slots Connect(numCommands,
|
||||
// numMessages), Disconnect(), SubmitCommand(command, id, audioFrame, data, notification),
|
||||
// PopMessage(message), GetNumMessages() and Release(). BetterXen has no ACP: commands are
|
||||
// accepted and no message arrives.
|
||||
void* object = nullptr;
|
||||
CHECK(AcpHalCreate(&object) == S_OK && object);
|
||||
auto* hal = static_cast<IUnknown*>(object);
|
||||
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
|
||||
CHECK(hal->Release() == 1);
|
||||
void* hal = object;
|
||||
const void* const* acp = *static_cast<const void* const* const*>(hal);
|
||||
using ConnectFn = HRESULT(WINAPI*)(void*, uint32_t, uint32_t);
|
||||
using DisconnectFn = HRESULT(WINAPI*)(void*);
|
||||
using SubmitFn = HRESULT(WINAPI*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
|
||||
using PopFn = bool(WINAPI*)(void*, void*);
|
||||
using CountFn = uint32_t(WINAPI*)(void*);
|
||||
using ReleaseFn = void(WINAPI*)(void*);
|
||||
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == E_UNEXPECTED); // before Connect
|
||||
CHECK(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000) == S_OK);
|
||||
CHECK(FAILED(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000)));
|
||||
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == S_OK);
|
||||
unsigned char message[64]{};
|
||||
CHECK(!reinterpret_cast<PopFn>(acp[3])(hal, message) && reinterpret_cast<CountFn>(acp[4])(hal) == 0);
|
||||
CHECK(reinterpret_cast<DisconnectFn>(acp[1])(hal) == S_OK);
|
||||
void *va = nullptr, *second = nullptr;
|
||||
uint32_t base = 0, other = 0;
|
||||
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
|
||||
@@ -165,20 +182,42 @@ int main() {
|
||||
CHECK(ApuFree(tail) == E_INVALIDARG);
|
||||
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
|
||||
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
|
||||
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
|
||||
CHECK(ApuFree(second) == S_OK);
|
||||
reinterpret_cast<ReleaseFn>(acp[5])(hal);
|
||||
|
||||
// AcpHal shape-context stubs: NDA-gated contract, so BetterXen returns
|
||||
// E_NOTIMPL and logs the symbol. Null and sentinel pointers must not crash.
|
||||
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_NOTIMPL);
|
||||
CHECK(AcpHalAllocateShapeContexts(reinterpret_cast<void*>(uintptr_t{0xDEADBEEF})) == E_NOTIMPL);
|
||||
CHECK(AcpHalReleaseShapeContexts() == E_NOTIMPL);
|
||||
CHECK(AcpHalReleaseShapeContexts() == E_NOTIMPL);
|
||||
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) (authorized GDK documentation): six counts in
|
||||
// (SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM), six CPU pointers and six APU addresses out, the
|
||||
// arrays from the APU heap (XMA elements are 64 bytes). A second allocation without a release
|
||||
// fails with ACP_E_ALREADY_ALLOCATED (0x8AC80001).
|
||||
struct ShapeContexts {
|
||||
uint32_t counts[6];
|
||||
void* arrays[6];
|
||||
uint32_t apu[6];
|
||||
};
|
||||
static_assert(sizeof(ShapeContexts) == 96 && offsetof(ShapeContexts, arrays) == 24 &&
|
||||
offsetof(ShapeContexts, apu) == 72,
|
||||
"SHAPE_CONTEXTS layout");
|
||||
constexpr HRESULT kAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
|
||||
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_INVALIDARG);
|
||||
CHECK(AcpHalReleaseShapeContexts() == S_OK); // nothing allocated
|
||||
ShapeContexts shape{};
|
||||
shape.counts[4] = 2; // two XMA contexts: 128 bytes, the whole 64 + 64 heap
|
||||
CHECK(AcpHalAllocateShapeContexts(&shape) == S_OK);
|
||||
CHECK(shape.arrays[4] && shape.apu[4] && ApuMapApuAddress(shape.apu[4]) == shape.arrays[4]);
|
||||
CHECK(!shape.arrays[0] && !shape.arrays[5] && !shape.apu[0]);
|
||||
CHECK(static_cast<const unsigned char*>(shape.arrays[4])[127] == 0); // zero-filled
|
||||
ShapeContexts again{};
|
||||
again.counts[4] = 1;
|
||||
CHECK(AcpHalAllocateShapeContexts(&again) == kAlreadyAllocated);
|
||||
CHECK(AcpHalReleaseShapeContexts() == S_OK && !ApuMapApuAddress(shape.apu[4]));
|
||||
CHECK(AcpHalAllocateShapeContexts(&again) == S_OK && again.arrays[4]);
|
||||
CHECK(AcpHalReleaseShapeContexts() == S_OK);
|
||||
|
||||
char log_path[MAX_PATH];
|
||||
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (log_len > 0 && log_len < sizeof(log_path)) {
|
||||
CHECK(file_contains(log_path, log_start, "\"event\":\"unimpl_api\"", "AcpHal.dll!AcpHalAllocateShapeContexts"));
|
||||
CHECK(file_contains(log_path, log_start, "\"event\":\"unimpl_api\"", "AcpHal.dll!AcpHalReleaseShapeContexts"));
|
||||
CHECK(file_contains(log_path, log_start, "\"event\":\"shape_contexts_allocated\"", "xma=2"));
|
||||
CHECK(file_contains(log_path, log_start, "\"event\":\"connect\"", "commands=4096"));
|
||||
} else {
|
||||
// Unreachable under `bx-cli run --log`. A SKIP that still exits 0 would
|
||||
// contradict the exit-77 protocol, so a missing log is a failure.
|
||||
|
||||
@@ -28,9 +28,9 @@ __declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
|
||||
__declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes);
|
||||
__declspec(dllimport) VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* count, PULONG_PTR pages, uint64_t flags);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(SIZE_T* count, PULONG_PTR pages, uint64_t flags);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, ULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size);
|
||||
}
|
||||
|
||||
@@ -888,9 +888,9 @@ int main() {
|
||||
SIZE_T page_count = 2;
|
||||
ULONG_PTR pages[2] = {};
|
||||
uint8_t* view = nullptr;
|
||||
bool mapped = XMemAllocatePhysicalPages(&page_count, pages, 0) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
|
||||
bool mapped = XMemAllocatePhysicalPages(0, &page_count, pages) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
|
||||
if (mapped) {
|
||||
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, 0, pages));
|
||||
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, pages));
|
||||
mapped = view != nullptr && (reinterpret_cast<uintptr_t>(view) % kAlign) == 0;
|
||||
if (mapped) {
|
||||
view[kAlign] = 0x5A;
|
||||
@@ -1688,11 +1688,10 @@ int main() {
|
||||
}
|
||||
|
||||
if (view) {
|
||||
XMemMapPhysicalPages(view, page_count, 0, nullptr);
|
||||
XMemMapPhysicalPages(view, page_count, nullptr);
|
||||
}
|
||||
if (pages[0] || pages[1]) {
|
||||
SIZE_T free_count = 2;
|
||||
XMemFreePhysicalPages(&free_count, pages, 0);
|
||||
XMemFreePhysicalPages(2, pages);
|
||||
}
|
||||
if (sync.ready) CloseHandle(sync.ready);
|
||||
if (sync.done) CloseHandle(sync.done);
|
||||
|
||||
@@ -38,11 +38,11 @@ extern "C" {
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void* adapter, const void* params, REFIID riid, void** ppv);
|
||||
alignas(8) static const unsigned char kPcLayoutParams[80] = {};
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
|
||||
__declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* page_count, PULONG_PTR pages, uint64_t flags);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(SIZE_T* page_count, PULONG_PTR pages, uint64_t flags);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, SIZE_T page_count, uint64_t flags,
|
||||
PULONG_PTR pages);
|
||||
__declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
|
||||
DWORD protect);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR page_count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR page_count, PULONG_PTR pages);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR page_count, PULONG_PTR pages);
|
||||
}
|
||||
|
||||
namespace {
|
||||
@@ -327,7 +327,7 @@ int main() {
|
||||
* 4. Verify XMemVirtualAlloc reservation works after Xbox configuration
|
||||
* (matching the caller's MEM_RESERVE + console high-bit pattern).
|
||||
*/
|
||||
PVOID reserved_va = XMemVirtualAlloc(nullptr, 2ull * 1024ull * 1024ull, 0x20402000u, 0x21u);
|
||||
PVOID reserved_va = XMemVirtualAlloc(nullptr, 2ull * 1024ull * 1024ull, 0x20402000u, 0x21u, PAGE_READWRITE);
|
||||
check(reserved_va != nullptr, "XMemVirtualAlloc reservation after Xbox config must succeed");
|
||||
if (reserved_va) {
|
||||
check(VirtualFree(reserved_va, 0, MEM_RELEASE) != 0, "release the XMemVirtualAlloc reservation");
|
||||
@@ -345,9 +345,9 @@ int main() {
|
||||
|
||||
SIZE_T page_count = 2;
|
||||
ULONG_PTR pages[2] = {};
|
||||
const BOOL phys_ok = XMemAllocatePhysicalPages(&page_count, pages, 0);
|
||||
const BOOL phys_ok = XMemAllocatePhysicalPages(0, &page_count, pages);
|
||||
check(phys_ok && page_count == 2, "XMemAllocatePhysicalPages(2) must succeed");
|
||||
uint8_t* mapped_region = phys_ok ? static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, 2, 0, pages)) : nullptr;
|
||||
uint8_t* mapped_region = phys_ok ? static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, 2, pages)) : nullptr;
|
||||
check(mapped_region != nullptr, "XMemMapPhysicalPages(2) must succeed");
|
||||
|
||||
if (device && mapped_region) {
|
||||
@@ -426,11 +426,10 @@ int main() {
|
||||
}
|
||||
|
||||
if (mapped_region) {
|
||||
XMemMapPhysicalPages(mapped_region, 2, 0, nullptr);
|
||||
XMemMapPhysicalPages(mapped_region, 2, nullptr);
|
||||
}
|
||||
if (phys_ok) {
|
||||
SIZE_T free_count = 2;
|
||||
XMemFreePhysicalPages(&free_count, pages, 0);
|
||||
XMemFreePhysicalPages(2, pages);
|
||||
}
|
||||
if (device) {
|
||||
device->Release();
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_xbox_layout main.cpp)
|
||||
target_compile_definitions(test_d3d12_xbox_layout PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_xbox_layout PRIVATE d3d12_xs xmem kernel32 uuid)
|
||||
@@ -0,0 +1,414 @@
|
||||
/*
|
||||
* ADR 0009: d3d12_xs.dll hands a title an Xbox-layout device, and the objects it creates are
|
||||
* Xbox-layout too. This program calls them the way a title built against the Xbox Series D3D12
|
||||
* header does: through the object's function table, by slot number.
|
||||
*
|
||||
* The slot numbers and object offsets below were written out by hand from that header (used
|
||||
* under Microsoft's authorization). They are not taken from the shim's generated tables.
|
||||
* Expected results come from a second device created in the PC layout (Version 0) and called
|
||||
* through <d3d12.h>, not from the Xbox objects.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR count, PULONG_PTR pages);
|
||||
extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages);
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PULONG_PTR pages);
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD type, uint64_t flags,
|
||||
DWORD protect);
|
||||
|
||||
namespace {
|
||||
|
||||
// Xbox function-table slots (Series header).
|
||||
constexpr int kQueryInterface = 0, kAddRef = 1, kRelease = 2;
|
||||
constexpr int kDevGetNodeCount = 7, kDevCheckFeatureSupport = 13, kDevGetResourceAllocationInfo = 25;
|
||||
constexpr int kDevCreateHeap = 28, kDevCreatePlacedResource = 29, kDevGetAdapterLuid = 43;
|
||||
constexpr int kDevCreateComponentPlacedResourceX = 45; // an Xbox-only slot still stubbed
|
||||
constexpr int kDevCreateCommittedResource1 = 92; // ID3D12Device4; PC places it elsewhere
|
||||
constexpr int kResMap = 8, kResGetDesc = 10, kResGetGpuVirtualAddress = 11;
|
||||
// Object offsets (Series header): m_RefCount at +12; ID3D12Device's m_OutOfLineFlags at +24.
|
||||
constexpr size_t kRefCountOffset = 12, kOutOfLineOffset = 24;
|
||||
|
||||
const IID kIidDevice11 = {0x5405c344, 0xd457, 0x444e, {0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39}};
|
||||
|
||||
int g_failed = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_xbox_layout:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
using QueryInterfaceFn = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**);
|
||||
using RefFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using GetNodeCountFn = UINT(STDMETHODCALLTYPE*)(void*);
|
||||
using CheckFeatureSupportFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_FEATURE, void*, UINT);
|
||||
using GetAllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT,
|
||||
const D3D12_RESOURCE_DESC*);
|
||||
using GetAdapterLuidFn = LUID(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_DESC*, REFIID, void**);
|
||||
using CreatePlacedFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64, const D3D12_RESOURCE_DESC*,
|
||||
D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using StubFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateCommitted1Fn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, void*, REFIID, void**);
|
||||
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
|
||||
using GetDescFn = void(STDMETHODCALLTYPE*)(void*, D3D12_RESOURCE_DESC*);
|
||||
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
|
||||
|
||||
D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = bytes;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
return desc;
|
||||
}
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// A title sets Version (the GDK documentation asks for D3D12_SDK_VERSION); a zeroed block is
|
||||
// BetterXen's synthetic PC-layout client.
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004;
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
alignas(8) static const unsigned char pc_params[80] = {};
|
||||
|
||||
ID3D12Device* pc = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, pc_params, __uuidof(ID3D12Device), reinterpret_cast<void**>(&pc));
|
||||
CHECK(hr == S_OK && pc, "PC-layout device hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
void* dev = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
// A host device without the interface the Xbox table forwards to (vkd3d stops at
|
||||
// ID3D12Device9) must refuse the Xbox-layout device rather than return the PC one.
|
||||
CHECK(dev == nullptr, "a refused Xbox-layout device clears the out pointer");
|
||||
if (pc) pc->Release();
|
||||
if (g_failed) return 1;
|
||||
std::printf("SKIP: test_d3d12_xbox_layout: this host cannot back an Xbox-layout device; the refusal "
|
||||
"(E_NOINTERFACE, null device) was verified, the layout checks need the D3DMetal backend\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev, "Xbox-layout device hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev || !pc) return 1;
|
||||
CHECK(*reinterpret_cast<void**>(dev) != *reinterpret_cast<void**>(pc), "Xbox device must not use the PC table");
|
||||
|
||||
// Object layout a title can read.
|
||||
CHECK(*reinterpret_cast<uint32_t*>(static_cast<char*>(dev) + kRefCountOffset) == 1, "m_RefCount starts at 1");
|
||||
CHECK(static_cast<uint8_t*>(dev)[kOutOfLineOffset] != 0, "m_OutOfLineFlags makes inline helpers call out");
|
||||
|
||||
// IUnknown slots; QueryInterface for the interface the title asks for returns the same object.
|
||||
void* dev11 = nullptr;
|
||||
CHECK(slot<QueryInterfaceFn>(dev, kQueryInterface)(dev, kIidDevice11, &dev11) == S_OK && dev11 == dev,
|
||||
"QueryInterface(ID3D12Device11) returns the Xbox device");
|
||||
CHECK(slot<RefFn>(dev, kAddRef)(dev) == 3, "AddRef counts the QueryInterface reference");
|
||||
CHECK(*reinterpret_cast<uint32_t*>(static_cast<char*>(dev) + kRefCountOffset) == 3, "m_RefCount mirrors AddRef");
|
||||
slot<RefFn>(dev, kRelease)(dev);
|
||||
slot<RefFn>(dev, kRelease)(dev);
|
||||
|
||||
// Shared ID3D12Device slots, including the two struct-return conventions.
|
||||
CHECK(slot<GetNodeCountFn>(dev, kDevGetNodeCount)(dev) == pc->GetNodeCount(), "GetNodeCount at slot 7");
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
|
||||
CHECK(slot<CheckFeatureSupportFn>(dev, kDevCheckFeatureSupport)(dev, D3D12_FEATURE_D3D12_OPTIONS, &options,
|
||||
sizeof(options)) == S_OK,
|
||||
"CheckFeatureSupport at slot 13");
|
||||
LUID pc_luid{};
|
||||
pc->GetAdapterLuid(&pc_luid);
|
||||
const LUID luid = slot<GetAdapterLuidFn>(dev, kDevGetAdapterLuid)(dev);
|
||||
CHECK(luid.LowPart == pc_luid.LowPart && luid.HighPart == pc_luid.HighPart,
|
||||
"GetAdapterLuid (8-byte struct, returned in RAX) matches the PC device");
|
||||
const D3D12_RESOURCE_DESC desc = buffer_desc(64 * 1024);
|
||||
D3D12_RESOURCE_ALLOCATION_INFO pc_info{};
|
||||
pc->GetResourceAllocationInfo(&pc_info, 0, 1, &desc);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO info =
|
||||
slot<GetAllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &desc);
|
||||
CHECK(info.SizeInBytes == pc_info.SizeInBytes && info.Alignment == pc_info.Alignment && info.SizeInBytes >= 65536,
|
||||
"GetResourceAllocationInfo (16-byte struct, hidden pointer) matches the PC device");
|
||||
|
||||
// An Xbox-only slot without an implementation is a logged stub.
|
||||
CHECK(slot<StubFn>(dev, kDevCreateComponentPlacedResourceX)(dev) == E_NOTIMPL, "CreateComponentPlacedResourceX is a stub");
|
||||
|
||||
// A Device4 method at its Xbox slot creates an Xbox-layout resource.
|
||||
D3D12_HEAP_PROPERTIES upload{};
|
||||
upload.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
void* resource = nullptr;
|
||||
hr = slot<CreateCommitted1Fn>(dev, kDevCreateCommittedResource1)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
nullptr, __uuidof(ID3D12Resource), &resource);
|
||||
CHECK(hr == S_OK && resource, "CreateCommittedResource1 at slot 92 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (resource) {
|
||||
D3D12_RESOURCE_DESC got{};
|
||||
slot<GetDescFn>(resource, kResGetDesc)(resource, &got);
|
||||
CHECK(got.Width == desc.Width && got.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, "resource GetDesc at slot 10");
|
||||
CHECK(slot<GetGpuVaFn>(resource, kResGetGpuVirtualAddress)(resource) != 0, "resource GPU VA at slot 11");
|
||||
void* mapped = nullptr;
|
||||
CHECK(slot<MapFn>(resource, kResMap)(resource, 0, nullptr, &mapped) == S_OK && mapped, "resource Map at slot 8");
|
||||
if (mapped) static_cast<unsigned char*>(mapped)[0] = 0x5a;
|
||||
CHECK(slot<RefFn>(resource, kRelease)(resource) == 0, "resource Release at slot 2");
|
||||
}
|
||||
|
||||
// An Xbox heap passed back into a forwarded call is unwrapped to its host.
|
||||
D3D12_HEAP_DESC heap_desc{};
|
||||
heap_desc.SizeInBytes = 64 * 1024;
|
||||
heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
|
||||
void* heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateHeap)(dev, &heap_desc, __uuidof(ID3D12Heap), &heap);
|
||||
CHECK(hr == S_OK && heap, "CreateHeap at slot 28 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (heap) {
|
||||
void* placed = nullptr;
|
||||
hr = slot<CreatePlacedFn>(dev, kDevCreatePlacedResource)(dev, heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), &placed);
|
||||
CHECK(hr == S_OK && placed, "CreatePlacedResource on an Xbox heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (placed) slot<RefFn>(placed, kRelease)(placed);
|
||||
slot<RefFn>(heap, kRelease)(heap);
|
||||
}
|
||||
|
||||
// Command recording through Xbox objects: queue, allocator and list from the Xbox methods, a
|
||||
// copy between two Xbox buffers with a barrier, execution and a fence wait.
|
||||
{
|
||||
struct QueueDescX { D3D12_COMMAND_LIST_TYPE Type; UINT Flags, EngineOrPipeIndex, QueueIndex; };
|
||||
struct ListDescX { D3D12_COMMAND_LIST_TYPE Type; UINT Flags, NodeMask, ResourceBarrierBatchSize; };
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
|
||||
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
|
||||
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
|
||||
using GetTypeFn = D3D12_COMMAND_LIST_TYPE(STDMETHODCALLTYPE*)(void*);
|
||||
using CopyBufferFn = void(STDMETHODCALLTYPE*)(void*, void*, UINT64, void*, UINT64, UINT64);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateFence = 36;
|
||||
constexpr int kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
|
||||
constexpr int kListGetType = 8, kListClose = 9, kListCopyBufferRegion = 15, kListResourceBarrier = 26;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
constexpr size_t kPutBufferOffset = 16, kPutBufferPointers = 5;
|
||||
|
||||
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
void* allocator = nullptr;
|
||||
void* list = nullptr;
|
||||
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
|
||||
"CreateCommandQueueX at slot 48");
|
||||
CHECK(slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
__uuidof(ID3D12CommandAllocator), &allocator) == S_OK,
|
||||
"CreateCommandAllocator at slot 9");
|
||||
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
hr = slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList), &list);
|
||||
CHECK(hr == S_OK && list, "CreateCommandListX at slot 73 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
D3D12_HEAP_PROPERTIES readback{};
|
||||
readback.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
void* src = nullptr;
|
||||
void* dst = nullptr;
|
||||
CHECK(slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), &src) == S_OK,
|
||||
"upload buffer at slot 27");
|
||||
CHECK(slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &readback, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &dst) == S_OK,
|
||||
"readback buffer at slot 27");
|
||||
void* fence = nullptr;
|
||||
CHECK(slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence) == S_OK,
|
||||
"CreateFence at slot 36");
|
||||
|
||||
// A buffer placed at a title-chosen address (CreatePlacedResourceX, slot 44) reports that
|
||||
// address and carries the title memory's contents to the GPU: it replaces `src` below.
|
||||
using CreatePlacedXFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, const D3D12_RESOURCE_DESC*,
|
||||
D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
constexpr int kDevCreatePlacedResourceXSlot = 44;
|
||||
auto* title_memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, 64 * 1024, MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_READWRITE));
|
||||
void* placed_x = nullptr;
|
||||
if (title_memory) {
|
||||
std::memset(title_memory, 0xa7, 256);
|
||||
const auto title_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(title_memory);
|
||||
hr = slot<CreatePlacedXFn>(dev, kDevCreatePlacedResourceXSlot)(dev, title_va, &desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), &placed_x);
|
||||
CHECK(hr == S_OK && placed_x, "CreatePlacedResourceX at slot 44 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (placed_x) {
|
||||
CHECK(slot<GetGpuVaFn>(placed_x, kResGetGpuVirtualAddress)(placed_x) == title_va,
|
||||
"a resource placed at a title address reports that address");
|
||||
if (src) slot<RefFn>(src, kRelease)(src);
|
||||
src = placed_x;
|
||||
}
|
||||
}
|
||||
|
||||
if (queue && allocator && list && src && dst && fence) {
|
||||
// Zero put-buffer pointers make the title's inline fast paths call through the table.
|
||||
const auto* put = reinterpret_cast<const uint64_t*>(static_cast<char*>(list) + kPutBufferOffset);
|
||||
bool zero = true;
|
||||
for (size_t i = 0; i < kPutBufferPointers; ++i) zero = zero && put[i] == 0;
|
||||
CHECK(zero, "command-list put-buffer pointers are zero");
|
||||
// The Xbox command list is 1384 bytes and header-inline code writes its fields, up to
|
||||
// the last one (authorized GDK documentation). Every field after the 16-byte base is
|
||||
// title-owned: overwriting all of them (with zeros, which the put-buffer pointers must
|
||||
// hold anyway) must not disturb BetterXen's state, so the list must still record,
|
||||
// close and execute below.
|
||||
constexpr size_t kXboxCommandListBytes = 1384, kXboxBaseBytes = 16;
|
||||
std::memset(static_cast<char*>(list) + kXboxBaseBytes, 0, kXboxCommandListBytes - kXboxBaseBytes);
|
||||
CHECK(slot<GetTypeFn>(list, kListGetType)(list) == D3D12_COMMAND_LIST_TYPE_DIRECT, "list GetType at slot 8");
|
||||
|
||||
if (!placed_x) {
|
||||
void* mapped = nullptr;
|
||||
CHECK(slot<MapFn>(src, kResMap)(src, 0, nullptr, &mapped) == S_OK && mapped, "upload Map");
|
||||
if (mapped) std::memset(mapped, 0xa7, 256);
|
||||
}
|
||||
D3D12_RESOURCE_BARRIER uav{};
|
||||
uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
|
||||
uav.UAV.pResource = static_cast<ID3D12Resource*>(src); // an Xbox object, unwrapped by the shim
|
||||
CHECK(slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &uav) == 0, "ResourceBarrier at slot 26 returns 0");
|
||||
slot<CopyBufferFn>(list, kListCopyBufferRegion)(list, dst, 0, src, 0, 256);
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close at slot 9");
|
||||
void* lists[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
|
||||
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal at slot 16");
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event at slot 9");
|
||||
CHECK(WaitForSingleObject(done, 5000) == WAIT_OBJECT_0, "GPU work completes");
|
||||
CloseHandle(done);
|
||||
void* result = nullptr;
|
||||
CHECK(slot<MapFn>(dst, kResMap)(dst, 0, nullptr, &result) == S_OK && result, "readback Map");
|
||||
CHECK(result && static_cast<unsigned char*>(result)[0] == 0xa7 && static_cast<unsigned char*>(result)[255] == 0xa7,
|
||||
"the copy recorded through Xbox objects reached the readback buffer (source: the title-address shadow)");
|
||||
}
|
||||
for (void* object : {fence, dst, src, list, allocator, queue}) {
|
||||
if (object) slot<RefFn>(object, kRelease)(object);
|
||||
}
|
||||
if (title_memory) VirtualFree(title_memory, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
// Console GPU page mappings (authorized GDK documentation): CopyPageMappingsX (queue slot 29),
|
||||
// ClearPageMappingsX (30); D3D12XBOX_PAGE_MAPPING_RANGE {RangeType, StartPageIndexInPool,
|
||||
// PageCount}, range types 0 incrementing, 1 constant, 2 null, 3 skip; 64 KiB pages. GPU
|
||||
// addresses are CPU addresses in BetterXen, so the result is visible through the CPU view.
|
||||
{
|
||||
struct Range {
|
||||
UINT type, start, count;
|
||||
};
|
||||
static_assert(sizeof(Range) == 12, "D3D12XBOX_PAGE_MAPPING_RANGE");
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const void*, REFIID, void**);
|
||||
using CopyMappingsFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, UINT, const Range*,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS, UINT, UINT);
|
||||
using ClearMappingsFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, UINT, UINT);
|
||||
constexpr int kDevCreateCommandQueueX = 48, kQueueCopyPageMappingsX = 29, kQueueClearPageMappingsX = 30;
|
||||
constexpr size_t kPage = 64 * 1024;
|
||||
const UINT qdesc[4] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
|
||||
"page-mapping queue");
|
||||
ULONG_PTR pool_pages[2] = {};
|
||||
ULONG_PTR two = 2;
|
||||
CHECK(XMemAllocatePhysicalPages(0, &two, pool_pages), "physical pages for the pool");
|
||||
auto* pool = static_cast<unsigned char*>(XMemMapPhysicalPages(nullptr, 2, pool_pages));
|
||||
// The destination is a GPU-only reservation with 64 KB pages (MEM_RESERVE | MEM_64K_PAGES,
|
||||
// CPU protection PAGE_NOACCESS with a GPU protection bit), the kind titles fill with page
|
||||
// mappings. BetterXen keeps it CPU-visible, so the mapping can be checked here.
|
||||
constexpr DWORD kMem64kPages = 0x20400000, kGpuOnly = PAGE_NOACCESS | 0x800;
|
||||
auto* dst = static_cast<unsigned char*>(XMemVirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | kMem64kPages, 0, kGpuOnly));
|
||||
CHECK(dst != nullptr, "GPU-only 64 KB-page reservation");
|
||||
if (queue && pool && dst) {
|
||||
pool[0] = 0x11;
|
||||
pool[kPage] = 0x22;
|
||||
const auto dva = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(dst);
|
||||
const auto pva = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(pool);
|
||||
auto copy = slot<CopyMappingsFn>(queue, kQueueCopyPageMappingsX);
|
||||
const Range constant[] = {{1, 1, 2}}; // both destination pages show pool page 1
|
||||
CHECK(copy(queue, dva, 1, constant, pva, 2, 0) == S_OK, "CopyPageMappingsX constant range");
|
||||
CHECK(dst[0] == 0x22 && dst[kPage] == 0x22, "a constant range maps every page onto one pool page");
|
||||
const Range ranges[] = {{0, 0, 1}, {3, 0, 1}}; // page 0 <- pool page 0, page 1 skipped
|
||||
CHECK(copy(queue, dva, 2, ranges, pva, 2, 0) == S_OK, "CopyPageMappingsX incrementing + skip");
|
||||
CHECK(dst[0] == 0x11 && dst[kPage] == 0x22, "incrementing maps pool page 0; skip leaves page 1 as it was");
|
||||
pool[0] = 0x33;
|
||||
CHECK(dst[0] == 0x33, "the destination shows the pool page, not a copy of it");
|
||||
CHECK(copy(queue, dva, 1, constant, pva, 1, 0) == E_INVALIDARG, "a pool page past PoolPageCount is refused");
|
||||
const Range null_page[] = {{2, 0, 1}};
|
||||
CHECK(copy(queue, dva + kPage, 1, null_page, pva, 2, 0) == S_OK, "CopyPageMappingsX null range");
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
CHECK(VirtualQuery(dst + kPage, &mbi, sizeof(mbi)) && mbi.State != MEM_COMMIT, "a null range unmaps the page");
|
||||
CHECK(slot<ClearMappingsFn>(queue, kQueueClearPageMappingsX)(queue, dva, 1, 0) == S_OK &&
|
||||
VirtualQuery(dst, &mbi, sizeof(mbi)) && mbi.State != MEM_COMMIT,
|
||||
"ClearPageMappingsX unmaps the page");
|
||||
}
|
||||
if (queue) slot<RefFn>(queue, kRelease)(queue);
|
||||
if (dst) VirtualFree(dst, 0, MEM_RELEASE); // xmem has no XMemVirtualFree; titles use VirtualFree
|
||||
XMemFreePhysicalPages(2, pool_pages);
|
||||
}
|
||||
|
||||
// Frame pacing: an interval, an origin event, and waits that return new frame tokens.
|
||||
{
|
||||
using SetIntervalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT, UINT, UINT);
|
||||
using ScheduleFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, void*, UINT);
|
||||
using WaitFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, void*, UINT, UINT64*);
|
||||
constexpr int kDevSetFrameIntervalX = 78, kDevScheduleFrameEventX = 79, kDevWaitFrameEventX = 80;
|
||||
constexpr UINT kOrigin = 0, kVblank = 1;
|
||||
UINT64 token = 0;
|
||||
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kVblank, 0, nullptr, 0, &token) == E_INVALIDARG,
|
||||
"waiting on an unscheduled event fails");
|
||||
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == E_INVALIDARG,
|
||||
"scheduling before an interval exists fails");
|
||||
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 5, 0) == E_INVALIDARG,
|
||||
"a period above 4 is refused");
|
||||
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 1, 0) == S_OK, "SetFrameIntervalX at slot 78");
|
||||
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == S_OK, "ScheduleFrameEventX at slot 79");
|
||||
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kOrigin, 1000, nullptr, 0, &token) == S_OK && token != 0,
|
||||
"WaitFrameEventX at slot 80 returns a frame token");
|
||||
UINT64 next = 0;
|
||||
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kOrigin, 1000, nullptr, 0, &next) == S_OK && next > token,
|
||||
"the next origin produces a newer token");
|
||||
}
|
||||
|
||||
CHECK(slot<RefFn>(dev, kRelease)(dev) == 0, "device Release at slot 2");
|
||||
pc->Release();
|
||||
|
||||
const std::string log = read_log();
|
||||
if (!log.empty()) {
|
||||
CHECK(log.find("device=xbox_function_tables") != std::string::npos, "log records the Xbox layout");
|
||||
CHECK(log.find("XboxDevice[45]::CreateComponentPlacedResourceX") != std::string::npos, "the stub slot is logged");
|
||||
}
|
||||
if (g_failed) return 1;
|
||||
std::printf("PASS: test_d3d12_xbox_layout\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -25,7 +25,8 @@
|
||||
*
|
||||
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
|
||||
* fixture deliberately invents no console structure layouts. The xg_xs
|
||||
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
|
||||
* descriptor and method order are the documented XG contract recorded in
|
||||
* shims/xg_xs/xg_xbox.cpp (derived facts, no header text).
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
@@ -33,6 +34,7 @@
|
||||
#include <immintrin.h>
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -41,7 +43,6 @@
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xg_texture.h"
|
||||
|
||||
#define BX_IMPORT __declspec(dllimport)
|
||||
|
||||
@@ -54,7 +55,8 @@ BX_IMPORT uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
BX_IMPORT PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes);
|
||||
BX_IMPORT VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
|
||||
BX_IMPORT BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t flags);
|
||||
BX_IMPORT PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect);
|
||||
BX_IMPORT PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
|
||||
DWORD protect);
|
||||
BX_IMPORT SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len);
|
||||
|
||||
/* xgameruntime.dll */
|
||||
@@ -96,7 +98,24 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
|
||||
/* GameInput.dll (ordinal 1) */
|
||||
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
|
||||
|
||||
/* xg_xs.dll is declared by "xg_texture.h". */
|
||||
/* xg_xs.dll: the documented XG_RESOURCE_DESC (56 bytes) and XGTextureAddressComputer, whose
|
||||
methods are AddRef, Release, GetResourceLayout, GetResourceSizeBytes,
|
||||
GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes, ... (no IUnknown QueryInterface). */
|
||||
struct XgResourceDesc {
|
||||
uint32_t Dimension;
|
||||
UINT64 Alignment;
|
||||
UINT64 Width;
|
||||
UINT Height;
|
||||
UINT16 DepthOrArraySize;
|
||||
UINT16 MipLevels;
|
||||
uint32_t Format;
|
||||
UINT SampleCount;
|
||||
UINT SampleQuality;
|
||||
uint32_t Layout;
|
||||
uint32_t MiscFlags;
|
||||
};
|
||||
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, void** computer);
|
||||
BX_IMPORT HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t flags, uint32_t* layout);
|
||||
|
||||
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
|
||||
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
|
||||
@@ -441,7 +460,7 @@ void stage_xmem(const bx_runtime_config_t* cfg) {
|
||||
std::memset(dst, 0, kHeapBytes);
|
||||
bool transfer_ok = XMemTransferMemory(dst, src, kHeapBytes, 0) && std::memcmp(src, dst, kHeapBytes) == 0;
|
||||
|
||||
auto* vmem = static_cast<uint8_t*>(XMemVirtualAlloc(nullptr, kVirtualBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
auto* vmem = static_cast<uint8_t*>(XMemVirtualAlloc(nullptr, kVirtualBytes, MEM_COMMIT | MEM_RESERVE, 0x1 /* XMEM_CPU */, PAGE_READWRITE));
|
||||
bool virtual_ok = false;
|
||||
if (vmem) {
|
||||
vmem[0] = 0xA5;
|
||||
@@ -653,25 +672,34 @@ void stage_acphal_heap() {
|
||||
|
||||
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
|
||||
|
||||
static_assert(sizeof(XgResourceDesc) == 56 && offsetof(XgResourceDesc, Alignment) == 8, "XG_RESOURCE_DESC");
|
||||
constexpr uint32_t kXgTexture2D = 3; // XG_RESOURCE_DIMENSION_TEXTURE2D
|
||||
constexpr uint32_t kXgLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
|
||||
enum : int { kXgAddRef = 0, kXgRelease = 1, kXgSizeBytes = 3, kXgBaseAlignment = 4, kXgMipOffset = 5 };
|
||||
|
||||
template <typename Fn>
|
||||
Fn xg_slot(void* computer, int slot) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(computer))[slot]);
|
||||
}
|
||||
|
||||
/*
|
||||
* 100x50 R8G8B8A8 with two mips, so both public D3D12 alignments matter. By hand:
|
||||
* mip 0: 100 * 4 = 400 bytes per row, pitch 512 (256-byte pitch alignment);
|
||||
* ends at 49 * 512 + 400 = 25488.
|
||||
* mip 1: starts at the next 512 boundary, 25600; 50 * 4 = 200 bytes per row,
|
||||
* pitch 256; ends at 25600 + 24 * 256 + 200 = 31944.
|
||||
* total: 31944 rounded up to 512 = 32256.
|
||||
* 100x50 R8G8B8A8 with two mips under BetterXen's linear rule (shims/xg_xs/xg_xbox.cpp: rows aligned
|
||||
* to 256 bytes, mips to 512, the resource to 64 KiB). By hand:
|
||||
* mip 0: 100 * 4 = 400 bytes per row, pitch 512; 50 rows = 25600 bytes at offset 0.
|
||||
* mip 1: offset 25600 (already 512-aligned); 50 * 4 = 200 bytes per row, pitch 256;
|
||||
* 25 rows = 6400 bytes, ending at 32000.
|
||||
* resource: 32000 rounded up to 64 KiB = 65536, base alignment 65536.
|
||||
*/
|
||||
void* stage_xg_texture_computer() {
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
bx_xg_resource_desc desc = {};
|
||||
desc.dimension = BX_XG_DIMENSION_TEXTURE2D;
|
||||
desc.width = 100;
|
||||
desc.height = 50;
|
||||
desc.depth_or_array_size = 1;
|
||||
desc.mip_levels = 2;
|
||||
desc.format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.sample_desc.count = 1;
|
||||
desc.layout = BX_XG_LAYOUT_LINEAR;
|
||||
XgResourceDesc desc = {};
|
||||
desc.Dimension = kXgTexture2D;
|
||||
desc.Width = 100;
|
||||
desc.Height = 50;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 2;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleCount = 1;
|
||||
|
||||
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(&desc, &object);
|
||||
@@ -680,41 +708,41 @@ void* stage_xg_texture_computer() {
|
||||
static_cast<unsigned long>(hr), object);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
bx_xg_placed_footprint mips[2] = {};
|
||||
uint32_t rows[2] = {};
|
||||
uint64_t row_bytes[2] = {};
|
||||
uint64_t total = 0;
|
||||
hr = computer->lpVtbl->GetResourceLayout(computer, 0, 2, 0, mips, rows, row_bytes, &total);
|
||||
auto shape_is = [](const bx_xg_subresource_footprint& f, uint32_t width, uint32_t height, uint32_t pitch) {
|
||||
return f.format == DXGI_FORMAT_R8G8B8A8_UNORM && f.width == width && f.height == height && f.depth == 1 &&
|
||||
f.row_pitch == pitch;
|
||||
};
|
||||
const bool mip0 = mips[0].offset == 0 && shape_is(mips[0].footprint, 100, 50, 512) && mips[0].copy_end == 25488 &&
|
||||
rows[0] == 50 && row_bytes[0] == 400;
|
||||
const bool mip1 = mips[1].offset == 25600 && shape_is(mips[1].footprint, 50, 25, 256) && mips[1].copy_end == 31944 &&
|
||||
rows[1] == 25 && row_bytes[1] == 200;
|
||||
if (hr == S_OK && mip0 && mip1 && total == 32256) {
|
||||
using U64Fn = UINT64(WINAPI*)(void*);
|
||||
using MipFn = UINT64(WINAPI*)(void*, UINT32, UINT32);
|
||||
const UINT64 size = xg_slot<U64Fn>(object, kXgSizeBytes)(object);
|
||||
const UINT64 alignment = xg_slot<U64Fn>(object, kXgBaseAlignment)(object);
|
||||
const UINT64 mip0 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 0);
|
||||
const UINT64 mip1 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 1);
|
||||
if (size == 65536 && alignment == 65536 && mip0 == 0 && mip1 == 25600) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Pass,
|
||||
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
|
||||
"100x50 RGBA8 two-mip linear layout matches hand-computed size, alignment and mip offsets");
|
||||
} else {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail,
|
||||
"GetResourceLayout hr=0x%08lx mip0_ok=%d mip1_ok=%d total=%llu",
|
||||
static_cast<unsigned long>(hr), mip0, mip1, static_cast<unsigned long long>(total));
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "size=%llu alignment=%llu mip0=%llu mip1=%llu",
|
||||
static_cast<unsigned long long>(size), static_cast<unsigned long long>(alignment),
|
||||
static_cast<unsigned long long>(mip0), static_cast<unsigned long long>(mip1));
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
void* stage_xg_xs() {
|
||||
begin_stage("xg_xs_swizzle_mode");
|
||||
/* D3D12_RESOURCE_DIMENSION_TEXTURE2D / DXGI_FORMAT_R8G8B8A8_UNORM, 256x256, 1 mip, 1 sample. */
|
||||
uint32_t mode_a = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
uint32_t mode_b = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
if (mode_a == BX_XG_LAYOUT_LINEAR && mode_b == mode_a) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (mode=%u)", mode_a);
|
||||
XgResourceDesc desc = {};
|
||||
desc.Dimension = kXgTexture2D;
|
||||
desc.Width = 256;
|
||||
desc.Height = 256;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleCount = 1;
|
||||
uint32_t mode_a = 0, mode_b = 0;
|
||||
const HRESULT hr_a = XGSuggestSwizzleMode(&desc, 0, &mode_a);
|
||||
const HRESULT hr_b = XGSuggestSwizzleMode(&desc, 0, &mode_b);
|
||||
if (hr_a == S_OK && hr_b == S_OK && mode_a == kXgLayoutSwizzleLinear && mode_b == mode_a) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (layout=0x%x)", mode_a);
|
||||
} else {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode hr=0x%08lx/0x%08lx layout=0x%x then 0x%x, expected linear",
|
||||
static_cast<unsigned long>(hr_a), static_cast<unsigned long>(hr_b), mode_a, mode_b);
|
||||
}
|
||||
|
||||
return stage_xg_texture_computer();
|
||||
@@ -874,8 +902,7 @@ int main(int argc, char** argv) {
|
||||
/* The fixture holds the only reference, so this Release must return 0. */
|
||||
ULONG texture_refs = 0;
|
||||
if (texture_computer) {
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(texture_computer);
|
||||
texture_refs = computer->lpVtbl->Release(computer);
|
||||
texture_refs = xg_slot<ULONG(WINAPI*)(void*)>(texture_computer, kXgRelease)(texture_computer);
|
||||
}
|
||||
release_com(game_input);
|
||||
bool dsp_closed = true;
|
||||
@@ -884,7 +911,8 @@ int main(int argc, char** argv) {
|
||||
dsp_closed = deact_hr == S_OK && XDspDisconnect(dsp) == S_OK;
|
||||
}
|
||||
bool apu_closed = apu_conn ? XApuDisconnect(apu_conn) == S_OK : true;
|
||||
release_com(acp_hal);
|
||||
/* IAcpHal is not COM: Release is its sixth slot and returns nothing. */
|
||||
if (acp_hal) reinterpret_cast<void(WINAPI*)(void*)>((*static_cast<void* const* const*>(acp_hal))[5])(acp_hal);
|
||||
release_com(dstorage_factory);
|
||||
if (psm_constrained_reg) UnregisterAppConstrainedChangeNotification(psm_constrained_reg);
|
||||
if (psm_state_reg) UnregisterAppStateChangeNotification(psm_state_reg);
|
||||
|
||||
@@ -29,9 +29,9 @@ __declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void*);
|
||||
// keeps the PC-layout proxy this test is written against (ADR 0009).
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void*, const void*, REFIID, void**);
|
||||
alignas(8) static const unsigned char kPcLayoutParams[80] = {};
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
}
|
||||
|
||||
namespace {
|
||||
@@ -110,9 +110,9 @@ struct Region {
|
||||
cleanup(D3D12ConfigureVirtualMemoryX(&config) == S_OK, "clear configured region");
|
||||
}
|
||||
if (view)
|
||||
cleanup(XMemMapPhysicalPages(view, count, 0, nullptr) == view, "unmap physical page");
|
||||
cleanup(XMemMapPhysicalPages(view, count, nullptr) == view, "unmap physical page");
|
||||
if (page)
|
||||
cleanup(XMemFreePhysicalPages(&count, &page, 0), "free physical page");
|
||||
cleanup(XMemFreePhysicalPages(count, &page), "free physical page");
|
||||
}
|
||||
};
|
||||
// Declared just before ExecuteCommandLists, so on a failure after the submit it is
|
||||
@@ -164,8 +164,8 @@ void run(bool inject_pixel_mismatch) {
|
||||
|
||||
stage = "placed_resource";
|
||||
Region region;
|
||||
require(XMemAllocatePhysicalPages(®ion.count, ®ion.page, 0) && region.count == 1, "allocate physical page");
|
||||
region.view = XMemMapPhysicalPages(nullptr, 1, 0, ®ion.page);
|
||||
require(XMemAllocatePhysicalPages(0, ®ion.count, ®ion.page) && region.count == 1, "allocate physical page");
|
||||
region.view = XMemMapPhysicalPages(nullptr, 1, ®ion.page);
|
||||
require(region.view, "map physical page");
|
||||
std::memset(region.view, Region::sentinel, Region::page_bytes);
|
||||
region.config.base_va = reinterpret_cast<uintptr_t>(region.view);
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_veh_breakpoint main.cpp)
|
||||
target_link_libraries(test_veh_breakpoint PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* runtime_veh records breakpoints and assertion failures even when the guest has replaced the
|
||||
* top-level exception filter, as a title with its own crash reporter does.
|
||||
*
|
||||
* The test installs its own top-level filter and a last-registered vectored handler that
|
||||
* resumes after each int3, then raises breakpoints at a labelled site and one
|
||||
* STATUS_ASSERTION_FAILURE. The expected RVA is the label's address minus this module's base,
|
||||
* computed here, not by the shim. Needs BX_LOG_FILE (bx-cli --log).
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
|
||||
extern "C" void bx_breakpoint_site(void);
|
||||
__asm__(".text\n"
|
||||
".globl bx_breakpoint_site\n"
|
||||
"bx_breakpoint_site:\n"
|
||||
" int3\n"
|
||||
" ret\n");
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
|
||||
constexpr int kRecordLimit = 16;
|
||||
int g_failures = 0;
|
||||
volatile LONG g_resumed = 0;
|
||||
volatile LONG g_filter_calls = 0;
|
||||
|
||||
void check(bool ok, const char* what) {
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "FAIL: test_veh_breakpoint: %s\n", what);
|
||||
++g_failures;
|
||||
}
|
||||
}
|
||||
|
||||
LONG WINAPI guest_filter(PEXCEPTION_POINTERS) {
|
||||
InterlockedIncrement(&g_filter_calls);
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
LONG CALLBACK resume(PEXCEPTION_POINTERS ep) {
|
||||
const DWORD code = ep->ExceptionRecord->ExceptionCode;
|
||||
if (code == EXCEPTION_BREAKPOINT) {
|
||||
ep->ContextRecord->Rip =
|
||||
reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) + 1;
|
||||
InterlockedIncrement(&g_resumed);
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
if (code == kStatusAssertionFailure) {
|
||||
InterlockedIncrement(&g_resumed);
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
std::string read_log_from(long offset) {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* file = std::fopen(path, "rb")) {
|
||||
if (std::fseek(file, offset, SEEK_SET) == 0) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
|
||||
}
|
||||
std::fclose(file);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
long log_size() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return -1;
|
||||
long size = 0;
|
||||
if (FILE* file = std::fopen(path, "rb")) {
|
||||
if (std::fseek(file, 0, SEEK_END) == 0) size = std::ftell(file);
|
||||
std::fclose(file);
|
||||
}
|
||||
return size < 0 ? 0 : size;
|
||||
}
|
||||
|
||||
int count_lines_with(const std::string& log, const char* a, const char* b = nullptr) {
|
||||
int count = 0;
|
||||
size_t start = 0;
|
||||
while (start < log.size()) {
|
||||
size_t end = log.find('\n', start);
|
||||
if (end == std::string::npos) end = log.size();
|
||||
const std::string line = log.substr(start, end - start);
|
||||
if (line.find(a) != std::string::npos && (!b || line.find(b) != std::string::npos)) {
|
||||
++count;
|
||||
}
|
||||
start = end + 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// Keep a static import on bx_runtime_veh.dll so its handler is installed at attach.
|
||||
volatile uint64_t attached = bx_veh_get_clwb_trap_count();
|
||||
(void)attached;
|
||||
|
||||
const long mark = log_size();
|
||||
if (mark < 0) {
|
||||
std::fprintf(stderr, "FAIL: test_veh_breakpoint: BX_LOG_FILE must be set\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// A title's crash reporter takes over the top-level filter after runtime_veh attached.
|
||||
SetUnhandledExceptionFilter(guest_filter);
|
||||
PVOID handler = AddVectoredExceptionHandler(0, resume);
|
||||
check(handler != nullptr, "AddVectoredExceptionHandler");
|
||||
|
||||
// A recorded breakpoint leaves the guest thread's last-error value as it was.
|
||||
SetLastError(0x12345678);
|
||||
bx_breakpoint_site();
|
||||
check(GetLastError() == 0x12345678, "a recorded breakpoint preserves the thread's last-error value");
|
||||
RaiseException(kStatusAssertionFailure, 0, 0, nullptr);
|
||||
for (int i = 0; i < kRecordLimit + 4; ++i) bx_breakpoint_site();
|
||||
RemoveVectoredExceptionHandler(handler);
|
||||
|
||||
check(g_resumed == kRecordLimit + 6, "every exception reached the guest's own handler");
|
||||
check(g_filter_calls == 0, "no exception went unhandled");
|
||||
|
||||
const uintptr_t base = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
|
||||
const uintptr_t site = reinterpret_cast<uintptr_t>(&bx_breakpoint_site);
|
||||
char rva[64];
|
||||
std::snprintf(rva, sizeof(rva), "\"rva\":\"0x%016llx\"",
|
||||
static_cast<unsigned long long>(site - base));
|
||||
|
||||
const std::string log = read_log_from(mark);
|
||||
const int records = count_lines_with(log, "\"event\":\"breakpoint_exception\"");
|
||||
check(records == kRecordLimit, "records stop at the per-process limit of 16");
|
||||
check(count_lines_with(log, "\"exception_code\":\"0x80000003\"", rva) == kRecordLimit - 1,
|
||||
"each recorded int3 names the labelled site's RVA");
|
||||
check(count_lines_with(log, "\"exception_code\":\"0xc0000420\"") == 1,
|
||||
"the assertion failure is recorded");
|
||||
// RaiseException reports an address inside kernelbase, so only the int3 records name this
|
||||
// module.
|
||||
check(count_lines_with(log, "\"module\":\"test_veh_breakpoint.exe\"") == kRecordLimit - 1,
|
||||
"int3 records name this module");
|
||||
check(count_lines_with(log, "\"event\":\"unhandled_exception\"") == 0,
|
||||
"nothing was reported as unhandled");
|
||||
|
||||
if (g_failures) return 1;
|
||||
std::printf("PASS: test_veh_breakpoint (%d records, cap %d)\n", records, kRecordLimit);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(test_veh_diagnostics main.cpp)
|
||||
target_include_directories(test_veh_diagnostics PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_veh_diagnostics PRIVATE bx_runtime_veh kernel32)
|
||||
# A fixed image base: the parent passes its own code address to the child's BX_VEH_HIT, which is
|
||||
# armed before the child's main runs.
|
||||
target_link_options(test_veh_diagnostics PRIVATE -Wl,--disable-dynamicbase)
|
||||
@@ -0,0 +1,389 @@
|
||||
// Conformance test for bx_runtime_veh.dll's opt-in diagnostics (BX_VEH_AV_CONTEXT, BX_VEH_AV_ALL,
|
||||
// BX_VEH_WATCH, BX_VEH_HIT, BX_VEH_SAMPLE).
|
||||
//
|
||||
// The switches are read when runtime_veh attaches, before main, so the parent starts this same
|
||||
// executable as a child once per mode with that mode's environment, then reads the shared JSONL
|
||||
// log (BX_LOG_FILE) for the records the child produced. Expected values come from what each child
|
||||
// does, not from runtime_veh. Every record must be valid JSON and valid UTF-8.
|
||||
//
|
||||
// Run under `bx-cli run --log`. Exit 0: all checks passed. Exit 1: a check failed. Exit 77: the
|
||||
// host cannot run a mode (logged as SKIP).
|
||||
#include <windows.h>
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" __declspec(dllimport) uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
|
||||
// A store whose length the child's handler knows (mov [rcx], rdx = 48 89 11), used to make a
|
||||
// write fault the child can step over.
|
||||
extern "C" void store_qword(volatile uint64_t* at, uint64_t value);
|
||||
asm(".globl store_qword\n"
|
||||
"store_qword:\n"
|
||||
" movq %rdx, (%rcx)\n"
|
||||
" ret\n");
|
||||
|
||||
// The code-breakpoint target. Not inlined, so the child calls the address the parent passes.
|
||||
extern "C" __attribute__((noinline)) int hit_target(const char* text) {
|
||||
volatile int sum = 0;
|
||||
for (const char* c = text; *c; ++c) sum += *c;
|
||||
return sum;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
int g_failures = 0;
|
||||
int g_checks = 0;
|
||||
|
||||
void check(bool ok, const char* what) {
|
||||
++g_checks;
|
||||
if (!ok) {
|
||||
++g_failures;
|
||||
std::printf("FAIL: test_veh_diagnostics: %s\n", what);
|
||||
}
|
||||
}
|
||||
|
||||
constexpr uintptr_t kWatchBase = 0x7A0000000ull; // the child's watched allocation
|
||||
|
||||
// --- Child side --------------------------------------------------------------------------------
|
||||
|
||||
volatile LONG g_child_avs = 0;
|
||||
|
||||
LONG CALLBACK child_handler(PEXCEPTION_POINTERS ep) {
|
||||
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return EXCEPTION_CONTINUE_SEARCH;
|
||||
InterlockedIncrement(&g_child_avs);
|
||||
// A real fault in store_qword: step over its 3-byte store.
|
||||
if (reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) == reinterpret_cast<uintptr_t>(&store_qword)) {
|
||||
ep->ContextRecord->Rip += 3;
|
||||
}
|
||||
return EXCEPTION_CONTINUE_EXECUTION; // a raised (continuable) one resumes after RaiseException
|
||||
}
|
||||
|
||||
void raise_av() {
|
||||
const ULONG_PTR info[2] = {1, 0x1234};
|
||||
RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 2, info);
|
||||
}
|
||||
|
||||
DWORD WINAPI raise_many(LPVOID) {
|
||||
for (int i = 0; i < 8; ++i) raise_av();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int child(const char* mode, const char* arg) {
|
||||
(void)bx_veh_get_clwb_trap_count(); // keeps the runtime_veh import
|
||||
AddVectoredExceptionHandler(0, child_handler); // after runtime_veh's own handler
|
||||
if (!std::strcmp(mode, "off")) {
|
||||
for (int i = 0; i < 4; ++i) raise_av();
|
||||
return g_child_avs == 4 ? 0 : 2;
|
||||
}
|
||||
if (!std::strcmp(mode, "av")) {
|
||||
HANDLE threads[4];
|
||||
for (auto& t : threads) t = CreateThread(nullptr, 0, raise_many, nullptr, 0, nullptr);
|
||||
WaitForMultipleObjects(4, threads, TRUE, 10000);
|
||||
for (auto t : threads) CloseHandle(t);
|
||||
return g_child_avs == 32 ? 0 : 2;
|
||||
}
|
||||
if (!std::strcmp(mode, "watch")) {
|
||||
auto* base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(kWatchBase), 0x10000,
|
||||
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
|
||||
if (base != reinterpret_cast<uint8_t*>(kWatchBase)) return 77;
|
||||
// The helper thread protects the page once it is committed.
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
for (int i = 0; i < 2000; ++i) {
|
||||
if (VirtualQuery(base, &mbi, sizeof(mbi)) && mbi.Protect == PAGE_READONLY) break;
|
||||
Sleep(1);
|
||||
}
|
||||
if (mbi.Protect != PAGE_READONLY) return 3;
|
||||
*reinterpret_cast<volatile uint64_t*>(base + 0x10) = 0x1122334455667788ull; // watched: logged
|
||||
*reinterpret_cast<volatile uint64_t*>(base + 0x200) = 7; // same page, not watched
|
||||
if (*reinterpret_cast<volatile uint64_t*>(base + 0x10) != 0x1122334455667788ull) return 4;
|
||||
// Decommit the watched page: the next write faults, and runtime_veh cannot unprotect the
|
||||
// page, so it must disarm and pass the fault on (to child_handler) rather than loop.
|
||||
if (!VirtualFree(base, 0x1000, MEM_DECOMMIT)) return 5;
|
||||
const LONG before = g_child_avs;
|
||||
store_qword(reinterpret_cast<volatile uint64_t*>(base + 0x10), 9);
|
||||
return g_child_avs == before + 1 ? 0 : 6;
|
||||
}
|
||||
if (!std::strcmp(mode, "hit")) {
|
||||
const uintptr_t expected = static_cast<uintptr_t>(std::strtoull(arg, nullptr, 16));
|
||||
if (expected != reinterpret_cast<uintptr_t>(&hit_target)) return 77; // image relocated
|
||||
hit_target("quote\" back\\ path");
|
||||
hit_target("second call");
|
||||
return 0;
|
||||
}
|
||||
if (!std::strcmp(mode, "sample")) {
|
||||
const DWORD until = GetTickCount() + 300;
|
||||
volatile uint64_t spin = 0;
|
||||
while (GetTickCount() < until) spin = spin + 1;
|
||||
return spin ? 0 : 2;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
|
||||
// --- Parent side -------------------------------------------------------------------------------
|
||||
|
||||
std::wstring widen(const char* s) {
|
||||
std::wstring out;
|
||||
while (*s) out.push_back(static_cast<wchar_t>(static_cast<unsigned char>(*s++)));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string read_log_from(const char* path, uint64_t offset) {
|
||||
std::string text;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return text;
|
||||
LARGE_INTEGER at;
|
||||
at.QuadPart = static_cast<LONGLONG>(offset);
|
||||
SetFilePointerEx(f, at, nullptr, FILE_BEGIN);
|
||||
char buf[65536];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
|
||||
uint64_t file_size(const char* path) {
|
||||
WIN32_FILE_ATTRIBUTE_DATA data{};
|
||||
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &data)) return 0;
|
||||
return (static_cast<uint64_t>(data.nFileSizeHigh) << 32) | data.nFileSizeLow;
|
||||
}
|
||||
|
||||
// A JSONL record: one object whose strings use only JSON escapes and no raw control characters,
|
||||
// in valid UTF-8.
|
||||
bool valid_record(const std::string& line) {
|
||||
if (line.size() < 2 || line.front() != '{' || line.back() != '}') return false;
|
||||
bool in_string = false;
|
||||
for (size_t i = 0; i < line.size(); ++i) {
|
||||
const unsigned char c = static_cast<unsigned char>(line[i]);
|
||||
if (c >= 0x80) { // UTF-8 sequence
|
||||
const int extra = (c & 0xE0) == 0xC0 ? 1 : (c & 0xF0) == 0xE0 ? 2 : (c & 0xF8) == 0xF0 ? 3 : -1;
|
||||
if (extra < 0 || i + extra >= line.size()) return false;
|
||||
for (int k = 1; k <= extra; ++k) {
|
||||
if ((static_cast<unsigned char>(line[i + k]) & 0xC0) != 0x80) return false;
|
||||
}
|
||||
i += extra;
|
||||
continue;
|
||||
}
|
||||
if (!in_string) {
|
||||
if (c == '"') in_string = true;
|
||||
continue;
|
||||
}
|
||||
if (c < 0x20) return false;
|
||||
if (c == '"') {
|
||||
in_string = false;
|
||||
} else if (c == '\\') {
|
||||
if (i + 1 >= line.size()) return false;
|
||||
const char e = line[++i];
|
||||
if (e == 'u') {
|
||||
if (i + 4 >= line.size()) return false;
|
||||
for (int k = 1; k <= 4; ++k) {
|
||||
if (!std::isxdigit(static_cast<unsigned char>(line[i + k]))) return false;
|
||||
}
|
||||
i += 4;
|
||||
} else if (!std::strchr("\"\\/bfnrt", e)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return !in_string;
|
||||
}
|
||||
|
||||
std::vector<std::string> records(const std::string& text, const char* event) {
|
||||
std::vector<std::string> out;
|
||||
const std::string needle = std::string("\"event\":\"") + event + "\"";
|
||||
size_t start = 0;
|
||||
while (start < text.size()) {
|
||||
size_t end = text.find('\n', start);
|
||||
if (end == std::string::npos) end = text.size();
|
||||
std::string line = text.substr(start, end - start);
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
if (line.find(needle) != std::string::npos) out.push_back(line);
|
||||
start = end + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
struct ChildRun {
|
||||
DWORD exit_code = 0xFFFFFFFF;
|
||||
std::string log;
|
||||
};
|
||||
|
||||
// Starts `exe` as a child in `mode` with the extra environment variables, waits for it, and
|
||||
// returns its exit code and the log lines it appended.
|
||||
ChildRun run_child(const std::wstring& exe, const char* mode, const char* arg,
|
||||
const std::vector<std::wstring>& extra_env, const char* log_path) {
|
||||
ChildRun run;
|
||||
std::wstring block;
|
||||
if (wchar_t* env = GetEnvironmentStringsW()) {
|
||||
for (const wchar_t* p = env; *p; p += std::wcslen(p) + 1) {
|
||||
std::wstring entry(p);
|
||||
if (entry.rfind(L"BX_VEH_", 0) == 0) continue; // only this mode's switches
|
||||
block += entry;
|
||||
block.push_back(L'\0');
|
||||
}
|
||||
FreeEnvironmentStringsW(env);
|
||||
}
|
||||
for (const auto& e : extra_env) {
|
||||
block += e;
|
||||
block.push_back(L'\0');
|
||||
}
|
||||
block.push_back(L'\0');
|
||||
std::wstring cmd = L"\"" + exe + L"\" child " + widen(mode) + L" " + widen(arg);
|
||||
STARTUPINFOW si{};
|
||||
si.cb = sizeof(si);
|
||||
PROCESS_INFORMATION pi{};
|
||||
const uint64_t before = file_size(log_path);
|
||||
if (!CreateProcessW(exe.c_str(), cmd.data(), nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT, block.data(),
|
||||
nullptr, &si, &pi)) {
|
||||
return run;
|
||||
}
|
||||
if (WaitForSingleObject(pi.hProcess, 60000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &run.exit_code);
|
||||
else TerminateProcess(pi.hProcess, 9);
|
||||
CloseHandle(pi.hThread);
|
||||
CloseHandle(pi.hProcess);
|
||||
run.log = read_log_from(log_path, before);
|
||||
return run;
|
||||
}
|
||||
|
||||
bool all_valid(const std::vector<std::string>& lines) {
|
||||
for (const auto& l : lines) {
|
||||
if (!valid_record(l)) {
|
||||
std::printf(" invalid record: %.200s\n", l.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int parent(const char* log_path) {
|
||||
wchar_t self[MAX_PATH];
|
||||
GetModuleFileNameW(nullptr, self, MAX_PATH);
|
||||
const std::wstring exe(self);
|
||||
int skipped = 0;
|
||||
|
||||
// Off: synthetic access violations produce no av_context record.
|
||||
{
|
||||
ChildRun r = run_child(exe, "off", "-", {}, log_path);
|
||||
check(r.exit_code == 0, "off: child handled its access violations (exit 0)");
|
||||
check(records(r.log, "av_context").empty(), "off: no av_context record without BX_VEH_AV_CONTEXT");
|
||||
}
|
||||
|
||||
// AV context from four threads at once, with a spec containing a quote, a backslash and a
|
||||
// control character and far too long for one line: 16 records (the cap), each valid JSON.
|
||||
std::wstring spec = L"BX_VEH_AV_CONTEXT=zz\"q\\b\x01,";
|
||||
for (int i = 0; i < 80; ++i) spec += L"*10+8,";
|
||||
{
|
||||
ChildRun r = run_child(exe, "av", "-", {spec, L"BX_VEH_AV_ALL=1"}, log_path);
|
||||
const auto lines = records(r.log, "av_context");
|
||||
check(r.exit_code == 0, "av: every access violation reached the child (exit 0)");
|
||||
check(lines.size() == 16, "av: 16 av_context records from 32 faults (the cap)");
|
||||
check(all_valid(lines), "av: every av_context record is valid JSON");
|
||||
bool escaped = false;
|
||||
for (const auto& l : lines) escaped = escaped || l.find("zz\\\"q\\\\b\\u0001") != std::string::npos;
|
||||
check(escaped, "av: the spec token is JSON-escaped");
|
||||
bool stack = true;
|
||||
for (const auto& l : lines) stack = stack && l.find("| stack:") != std::string::npos;
|
||||
check(stack, "av: a truncated spec still leaves room for the stack");
|
||||
}
|
||||
|
||||
// A non-ASCII module name in the stack must stay valid UTF-8.
|
||||
{
|
||||
std::wstring dir = exe.substr(0, exe.find_last_of(L'\\') + 1);
|
||||
const std::wstring copy = dir + L"veh_ünïcode.exe";
|
||||
if (CopyFileW(exe.c_str(), copy.c_str(), FALSE)) {
|
||||
ChildRun r = run_child(copy, "av", "-", {L"BX_VEH_AV_CONTEXT=1", L"BX_VEH_AV_ALL=1"}, log_path);
|
||||
const auto lines = records(r.log, "av_context");
|
||||
check(r.exit_code == 0 && !lines.empty(), "unicode: the renamed child logged av_context");
|
||||
check(all_valid(lines), "unicode: records with a non-ASCII module name are valid JSON and UTF-8");
|
||||
bool named = false;
|
||||
for (const auto& l : lines) named = named || l.find("veh_\xc3\xbc" "n\xc3\xaf" "code") != std::string::npos;
|
||||
check(named, "unicode: the module name is written in UTF-8");
|
||||
DeleteFileW(copy.c_str());
|
||||
} else {
|
||||
std::printf("SKIP: unicode mode: could not copy the executable\n");
|
||||
++skipped;
|
||||
}
|
||||
}
|
||||
|
||||
// Write watch: one logged write, a write outside the range not logged, and a protection
|
||||
// failure that disarms the watch and lets the fault reach the guest.
|
||||
{
|
||||
wchar_t watch[64];
|
||||
std::swprintf(watch, 64, L"BX_VEH_WATCH=%llx:8", static_cast<unsigned long long>(kWatchBase + 0x10));
|
||||
ChildRun r = run_child(exe, "watch", "-", {watch}, log_path);
|
||||
if (r.exit_code == 77) {
|
||||
std::printf("SKIP: watch mode: the fixed test address is not free in this process\n");
|
||||
++skipped;
|
||||
} else {
|
||||
const auto writes = records(r.log, "watched_write");
|
||||
const auto disarmed = records(r.log, "diagnostic_disarmed");
|
||||
check(r.exit_code == 0, "watch: the write to the decommitted page reached the child (exit 0)");
|
||||
check(writes.size() == 1 && writes[0].find("address=7a0000010") != std::string::npos &&
|
||||
writes[0].find("value_after=1122334455667788") != std::string::npos,
|
||||
"watch: exactly the watched write is logged, with its value");
|
||||
check(disarmed.size() == 1 && disarmed[0].find("watch: could not unprotect") != std::string::npos,
|
||||
"watch: a failed protection change disarms the watch and is logged");
|
||||
check(all_valid(writes) && all_valid(disarmed), "watch: records are valid JSON");
|
||||
}
|
||||
}
|
||||
|
||||
// Code breakpoint: two calls, two hits (the breakpoint is re-armed), the string argument safe.
|
||||
{
|
||||
char address[32];
|
||||
std::snprintf(address, sizeof(address), "%llx", static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(&hit_target)));
|
||||
std::wstring hit = L"BX_VEH_HIT=" + widen(address);
|
||||
ChildRun r = run_child(exe, "hit", address, {hit}, log_path);
|
||||
if (r.exit_code == 77) {
|
||||
std::printf("SKIP: hit mode: the child's image was relocated\n");
|
||||
++skipped;
|
||||
} else {
|
||||
const auto hits = records(r.log, "code_hit");
|
||||
check(r.exit_code == 0, "hit: the child ran through both breakpoint hits (exit 0)");
|
||||
check(hits.size() == 2, "hit: both calls are logged (the breakpoint is re-armed)");
|
||||
check(all_valid(hits), "hit: code_hit records are valid JSON");
|
||||
bool text = false;
|
||||
for (const auto& l : hits) text = text || l.find("[rcx]s=quote_ back_ path") != std::string::npos;
|
||||
check(text, "hit: a string argument is logged with quote and backslash made safe");
|
||||
}
|
||||
}
|
||||
|
||||
// Sampler: records while the child runs, valid JSON, and a clean exit.
|
||||
{
|
||||
ChildRun r = run_child(exe, "sample", "-", {L"BX_VEH_SAMPLE=5"}, log_path);
|
||||
const auto samples = records(r.log, "sample");
|
||||
check(r.exit_code == 0, "sample: the child exits normally with the sampler running");
|
||||
check(!samples.empty(), "sample: sample records are written");
|
||||
check(all_valid(samples), "sample: sample records are valid JSON");
|
||||
}
|
||||
|
||||
if (g_failures) {
|
||||
std::printf("FAIL: test_veh_diagnostics (%d of %d checks failed)\n", g_failures, g_checks);
|
||||
return 1;
|
||||
}
|
||||
if (skipped) {
|
||||
std::printf("SKIP: test_veh_diagnostics: %d mode(s) could not run on this host (%d checks passed)\n", skipped, g_checks);
|
||||
return 77;
|
||||
}
|
||||
std::printf("PASS: test_veh_diagnostics (%d checks: off, AV context, UTF-8 module names, write watch, code hit, sampler)\n",
|
||||
g_checks);
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc >= 4 && !std::strcmp(argv[1], "child")) return child(argv[2], argv[3]);
|
||||
char log_path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (n == 0 || n >= sizeof(log_path)) {
|
||||
std::printf("FAIL: test_veh_diagnostics: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
return parent(log_path);
|
||||
}
|
||||
@@ -129,6 +129,28 @@ bool file_contains(const char* path, const char* needle) {
|
||||
|
||||
} // namespace
|
||||
|
||||
/* "tile %04d ok;" for i % 97, i = 0..399 (5200 bytes), zlib-compressed at level 9 by CPython's
|
||||
* zlib module; a dynamic-Huffman deflate block. */
|
||||
constexpr size_t kZlibPlainSize = 5200;
|
||||
const uint8_t kZlibStream[] = {
|
||||
0x78, 0xda, 0xed, 0xd4, 0x2b, 0x4e, 0x05, 0x40, 0x10, 0x44, 0xd1, 0xad, 0xbc, 0x25, 0xd0, 0xf3,
|
||||
0xe9, 0x9e, 0x09, 0xeb, 0x41, 0x10, 0x48, 0x30, 0x6f, 0xff, 0x01, 0x81, 0x38, 0x68, 0x6c, 0x97,
|
||||
0x2b, 0x77, 0xd4, 0x7d, 0xbe, 0x7f, 0xbe, 0x3d, 0x5e, 0x7e, 0xf6, 0xf8, 0xfa, 0x78, 0x7d, 0xfe,
|
||||
0x9e, 0xf0, 0x0c, 0xcf, 0xf4, 0x2c, 0xcf, 0xf6, 0xa4, 0xa7, 0x3c, 0xc7, 0x73, 0x39, 0xa1, 0x20,
|
||||
0x14, 0x84, 0x82, 0x50, 0x10, 0x0a, 0x42, 0x41, 0x28, 0x08, 0x05, 0xa1, 0x20, 0x14, 0x0c, 0x05,
|
||||
0x43, 0xc1, 0x50, 0x30, 0x14, 0x0c, 0x05, 0x43, 0xc1, 0x50, 0x30, 0x14, 0x0c, 0x05, 0x43, 0xc1,
|
||||
0x54, 0x30, 0x15, 0x4c, 0x05, 0x53, 0xc1, 0x54, 0x30, 0x15, 0x4c, 0x05, 0x53, 0xc1, 0x54, 0x30,
|
||||
0x15, 0x2c, 0x05, 0x4b, 0xc1, 0x52, 0xb0, 0x14, 0x2c, 0x05, 0x4b, 0xc1, 0x52, 0xb0, 0x14, 0x2c,
|
||||
0x05, 0x4b, 0xc1, 0x56, 0xb0, 0x15, 0x6c, 0x05, 0x5b, 0xc1, 0x56, 0xb0, 0x15, 0x6c, 0x05, 0x5b,
|
||||
0xc1, 0x56, 0xb0, 0x15, 0xa4, 0x82, 0x54, 0x90, 0x0a, 0x52, 0x41, 0x2a, 0x48, 0x05, 0xa9, 0x20,
|
||||
0x15, 0xa4, 0x82, 0x54, 0x50, 0x0a, 0x4a, 0x41, 0x29, 0x28, 0x05, 0xa5, 0xa0, 0x14, 0x94, 0x82,
|
||||
0x52, 0x50, 0x0a, 0x4a, 0xc1, 0x51, 0x70, 0x14, 0x1c, 0x05, 0x47, 0xc1, 0x51, 0x70, 0x14, 0x1c,
|
||||
0x05, 0x47, 0xc1, 0x51, 0x70, 0x14, 0x5c, 0x05, 0x57, 0xc1, 0x55, 0x70, 0x15, 0x5c, 0x05, 0x57,
|
||||
0xc1, 0xfd, 0x53, 0xa4, 0x8e, 0x5d, 0xc7, 0xae, 0x63, 0xd7, 0xb1, 0xeb, 0xd8, 0x75, 0xec, 0x3a,
|
||||
0x76, 0x1d, 0xbb, 0x8e, 0x5d, 0xc7, 0xae, 0x63, 0xd7, 0xb1, 0xeb, 0xd8, 0x75, 0xec, 0x3a, 0x76,
|
||||
0xff, 0x8a, 0xdd, 0x37, 0x11, 0xdb, 0xee, 0x70,
|
||||
};
|
||||
|
||||
int main() {
|
||||
/* BX_LOG_FILE must name the log before launch (bx-cli run --log): the log checks
|
||||
* below are the only evidence for the BX_VTABLE_STUB_LOG records. */
|
||||
@@ -233,16 +255,71 @@ int main() {
|
||||
static_cast<unsigned long>(status->GetHResult(0)));
|
||||
check(std::memcmp(dest, payload + 64, sizeof(dest)) == 0, "file read bytes must match payload[64..192]");
|
||||
|
||||
/* Compressed request must fail with E_NOTIMPL and log stub. */
|
||||
XboxRequest comp_req = req;
|
||||
comp_req.options = 1;
|
||||
file_q->EnqueueRequest(&comp_req);
|
||||
/* DSTORAGE_REQUEST_OPTIONS.BcpackMode (bits 1-4) has no decoder: E_NOTIMPL and a stub log. */
|
||||
XboxRequest bcpack_req = req;
|
||||
bcpack_req.options = 1ull << 1;
|
||||
file_q->EnqueueRequest(&bcpack_req);
|
||||
file_q->EnqueueStatus(status, 1);
|
||||
file_q->Submit();
|
||||
check(wait_complete(status, 1), "compressed request status must complete");
|
||||
check(status->GetHResult(1) == E_NOTIMPL, "compressed request must report E_NOTIMPL (hr=0x%08lx)",
|
||||
check(wait_complete(status, 1), "BCPack request status must complete");
|
||||
check(status->GetHResult(1) == E_NOTIMPL, "BCPack request must report E_NOTIMPL (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(status->GetHResult(1)));
|
||||
|
||||
/* A zlib request must be smaller than its output (GDK DirectStorage compression rules). */
|
||||
XboxRequest same_size = req;
|
||||
same_size.options = 1;
|
||||
file_q->EnqueueRequest(&same_size);
|
||||
file_q->EnqueueStatus(status, 1);
|
||||
file_q->Submit();
|
||||
check(wait_complete(status, 1), "same-size zlib request status must complete");
|
||||
check(status->GetHResult(1) == E_DSTORAGE_INVALID_DESTINATION_SIZE,
|
||||
"a zlib request whose source is not smaller than its destination must be rejected (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(status->GetHResult(1)));
|
||||
|
||||
/* A zlib request whose source is a file, at a non-zero offset (how titles stream packed
|
||||
* data): the stream is read from the file and inflated into the destination. */
|
||||
WCHAR zlib_file[MAX_PATH] = {};
|
||||
check(GetTempFileNameW(temp_dir, L"bxz", 0, zlib_file) != 0, "GetTempFileNameW (zlib) must succeed");
|
||||
HANDLE zraw = CreateFileW(zlib_file, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
check(zraw != INVALID_HANDLE_VALUE, "CreateFileW for the zlib payload must succeed");
|
||||
if (zraw != INVALID_HANDLE_VALUE) {
|
||||
uint8_t prefix[100];
|
||||
std::memset(prefix, 0xCC, sizeof(prefix));
|
||||
DWORD written = 0;
|
||||
check(WriteFile(zraw, prefix, sizeof(prefix), &written, nullptr) && written == sizeof(prefix) &&
|
||||
WriteFile(zraw, kZlibStream, sizeof(kZlibStream), &written, nullptr) &&
|
||||
written == sizeof(kZlibStream),
|
||||
"WriteFile must write the zlib payload");
|
||||
CloseHandle(zraw);
|
||||
}
|
||||
IXboxDStorageFile* zfile = nullptr;
|
||||
hr = factory->OpenFile(zlib_file, kXboxFileIid, reinterpret_cast<void**>(&zfile));
|
||||
check(hr == S_OK && zfile, "OpenFile(zlib payload) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
|
||||
if (zfile) {
|
||||
static char expected_text[kZlibPlainSize + 1];
|
||||
for (int i = 0, at = 0; i < 400; ++i) {
|
||||
at += std::snprintf(expected_text + at, sizeof(expected_text) - at, "tile %04d ok;", i % 97);
|
||||
}
|
||||
static uint8_t file_inflated[kZlibPlainSize];
|
||||
XboxRequest fz{};
|
||||
fz.options = 1; // ZlibDecompress, file source
|
||||
fz.destination = file_inflated;
|
||||
fz.destination_size = kZlibPlainSize;
|
||||
fz.source_ptr = zfile;
|
||||
fz.file_offset = 100;
|
||||
fz.source_size = sizeof(kZlibStream);
|
||||
file_q->EnqueueRequest(&fz);
|
||||
file_q->EnqueueStatus(status, 1);
|
||||
file_q->Submit();
|
||||
check(wait_complete(status, 1) && status->GetHResult(1) == S_OK,
|
||||
"file-source zlib request must succeed (hr=0x%08lx)", static_cast<unsigned long>(status->GetHResult(1)));
|
||||
check(std::memcmp(file_inflated, expected_text, kZlibPlainSize) == 0,
|
||||
"file-source zlib request must inflate to the expected text");
|
||||
zfile->Close();
|
||||
zfile->Release();
|
||||
}
|
||||
DeleteFileW(zlib_file);
|
||||
|
||||
/* The Xbox output layout is unverified. A PC-sized test buffer
|
||||
* detects any accidental writes while keeping the test memory safe. */
|
||||
DSTORAGE_ERROR_RECORD record;
|
||||
@@ -284,6 +361,136 @@ int main() {
|
||||
static_cast<unsigned long>(status->GetHResult(0)));
|
||||
check(std::memcmp(dest, payload + 32, sizeof(dest)) == 0, "memory copy bytes must match payload[32..96]");
|
||||
|
||||
/* ZlibDecompress (bit 0): an RFC 1950 stream produced by an independent zlib encoder,
|
||||
* checked against plain text this test builds itself. */
|
||||
static char expected[kZlibPlainSize + 1];
|
||||
for (int i = 0, at = 0; i < 400; ++i) at += std::snprintf(expected + at, sizeof(expected) - at, "tile %04d ok;", i % 97);
|
||||
static uint8_t inflated[kZlibPlainSize];
|
||||
XboxRequest zreq{};
|
||||
zreq.options = 0x400000ull | 1ull;
|
||||
zreq.destination = inflated;
|
||||
zreq.destination_size = kZlibPlainSize;
|
||||
zreq.source_ptr = const_cast<uint8_t*>(kZlibStream);
|
||||
zreq.source_size = sizeof(kZlibStream);
|
||||
mem_q->EnqueueRequest(&zreq);
|
||||
mem_q->EnqueueStatus(status, 1);
|
||||
mem_q->Submit();
|
||||
check(wait_complete(status, 1) && status->GetHResult(1) == S_OK, "zlib request must succeed (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(status->GetHResult(1)));
|
||||
check(std::memcmp(inflated, expected, kZlibPlainSize) == 0, "zlib request must inflate to the expected text");
|
||||
|
||||
/* DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled (flags bit 0, authorized GDK documentation):
|
||||
* enqueued work waits for Submit. Without it the queue submits by itself once half full
|
||||
* (public DirectStorage behaviour). Observed through the destination bytes. */
|
||||
auto copied = [&](const uint8_t* dst, DWORD wait_ms) {
|
||||
for (DWORD waited = 0;; waited += 10) {
|
||||
if (std::memcmp(dst, payload + 32, 16) == 0) return true;
|
||||
if (waited >= wait_ms) return false;
|
||||
Sleep(10);
|
||||
}
|
||||
};
|
||||
for (const UINT64 flags : {UINT64{1}, UINT64{0}}) {
|
||||
XboxQueueDesc qd{};
|
||||
qd.source_type = 1;
|
||||
qd.capacity = 4;
|
||||
qd.priority = 1;
|
||||
qd.name = flags ? "xbox_held_queue" : "xbox_auto_queue";
|
||||
qd.flags = flags;
|
||||
IXboxDStorageQueue* q = nullptr;
|
||||
check(factory->CreateQueueX(&qd, kXboxQueueIid, reinterpret_cast<void**>(&q)) == S_OK && q,
|
||||
"CreateQueueX(capacity 4, flags %llu) must succeed", static_cast<unsigned long long>(flags));
|
||||
if (!q) continue;
|
||||
static uint8_t held_dst[2][16];
|
||||
std::memset(held_dst, 0, sizeof(held_dst));
|
||||
for (auto& dst : held_dst) {
|
||||
XboxRequest r{};
|
||||
r.options = 0x400000ull;
|
||||
r.destination = dst;
|
||||
r.destination_size = sizeof(dst);
|
||||
r.source_ptr = payload + 32;
|
||||
r.source_size = sizeof(dst);
|
||||
q->EnqueueRequest(&r);
|
||||
}
|
||||
if (flags) {
|
||||
check(!copied(held_dst[1], 300), "AutoSubmitDisabled: two of four slots filled must not run before Submit");
|
||||
q->Submit();
|
||||
}
|
||||
check(copied(held_dst[0], 5000) && copied(held_dst[1], 5000),
|
||||
flags ? "AutoSubmitDisabled: requests must run after Submit"
|
||||
: "without AutoSubmitDisabled a half-full queue must submit by itself");
|
||||
q->Close();
|
||||
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));
|
||||
corrupted[sizeof(corrupted) - 1] ^= 0xFF; // the Adler-32 trailer
|
||||
zreq.source_ptr = corrupted;
|
||||
mem_q->EnqueueRequest(&zreq);
|
||||
mem_q->EnqueueStatus(status, 1);
|
||||
mem_q->Submit();
|
||||
check(wait_complete(status, 1) && status->GetHResult(1) == E_DSTORAGE_DECOMPRESSION_ERROR,
|
||||
"a corrupted zlib stream must report E_DSTORAGE_DECOMPRESSION_ERROR (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(status->GetHResult(1)));
|
||||
|
||||
/* A rejected null fence still signals the queue's error event. */
|
||||
mem_q->EnqueueSignal(nullptr, 1);
|
||||
mem_q->Submit();
|
||||
@@ -366,8 +573,9 @@ int main() {
|
||||
"log must record that Xbox SetStagingBufferSize has no effect");
|
||||
check(file_contains(log_path, "dstorage_queue_closed"),
|
||||
"log must record the request enqueued after Close as dropped");
|
||||
check(file_contains(log_path, "IDStorageQueueX[3]::EnqueueRequest_compressed"),
|
||||
"log must record compressed request stub");
|
||||
check(file_contains(log_path, "IDStorageQueueX[3]::EnqueueRequest_bcpack"),
|
||||
"log must record the BCPack request stub");
|
||||
check(file_contains(log_path, "dstorage_zlib_failed"), "log must record the corrupted zlib stream");
|
||||
check(file_contains(log_path, "IDStorageQueueX[10]::RetrieveErrorRecord"),
|
||||
"log must record the unimplemented Xbox error-record output");
|
||||
const auto check_rejection = [&](const char* method, HRESULT hr) {
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_xg_xbox main.cpp)
|
||||
target_link_libraries(test_xg_xbox PRIVATE kernel32)
|
||||
@@ -0,0 +1,468 @@
|
||||
// Conformance test for the XG contract titles call (XGCreateTextureComputer / XGSuggestSwizzleMode
|
||||
// with XG_RESOURCE_DESC and the 14-method XGTextureAddressComputer). Structure layouts, enum values
|
||||
// and the method order are derived facts recorded in shims/xg_xs/xg_xbox.cpp; no header text.
|
||||
//
|
||||
// Expected values are computed here, not by xg_xs.dll:
|
||||
// - Linear layouts follow BetterXen's documented rule (rows aligned to 256 bytes, mips to 512, the
|
||||
// resource and each plane to 64 KiB), worked out by hand below.
|
||||
// - SW_64KB_S at 4 bytes per element is checked against Microsoft's public D3D12 standard-swizzle
|
||||
// definition, offset = pdep(x * 4, 0xAA8F) | pdep(y, 0x5570), an independent source from the
|
||||
// AddrLib tables the shim uses. The 8-byte row has only the AddrLib source, so it is checked for
|
||||
// the properties every tile pattern must have (a bijection of aligned slots inside 64 KiB).
|
||||
#include <windows.h>
|
||||
#include <dxgiformat.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
|
||||
static int g_checks = 0;
|
||||
static int g_failures = 0;
|
||||
|
||||
static void check(bool ok, const char* what) {
|
||||
++g_checks;
|
||||
if (!ok) {
|
||||
std::printf("FAIL: test_xg_xbox: %s\n", what);
|
||||
++g_failures;
|
||||
}
|
||||
}
|
||||
|
||||
struct XgResourceDesc {
|
||||
uint32_t Dimension;
|
||||
UINT64 Alignment;
|
||||
UINT64 Width;
|
||||
UINT Height;
|
||||
UINT16 DepthOrArraySize;
|
||||
UINT16 MipLevels;
|
||||
uint32_t Format;
|
||||
UINT SampleCount;
|
||||
UINT SampleQuality;
|
||||
uint32_t Layout;
|
||||
uint32_t MiscFlags;
|
||||
};
|
||||
struct XgMipLevelLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 OffsetBytes;
|
||||
UINT64 Slice2DSizeBytes;
|
||||
UINT32 PitchPixels;
|
||||
UINT32 PitchBytes;
|
||||
UINT32 AlignmentBytes;
|
||||
UINT32 PaddedWidthElements;
|
||||
UINT32 PaddedHeightElements;
|
||||
UINT32 PaddedDepthOrArraySize;
|
||||
UINT32 WidthElements;
|
||||
UINT32 HeightElements;
|
||||
UINT32 WidthPixels;
|
||||
UINT32 HeightPixels;
|
||||
UINT32 DepthOrArraySize;
|
||||
UINT32 SampleCount;
|
||||
uint32_t SwizzleMode;
|
||||
UINT64 BankRotationAddressBitMask;
|
||||
UINT64 BankRotationBytesPerSlice;
|
||||
UINT32 SliceDepthElements;
|
||||
UINT32 IsMipTail;
|
||||
UINT32 MipTailOffsets;
|
||||
};
|
||||
struct XgPlaneLayout {
|
||||
uint32_t Usage;
|
||||
UINT64 SizeBytes;
|
||||
UINT64 SliceSizeBytes;
|
||||
UINT64 BaseOffsetBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 BytesPerElement;
|
||||
UINT32 StandardMipCount;
|
||||
UINT32 MipTailMipCount;
|
||||
XgMipLevelLayout MipLayout[15];
|
||||
};
|
||||
struct XgResourceLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 MipLevels;
|
||||
UINT32 Planes;
|
||||
XgPlaneLayout Plane[4];
|
||||
uint32_t Dimension;
|
||||
};
|
||||
static_assert(sizeof(XgResourceDesc) == 56 && offsetof(XgResourceDesc, Alignment) == 8, "XG_RESOURCE_DESC");
|
||||
static_assert(sizeof(XgMipLevelLayout) == 112, "XG_MIPLEVEL_LAYOUT");
|
||||
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 {
|
||||
public:
|
||||
virtual ULONG AddRef() = 0;
|
||||
virtual ULONG Release() = 0;
|
||||
virtual HRESULT GetResourceLayout(XgResourceLayout*) = 0;
|
||||
virtual UINT64 GetResourceSizeBytes() = 0;
|
||||
virtual UINT64 GetResourceBaseAlignmentBytes() = 0;
|
||||
virtual UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) = 0;
|
||||
virtual UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z, UINT32 sample,
|
||||
UINT32* bit) = 0;
|
||||
virtual HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y, UINT32* z,
|
||||
UINT32* sample) = 0;
|
||||
virtual HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 sub, const void* linear, UINT32 row_pitch,
|
||||
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 GetTextureViewDescriptor(UINT32, void*) = 0;
|
||||
virtual bool IsTiledResource() = 0;
|
||||
virtual HRESULT GetSwizzlePatternInfo(UINT32, void*) = 0;
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
using CreateFn = HRESULT(WINAPI*)(const XgResourceDesc*, Computer**);
|
||||
using SuggestFn = HRESULT(WINAPI*)(const XgResourceDesc*, uint32_t, uint32_t*);
|
||||
CreateFn g_create = nullptr;
|
||||
|
||||
constexpr uint32_t kTexture2D = 3, kBuffer = 1;
|
||||
constexpr uint32_t kLayoutLinear = 0x100, kLayout64KbS = 0x109, kLayout64KbD = 0x10a;
|
||||
|
||||
XgResourceDesc tex2d(uint32_t format, uint64_t w, uint32_t h, uint16_t mips, uint32_t layout) {
|
||||
XgResourceDesc d{};
|
||||
d.Dimension = kTexture2D;
|
||||
d.Width = w;
|
||||
d.Height = h;
|
||||
d.DepthOrArraySize = 1;
|
||||
d.MipLevels = mips;
|
||||
d.Format = format;
|
||||
d.SampleCount = 1;
|
||||
d.Layout = layout;
|
||||
return d;
|
||||
}
|
||||
|
||||
uint32_t pdep(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; mask; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & bit) out |= lowest;
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void test_linear_mips() {
|
||||
const auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 256, 128, 3, kLayoutLinear);
|
||||
Computer* c = nullptr;
|
||||
check(g_create(&d, &c) == S_OK && c, "linear RGBA8 created");
|
||||
if (!c) return;
|
||||
XgResourceLayout L{};
|
||||
check(c->GetResourceLayout(&L) == S_OK, "linear layout");
|
||||
const auto& m = L.Plane[0].MipLayout;
|
||||
// mip0 1024-byte rows x 128; mip1 512 x 64 at 131072; mip2 256 x 32 at 163840; end 172032.
|
||||
check(L.MipLevels == 3 && L.Planes == 1, "linear mip and plane counts");
|
||||
check(m[0].PitchBytes == 1024 && m[0].OffsetBytes == 0 && m[0].SizeBytes == 131072, "mip0");
|
||||
check(m[1].PitchBytes == 512 && m[1].OffsetBytes == 131072 && m[1].SizeBytes == 32768, "mip1");
|
||||
check(m[2].PitchBytes == 256 && m[2].OffsetBytes == 163840 && m[2].SizeBytes == 8192, "mip2");
|
||||
check(m[0].SwizzleMode == 0 && m[2].SwizzleMode == 0, "linear swizzle mode");
|
||||
check(c->GetResourceSizeBytes() == 196608 && L.SizeBytes == 196608, "linear size rounded to 64 KiB");
|
||||
check(c->GetMipLevelOffsetBytes(0, 2) == 163840, "mip offset");
|
||||
check(c->GetTexelElementOffsetBytes(0, 1, 5, 3, 0, 0, nullptr) == 131072 + 3 * 512 + 5 * 4, "linear texel offset");
|
||||
UINT32 plane = 9, mip = 9, y = 0, z = 9, sample = 9;
|
||||
UINT64 x = 0;
|
||||
check(c->GetTexelCoordinate(131072 + 3 * 512 + 5 * 4, &plane, &mip, &x, &y, &z, &sample) == S_OK && plane == 0 &&
|
||||
mip == 1 && x == 5 && y == 3 && z == 0 && sample == 0,
|
||||
"linear coordinate inverse");
|
||||
std::vector<uint32_t> src(256 * 128), back(256 * 128);
|
||||
for (uint32_t i = 0; i < src.size(); ++i) src[i] = i * 2654435761u;
|
||||
std::vector<uint8_t> mem(c->GetResourceSizeBytes());
|
||||
check(c->CopyIntoSubresource(mem.data(), 0, 0, src.data(), 1024, 1024 * 128) == S_OK, "linear copy into");
|
||||
check(std::memcmp(mem.data() + 7 * 1024, &src[7 * 256], 1024) == 0, "linear copy places row 7");
|
||||
check(c->CopyFromSubresource(back.data(), 0, 0, 0, mem.data(), 1024, 1024 * 128) == S_OK && src == back,
|
||||
"linear copy round trip");
|
||||
c->Release();
|
||||
}
|
||||
|
||||
void test_depth_stencil_bc_buffer() {
|
||||
auto d = tex2d(DXGI_FORMAT_D24_UNORM_S8_UINT, 64, 64, 1, 0);
|
||||
Computer* c = nullptr;
|
||||
check(g_create(&d, &c) == S_OK && c, "D24S8 created");
|
||||
if (c) {
|
||||
XgResourceLayout L{};
|
||||
c->GetResourceLayout(&L);
|
||||
// Depth: 4-byte elements, 256-byte rows, 16 KiB. Stencil: 1-byte elements in its own 64 KiB-aligned plane.
|
||||
check(L.Planes == 2 && L.Plane[0].BytesPerElement == 4 && L.Plane[1].BytesPerElement == 1, "depth/stencil planes");
|
||||
check(L.Plane[0].Usage == 7 && L.Plane[1].Usage == 8, "plane usages depth=7 stencil=8");
|
||||
check(L.Plane[1].BaseOffsetBytes == 65536 && L.Plane[1].MipLayout[0].OffsetBytes == 65536, "stencil plane offset");
|
||||
check(L.SizeBytes == 131072, "depth/stencil size");
|
||||
c->Release();
|
||||
}
|
||||
d = tex2d(DXGI_FORMAT_BC1_UNORM, 64, 64, 1, kLayoutLinear);
|
||||
c = nullptr;
|
||||
check(g_create(&d, &c) == S_OK && c, "BC1 created");
|
||||
if (c) {
|
||||
// 16x16 blocks of 8 bytes: 128-byte rows padded to 256. Texel (8, 4) is block (2, 1).
|
||||
check(c->GetTexelElementOffsetBytes(0, 0, 8, 4, 0, 0, nullptr) == 256 + 16, "BC1 texel offset");
|
||||
c->Release();
|
||||
}
|
||||
XgResourceDesc b{};
|
||||
b.Dimension = kBuffer;
|
||||
b.Width = 1000;
|
||||
b.SampleCount = 1;
|
||||
c = nullptr;
|
||||
check(g_create(&b, &c) == S_OK && c && c->GetResourceSizeBytes() == 65536, "buffer rounded to 64 KiB");
|
||||
if (c) c->Release();
|
||||
}
|
||||
|
||||
void test_64kb_s_32bpp() {
|
||||
const auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 128, 128, 1, kLayout64KbS);
|
||||
Computer* c = nullptr;
|
||||
check(g_create(&d, &c) == S_OK && c, "64KB_S RGBA8 one tile created");
|
||||
if (!c) return;
|
||||
XgResourceLayout L{};
|
||||
c->GetResourceLayout(&L);
|
||||
check(L.Plane[0].MipLayout[0].SwizzleMode == 9, "64KB_S reported as swizzle mode 9");
|
||||
check(c->GetResourceSizeBytes() == 65536 && c->GetResourceBaseAlignmentBytes() >= 65536, "64KB_S one tile");
|
||||
bool all = true, inverse = true;
|
||||
for (uint32_t y = 0; y < 128; ++y) {
|
||||
for (uint32_t x = 0; x < 128; ++x) {
|
||||
const uint64_t want = pdep(x * 4, 0xAA8F) | pdep(y, 0x5570);
|
||||
if (c->GetTexelElementOffsetBytes(0, 0, x, y, 0, 0, nullptr) != want) all = false;
|
||||
UINT64 gx = 0;
|
||||
UINT32 gy = 0;
|
||||
if (c->GetTexelCoordinate(want, nullptr, nullptr, &gx, &gy, nullptr, nullptr) != S_OK || gx != x || gy != y) {
|
||||
inverse = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
check(all, "64KB_S 32bpp offsets equal the D3D12 standard swizzle");
|
||||
check(inverse, "64KB_S coordinate inverse");
|
||||
std::vector<uint32_t> src(128 * 128), back(128 * 128);
|
||||
for (uint32_t y = 0; y < 128; ++y)
|
||||
for (uint32_t x = 0; x < 128; ++x) src[y * 128 + x] = y << 16 | x;
|
||||
std::vector<uint8_t> tile(65536);
|
||||
check(c->CopyIntoSubresource(tile.data(), 0, 0, src.data(), 512, 512 * 128) == S_OK, "64KB_S copy into");
|
||||
uint32_t at = 0;
|
||||
std::memcpy(&at, tile.data() + (pdep(37 * 4, 0xAA8F) | pdep(91, 0x5570)), 4);
|
||||
check(at == (91u << 16 | 37u), "64KB_S copy places texel (37, 91)");
|
||||
check(c->CopyFromSubresource(back.data(), 0, 0, 0, tile.data(), 512, 512 * 128) == S_OK && src == back,
|
||||
"64KB_S copy round trip");
|
||||
c->Release();
|
||||
}
|
||||
|
||||
void test_64kb_s_bc1() {
|
||||
// 512x256 texels = 128x64 blocks of 8 bytes: exactly one tile.
|
||||
const auto d = tex2d(DXGI_FORMAT_BC1_UNORM, 512, 256, 1, kLayout64KbS);
|
||||
Computer* c = nullptr;
|
||||
check(g_create(&d, &c) == S_OK && c, "64KB_S BC1 one tile created");
|
||||
if (!c) return;
|
||||
std::vector<bool> used(65536 / 8, false);
|
||||
bool ok = true;
|
||||
for (uint32_t by = 0; by < 64; ++by) {
|
||||
for (uint32_t bx = 0; bx < 128; ++bx) {
|
||||
const uint64_t off = c->GetTexelElementOffsetBytes(0, 0, bx * 4, by * 4, 0, 0, nullptr);
|
||||
if (off >= 65536 || off % 8 || used[off / 8]) ok = false;
|
||||
else used[off / 8] = true;
|
||||
}
|
||||
}
|
||||
check(ok, "64KB_S BC1 offsets are a bijection of aligned 8-byte slots in the tile");
|
||||
// A BC block is one element: all 16 texels of a block share its byte offset.
|
||||
bool shared = true;
|
||||
for (uint32_t b = 0; b < 4; ++b) {
|
||||
const uint32_t bx = 17 * b + 3, by = 11 * b + 5;
|
||||
const uint64_t base = c->GetTexelElementOffsetBytes(0, 0, bx * 4, by * 4, 0, 0, nullptr);
|
||||
for (uint32_t t = 0; t < 16; ++t) {
|
||||
if (c->GetTexelElementOffsetBytes(0, 0, bx * 4 + t % 4, by * 4 + t / 4, 0, 0, nullptr) != base) shared = false;
|
||||
}
|
||||
}
|
||||
check(shared, "64KB_S BC1 texels of one block share the block's offset");
|
||||
c->Release();
|
||||
}
|
||||
|
||||
void test_64kb_s_128bpp() {
|
||||
// 64x64 elements of 16 bytes: exactly one tile.
|
||||
const auto d = tex2d(DXGI_FORMAT_R32G32B32A32_FLOAT, 64, 64, 1, kLayout64KbS);
|
||||
Computer* c = nullptr;
|
||||
check(g_create(&d, &c) == S_OK && c, "64KB_S 128bpp one tile created");
|
||||
if (!c) return;
|
||||
std::vector<bool> used(65536 / 16, false);
|
||||
bool ok = true;
|
||||
for (uint32_t y = 0; y < 64; ++y) {
|
||||
for (uint32_t x = 0; x < 64; ++x) {
|
||||
const uint64_t off = c->GetTexelElementOffsetBytes(0, 0, x, y, 0, 0, nullptr);
|
||||
if (off >= 65536 || off % 16 || used[off / 16]) ok = false;
|
||||
else used[off / 16] = true;
|
||||
}
|
||||
}
|
||||
check(ok, "64KB_S 128bpp offsets are a bijection of aligned 16-byte slots in the tile");
|
||||
c->Release();
|
||||
}
|
||||
|
||||
// A requested mode this layer does not implement: created, laid out and reported as LINEAR.
|
||||
bool linear_fallback(const XgResourceDesc& d) {
|
||||
Computer* c = nullptr;
|
||||
if (g_create(&d, &c) != S_OK || !c) return false;
|
||||
XgResourceLayout L{};
|
||||
const bool ok = c->GetResourceLayout(&L) == S_OK && L.Plane[0].MipLayout[0].SwizzleMode == 0;
|
||||
c->Release();
|
||||
return ok;
|
||||
}
|
||||
|
||||
void test_refusals_and_suggest(SuggestFn suggest) {
|
||||
Computer* c = nullptr;
|
||||
auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, kLayout64KbS);
|
||||
check(linear_fallback(d), "64KB_S beyond one tile falls back to a reported LINEAR layout");
|
||||
d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 2, kLayout64KbS);
|
||||
check(linear_fallback(d), "64KB_S with two mips falls back to a reported LINEAR layout");
|
||||
d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 1, kLayout64KbD);
|
||||
check(linear_fallback(d), "64KB_D falls back to a reported LINEAR layout (logged)");
|
||||
d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 1, 2); // 64 KB, undefined swizzle: XG chooses
|
||||
check(g_create(&d, &c) == S_OK && c, "undefined-swizzle request accepted");
|
||||
if (c) {
|
||||
XgResourceLayout L{};
|
||||
c->GetResourceLayout(&L);
|
||||
check(L.Plane[0].MipLayout[0].SwizzleMode == 0, "undefined-swizzle request laid out linearly");
|
||||
c->Release();
|
||||
c = nullptr;
|
||||
}
|
||||
check(g_create(nullptr, &c) == E_INVALIDARG && g_create(&d, nullptr) == E_INVALIDARG, "null arguments");
|
||||
uint32_t layout = 0;
|
||||
check(suggest && suggest(&d, 0, &layout) == S_OK && layout == kLayoutLinear, "suggested layout is linear");
|
||||
}
|
||||
|
||||
} // 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");
|
||||
if (!xg) {
|
||||
std::printf("FAIL: test_xg_xbox: xg_xs.dll not loaded\n");
|
||||
return 1;
|
||||
}
|
||||
g_create = reinterpret_cast<CreateFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGCreateTextureComputer")));
|
||||
const auto suggest = reinterpret_cast<SuggestFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGSuggestSwizzleMode")));
|
||||
if (!g_create) {
|
||||
std::printf("FAIL: test_xg_xbox: XGCreateTextureComputer missing\n");
|
||||
return 1;
|
||||
}
|
||||
test_linear_mips();
|
||||
test_depth_stencil_bc_buffer();
|
||||
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 "
|
||||
"standard swizzle, linear fallbacks)\n",
|
||||
g_checks);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
add_executable(test_xg_xs main.cpp)
|
||||
target_include_directories(test_xg_xs PRIVATE
|
||||
"${BX_ABI_INCLUDE_DIR}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../../../shims/xg_xs")
|
||||
target_link_libraries(test_xg_xs PRIVATE xg_xs kernel32)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -396,6 +396,17 @@ std::string utf8(const wchar_t* text) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// The executable's directory in UTF-8, as XPackageGetMountPath reports it: a drive root keeps its
|
||||
// separator ("G:\\" when bx-cli maps the package root to G: and launches from there).
|
||||
std::string executable_directory_utf8() {
|
||||
wchar_t exe_w[MAX_PATH]{};
|
||||
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
|
||||
wchar_t* slash = std::wcsrchr(exe_w, L'\\');
|
||||
CHECK(slash != nullptr);
|
||||
slash[slash == exe_w + 2 && exe_w[1] == L':' ? 1 : 0] = L'\0';
|
||||
return utf8(exe_w);
|
||||
}
|
||||
|
||||
// --- Concurrency ---
|
||||
|
||||
constexpr char kShared[] = "shared/race";
|
||||
@@ -592,10 +603,7 @@ void check_public_dispatch(void* user, void* synthetic_save, void* synthetic_pac
|
||||
CHECK(std::strncmp(id, "BXPKG", 5) == 0 && std::strlen(id) == 21);
|
||||
uint32_t kind = 99;
|
||||
CHECK(slot<GetKindFn>(package, kPkKind)(package, id, &kind) == S_OK && kind == 0);
|
||||
wchar_t exe_w[MAX_PATH]{};
|
||||
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
|
||||
*std::wcsrchr(exe_w, L'\\') = L'\0';
|
||||
const std::string exe_dir = utf8(exe_w);
|
||||
const std::string exe_dir = executable_directory_utf8();
|
||||
void* mount = nullptr;
|
||||
CHECK(slot<MountFn>(package, kPkMount)(package, id, &mount) == S_OK && mount);
|
||||
size_t path_size = 0;
|
||||
@@ -995,10 +1003,7 @@ int main() {
|
||||
CHECK(slot<GetKindFn>(package, kGetKind)(package, "BXPKG0000000000000000", &kind) == kNotFound);
|
||||
|
||||
// The mount path is the executable's directory in UTF-8 (W API, so non-ASCII paths work).
|
||||
wchar_t exe_w[MAX_PATH]{};
|
||||
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
|
||||
*std::wcsrchr(exe_w, L'\\') = L'\0';
|
||||
const std::string exe_dir = utf8(exe_w);
|
||||
const std::string exe_dir = executable_directory_utf8();
|
||||
void* mount = nullptr;
|
||||
CHECK(slot<MountFn>(package, kMount)(package, "BXPKG0000000000000000", &mount) == kNotFound && !mount);
|
||||
CHECK(slot<MountFn>(package, kMount)(package, id, &mount) == S_OK && mount);
|
||||
@@ -1016,6 +1021,107 @@ 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");
|
||||
@@ -1066,6 +1172,11 @@ 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);
|
||||
|
||||
@@ -12,13 +12,16 @@ PVOID WINAPI XMemAlloc(SIZE_T, uint64_t);
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFree(PVOID, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
SIZE_T WINAPI XMemVirtualQuery(LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T);
|
||||
BOOL WINAPI XMemTransferMemory(PVOID, LPCVOID, SIZE_T, uint64_t);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
BOOL WINAPI XMemIsToolsMemAvailable();
|
||||
}
|
||||
|
||||
/* XMEM_CPU from the authorized GDK documentation of XMemVirtualAlloc. */
|
||||
constexpr uint64_t kXMemCpu = 0x1;
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
@@ -68,17 +71,17 @@ int main() {
|
||||
CHECK(!XMemAllocDefault(stats.title_limit_bytes, 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, stats.title_limit_bytes,
|
||||
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
MEM_COMMIT | MEM_RESERVE, kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
|
||||
XMemFreeDefault(empty, 0);
|
||||
XMemFree(ordinary, 0);
|
||||
|
||||
auto* reserved = static_cast<unsigned char*>(
|
||||
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, PAGE_READWRITE));
|
||||
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(reserved && reinterpret_cast<uintptr_t>(reserved) % page == 0);
|
||||
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, PAGE_READWRITE) == reserved);
|
||||
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, PAGE_READWRITE)
|
||||
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, kXMemCpu, PAGE_READWRITE) == reserved);
|
||||
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, kXMemCpu, PAGE_READWRITE)
|
||||
== reserved + page);
|
||||
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
@@ -100,11 +103,15 @@ int main() {
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.committed_virtual_bytes == 0 && stats.peak_committed_bytes == page * 3);
|
||||
|
||||
// Console callers pass multi-bit attributes (e.g. 0x21) in arg 4 and high bits in alloc_type.
|
||||
// Documented form: XMem flags in argument 4, page protection in argument 5, and a page-size
|
||||
// bit (MEM_64K_PAGES, 0x20400000) in the allocation type.
|
||||
auto* console_res = static_cast<unsigned char*>(
|
||||
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, 0x21u));
|
||||
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(console_res != nullptr);
|
||||
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, 0x21u) == console_res);
|
||||
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, kXMemCpu, PAGE_READWRITE) == console_res);
|
||||
MEMORY_BASIC_INFORMATION console_region{};
|
||||
CHECK(VirtualQuery(console_res, &console_region, sizeof(console_region)));
|
||||
CHECK(console_region.Protect == PAGE_READWRITE);
|
||||
console_res[0] = 0x5Au;
|
||||
CHECK(console_res[0] == 0x5Au);
|
||||
CHECK(VirtualFree(console_res, 0, MEM_RELEASE));
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ int main() {
|
||||
|
||||
// ...and a later XMem commit is refused against the same cap.
|
||||
SetLastError(0);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
CHECK(!XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, 0x1 /* XMEM_CPU */, PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
|
||||
// An over-release is refused and leaves the outstanding charge in place.
|
||||
@@ -62,7 +62,7 @@ int main() {
|
||||
bx_xmem_release_charge_external(headroom);
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.committed_virtual_bytes + stats.allocated_physical_bytes == used);
|
||||
void* block = XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
void* block = XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, 0x1 /* XMEM_CPU */, PAGE_READWRITE);
|
||||
CHECK(block != nullptr);
|
||||
CHECK(VirtualFree(block, 0, MEM_RELEASE));
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_xmem_hooks main.cpp)
|
||||
target_link_libraries(test_xmem_hooks PRIVATE xmem kernel32)
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* XMEM_SET_ALLOCATION_HOOKS (authorized GDK documentation, xmem.h): a title exports
|
||||
* `__XMemAllocationHooks__ = { AllocRoutine, FreeRoutine }` and XMemAlloc / XMemFree call them.
|
||||
* This program is such a title: its hook serves one object type from its own buffer and passes
|
||||
* everything else to XMemAllocDefault / XMemFreeDefault.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
extern "C" {
|
||||
__declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
__declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
__declspec(dllimport) PVOID WINAPI XMemAllocDefault(SIZE_T size, ULONGLONG attributes);
|
||||
__declspec(dllimport) VOID WINAPI XMemFreeDefault(PVOID address, ULONGLONG attributes);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kObjectTypeMask = 0x3fff; // XALLOC_ATTRIBUTES.ObjectType, bits 0-13
|
||||
constexpr ULONGLONG kServedType = 4;
|
||||
alignas(64) unsigned char g_reserved[4096];
|
||||
int g_allocs = 0;
|
||||
int g_frees = 0;
|
||||
|
||||
PVOID WINAPI alloc_hook(SIZE_T size, ULONGLONG attributes) {
|
||||
++g_allocs;
|
||||
if ((attributes & kObjectTypeMask) == kServedType && size <= sizeof(g_reserved)) return g_reserved;
|
||||
return XMemAllocDefault(size, attributes);
|
||||
}
|
||||
|
||||
VOID WINAPI free_hook(PVOID address, ULONGLONG attributes) {
|
||||
++g_frees;
|
||||
if (address != g_reserved) XMemFreeDefault(address, attributes);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct AllocationHooks {
|
||||
PVOID (WINAPI* alloc)(SIZE_T, ULONGLONG);
|
||||
VOID (WINAPI* free)(PVOID, ULONGLONG);
|
||||
};
|
||||
extern "C" __declspec(dllexport) AllocationHooks __XMemAllocationHooks__ = {alloc_hook, free_hook};
|
||||
|
||||
int main() {
|
||||
int failed = 0;
|
||||
auto check = [&](bool ok, const char* what) {
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "FAIL: test_xmem_hooks: %s\n", what);
|
||||
++failed;
|
||||
}
|
||||
};
|
||||
const ULONGLONG allocator_d3d = 128ull << 16; // AllocatorId, bits 16-23
|
||||
void* served = XMemAlloc(256, allocator_d3d | kServedType);
|
||||
check(served == g_reserved, "XMemAlloc goes through the title's AllocRoutine");
|
||||
void* passed = XMemAlloc(256, allocator_d3d | 1);
|
||||
check(passed && passed != g_reserved, "the hook passes other object types to XMemAllocDefault");
|
||||
check(g_allocs == 2, "both XMemAlloc calls reached the hook");
|
||||
XMemFree(served, allocator_d3d | kServedType);
|
||||
XMemFree(passed, allocator_d3d | 1);
|
||||
check(g_frees == 2, "XMemFree goes through the title's FreeRoutine");
|
||||
void* direct = XMemAllocDefault(64, 0);
|
||||
check(direct && g_allocs == 2, "XMemAllocDefault does not call the hook");
|
||||
XMemFreeDefault(direct, 0);
|
||||
if (failed) return 1;
|
||||
std::printf("PASS: test_xmem_hooks\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* Physical pages in xmem.dll, against the signatures and rules of the authorized GDK
|
||||
* documentation: XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray) in 64 KB pages,
|
||||
* XMemFreePhysicalPages(NumberOfPages, PageArray), XMemMapPhysicalPages(VirtualAddress,
|
||||
* NumberOfPages, PageArray) and XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages,
|
||||
* PageArray), mapping into XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)
|
||||
* reservations. The constants below are written out from that documentation.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
@@ -8,13 +16,28 @@
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemMapPhysicalPagesScatter(PVOID*, ULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr SIZE_T kPage = 64 * 1024;
|
||||
constexpr DWORD kMem64KPages = 0x20400000;
|
||||
constexpr DWORD kMem2MBPages = 0x20000000;
|
||||
constexpr uint64_t kXMemCpu = 0x1;
|
||||
constexpr uint64_t kXMemMappable = 0x20;
|
||||
constexpr uint64_t kXMem2MBClusters = 0x20000000;
|
||||
constexpr uint64_t kXMemGpuOptimalBandwidthRequired = 0x280;
|
||||
constexpr uint64_t kXMemGraphics32BitAddress = 0x7;
|
||||
constexpr DWORD kMemReservePlaceholder = 0x40000;
|
||||
constexpr DWORD kMemReplacePlaceholder = 0x4000;
|
||||
constexpr DWORD kPageGraphicsReadWrite = 0x2000;
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
@@ -24,124 +47,183 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
bool check_aliases(SIZE_T page_size, uint64_t flags) {
|
||||
DWORD state_of(const void* address) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
return VirtualQuery(address, ®ion, sizeof(region)) ? region.State : 0;
|
||||
}
|
||||
|
||||
bool check_physical_pages() {
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
|
||||
SIZE_T count = 2;
|
||||
ULONG_PTR pages[2]{};
|
||||
// Invalid flags must be rejected cleanly before touching stats or tags.
|
||||
CHECK(!XMemAllocatePhysicalPages(&count, pages, 0x12345));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
// Flags outside 2 MB clusters and the bandwidth values are refused before anything changes.
|
||||
ULONG_PTR count = 4;
|
||||
ULONG_PTR pages[4]{};
|
||||
CHECK(!XMemAllocatePhysicalPages(0x12345, &count, pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && count == 4 && !pages[0]);
|
||||
CHECK(!XMemAllocatePhysicalPages(kXMem2MBClusters, &count, pages));
|
||||
CHECK(GetLastError() == ERROR_NOT_SUPPORTED && !pages[0]);
|
||||
|
||||
CHECK(XMemAllocatePhysicalPages(&count, pages, flags));
|
||||
CHECK(count == 2 && pages[0] && pages[1] && pages[0] != pages[1]);
|
||||
|
||||
// Working-set statistics and internal stats must both reflect physical pages.
|
||||
// A bandwidth value is accepted; pages are 64 KB and counted against the title budget.
|
||||
CHECK(XMemAllocatePhysicalPages(kXMemGpuOptimalBandwidthRequired, &count, pages));
|
||||
CHECK(count == 4 && pages[0] && pages[1] && pages[2] && pages[3]);
|
||||
CHECK(pages[0] != pages[1] && pages[1] != pages[2] && pages[2] != pages[3]);
|
||||
// Page numbers count 4 KiB frames, so a 64 KiB page's number is a multiple of 16 (target-build
|
||||
// observation: callers keep number >> 4 and rebuild it with << 4). Distinct pages must stay
|
||||
// distinct after that shift: consecutive numbers collapsed 16 pages into one.
|
||||
for (int i = 0; i < 4; ++i) CHECK(pages[i] % 16 == 0 && ((pages[i] >> 4) << 4) == pages[i]);
|
||||
CHECK((pages[0] >> 4) != (pages[1] >> 4) && (pages[1] >> 4) != (pages[2] >> 4) && (pages[2] >> 4) != (pages[3] >> 4));
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
CHECK(stats.peak_committed_bytes >= count * page_size);
|
||||
CHECK(stats.allocated_physical_bytes == 4 * kPage);
|
||||
bx_xmem_stats_t ws_stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&ws_stats, sizeof(ws_stats)));
|
||||
CHECK(ws_stats.allocated_physical_bytes == count * page_size);
|
||||
CHECK(ws_stats.allocated_physical_bytes == 4 * kPage);
|
||||
|
||||
// Shared title budget cap: existing physical pages must block both full-cap
|
||||
// physical and full-cap heap allocations without allocating gigabytes.
|
||||
SIZE_T cap_pages = static_cast<SIZE_T>(stats.title_limit_bytes / page_size);
|
||||
CHECK(!XMemAllocatePhysicalPages(&cap_pages, pages, flags));
|
||||
ULONG_PTR cap_pages = static_cast<ULONG_PTR>(stats.title_limit_bytes / kPage);
|
||||
CHECK(!XMemAllocatePhysicalPages(0, &cap_pages, pages));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemAllocDefault(static_cast<SIZE_T>(stats.title_limit_bytes), 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, 0x12345, pages));
|
||||
// A mappable reservation stays reserved, uncommitted, until pages are mapped into it.
|
||||
auto* base = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, 8 * kPage, MEM_RESERVE | kMem64KPages,
|
||||
kXMemMappable | kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(base && reinterpret_cast<uintptr_t>(base) % kPage == 0);
|
||||
CHECK(state_of(base) == MEM_RESERVE && state_of(base + 7 * kPage) == MEM_RESERVE);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT | kMem64KPages, kXMemMappable,
|
||||
PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
auto* linear = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, count, flags, pages));
|
||||
CHECK(linear && reinterpret_cast<uintptr_t>(linear) % page_size == 0);
|
||||
ULONG_PTR reversed[] = {pages[1], pages[0]};
|
||||
auto* scatter = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, reversed));
|
||||
CHECK(scatter && scatter != linear && reinterpret_cast<uintptr_t>(scatter) % page_size == 0);
|
||||
// Map four pages, then alias them in reverse order in the next four slots.
|
||||
CHECK(XMemMapPhysicalPages(base, 4, pages) == base);
|
||||
for (int i = 0; i < 4; ++i) base[i * kPage + 9] = static_cast<BYTE>(0x40 + i);
|
||||
ULONG_PTR reversed[] = {pages[3], pages[2], pages[1], pages[0]};
|
||||
CHECK(XMemMapPhysicalPages(base + 4 * kPage, 4, reversed) == base + 4 * kPage);
|
||||
CHECK(base[4 * kPage + 9] == 0x43 && base[7 * kPage + 9] == 0x40);
|
||||
base[5 * kPage + 1] = 0x7e;
|
||||
CHECK(base[2 * kPage + 1] == 0x7e);
|
||||
|
||||
linear[7] = 0x41;
|
||||
linear[page_size + 7] = 0x73;
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
scatter[page_size + 30] = 0xf2;
|
||||
CHECK(linear[30] == 0xf2);
|
||||
bx_xmem_region_info_t info{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(base + 4 * kPage + 3), &info));
|
||||
CHECK(info.base_va == reinterpret_cast<uintptr_t>(base + 4 * kPage) && info.physical_tag == pages[3]);
|
||||
CHECK(info.size_bytes == kPage && info.protect_flags == PAGE_READWRITE && info.mem_type_flags == MEM_MAPPED);
|
||||
|
||||
// Duplicate tags are valid when mapping (intra-span ring-buffer/tile aliasing).
|
||||
ULONG_PTR dup_map[] = {pages[0], pages[0]};
|
||||
auto* dup_view = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, dup_map));
|
||||
CHECK(dup_view && reinterpret_cast<uintptr_t>(dup_view) % page_size == 0);
|
||||
dup_view[13] = 0x9b;
|
||||
CHECK(dup_view[page_size + 13] == 0x9b && linear[13] == 0x9b);
|
||||
bx_xmem_region_info_t dup0{};
|
||||
bx_xmem_region_info_t dup1{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view + page_size), &dup1));
|
||||
CHECK(dup0.physical_tag == pages[0] && dup1.physical_tag == pages[0]);
|
||||
CHECK(XMemMapPhysicalPagesScatter(dup_view, count, flags, nullptr) == dup_view);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
// Mapping over mapped pages replaces them.
|
||||
CHECK(XMemMapPhysicalPages(base, 4, reversed) == base);
|
||||
CHECK(base[9] == 0x43 && base[3 * kPage + 9] == 0x40);
|
||||
|
||||
bx_xmem_region_info_t first{};
|
||||
bx_xmem_region_info_t alias{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear + 7), &first));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter + page_size + 7), &alias));
|
||||
CHECK(first.base_va == reinterpret_cast<uintptr_t>(linear));
|
||||
CHECK(alias.base_va == reinterpret_cast<uintptr_t>(scatter + page_size));
|
||||
CHECK(alias.physical_tag == first.physical_tag && first.physical_tag == pages[0]);
|
||||
CHECK(first.size_bytes == page_size && alias.page_size_bytes == page_size);
|
||||
CHECK(first.protect_flags == PAGE_READWRITE && first.mem_type_flags == MEM_MAPPED);
|
||||
// A NULL page array unmaps; the range stays reserved and can be mapped again.
|
||||
CHECK(XMemMapPhysicalPages(base, 4, nullptr) == base);
|
||||
CHECK(state_of(base) == MEM_RESERVE && !bx_xmem_query_region(reinterpret_cast<uintptr_t>(base), &info));
|
||||
CHECK(base[4 * kPage + 9] == 0x43);
|
||||
CHECK(XMemMapPhysicalPages(base, 4, pages) == base);
|
||||
CHECK(base[9] == 0x40);
|
||||
|
||||
// Rejected frees (stale or duplicate tags) must fail without modifying
|
||||
// page_array or disturbing live mappings.
|
||||
// Mapping outside a mappable reservation is refused.
|
||||
void* plain = VirtualAlloc(nullptr, kPage, MEM_RESERVE, PAGE_NOACCESS);
|
||||
CHECK(plain && !XMemMapPhysicalPages(plain, 1, pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
VirtualFree(plain, 0, MEM_RELEASE);
|
||||
|
||||
// Scatter: parallel arrays of slots and tags; a 0 tag unmaps its slot.
|
||||
PVOID slots[] = {base + 7 * kPage, base + 6 * kPage};
|
||||
ULONG_PTR scatter_pages[] = {pages[0], 0};
|
||||
CHECK(XMemMapPhysicalPagesScatter(slots, 2, scatter_pages));
|
||||
CHECK(base[7 * kPage + 9] == 0x40 && state_of(base + 6 * kPage) == MEM_RESERVE);
|
||||
// One bad slot refuses the whole call before anything changes.
|
||||
PVOID bad_slots[] = {base + 6 * kPage, base + 1};
|
||||
ULONG_PTR bad_pages[] = {pages[1], pages[2]};
|
||||
CHECK(!XMemMapPhysicalPagesScatter(bad_slots, 2, bad_pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && state_of(base + 6 * kPage) == MEM_RESERVE);
|
||||
CHECK(!XMemMapPhysicalPagesScatter(nullptr, 1, bad_pages));
|
||||
CHECK(XMemMapPhysicalPagesScatter(slots, 2, nullptr));
|
||||
CHECK(state_of(base + 7 * kPage) == MEM_RESERVE);
|
||||
|
||||
// Frees with stale or duplicate tags fail without changing the array or live mappings.
|
||||
ULONG_PTR stale[] = {pages[0], 0};
|
||||
CHECK(!XMemFreePhysicalPages(&count, stale, flags));
|
||||
CHECK(!XMemFreePhysicalPages(2, stale));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && stale[0] == pages[0] && stale[1] == 0);
|
||||
CHECK(linear[7] == 0x41);
|
||||
ULONG_PTR dup_free[] = {pages[0], pages[0]};
|
||||
CHECK(!XMemFreePhysicalPages(&count, dup_free, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER
|
||||
&& dup_free[0] == pages[0] && dup_free[1] == pages[0]);
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
CHECK(!XMemFreePhysicalPages(2, dup_free));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && base[9] == 0x40);
|
||||
|
||||
CHECK(!XMemMapPhysicalPagesScatter(nullptr, count, flags, stale));
|
||||
// Freeing unmaps every view of the pages and leaves the reservation reserved.
|
||||
CHECK(XMemFreePhysicalPages(4, pages));
|
||||
CHECK(!pages[0] && !pages[3]);
|
||||
CHECK(state_of(base) == MEM_RESERVE && state_of(base + 4 * kPage) == MEM_RESERVE);
|
||||
CHECK(!XMemMapPhysicalPages(base, 4, reversed));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(!XMemMapPhysicalPages(linear, count, flags, pages));
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
// Partial/over-wide unmap must fail cleanly and leave mapped pages intact.
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count + 1, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
|
||||
// Exact unmap succeeds; repeating unmap on the now-empty span must fail.
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr) == scatter);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, reversed) == scatter);
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
CHECK(XMemFreePhysicalPages(&count, pages, flags));
|
||||
CHECK(!pages[0] && !pages[1]);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear), &first));
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, flags, reversed));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
CHECK(VirtualFree(base, 0, MEM_RELEASE));
|
||||
|
||||
// 2 MB-page reservations exist, but mapping into them is not implemented.
|
||||
ULONG_PTR one = 1;
|
||||
ULONG_PTR page[1]{};
|
||||
CHECK(XMemAllocatePhysicalPages(0, &one, page));
|
||||
auto* large = XMemVirtualAlloc(nullptr, 2 * 1024 * 1024, MEM_RESERVE | kMem2MBPages, kXMemMappable,
|
||||
PAGE_READWRITE);
|
||||
CHECK(large && reinterpret_cast<uintptr_t>(large) % (2 * 1024 * 1024) == 0);
|
||||
CHECK(!XMemMapPhysicalPages(large, 1, page));
|
||||
CHECK(GetLastError() == ERROR_NOT_SUPPORTED);
|
||||
VirtualFree(large, 0, MEM_RELEASE);
|
||||
|
||||
// A title can manage the placeholder itself: reserve one below 4 GB, split it with VirtualFree
|
||||
// and MEM_PRESERVE_PLACEHOLDER, turn one part into a mappable range with MEM_REPLACE_PLACEHOLDER
|
||||
// (with GPU protection bits the host ignores) and map pages into it.
|
||||
auto* region = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE | kMemReservePlaceholder,
|
||||
kXMemGraphics32BitAddress, PAGE_NOACCESS));
|
||||
CHECK(region && reinterpret_cast<uintptr_t>(region) + 4 * kPage <= 0x100000000ull);
|
||||
CHECK(VirtualFree(region, 2 * kPage, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER));
|
||||
auto* part = static_cast<BYTE*>(XMemVirtualAlloc(region, 2 * kPage,
|
||||
MEM_RESERVE | kMemReplacePlaceholder | kMem64KPages,
|
||||
kXMemMappable | kXMemGraphics32BitAddress,
|
||||
PAGE_READWRITE | kPageGraphicsReadWrite));
|
||||
CHECK(part == region);
|
||||
ULONG_PTR two = 2;
|
||||
ULONG_PTR part_pages[2]{};
|
||||
CHECK(XMemAllocatePhysicalPages(kXMemGpuOptimalBandwidthRequired, &two, part_pages));
|
||||
CHECK(XMemMapPhysicalPages(part, 2, part_pages) == part);
|
||||
part[kPage + 5] = 0x6c;
|
||||
CHECK(part[kPage + 5] == 0x6c && state_of(part) == MEM_COMMIT);
|
||||
CHECK(state_of(region + 2 * kPage) == MEM_RESERVE);
|
||||
// Replacing a range that is not a placeholder fails.
|
||||
CHECK(!XMemVirtualAlloc(part, kPage, MEM_RESERVE | kMemReplacePlaceholder | kMem64KPages, kXMemMappable,
|
||||
PAGE_READWRITE));
|
||||
CHECK(XMemFreePhysicalPages(2, part_pages));
|
||||
CHECK(state_of(part) == MEM_RESERVE);
|
||||
|
||||
// The public samples' shape: physical pages allocated with MEM_64K_PAGES (MEM_2MB_PAGES |
|
||||
// MEM_PHYSICAL, so it is not XMEM_2MB_CLUSTERS) mapped into a mappable reservation made with
|
||||
// PAGE_READWRITE | PAGE_WRITECOMBINE | PAGE_GRAPHICS_READWRITE (0x2404).
|
||||
auto* sample = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, kPage, MEM_RESERVE | kMem64KPages, kXMemMappable,
|
||||
PAGE_READWRITE | PAGE_WRITECOMBINE | kPageGraphicsReadWrite));
|
||||
CHECK(sample != nullptr);
|
||||
ULONG_PTR one_64k = 1;
|
||||
ULONG_PTR page_64k[1]{};
|
||||
CHECK(XMemAllocatePhysicalPages(kMem64KPages, &one_64k, page_64k) && page_64k[0]);
|
||||
CHECK(sample && XMemMapPhysicalPages(sample, 1, page_64k) == sample);
|
||||
if (sample) {
|
||||
sample[kPage - 1] = 0x5d;
|
||||
CHECK(sample[kPage - 1] == 0x5d && state_of(sample) == MEM_COMMIT);
|
||||
}
|
||||
CHECK(XMemFreePhysicalPages(1, page_64k));
|
||||
|
||||
// BetterXen extension: a NULL address picks a span; unmapping it frees it.
|
||||
auto* picked = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, 1, page));
|
||||
CHECK(picked && reinterpret_cast<uintptr_t>(picked) % kPage == 0);
|
||||
picked[0] = 0x5a;
|
||||
CHECK(XMemMapPhysicalPages(picked, 1, nullptr) == picked);
|
||||
CHECK(state_of(picked) == MEM_FREE);
|
||||
CHECK(XMemFreePhysicalPages(1, page));
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
if (!check_aliases(64 * 1024, 0) || !check_aliases(2 * 1024 * 1024, 2 * 1024 * 1024)) {
|
||||
if (!check_physical_pages()) {
|
||||
return 1;
|
||||
}
|
||||
std::puts("test_xmem_physical: passed");
|
||||
|
||||
Reference in new issue
Block a user