mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 09:31:11 +00:00
Compare commits
169
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2d153605d | ||
|
|
4a34ec3e50 | ||
|
|
2e96d93439 | ||
|
|
30e666b86c | ||
|
|
41bc72887b | ||
|
|
c206a3f85d | ||
|
|
c893436269 | ||
|
|
00b8344a40 | ||
|
|
451c6308c0 | ||
|
|
4d69562b59 | ||
|
|
656eff8459 | ||
|
|
3ba0eb20d5 | ||
|
|
8a00743d99 | ||
|
|
ce1940d84c | ||
|
|
bd744727bd | ||
|
|
b141c4b261 | ||
|
|
c7a4b4cf19 | ||
|
|
b88ea24a30 | ||
|
|
b2ae7a604e | ||
|
|
901b68ffba | ||
|
|
3eb8900442 | ||
|
|
335e3e4d60 | ||
|
|
c345ada8e9 | ||
|
|
3154497424 | ||
|
|
6eaf8faa95 | ||
|
|
3c1ee93df5 | ||
|
|
87a03d0421 | ||
|
|
bf9dd7b383 | ||
|
|
b59696975a | ||
|
|
43bb5636bf | ||
|
|
b7a660d4b9 | ||
|
|
10f78645cb | ||
|
|
8c4610b51c | ||
|
|
3b1d168de7 | ||
|
|
7a380bd3d7 | ||
|
|
931c09c6af | ||
|
|
186836e1d6 | ||
|
|
133ffd4c97 | ||
|
|
0d9997ce66 | ||
|
|
bfbc84d251 | ||
|
|
e96de7c455 | ||
|
|
4b2985114a | ||
|
|
fe749b1436 | ||
|
|
b76066eafb | ||
|
|
b7bb7615d8 | ||
|
|
2b2a9e15a6 | ||
|
|
3c65b393a4 | ||
|
|
67f3b618ab | ||
|
|
b0e40e29ea | ||
|
|
90dc310b61 | ||
|
|
4bf52b14a3 | ||
|
|
bc7b622018 | ||
|
|
d8fea7b351 | ||
|
|
fe50a8edff | ||
|
|
d47eac809f | ||
|
|
8db5552e32 | ||
|
|
297251fb00 | ||
|
|
030c63f8c9 | ||
|
|
9a6f71abbc | ||
|
|
ad4bcc66b1 | ||
|
|
3d244ddcb0 | ||
|
|
b29ccc60e1 | ||
|
|
5f8235f607 | ||
|
|
c1b3edf9ba | ||
|
|
1eecf6a20c | ||
|
|
ceaad9aee9 | ||
|
|
6bf2b9ab95 | ||
|
|
527cd6208f | ||
|
|
93a1f12bc6 | ||
|
|
32b371e55f | ||
|
|
e48454bdd3 | ||
|
|
55dfa39600 | ||
|
|
c39d33821e | ||
|
|
e17a8281eb | ||
|
|
355197c4ac | ||
|
|
01ef819910 | ||
|
|
085e0d450e | ||
|
|
2d2ee990a7 | ||
|
|
1f3e45eaf7 | ||
|
|
a4742dd137 | ||
|
|
d5eb5ae97d | ||
|
|
2fc6c16f9d | ||
|
|
cb6688c836 | ||
|
|
f1db93e2b4 | ||
|
|
71fa30c29b | ||
|
|
050b0b279c | ||
|
|
162ed81eaf | ||
|
|
dcd0a5127d | ||
|
|
f644569578 | ||
|
|
5b015a2b9e | ||
|
|
2549d724dd | ||
|
|
9bcb121322 | ||
|
|
48378f8c35 | ||
|
|
88e6cf00b9 | ||
|
|
0521ea0c6c | ||
|
|
ce23d0b2b9 | ||
|
|
d17525c165 | ||
|
|
3cfb9ed690 | ||
|
|
51ac3bd766 | ||
|
|
e816c16495 | ||
|
|
076b354d61 | ||
|
|
0bd188e602 | ||
|
|
b86be87576 | ||
|
|
62290b2f21 | ||
|
|
d93a3f3084 | ||
|
|
30c071845f | ||
|
|
781f473ea3 | ||
|
|
6b83bbbd8b | ||
|
|
9f81aadc49 | ||
|
|
724347fd98 | ||
|
|
6f588bc862 | ||
|
|
74fffaa350 | ||
|
|
23de596a23 | ||
|
|
00e1b2fce9 | ||
|
|
846690befc | ||
|
|
04ad81ee26 | ||
|
|
e0f8b0e8f6 | ||
|
|
2fc82c4d58 | ||
|
|
c33199264a | ||
|
|
82ec02e754 | ||
|
|
6cd94140b1 | ||
|
|
c08571ac74 | ||
|
|
d57aba26b9 | ||
|
|
de0d5bd7d9 | ||
|
|
f48c42fd20 | ||
|
|
2217eb83a1 | ||
|
|
63f5640a99 | ||
|
|
0f5a2ab6fd | ||
|
|
56a27dfd80 | ||
|
|
8d904a7f69 | ||
|
|
1300eb7892 | ||
|
|
1894ef23b7 | ||
|
|
989abbdc2c | ||
|
|
140dce0be1 | ||
|
|
1b25f3422b | ||
|
|
766055e948 | ||
|
|
494e53b8fb | ||
|
|
54b87f613c | ||
|
|
bbd3b8a9d4 | ||
|
|
32d02efc33 | ||
|
|
ac82a55039 | ||
|
|
e40d7293f8 | ||
|
|
981bd3c64e | ||
|
|
63b5f5dac6 | ||
|
|
6484cb70a3 | ||
|
|
87da1752ad | ||
|
|
1bc42fcaec | ||
|
|
25ceb05230 | ||
|
|
2bc97a4f68 | ||
|
|
f2efeaf79d | ||
|
|
ab81b0beca | ||
|
|
b16797f576 | ||
|
|
3409bf4ec0 | ||
|
|
420c2329b7 | ||
|
|
ae869522ce | ||
|
|
6e3ef5459b | ||
|
|
bec15f43b6 | ||
|
|
7dde71e2fd | ||
|
|
33d439f828 | ||
|
|
a27284ab26 | ||
|
|
311f4124fa | ||
|
|
46a6a4baca | ||
|
|
8245c30b56 | ||
|
|
be647332cb | ||
|
|
fbd2f8cf43 | ||
|
|
6a1451b265 | ||
|
|
c64534fb21 | ||
|
|
b096424f33 | ||
|
|
f2af367da6 |
No files matched your search
@@ -29,6 +29,8 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Unit-test the hygiene checks
|
||||
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
|
||||
+98
-1
@@ -9,19 +9,97 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- `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
|
||||
- `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.
|
||||
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
|
||||
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
|
||||
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
|
||||
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
|
||||
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
|
||||
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
|
||||
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
|
||||
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- 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.
|
||||
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
|
||||
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
|
||||
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
|
||||
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
|
||||
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
|
||||
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
|
||||
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
|
||||
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
|
||||
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
|
||||
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
|
||||
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
|
||||
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
|
||||
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
|
||||
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
|
||||
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
|
||||
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
|
||||
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
|
||||
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
|
||||
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
|
||||
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
|
||||
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
|
||||
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
|
||||
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
|
||||
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
|
||||
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
|
||||
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
|
||||
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
|
||||
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
|
||||
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
|
||||
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
|
||||
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
|
||||
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
|
||||
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
|
||||
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
|
||||
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
|
||||
- **Not included:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source. Provenance is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
|
||||
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
|
||||
- `bx-cli`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
|
||||
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
|
||||
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
|
||||
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
|
||||
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
|
||||
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
|
||||
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
|
||||
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
|
||||
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
|
||||
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
|
||||
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
|
||||
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
|
||||
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
|
||||
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
|
||||
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
|
||||
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
|
||||
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
|
||||
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
|
||||
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
|
||||
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
|
||||
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
|
||||
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
|
||||
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
|
||||
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
|
||||
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
|
||||
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
|
||||
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
|
||||
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
|
||||
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
|
||||
@@ -69,6 +147,11 @@ remains unsupported.
|
||||
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
|
||||
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
|
||||
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
|
||||
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
|
||||
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
|
||||
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
|
||||
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
|
||||
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
|
||||
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
|
||||
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
|
||||
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
|
||||
@@ -149,7 +232,21 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
|
||||
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
|
||||
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
|
||||
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
|
||||
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
|
||||
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
|
||||
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
|
||||
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
|
||||
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
|
||||
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
|
||||
- `bx-cli`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
|
||||
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
|
||||
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
|
||||
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
|
||||
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
|
||||
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
|
||||
|
||||
@@ -211,7 +211,9 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads the 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine. It does **not** load `bx_shader_bridge.dll`; the Rust bridge is exercised by `test_shader_gate.exe` instead.
|
||||
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
|
||||
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
|
||||
- **Not yet implemented (M1–M6):**
|
||||
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
|
||||
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
|
||||
|
||||
@@ -15,3 +15,5 @@ EXPORTS
|
||||
XMemVirtualQuery
|
||||
bx_xmem_query_region
|
||||
bx_xmem_get_internal_stats
|
||||
bx_xmem_try_charge_external
|
||||
bx_xmem_release_charge_external
|
||||
@@ -33,9 +33,24 @@ typedef struct bx_xmem_stats {
|
||||
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
|
||||
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
|
||||
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
|
||||
* committed_virtual_bytes includes bytes admitted through
|
||||
* bx_xmem_try_charge_external(), so committed + physical is everything the
|
||||
* cap counts and peak_committed_bytes never exceeds what was reported. */
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
|
||||
|
||||
/* Admit `bytes` against the combined title cap, counting every owner.
|
||||
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
|
||||
* bookkeeping could not be refreshed (logged as external_charge). On success the
|
||||
* caller owns the charge and must release it exactly once with
|
||||
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
|
||||
int bx_xmem_try_charge_external(uint64_t bytes);
|
||||
|
||||
/* Release a charge previously admitted by bx_xmem_try_charge_external().
|
||||
* Releasing more than is outstanding is refused: the counter is left
|
||||
* unchanged and an external_charge error is logged. */
|
||||
void bx_xmem_release_charge_external(uint64_t bytes);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+1
-1
@@ -31,6 +31,6 @@
|
||||
|
||||
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
|
||||
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
|
||||
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
|
||||
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
|
||||
@@ -64,9 +64,9 @@ Revisit this ADR in any of these cases:
|
||||
## Consequences
|
||||
|
||||
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
|
||||
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
|
||||
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
|
||||
- **Not covered by the gate yet:**
|
||||
- **Stream PSOs:** `ID3D12Device2::CreatePipelineState` stream descriptions are still forwarded unparsed.
|
||||
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
|
||||
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
|
||||
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
|
||||
|
||||
@@ -1,4 +1,30 @@
|
||||
# Source review is distinct from a Xenora test run.
|
||||
#
|
||||
# Evidence classes (derived from existing usage; claim classes are unchanged):
|
||||
# A — Executed measurement on a named Apple Silicon host, with an independent
|
||||
# CPU/reference expectation. Valid only for the named host/software versions;
|
||||
# implementer-run unless independently reproduced. Never Xbox verification.
|
||||
# B — Source-derived semantics from a public vendor specification, scoped to the
|
||||
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
|
||||
# exercised by synthetic tests, but does not establish console applicability.
|
||||
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
|
||||
# without console execution. Establishes only what the reviewed source states.
|
||||
# E — Public tool/format documentation or observed behavior of a public
|
||||
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
|
||||
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
|
||||
# Documentation review and execution are distinct; the claim's test field
|
||||
# records which one applies.
|
||||
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
|
||||
# about the evidence reviewed, not proof that no authorized source exists.
|
||||
#
|
||||
# Use B for semantics from a specification, D for a claim about what a public
|
||||
# document or sample says, and E for a claim about a tool or its format support.
|
||||
# The current registry does not assign class C.
|
||||
#
|
||||
# These are the repository's evidence classes. AGENTS.md §5 refers to this
|
||||
# file and does not define a second vocabulary; the longer VERIFIED /
|
||||
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
|
||||
# present in the in-tree AGENTS.md, so no mapping is invented here.
|
||||
schema_version = 1
|
||||
|
||||
[[claim]]
|
||||
|
||||
@@ -108,7 +108,7 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
|
||||
| `device.shader_model` | 6.6 |
|
||||
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
|
||||
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
|
||||
| `wave.wavesize64` | created but not run (output still sentinel) |
|
||||
@@ -118,6 +118,12 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
|
||||
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
|
||||
|
||||
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
|
||||
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
|
||||
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
|
||||
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
|
||||
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
|
||||
|
||||
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
|
||||
(D3DMetal 3.0) by another contributor.
|
||||
|
||||
|
||||
@@ -84,3 +84,91 @@ Identification is not execution. `xenora shaders coverage` reports forms
|
||||
discovered in metadata against forms the semantic decoder accepts
|
||||
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
|
||||
per form remains in `docs/status.toml`.
|
||||
|
||||
## 64 KiB swizzle (`SW_64KB_S`) — public sources (#505)
|
||||
|
||||
`xg_xs.dll` implements `SW_64KB_S` tile addressing for `TEXTURE2D`, one array
|
||||
slice and one mip, over the element sizes the RB+ tables specify: 32-bpp RGBA8
|
||||
(4-byte elements) and the BC family — BC1/BC4 with 8-byte blocks and
|
||||
BC2/3/5/6H/7 with 16-byte blocks, where one "texel" element is a 4x4 block and
|
||||
`elemLog2 = log2(block_bytes)`. At 32 bpp the two public sources below agree
|
||||
bit-for-bit, which is why this is the mode implemented first; the 8- and 16-byte
|
||||
rows come from AddrLib alone.
|
||||
|
||||
**Microsoft, `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE`** (public, no NDA):
|
||||
<https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout>.
|
||||
The page gives the 32-bpp masks `xBytesMask = 0xAA8F` and `yMask = 0x5570`,
|
||||
combined with `_pdep_u32`. It states that tail-mip packing is **adapter-specific**,
|
||||
which is why only the single-mip case is implemented. It has no `D` or `R` variant.
|
||||
|
||||
**AMD AddrLib (MIT)** — the authoritative public implementation, in both
|
||||
[Mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib)
|
||||
and [AMD PAL](https://github.com/GPUOpen-Drivers/pal/tree/dev/src/core/imported/addrlib)
|
||||
(`SPDX-License-Identifier: MIT`, AMD copyright; PAL `LICENSE.txt` is MIT):
|
||||
|
||||
- `src/amd/addrlib/inc/addrtypes.h` — `AddrSwizzleMode`: `ADDR_SW_64KB_S` = 9,
|
||||
`_D` = 10, `_R` = 11 (Reserved on GFX10).
|
||||
- `src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h` — `GFX10_SW_64K_S_PATINFO`
|
||||
and `GFX10_SW_64K_S_RBPLUS_PATINFO`, plus the `GFX10_SW_PATTERN_NIBBLE01/2/3/4`
|
||||
tables. The RB+ variant is used because `gfx1030` is Navi2x.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.h` — `GetSwizzlePatternFromPatternInfo`,
|
||||
`IsInMipTail`.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp` — `GetSwizzlePatternInfo`,
|
||||
`HwlComputeSurfaceAddrFromCoordTiled`, `ComputeSurfaceAddrFromCoordMacroTiled`.
|
||||
- `src/amd/addrlib/src/core/addrlib2.cpp` — `ComputeThinBlockDimension`,
|
||||
`Block256_2d`.
|
||||
|
||||
There is **no** standalone GPUOpen `addrlib` repository (404). The public
|
||||
[RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf)
|
||||
only names a 5-bit "SW mode" field in the T# descriptor (bits 120:116) and does
|
||||
not define the patterns.
|
||||
|
||||
### S versus D versus R
|
||||
|
||||
- **S and D are not interchangeable.** At 32 bpp RB+, D uses nibble01 index 39
|
||||
(`[0,0,X0,X1,Y0,Y1,X2,Y2]`) while S uses index 2
|
||||
(`[0,0,X0,X1,Y0,Y1,Y2,X2]`) — address bits 6 and 7 swapped.
|
||||
- **`SW_64KB_R` has no public GFX10 form.** Mesa's `SwizzleModeTable` marks
|
||||
`ADDR_SW_64KB_R` (enum 11) as Reserved; the render-target mode is
|
||||
`ADDR_SW_64KB_R_X`, whose pipe/packer XOR depends on the console
|
||||
`GB_ADDR_CONFIG`, which is not public.
|
||||
|
||||
### Xbox `XG` tile modes are NDA
|
||||
|
||||
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
|
||||
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
|
||||
not public, so BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are **local** constants,
|
||||
not the console's.
|
||||
|
||||
### Element sizes and the derived masks
|
||||
|
||||
For a 64 KiB tile the intra-tile byte offset of element (x, y) is
|
||||
`pdep(x, x_mask) | pdep(y, y_mask)`, where x and y are **block** indices (one
|
||||
4x4 block for BC, one texel for 32 bpp). The masks were expanded by hand from
|
||||
`GFX10_SW_PATTERN_NIBBLE01/2/3` at the patinfo indices
|
||||
`GFX10_SW_64K_S_RBPLUS_PATINFO` selects for each `elemLog2`:
|
||||
|
||||
| block bytes | formats | `elemLog2` | x mask | y mask | tile (blocks) |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 4 | R8G8B8A8_* | 2 | `0xAA8C` | `0x5570` | 128 x 128 |
|
||||
| 8 | BC1, BC4 | 3 | `0xAAC8` | `0x5530` | 128 x 64 |
|
||||
| 16 | BC2, BC3, BC5, BC6H, BC7 | 4 | `0xAAC0` | `0x5530` | 64 x 64 |
|
||||
|
||||
At 32 bpp the x mask `0xAA8C` is Microsoft's public `xBytesMask` `0xAA8F` with
|
||||
the two intra-texel byte bits cleared (`0xAA8F & ~0x3`), and the y mask matches
|
||||
`0x5570` exactly. The 8- and 16-byte rows have no D3D12 page to cross-check
|
||||
against; they are AddrLib-only, which is stated in the PR risks. All three rows
|
||||
were checked to be bijections over their 64 KiB tile (16384 / 8192 / 4096
|
||||
distinct offsets, each block-aligned and inside the tile).
|
||||
|
||||
### Verification
|
||||
|
||||
The three masks above were expanded and their bijectivity checked against an
|
||||
independently written `pdep` reference, outside the shim. `test_xg_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
|
||||
Xbox-hardware claim.
|
||||
@@ -0,0 +1,548 @@
|
||||
//! Xbox title drive letters, linked in the prefix's `dosdevices` before launch.
|
||||
//!
|
||||
//! The project-authorized target title we traced reads its package from `G:` and writes
|
||||
//! temporary files such as crash logs to `T:`. That is an observation of one title at startup;
|
||||
//! that `G:` is the package root and `T:` temporary storage for Xbox titles in general is an
|
||||
//! inference. A Wine prefix has neither drive, so that title's first `G:\...` open fails with
|
||||
//! `STATUS_OBJECT_PATH_NOT_FOUND`. `bx-cli run` links `g:` to the executable's directory and
|
||||
//! `t:` to `drive_c/bx_temp`.
|
||||
//!
|
||||
//! As with system32 staging (#474), a drive letter the prefix already uses is not ours. A
|
||||
//! `.bx-drives` manifest in `dosdevices` records each link this tool made, and only a link that
|
||||
//! is listed and still points where it was pointed is replaced. Any other mapping to a
|
||||
//! different target is reported and left unchanged.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::ffi::{OsStrExt, OsStringExt};
|
||||
use std::os::unix::fs::{OpenOptionsExt, symlink};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MANIFEST: &str = ".bx-drives";
|
||||
const LOCK_FILE: &str = ".bx-drive-mapping.lock";
|
||||
|
||||
/// The prefix-relative target of `t:`, in the form Wine itself uses for `c:`.
|
||||
pub const TEMP_TARGET: &str = "../drive_c/bx_temp";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DriveMappingLock {
|
||||
_file: fs::File,
|
||||
}
|
||||
|
||||
/// Holds the prefix's drive mappings stable until the returned lock is dropped.
|
||||
pub fn lock_drive_mappings(prefix: &Path) -> Result<DriveMappingLock, String> {
|
||||
fs::create_dir_all(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot prepare prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let prefix = fs::canonicalize(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot resolve prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let path = prefix.join(LOCK_FILE);
|
||||
let file = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open drive lock {}: {e}", path.display()))?;
|
||||
|
||||
loop {
|
||||
// The open file descriptor stays alive in DriveMappingLock for the full launch.
|
||||
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
|
||||
if result == 0 {
|
||||
return Ok(DriveMappingLock { _file: file });
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.kind() == io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
if error.kind() == io::ErrorKind::WouldBlock {
|
||||
return Err(format!(
|
||||
"another bx-cli run is active for prefix {}; refusing to launch with shared Xbox drive mappings",
|
||||
prefix.display()
|
||||
));
|
||||
}
|
||||
return Err(format!("cannot lock {}: {error}", path.display()));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Mapping {
|
||||
Created(char, PathBuf),
|
||||
/// A link this tool made earlier, pointed at a new target.
|
||||
Retargeted(char, PathBuf),
|
||||
Unchanged(char, PathBuf),
|
||||
/// A mapping this tool did not make, to a different target; left as it is.
|
||||
Foreign {
|
||||
letter: char,
|
||||
existing: String,
|
||||
wanted: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
impl Mapping {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
Mapping::Created(l, t) => {
|
||||
format!("mapped {}: to {}", l.to_ascii_uppercase(), t.display())
|
||||
}
|
||||
Mapping::Retargeted(l, t) => {
|
||||
format!(
|
||||
"remapped own {}: to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Unchanged(l, t) => {
|
||||
format!(
|
||||
"{}: already maps to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Foreign {
|
||||
letter,
|
||||
existing,
|
||||
wanted,
|
||||
} => format!(
|
||||
"warning: {}: already maps to {existing}, not {}; left unchanged, so the guest \
|
||||
may not find its files there",
|
||||
letter.to_ascii_uppercase(),
|
||||
wanted.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_manifest(dosdevices: &Path) -> Result<BTreeMap<char, PathBuf>, String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
|
||||
};
|
||||
let mut owned = BTreeMap::new();
|
||||
for line in text.lines().filter(|l| !l.is_empty()) {
|
||||
let mut chars = line.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(letter), Some('\t')) if letter.is_ascii_lowercase() => {
|
||||
let encoded = chars.as_str();
|
||||
let target = match encoded.strip_prefix('@') {
|
||||
Some(hex) => decode_path(hex)
|
||||
.ok_or_else(|| format!("malformed path in {}: {line:?}", path.display()))?,
|
||||
None => PathBuf::from(encoded),
|
||||
};
|
||||
owned.insert(letter, target);
|
||||
}
|
||||
_ => return Err(format!("malformed line in {}: {line:?}", path.display())),
|
||||
}
|
||||
}
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
fn write_manifest(dosdevices: &Path, owned: &BTreeMap<char, PathBuf>) -> Result<(), String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
let mut text = String::new();
|
||||
for (letter, target) in owned {
|
||||
text.push_str(&format!("{letter}\t@{}\n", encode_path(target)));
|
||||
}
|
||||
// Written to a temporary file and renamed over the manifest, like `relink`, so an
|
||||
// interrupted write can never leave a truncated manifest that later runs refuse to parse.
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp)
|
||||
.map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
|
||||
let written = file.write_all(text.as_bytes()).and_then(|()| {
|
||||
drop(file);
|
||||
fs::rename(&tmp, &path)
|
||||
});
|
||||
if written.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
written.map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn encode_path(path: &Path) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let bytes = path.as_os_str().as_bytes();
|
||||
let mut encoded = String::with_capacity(bytes.len() * 2);
|
||||
for &byte in bytes {
|
||||
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
|
||||
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn decode_path(hex: &str) -> Option<PathBuf> {
|
||||
fn nibble(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = hex.as_bytes();
|
||||
if bytes.len() % 2 != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut decoded = Vec::with_capacity(bytes.len() / 2);
|
||||
for pair in bytes.chunks_exact(2) {
|
||||
decoded.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(decoded)))
|
||||
}
|
||||
|
||||
/// Points `link` at `target`, replacing what is there through a rename so the link never
|
||||
/// disappears in between.
|
||||
fn relink(dosdevices: &Path, link: &Path, target: &Path) -> io::Result<()> {
|
||||
let tmp = dosdevices.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
let _ = fs::remove_file(&tmp);
|
||||
symlink(target, &tmp)?;
|
||||
let result = fs::rename(&tmp, link);
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Links `g:` to `package_dir` and `t:` to [`TEMP_TARGET`] in `prefix`'s `dosdevices`.
|
||||
pub fn map_xbox_drives(prefix: &Path, package_dir: &Path) -> Result<Vec<Mapping>, String> {
|
||||
let dosdevices = prefix.join("dosdevices");
|
||||
if !dosdevices.is_dir() {
|
||||
return Err(format!(
|
||||
"{} does not exist (start the prefix once so Wine creates it)",
|
||||
dosdevices.display()
|
||||
));
|
||||
}
|
||||
let temp_dir = prefix.join("drive_c/bx_temp");
|
||||
fs::create_dir_all(&temp_dir)
|
||||
.map_err(|e| format!("cannot create {}: {e}", temp_dir.display()))?;
|
||||
|
||||
let mut owned = read_manifest(&dosdevices)?;
|
||||
let mut mappings = Vec::new();
|
||||
for (letter, target) in [
|
||||
('g', package_dir.to_path_buf()),
|
||||
('t', PathBuf::from(TEMP_TARGET)),
|
||||
] {
|
||||
let link = dosdevices.join(format!("{letter}:"));
|
||||
let current = match fs::symlink_metadata(&link) {
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(format!("cannot inspect {}: {e}", link.display())),
|
||||
Ok(meta) if meta.file_type().is_symlink() => Some(
|
||||
fs::read_link(&link).map_err(|e| format!("cannot read {}: {e}", link.display()))?,
|
||||
),
|
||||
Ok(_) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: format!("a non-link entry {}", link.display()),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mapping = match current {
|
||||
None => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
relink(&dosdevices, &link, &target)
|
||||
.map_err(|e| format!("cannot create {}: {e}", link.display()))?;
|
||||
Mapping::Created(letter, target.clone())
|
||||
}
|
||||
Some(current) if current == target => Mapping::Unchanged(letter, target.clone()),
|
||||
Some(current) if owned.get(&letter) == Some(¤t) => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
if let Err(error) = relink(&dosdevices, &link, &target) {
|
||||
owned.insert(letter, current);
|
||||
let restore = write_manifest(&dosdevices, &owned);
|
||||
let detail = restore
|
||||
.err()
|
||||
.map(|e| format!("; also could not restore the drive manifest: {e}"))
|
||||
.unwrap_or_default();
|
||||
return Err(format!(
|
||||
"cannot replace {}: {error}{detail}",
|
||||
link.display()
|
||||
));
|
||||
}
|
||||
Mapping::Retargeted(letter, target.clone())
|
||||
}
|
||||
Some(current) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: current.display().to_string(),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
mappings.push(mapping);
|
||||
}
|
||||
Ok(mappings)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"bx-drives-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&p);
|
||||
fs::create_dir_all(p.join("prefix/dosdevices")).unwrap();
|
||||
fs::create_dir_all(p.join("game")).unwrap();
|
||||
TempDir(p)
|
||||
}
|
||||
fn prefix(&self) -> PathBuf {
|
||||
self.0.join("prefix")
|
||||
}
|
||||
fn game(&self) -> PathBuf {
|
||||
self.0.join("game")
|
||||
}
|
||||
fn link(&self, letter: char) -> PathBuf {
|
||||
self.0.join(format!("prefix/dosdevices/{letter}:"))
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_drives_are_created_and_resolve() {
|
||||
let t = TempDir::new("create");
|
||||
fs::write(t.game().join("package.bin"), b"pkg").unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Created('g', _), Mapping::Created('t', _)]
|
||||
));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
fs::read_link(t.link('t')).unwrap(),
|
||||
PathBuf::from(TEMP_TARGET)
|
||||
);
|
||||
// Both links resolve the way Wine resolves them, from inside dosdevices.
|
||||
assert_eq!(fs::read(t.link('g').join("package.bin")).unwrap(), b"pkg");
|
||||
assert!(t.link('t').is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_changes_nothing() {
|
||||
let t = TempDir::new("rerun");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Unchanged('g', _), Mapping::Unchanged('t', _)]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_follows_a_new_package_directory() {
|
||||
let t = TempDir::new("retarget");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(mappings[0], Mapping::Retargeted('g', _)));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_mapping_is_reported_and_kept() {
|
||||
let t = TempDir::new("foreign");
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert!(mappings[0].describe().starts_with("warning: G:"));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
// A link this tool did not record is never treated as its own on a later run.
|
||||
let again = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_changed_by_someone_else_becomes_foreign() {
|
||||
let t = TempDir::new("changed");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
fs::remove_file(t.link('g')).unwrap();
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_link_entry_is_never_touched() {
|
||||
let t = TempDir::new("nonlink");
|
||||
fs::create_dir_all(t.link('t')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[1], Mapping::Foreign { letter: 't', .. }));
|
||||
assert!(t.link('t').is_dir() && !fs::symlink_metadata(t.link('t')).unwrap().is_symlink());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_without_dosdevices_is_an_error() {
|
||||
let t = TempDir::new("nodos");
|
||||
fs::remove_dir_all(t.prefix().join("dosdevices")).unwrap();
|
||||
let e = map_xbox_drives(&t.prefix(), &t.game()).unwrap_err();
|
||||
assert!(e.contains("dosdevices"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_manifest_is_an_error_not_an_ownership_claim() {
|
||||
let t = TempDir::new("badmanifest");
|
||||
fs::write(t.prefix().join("dosdevices").join(MANIFEST), "g /x\n").unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_manifest_write_leaves_no_unrecorded_link() {
|
||||
let t = TempDir::new("orphan");
|
||||
// A directory where the manifest's temporary file goes makes the write fail.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
assert!(
|
||||
fs::symlink_metadata(t.link('g')).is_err(),
|
||||
"g: must not be created before ownership is recorded"
|
||||
);
|
||||
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interrupted_manifest_write_keeps_the_previous_manifest() {
|
||||
let t = TempDir::new("atomic");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let manifest = t.prefix().join("dosdevices").join(MANIFEST);
|
||||
let before = fs::read(&manifest).unwrap();
|
||||
// Fail the next write after the new contents would have been produced: the old
|
||||
// manifest must survive whole, never truncated or half written.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(
|
||||
fs::read(&manifest).unwrap(),
|
||||
before,
|
||||
"previous manifest kept intact"
|
||||
);
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
// The intact manifest still proves ownership, so the retry re-points g:.
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
assert!(
|
||||
fs::read_dir(t.prefix().join("dosdevices"))
|
||||
.unwrap()
|
||||
.all(|e| !e.unwrap().file_name().to_string_lossy().contains(".tmp."))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_temp_does_not_follow_an_existing_symlink() {
|
||||
let t = TempDir::new("manifest-symlink");
|
||||
let dosdevices = t.prefix().join("dosdevices");
|
||||
let target = t.0.join("outside-manifest");
|
||||
fs::write(&target, b"unchanged").unwrap();
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
symlink(&target, &tmp).unwrap();
|
||||
|
||||
assert!(write_manifest(&dosdevices, &BTreeMap::new()).is_err());
|
||||
assert_eq!(fs::read(&target).unwrap(), b"unchanged");
|
||||
assert_eq!(fs::read_link(&tmp).unwrap(), target);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_retarget_restores_the_previous_manifest_and_link() {
|
||||
let t = TempDir::new("retarget-failure");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
|
||||
let temp_link = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
fs::create_dir(&temp_link).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
t.game()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_lock_rejects_another_launcher_until_released() {
|
||||
let t = TempDir::new("lock");
|
||||
let lock = lock_drive_mappings(&t.prefix()).unwrap();
|
||||
let error = lock_drive_mappings(&t.prefix()).unwrap_err();
|
||||
assert!(error.contains("another bx-cli run"), "{error}");
|
||||
|
||||
drop(lock);
|
||||
assert!(lock_drive_mappings(&t.prefix()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_utf8_target_round_trips_through_the_manifest() {
|
||||
let t = TempDir::new("non-utf8");
|
||||
let mut game_bytes = t.0.as_os_str().as_bytes().to_vec();
|
||||
game_bytes.extend_from_slice(b"/game-\xff");
|
||||
let game = PathBuf::from(std::ffi::OsString::from_vec(game_bytes));
|
||||
let owned = BTreeMap::from([('g', game.clone())]);
|
||||
write_manifest(&t.prefix().join("dosdevices"), &owned).unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
game
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_plain_text_target_still_reads() {
|
||||
let t = TempDir::new("legacy-manifest");
|
||||
let legacy_target = t.0.join("old-game");
|
||||
fs::write(
|
||||
t.prefix().join("dosdevices").join(MANIFEST),
|
||||
format!("g\t{}\n", legacy_target.display()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
legacy_target
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
|
||||
|
||||
mod drives;
|
||||
mod stage;
|
||||
mod supervise;
|
||||
|
||||
@@ -13,7 +14,7 @@ use std::process::{Command, ExitCode};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
|
||||
use bx_telemetry::{ShaderGap, TraceSummary, TrapCount, summarize_jsonl};
|
||||
use bx_telemetry::{ShaderGap, ShaderGapGroup, TraceSummary, TrapCount, summarize_jsonl};
|
||||
use dxbc_accc::inspect_dxbc;
|
||||
use supervise::{Outcome, Stop};
|
||||
|
||||
@@ -40,18 +41,16 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
|
||||
"XPC_SERVICE_NAME",
|
||||
];
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!(
|
||||
"BetterXen Hybrid CLI (bx-cli)\n\
|
||||
\n\
|
||||
Usage:\n\
|
||||
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
|
||||
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
|
||||
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
|
||||
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
|
||||
);
|
||||
fn usage_text() -> &'static str {
|
||||
"BetterXen Hybrid CLI (bx-cli)\n\
|
||||
\n\
|
||||
Usage:\n\
|
||||
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
|
||||
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
|
||||
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
|
||||
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
|
||||
}
|
||||
|
||||
fn run_capture(program: &str, args: &[&str]) -> Option<String> {
|
||||
@@ -219,6 +218,27 @@ fn format_shader_gap_line(gap: &ShaderGap) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// One `(pso, stage)` group of gap records, with its count and every distinct constraint set
|
||||
/// (#590). Missing fields say `unknown` rather than being lost.
|
||||
fn format_shader_gap_group(group: &ShaderGapGroup) -> String {
|
||||
let mut out = format!(
|
||||
" {:5}x pso={} stage={}\n",
|
||||
group.count,
|
||||
group.pso.as_deref().unwrap_or("unknown"),
|
||||
group.stage.as_deref().unwrap_or("unknown"),
|
||||
);
|
||||
for variant in &group.variants {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" wave_lanes_min={} atomic64_flags={} ({}x)",
|
||||
variant.wave_lanes_min.as_deref().unwrap_or("unknown"),
|
||||
variant.atomic64_flags.as_deref().unwrap_or("unknown"),
|
||||
variant.count,
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One line per gate record whose decision is not a pass, naming the pipeline,
|
||||
/// stage, decision and HRESULT. These are the records a reader needs to find a
|
||||
/// blocker; the counted breakdown alone does not say which pipeline failed
|
||||
@@ -277,6 +297,28 @@ fn format_shader_gate_section(summary: &TraceSummary) -> String {
|
||||
for gap in &summary.shader_gaps {
|
||||
out.push_str(&format_shader_gap_line(gap));
|
||||
}
|
||||
// #590: the same records grouped by pipeline and stage, so a reader can tell which
|
||||
// pipelines are created-but-not-run. Additive: the per-record list above is unchanged.
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nD3DMetal gaps by kind/stage ({}):",
|
||||
summary.shader_gap_groups.len()
|
||||
);
|
||||
for group in &summary.shader_gap_groups {
|
||||
out.push_str(&format_shader_gap_group(group));
|
||||
}
|
||||
if summary.shader_gaps_missing_identity > 0 {
|
||||
out.push_str(&format_shader_line(
|
||||
"gaps w/o pso/stage",
|
||||
summary.shader_gaps_missing_identity,
|
||||
));
|
||||
}
|
||||
if summary.shader_gaps_missing_constraints > 0 {
|
||||
out.push_str(&format_shader_line(
|
||||
"gaps w/o constraints",
|
||||
summary.shader_gaps_missing_constraints,
|
||||
));
|
||||
}
|
||||
}
|
||||
if !summary.shader_bridge_missing.is_empty() {
|
||||
let _ = writeln!(
|
||||
@@ -817,6 +859,18 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
supervise::install_signal_handlers();
|
||||
let started = Instant::now();
|
||||
|
||||
// Drive links are prefix-global. Keep them stable until this guest exits so another bx-cli
|
||||
// process cannot retarget G: underneath a running title. Taken before system32 staging, so
|
||||
// a run refused here has not touched the shared prefix. Runs sharing a prefix are therefore
|
||||
// serial: a second launcher on the same prefix is refused while the first is running.
|
||||
let _drive_lock = match drives::lock_drive_mappings(&environment_dir) {
|
||||
Ok(lock) => lock,
|
||||
Err(e) => {
|
||||
diag(format_args!("error: {e}"));
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
// #457: shims loaded with LOAD_LIBRARY_SEARCH_SYSTEM32 never see WINEPATH, so they are
|
||||
// copied into the environment's system32 first. A bare prefix is initialized for that.
|
||||
let system32 = stage::system32_dir(&environment_dir);
|
||||
@@ -878,6 +932,25 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
// An Xbox title opens its package on G: and writes temporary files to T:. A missing drive
|
||||
// only matters to such a title, so it is reported and the run goes on.
|
||||
match abs_exe.parent() {
|
||||
Some(package_dir) => match drives::map_xbox_drives(&environment_dir, package_dir) {
|
||||
Ok(mappings) => {
|
||||
for mapping in &mappings {
|
||||
match mapping {
|
||||
drives::Mapping::Foreign { .. } => diag(mapping.describe()),
|
||||
_ => diag(format_args!("bx-cli: {}", mapping.describe())),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => diag(format_args!(
|
||||
"warning: Xbox drives G: and T: not mapped: {e}"
|
||||
)),
|
||||
},
|
||||
None => diag("warning: Xbox drive G: not mapped: the executable has no parent directory"),
|
||||
}
|
||||
|
||||
let mut cmd = if let Some(ref bname) = bottle {
|
||||
let mut c = Command::new(&wine_wrapper);
|
||||
c.args(["--bottle", bname])
|
||||
@@ -1048,22 +1121,66 @@ fn cmd_shader(path: &str) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a bare invocation of `bx-cli` should do. Split out from `main` so the
|
||||
/// choice is testable without spawning a process.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Dispatch<'a> {
|
||||
/// An explicit `--help` / `-h` / `help`: usage on stdout, succeed.
|
||||
Help,
|
||||
/// Nothing was asked for: usage on stderr, fail as a usage error.
|
||||
NoArgs,
|
||||
/// An unrecognised subcommand: usage on stderr, fail.
|
||||
Unknown(&'a str),
|
||||
/// A real subcommand.
|
||||
Sub(&'a str),
|
||||
}
|
||||
|
||||
impl<'a> Dispatch<'a> {
|
||||
fn classify(args: &'a [String]) -> Self {
|
||||
let Some(sub) = args.first() else {
|
||||
return Dispatch::NoArgs;
|
||||
};
|
||||
match sub.as_str() {
|
||||
"--help" | "-h" | "help" => Dispatch::Help,
|
||||
"doctor" | "probe" | "shader" | "trace" | "run" => Dispatch::Sub(sub.as_str()),
|
||||
_ => Dispatch::Unknown(sub.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the usage text goes to stdout rather than stderr.
|
||||
fn usage_on_stdout(self) -> bool {
|
||||
matches!(self, Dispatch::Help)
|
||||
}
|
||||
|
||||
/// True when the invocation must not report success.
|
||||
fn is_usage_error(self) -> bool {
|
||||
matches!(self, Dispatch::NoArgs | Dispatch::Unknown(_))
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = env::args().skip(1).collect();
|
||||
let Some(sub) = args.first() else {
|
||||
print_usage();
|
||||
return ExitCode::SUCCESS;
|
||||
};
|
||||
match sub.as_str() {
|
||||
"doctor" => cmd_doctor(),
|
||||
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
|
||||
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
|
||||
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
|
||||
"run" => cmd_run(&args[1..]),
|
||||
_ => {
|
||||
print_usage();
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
let dispatch = Dispatch::classify(&args);
|
||||
if dispatch.usage_on_stdout() {
|
||||
print!("{}", usage_text());
|
||||
} else if dispatch.is_usage_error() {
|
||||
eprint!("{}", usage_text());
|
||||
}
|
||||
match dispatch {
|
||||
Dispatch::Help => ExitCode::SUCCESS,
|
||||
Dispatch::NoArgs | Dispatch::Unknown(_) => ExitCode::FAILURE,
|
||||
Dispatch::Sub(sub) => match sub {
|
||||
"doctor" => cmd_doctor(),
|
||||
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
|
||||
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
|
||||
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
|
||||
"run" => cmd_run(&args[1..]),
|
||||
// Only reachable when a subcommand that needs an argument got none.
|
||||
_ => {
|
||||
eprint!("{}", usage_text());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1662,4 +1779,116 @@ sub setup_bottle_wineprefix {
|
||||
assert!(rendered.contains("unparsed details : 1"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x pass_dxil"), "{rendered}");
|
||||
}
|
||||
|
||||
/// The usage paths must not be inverted: an explicit `--help` succeeded,
|
||||
/// a bare invocation did nothing, and an unknown subcommand is an error.
|
||||
#[test]
|
||||
fn help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error() {
|
||||
for flag in ["--help", "-h", "help"] {
|
||||
let argv = args(&[flag]);
|
||||
let dispatch = Dispatch::classify(&argv);
|
||||
assert_eq!(
|
||||
dispatch,
|
||||
Dispatch::Help,
|
||||
"{flag} is an explicit help request"
|
||||
);
|
||||
assert!(dispatch.usage_on_stdout(), "{flag} prints usage on stdout");
|
||||
assert!(!dispatch.is_usage_error(), "{flag} must exit 0");
|
||||
}
|
||||
|
||||
let empty: Vec<String> = Vec::new();
|
||||
let none = Dispatch::classify(&empty);
|
||||
assert_eq!(none, Dispatch::NoArgs);
|
||||
assert!(!none.usage_on_stdout(), "a bare invocation writes stderr");
|
||||
assert!(
|
||||
none.is_usage_error(),
|
||||
"a bare invocation did nothing, so it must not report success"
|
||||
);
|
||||
|
||||
let bogus_argv = args(&["definitely-not-a-subcommand"]);
|
||||
let bogus = Dispatch::classify(&bogus_argv);
|
||||
assert_eq!(bogus, Dispatch::Unknown("definitely-not-a-subcommand"));
|
||||
assert!(
|
||||
!bogus.usage_on_stdout(),
|
||||
"an unknown subcommand writes stderr"
|
||||
);
|
||||
assert!(bogus.is_usage_error(), "an unknown subcommand is an error");
|
||||
|
||||
for real in ["doctor", "probe", "shader", "trace", "run"] {
|
||||
let argv = args(&[real]);
|
||||
let dispatch = Dispatch::classify(&argv);
|
||||
assert_eq!(dispatch, Dispatch::Sub(real), "{real} is a real subcommand");
|
||||
assert!(!dispatch.usage_on_stdout(), "{real} prints no usage");
|
||||
assert!(!dispatch.is_usage_error(), "{real} is not a usage error");
|
||||
}
|
||||
}
|
||||
|
||||
/// The usage text must name every subcommand, so the classifier above is
|
||||
/// not testing a table that nothing prints.
|
||||
#[test]
|
||||
fn the_usage_text_names_every_subcommand() {
|
||||
let text = usage_text();
|
||||
assert!(
|
||||
text.contains("BetterXen Hybrid CLI"),
|
||||
"usage carries the banner"
|
||||
);
|
||||
for sub in ["doctor", "probe", "shader", "trace", "run"] {
|
||||
assert!(text.contains(sub), "usage documents {sub}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #590: the grouped view names each `(pso, stage)` pair with its count, wave width and
|
||||
/// 64-bit-atomic flags, in first-seen order, and says when a record lost its identity.
|
||||
#[test]
|
||||
fn renders_gaps_grouped_by_pipeline_and_stage() {
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"garbage"}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
// The #496 per-record list is unchanged.
|
||||
assert!(rendered.contains("D3DMetal gaps (4):"), "{rendered}");
|
||||
assert!(
|
||||
rendered.contains(" pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000"),
|
||||
"{rendered}"
|
||||
);
|
||||
// The additive grouped view.
|
||||
assert!(
|
||||
rendered.contains("D3DMetal gaps by kind/stage (3):"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains(" 1x pso=graphics stage=VS"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains(" 2x pso=compute stage=CS"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains(" wave_lanes_min=64 atomic64_flags=0x400000 (2x)"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains(" 1x pso=unknown stage=unknown"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(rendered.contains("gaps w/o pso/stage : 1"), "{rendered}");
|
||||
assert!(rendered.contains("gaps w/o constraints : 1"), "{rendered}");
|
||||
// First-seen order: the graphics/VS group comes before the compute/CS one.
|
||||
let vs = rendered.find("pso=graphics stage=VS").unwrap();
|
||||
let cs = rendered.find(" 2x pso=compute stage=CS").unwrap();
|
||||
assert!(vs < cs, "{rendered}");
|
||||
}
|
||||
|
||||
/// #590: a run with no gap records renders no grouped section at all.
|
||||
#[test]
|
||||
fn a_run_with_no_gaps_renders_no_grouped_section() {
|
||||
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(rendered.contains("Shader gate:"), "{rendered}");
|
||||
assert!(!rendered.contains("D3DMetal gaps"), "{rendered}");
|
||||
assert!(!rendered.contains("gaps w/o"), "{rendered}");
|
||||
}
|
||||
}
|
||||
@@ -447,7 +447,7 @@ mod tests {
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!(
|
||||
"#!/bin/sh\n/bin/ps -o pgid= -p $$ >> '{}'\n",
|
||||
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
|
||||
seen.display()
|
||||
),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Runs the built `bx-cli` binary to check what `main` prints and returns for the
|
||||
//! usage paths (#532). The unit tests cover `Dispatch::classify`; these cover the
|
||||
//! mapping from that classification to the real exit code and output stream.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn run(args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_bx-cli"))
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.output()
|
||||
.expect("bx-cli must start")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_prints_usage_on_stdout_and_succeeds() {
|
||||
for flag in ["--help", "-h", "help"] {
|
||||
let out = run(&[flag]);
|
||||
assert!(out.status.success(), "{flag}: {:?}", out.status);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
stdout.contains("bx-cli run --exe"),
|
||||
"{flag}: usage on stdout: {stdout}"
|
||||
);
|
||||
assert!(out.stderr.is_empty(), "{flag}: nothing on stderr");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_invocation_is_a_usage_error_on_stderr() {
|
||||
let out = run(&[]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_subcommand_is_a_usage_error_on_stderr() {
|
||||
let out = run(&["frobnicate"]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PeSummary {
|
||||
pub image_base: u64,
|
||||
pub size_of_image: u32,
|
||||
@@ -128,12 +128,21 @@ struct Section {
|
||||
}
|
||||
|
||||
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
|
||||
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
|
||||
}
|
||||
|
||||
/// Map an RVA to a file offset and report how many raw bytes remain in that
|
||||
/// section from the mapped offset. The bound lets callers walk a table without
|
||||
/// leaving the section that contains it.
|
||||
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
|
||||
for s in sections {
|
||||
let span = s.vsize.max(s.raw_size);
|
||||
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
|
||||
let delta = rva - s.vaddr;
|
||||
if delta < s.raw_size {
|
||||
return Some((s.raw_ptr + delta) as usize);
|
||||
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
|
||||
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
|
||||
return Some((off, remaining));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,8 +176,36 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
|
||||
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
|
||||
|
||||
let mut sections = Vec::with_capacity(section_count as usize);
|
||||
// The import data directory is entry index 1, an 8-byte RVA/size pair at
|
||||
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
|
||||
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
|
||||
// validated while the optional header is read: a short optional header must
|
||||
// not let the read fall through into the section table.
|
||||
const IMPORT_DIR_INDEX: u32 = 1;
|
||||
const IMPORT_DIR_OFF: usize = 112 + 8;
|
||||
let mut import_dir: Option<(u32, u32)> = None;
|
||||
if num_rvas > IMPORT_DIR_INDEX {
|
||||
let entry = bytes
|
||||
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
|
||||
if IMPORT_DIR_OFF + 8 > opt_size {
|
||||
return Err(ProbeError::NotPe32Plus(
|
||||
"import directory outside SizeOfOptionalHeader",
|
||||
));
|
||||
}
|
||||
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
|
||||
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
|
||||
import_dir = Some((rva, size));
|
||||
}
|
||||
|
||||
let sec_base = opt + opt_size;
|
||||
let section_table_size = (section_count as usize)
|
||||
.checked_mul(40)
|
||||
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
|
||||
bytes
|
||||
.get(sec_base..sec_base + section_table_size)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
|
||||
let mut sections = Vec::with_capacity(section_count as usize);
|
||||
for i in 0..section_count as usize {
|
||||
let so = sec_base + i * 40;
|
||||
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
|
||||
@@ -184,16 +221,22 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
}
|
||||
|
||||
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
if num_rvas > 1 {
|
||||
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
|
||||
if let Some((imp_rva, imp_size)) = import_dir {
|
||||
if imp_rva != 0
|
||||
&& let Some(mut desc_off) = rva_to_off(§ions, imp_rva)
|
||||
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(§ions, imp_rva)
|
||||
{
|
||||
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) {
|
||||
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
|
||||
// declared directory Size and the section's raw bytes, whichever
|
||||
// ends first, so descriptors past the directory are not reported.
|
||||
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
|
||||
while desc_bytes_left >= 20 {
|
||||
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) else {
|
||||
break;
|
||||
};
|
||||
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -225,6 +268,7 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
imports.entry(dll).or_default().extend(syms);
|
||||
}
|
||||
desc_off += 20;
|
||||
desc_bytes_left -= 20;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +286,129 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PE_OFF: usize = 0x80;
|
||||
const COFF: usize = PE_OFF + 4;
|
||||
const OPT: usize = COFF + 20;
|
||||
const OPT_SIZE: usize = 0xF0;
|
||||
const SEC: usize = OPT + OPT_SIZE;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
const RAW_PTR: u32 = 0x200;
|
||||
|
||||
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
|
||||
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
|
||||
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
|
||||
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
|
||||
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
|
||||
put_u32(bytes, base + 8, raw_size);
|
||||
put_u32(bytes, base + 12, rva);
|
||||
put_u32(bytes, base + 16, raw_size);
|
||||
put_u32(bytes, base + 20, raw_ptr);
|
||||
}
|
||||
|
||||
fn minimal_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = vec![0u8; 0x400];
|
||||
bytes[0..2].copy_from_slice(b"MZ");
|
||||
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
|
||||
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
|
||||
put_u16(&mut bytes, COFF, 0x8664);
|
||||
put_u16(&mut bytes, COFF + 2, 1);
|
||||
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
|
||||
put_u16(&mut bytes, OPT, 0x020B);
|
||||
put_u32(&mut bytes, OPT + 16, 0x1234);
|
||||
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
|
||||
put_u32(&mut bytes, OPT + 56, 0x2000);
|
||||
put_u32(&mut bytes, OPT + 108, 16);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn two_import_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
let import_rva = SECTION_RVA;
|
||||
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
|
||||
|
||||
// Two descriptors followed by the required all-zero terminator.
|
||||
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
|
||||
|
||||
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
|
||||
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
|
||||
|
||||
put_u64(
|
||||
&mut bytes,
|
||||
RAW_PTR as usize + 0x80,
|
||||
u64::from(SECTION_RVA + 0x60),
|
||||
);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
|
||||
|
||||
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
|
||||
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Two sections: an import-descriptor section holding exactly two
|
||||
/// descriptors and no terminator, and a data section for names and thunks.
|
||||
/// Ellipsis bytes just past the descriptor section spell a third valid
|
||||
/// descriptor, so an unbounded walk reports a DLL that is not imported.
|
||||
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
|
||||
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
|
||||
const DATA_PTR: u32 = 0x300;
|
||||
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
put_u16(&mut bytes, COFF + 2, 2);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
|
||||
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
|
||||
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
|
||||
// Declare the directory to cover the whole descriptor section, so the
|
||||
// section bound (not the Size) is what this fixture exercises.
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 40);
|
||||
|
||||
for (base, dll_rva, thunk_rva) in [
|
||||
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
|
||||
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
|
||||
] {
|
||||
put_u32(&mut bytes, base, thunk_rva);
|
||||
put_u32(&mut bytes, base + 12, dll_rva);
|
||||
put_u32(&mut bytes, base + 16, thunk_rva);
|
||||
}
|
||||
|
||||
// A third, entirely valid descriptor just past the section boundary.
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
|
||||
|
||||
for (delta, name) in [
|
||||
(0x00, &b"ONE.DLL\0"[..]),
|
||||
(0x20, &b"TWO.DLL\0"[..]),
|
||||
(0x40, &b"THREE.DLL\0"[..]),
|
||||
] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
bytes[off..off + name.len()].copy_from_slice(name);
|
||||
}
|
||||
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
|
||||
put_u64(&mut bytes, off + 8, 0);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_tracks_accurately() {
|
||||
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
|
||||
@@ -263,4 +430,175 @@ mod tests {
|
||||
);
|
||||
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_minimal_pe32_plus_without_imports() {
|
||||
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
|
||||
assert_eq!(summary.entry_point_rva, 0x1234);
|
||||
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
|
||||
assert_eq!(summary.size_of_image, 0x2000);
|
||||
assert_eq!(summary.section_count, 1);
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_named_and_ordinal_imports_from_two_dlls() {
|
||||
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
|
||||
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncation_at_every_header_boundary() {
|
||||
let image = minimal_pe32_plus();
|
||||
for len in 0..=0x100 {
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
|
||||
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
|
||||
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_rva_mapping_that_would_wrap_u32() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
|
||||
put_u32(&mut image, SEC + 20, u32::MAX);
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
|
||||
assert!(result.is_ok(), "raw pointer addition panicked");
|
||||
assert!(result.unwrap().unwrap().imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_count_larger_than_file() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, COFF + 2, u16::MAX);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated section table")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_pe32_magic() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, OPT, 0x010B);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_outside_all_sections_is_safe() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, 0x8000);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_import_directory() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
// An empty section table that fits, an optional header long enough to
|
||||
// declare the import entry, and a file cut after two of the entry's
|
||||
// RVA bytes.
|
||||
put_u16(&mut image, COFF + 2, 0);
|
||||
put_u16(&mut image, COFF + 16, 0xE0);
|
||||
image.truncate(OPT + 112 + 8 + 2);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated import directory")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_unterminated_import_descriptor_walk() {
|
||||
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
|
||||
/// past the end of the optional header, so its 8 bytes would otherwise be
|
||||
/// read from the section table. The entry index is still within
|
||||
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
|
||||
#[test]
|
||||
fn rejects_import_directory_outside_short_optional_header() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
// Import entry spans optional-header offsets 120..128; declare the
|
||||
// optional header to end at 120, inside the entry.
|
||||
put_u16(&mut image, COFF + 16, 120);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// One byte short of the full 8-byte entry is still out of range.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 127);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// Exactly 128 bytes covers the whole entry, so the import directory is
|
||||
// read normally. The section table now starts at OPT + 128, so write it
|
||||
// there for this size.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 128);
|
||||
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.contains_key("ALPHA.DLL"));
|
||||
assert!(summary.imports.contains_key("BETA.DLL"));
|
||||
}
|
||||
|
||||
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
|
||||
/// import entry (index 1) must not be probed even though its bytes are
|
||||
/// present and inside SizeOfOptionalHeader.
|
||||
#[test]
|
||||
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u32(&mut image, OPT + 108, 1);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
/// (b) The declared import directory Size is shorter than the containing
|
||||
/// section, so descriptors past the declared size must not be reported even
|
||||
/// though they are valid and inside the section's raw bytes.
|
||||
#[test]
|
||||
fn bounds_import_descriptor_walk_by_declared_directory_size() {
|
||||
// Size 40 covers exactly the two real descriptors; the third valid
|
||||
// descriptor at +40 lies outside the directory but inside the section.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 40);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
assert!(!summary.imports.contains_key("THREE.DLL"));
|
||||
|
||||
// Size 20 reports only the first descriptor.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 20);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
|
||||
// A size that is not a multiple of 20 stops before the next descriptor
|
||||
// would exceed the directory.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 39);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,45 @@ pub struct TraceSummary {
|
||||
pub shader_gate: ShaderGateSummary,
|
||||
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
|
||||
pub shader_gaps: Vec<ShaderGap>,
|
||||
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
|
||||
pub shader_gap_groups: Vec<ShaderGapGroup>,
|
||||
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
|
||||
/// they are grouped under `unknown`. Counted here so the group counts reconcile
|
||||
/// with [`TraceSummary::shader_gaps`].
|
||||
pub shader_gaps_missing_identity: usize,
|
||||
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
|
||||
/// value for one). Counted here rather than dropped or assumed.
|
||||
pub shader_gaps_missing_constraints: usize,
|
||||
/// `shader_bridge_missing` messages, in log order.
|
||||
pub shader_bridge_missing: Vec<String>,
|
||||
}
|
||||
|
||||
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapGroup {
|
||||
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
|
||||
/// `unknown`).
|
||||
pub pso: Option<String>,
|
||||
/// The emitted `stage=` value, or `None` when the record carried none.
|
||||
pub stage: Option<String>,
|
||||
/// How many gap records this `(pso, stage)` pair covers.
|
||||
pub count: usize,
|
||||
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
|
||||
/// first-seen order. Two pipelines of the same kind and stage can need different
|
||||
/// wave widths or atomic features, so a group keeps each constraint set rather than
|
||||
/// reporting only the first and losing the rest.
|
||||
pub variants: Vec<ShaderGapVariant>,
|
||||
}
|
||||
|
||||
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapVariant {
|
||||
pub wave_lanes_min: Option<String>,
|
||||
pub atomic64_flags: Option<String>,
|
||||
/// How many records in the group carried exactly these constraints.
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
|
||||
/// their emitted string so unknown values are counted rather than dropped.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
@@ -200,18 +235,77 @@ fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
|
||||
gate.records.push(record);
|
||||
}
|
||||
|
||||
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
|
||||
/// always writes a value, so an empty one means the record is malformed, not that the
|
||||
/// pipeline is named "".
|
||||
fn non_empty(value: Option<String>) -> Option<String> {
|
||||
value.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
|
||||
///
|
||||
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
|
||||
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
|
||||
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
|
||||
let pso = non_empty(gap.pso.clone());
|
||||
let stage = non_empty(gap.stage.clone());
|
||||
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
|
||||
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
|
||||
if pso.is_none() || stage.is_none() {
|
||||
groups.shader_gaps_missing_identity += 1;
|
||||
}
|
||||
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
|
||||
groups.shader_gaps_missing_constraints += 1;
|
||||
}
|
||||
|
||||
// The group list is small (one entry per affected pipeline stage), so a linear scan
|
||||
// keeps first-seen order without a second index to keep in sync.
|
||||
let group_index = match groups
|
||||
.shader_gap_groups
|
||||
.iter()
|
||||
.position(|g| g.pso == pso && g.stage == stage)
|
||||
{
|
||||
Some(index) => index,
|
||||
None => {
|
||||
groups.shader_gap_groups.push(ShaderGapGroup {
|
||||
pso,
|
||||
stage,
|
||||
count: 0,
|
||||
variants: Vec::new(),
|
||||
});
|
||||
groups.shader_gap_groups.len() - 1
|
||||
}
|
||||
};
|
||||
let group = &mut groups.shader_gap_groups[group_index];
|
||||
group.count += 1;
|
||||
match group
|
||||
.variants
|
||||
.iter()
|
||||
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
|
||||
{
|
||||
Some(index) => group.variants[index].count += 1,
|
||||
None => group.variants.push(ShaderGapVariant {
|
||||
wave_lanes_min,
|
||||
atomic64_flags,
|
||||
count: 1,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
|
||||
let pairs = parse_key_values(detail, true);
|
||||
// The emitter appends `: D3DMetal creates such pipelines ...` directly
|
||||
// after the flags value, so strip the trailing colon.
|
||||
let atomic64_flags = get_field(&pairs, "atomic64_flags")
|
||||
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
|
||||
summary.shader_gaps.push(ShaderGap {
|
||||
let gap = ShaderGap {
|
||||
pso: get_field(&pairs, "pso"),
|
||||
stage: get_field(&pairs, "stage"),
|
||||
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
|
||||
atomic64_flags,
|
||||
});
|
||||
};
|
||||
record_shader_gap_group(summary, &gap);
|
||||
summary.shader_gaps.push(gap);
|
||||
}
|
||||
|
||||
pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
@@ -569,4 +663,179 @@ mod tests {
|
||||
assert_eq!(pairs.len(), 2);
|
||||
assert_eq!(pairs[1], ("stage", "pixel"));
|
||||
}
|
||||
|
||||
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
|
||||
/// with its own wave width and 64-bit-atomic flags.
|
||||
#[test]
|
||||
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
|
||||
// Same pso, different stages: grouping on pso alone would collapse these, so the
|
||||
// test discriminates the (pso, stage) key rather than only the pso.
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 3);
|
||||
|
||||
let first = &summary.shader_gap_groups[0];
|
||||
assert_eq!(first.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(first.stage.as_deref(), Some("VS"));
|
||||
assert_eq!(first.count, 1);
|
||||
assert_eq!(
|
||||
first.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
|
||||
let second = &summary.shader_gap_groups[1];
|
||||
assert_eq!(second.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(second.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(second.count, 1);
|
||||
|
||||
// A second stage of the *same* pso stays its own group, which is what separates a
|
||||
// (pso, stage) key from a pso-only key.
|
||||
let third = &summary.shader_gap_groups[2];
|
||||
assert_eq!(third.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(third.stage.as_deref(), Some("PS"));
|
||||
assert_eq!(third.count, 1);
|
||||
}
|
||||
|
||||
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
|
||||
/// identical records are not adjacent.
|
||||
#[test]
|
||||
fn groups_identical_gaps_together() {
|
||||
let record = r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let log = format!("{record}\n{other}\n{record}\n");
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 2);
|
||||
let compute = &summary.shader_gap_groups[0];
|
||||
assert_eq!(compute.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(compute.count, 2);
|
||||
assert_eq!(
|
||||
compute.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 2,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gap_groups[1].count, 1);
|
||||
// Every record is in exactly one group.
|
||||
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
|
||||
assert_eq!(grouped, summary.shader_gaps.len());
|
||||
}
|
||||
|
||||
/// #590: one pipeline kind and stage can need different wave widths or atomic
|
||||
/// features, so a group keeps every distinct constraint set, not only the first.
|
||||
#[test]
|
||||
fn one_group_keeps_each_distinct_constraint_set() {
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 1);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 3);
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 2,
|
||||
},
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 1,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
|
||||
/// #590: a gap record with a missing or empty field must not panic. It is grouped
|
||||
/// under `unknown` and counted, never dropped or guessed.
|
||||
#[test]
|
||||
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
|
||||
for (detail, missing_identity, missing_constraints) in [
|
||||
("", 1, 1),
|
||||
("garbage", 1, 1),
|
||||
("pso=compute", 1, 1),
|
||||
("stage=CS", 1, 1),
|
||||
(
|
||||
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
|
||||
1,
|
||||
0,
|
||||
),
|
||||
("pso=compute stage=CS", 0, 1),
|
||||
(
|
||||
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
|
||||
0,
|
||||
1,
|
||||
),
|
||||
] {
|
||||
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
|
||||
assert_eq!(
|
||||
summary.shader_gap_groups.len(),
|
||||
1,
|
||||
"detail={detail:?} lost its record"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_identity, missing_identity,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_constraints, missing_constraints,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 1, "detail={detail:?}");
|
||||
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
|
||||
assert_eq!(recorded, 1, "detail={detail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #590: the fields a malformed record does carry are still reported.
|
||||
#[test]
|
||||
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
|
||||
let log =
|
||||
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(group.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: None,
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 1);
|
||||
}
|
||||
|
||||
/// #590: a run with no gap records produces no groups and no missing-field counts, so
|
||||
/// the trace renders as it did before the grouping existed.
|
||||
#[test]
|
||||
fn a_run_with_no_gaps_has_no_groups() {
|
||||
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert!(summary.shader_gaps.is_empty());
|
||||
assert!(summary.shader_gap_groups.is_empty());
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
}
|
||||
+117
-21
@@ -4,11 +4,15 @@
|
||||
Checks only tracked files:
|
||||
1. no merge-conflict markers in tracked text files;
|
||||
2. every relative Markdown link points at a tracked file or directory;
|
||||
3. every workflow file under .github/workflows parses as YAML.
|
||||
3. every fragment (``#heading``) in a Markdown link resolves to a real
|
||||
heading in the target Markdown file, including in-page ``](#foo)``
|
||||
links validated against the same file's headings;
|
||||
4. every workflow file under .github/workflows parses as YAML.
|
||||
|
||||
External URLs and in-page anchors are not fetched or validated, so the result
|
||||
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
|
||||
when PyYAML is missing.
|
||||
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
|
||||
fetched or validated, so the result does not depend on the network.
|
||||
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
|
||||
not skip, when PyYAML is missing.
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
@@ -17,9 +21,16 @@ from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import unquote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
|
||||
MARKER = re.compile(r"^(<{7}( |$)|\|{7}( |$)|={7}$|>{7}( |$))")
|
||||
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
||||
FENCE = re.compile(r"^\s*(```|~~~)")
|
||||
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
|
||||
# GitHub slugs the rendered heading, so an inline link contributes only its
|
||||
# text: ``## See [ADR](x.md)`` slugs as ``see-adr``, not ``see-adrxmd``.
|
||||
# Link syntax inside a code span stays literal, so those spans are set aside
|
||||
# before substituting and put back afterwards.
|
||||
INLINE_LINK = re.compile(r"(?<!\!)\[([^\]]*)\]\([^)]*\)")
|
||||
CODE_SPAN = re.compile(r"(`+)(.+?)\1")
|
||||
|
||||
|
||||
def tracked():
|
||||
@@ -35,6 +46,63 @@ def text(path):
|
||||
return data.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _slug(text):
|
||||
"""GitHub-style slug: lowercase, strip non-alnum/-/_/space, spaces -> -."""
|
||||
text = text.lower()
|
||||
text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE)
|
||||
return text.replace(" ", "-")
|
||||
|
||||
|
||||
def _heading_text(text):
|
||||
"""Rendered text of a heading: link text in, code spans left literal."""
|
||||
spans = []
|
||||
|
||||
def stash(match):
|
||||
spans.append(match.group(0))
|
||||
return "\x00%d\x00" % (len(spans) - 1)
|
||||
|
||||
stashed = CODE_SPAN.sub(stash, text)
|
||||
substituted = INLINE_LINK.sub(r"\1", stashed)
|
||||
for index, span in enumerate(spans):
|
||||
substituted = substituted.replace("\x00%d\x00" % index, span)
|
||||
return substituted
|
||||
|
||||
|
||||
def markdown_slugs(body):
|
||||
"""Return the set of GitHub-style heading slugs in a Markdown document.
|
||||
|
||||
Duplicate headings get ``-1``, ``-2``, ... suffixes. Headings inside
|
||||
fenced code blocks are ignored.
|
||||
"""
|
||||
slugs = set()
|
||||
seen = {}
|
||||
in_fence = False
|
||||
for line in body.splitlines():
|
||||
if FENCE.match(line):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
m = HEADING.match(line)
|
||||
if not m:
|
||||
continue
|
||||
base = _slug(_heading_text(m.group(2)))
|
||||
if not base:
|
||||
continue
|
||||
# Advance the numeric suffix until we find a slug that has not
|
||||
# already been emitted. Counting only identical bases is not
|
||||
# enough: a literal heading such as ``Foo-1`` may already own
|
||||
# ``foo-1``, so the next ``Foo`` must become ``foo-2``.
|
||||
count = seen.get(base, 0)
|
||||
slug = base if count == 0 else f"{base}-{count}"
|
||||
while slug in slugs:
|
||||
count += 1
|
||||
slug = f"{base}-{count}"
|
||||
seen[base] = count + 1
|
||||
slugs.add(slug)
|
||||
return slugs
|
||||
|
||||
|
||||
def check_markers(files, problems):
|
||||
for path in files:
|
||||
if path.endswith((".patch", ".diff")):
|
||||
@@ -47,9 +115,30 @@ def check_markers(files, problems):
|
||||
problems.append(f"{path}:{number}: merge conflict marker")
|
||||
|
||||
|
||||
def _resolve_link(path, target):
|
||||
"""Resolve a relative link target to a repo-root-relative POSIX path."""
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def check_links(files, problems):
|
||||
known = set(files)
|
||||
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
|
||||
slug_cache = {}
|
||||
|
||||
def slugs_for(md_path):
|
||||
if md_path not in slug_cache:
|
||||
slug_cache[md_path] = markdown_slugs(text(md_path) or "")
|
||||
return slug_cache[md_path]
|
||||
|
||||
for path in files:
|
||||
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
|
||||
continue
|
||||
@@ -61,24 +150,31 @@ def check_links(files, problems):
|
||||
if in_fence:
|
||||
continue
|
||||
line = re.sub(r"`[^`]*`", "", line)
|
||||
for target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
|
||||
for raw_target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|//)", raw_target, re.I):
|
||||
continue
|
||||
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target:
|
||||
if raw_target == "#":
|
||||
continue
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
norm = "/".join(parts)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
fragment = ""
|
||||
if "#" in raw_target:
|
||||
fragment = unquote(raw_target.split("#", 1)[1])
|
||||
target = unquote(raw_target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target and not fragment:
|
||||
continue
|
||||
if target:
|
||||
norm = _resolve_link(path, target)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
continue
|
||||
else:
|
||||
norm = path
|
||||
if fragment and norm.endswith(".md") and norm in known:
|
||||
if fragment not in slugs_for(norm):
|
||||
shown = raw_target
|
||||
problems.append(
|
||||
f"{path}:{number}: broken fragment '#{fragment}' "
|
||||
f"in link '{shown}' (heading not found)"
|
||||
)
|
||||
|
||||
|
||||
def check_workflows(files, problems, require_yaml):
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
|
||||
|
||||
Run with:
|
||||
python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
"""
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
|
||||
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
|
||||
docs_hygiene = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["docs_hygiene"] = docs_hygiene
|
||||
_spec.loader.exec_module(docs_hygiene)
|
||||
|
||||
|
||||
class SlugTests(unittest.TestCase):
|
||||
def test_basic_slug(self):
|
||||
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
|
||||
self.assertIn("hello-world", slugs)
|
||||
|
||||
def test_strips_punctuation(self):
|
||||
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
|
||||
self.assertIn("whats-new-2024", slugs)
|
||||
|
||||
def test_keeps_underscore_and_hyphen(self):
|
||||
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
|
||||
self.assertIn("foo_bar-baz", slugs)
|
||||
|
||||
def test_duplicate_headings(self):
|
||||
body = "# Setup\n\n# Setup\n\n# Setup\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("setup", slugs)
|
||||
self.assertIn("setup-1", slugs)
|
||||
self.assertIn("setup-2", slugs)
|
||||
|
||||
def test_suffix_skips_literal_heading_slug(self):
|
||||
# Regression: counting identical bases alone lets a generated
|
||||
# suffix collide with a literal heading slug, so the third `Foo`
|
||||
# also became `foo-1` and a link to the wrong heading validated.
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_suffix_skips_multiple_literal_heading_slugs(self):
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
|
||||
|
||||
def test_three_identical_headings(self):
|
||||
body = "# Foo\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_literal_slug_before_duplicates(self):
|
||||
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
|
||||
|
||||
def test_heading_link_contributes_only_its_text(self):
|
||||
# GitHub slugs the rendered heading, where the link's URL is gone.
|
||||
# Slugging the raw source appended the URL and made the first real
|
||||
# link to the anchor look broken.
|
||||
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
|
||||
self.assertEqual(slugs, {"setup-guide-notes"})
|
||||
|
||||
def test_heading_link_matches_github_for_the_readme_heading(self):
|
||||
# The exact heading at README.md:53; GitHub renders
|
||||
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
|
||||
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
|
||||
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(
|
||||
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
|
||||
|
||||
def test_heading_link_duplicate_still_gets_a_suffix(self):
|
||||
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
|
||||
|
||||
def test_heading_link_inside_a_code_span_stays_literal(self):
|
||||
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
|
||||
# the slug. Substituting links first made this `code-x-span`.
|
||||
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
|
||||
self.assertEqual(slugs, {"code-xy-span"})
|
||||
|
||||
def test_heading_mixes_a_code_span_and_a_link(self):
|
||||
# Only the real link loses its URL; the code span keeps its text.
|
||||
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
|
||||
self.assertEqual(slugs, {"see-a-and-b"})
|
||||
|
||||
def test_heading_double_backtick_code_span(self):
|
||||
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
|
||||
# the inner single-backtick run closes the outer span early, so the
|
||||
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
|
||||
# observed GitHub anchor keeps this honest rather than assuming the
|
||||
# "obvious" answer.
|
||||
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
|
||||
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
|
||||
|
||||
def test_heading_image_is_not_treated_as_a_link(self):
|
||||
# An image contributes its alt text through GitHub's rendering, but
|
||||
# the `(?<!\!)` guard must keep this path unchanged for now.
|
||||
slugs = docs_hygiene.markdown_slugs("##  caption\n")
|
||||
self.assertEqual(len(slugs), 1)
|
||||
|
||||
def test_fenced_code_block_ignored(self):
|
||||
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("real-heading", slugs)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_tilde_fence_ignored(self):
|
||||
body = "~~~\n# Not A Heading\n~~~\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_atx_levels(self):
|
||||
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
for s in ("one", "two", "three", "four", "five", "six"):
|
||||
self.assertIn(s, slugs)
|
||||
|
||||
|
||||
class CheckLinksTests(unittest.TestCase):
|
||||
"""Exercise check_links with a synthetic in-memory file set."""
|
||||
|
||||
def _run(self, files):
|
||||
"""files: dict mapping repo-relative path -> Markdown body."""
|
||||
problems = []
|
||||
original_text = docs_hygiene.text
|
||||
|
||||
def fake_text(path):
|
||||
return files.get(path)
|
||||
|
||||
docs_hygiene.text = fake_text
|
||||
try:
|
||||
docs_hygiene.check_links(list(files), problems)
|
||||
finally:
|
||||
docs_hygiene.text = original_text
|
||||
return problems
|
||||
|
||||
def test_existing_heading_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_in_page_anchor_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#no-such-heading)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#no-such-heading", problems[0])
|
||||
self.assertIn("heading not found", problems[0])
|
||||
|
||||
def test_in_page_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#this-heading-does-not-exist", problems[0])
|
||||
|
||||
def test_duplicate_heading_addressable(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#setup-1)\n",
|
||||
"docs/b.md": "# Setup\n\n# Setup\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_fenced_heading_not_a_slug(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#not-a-heading)\n",
|
||||
"docs/b.md": "```\n# Not A Heading\n```\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#not-a-heading", problems[0])
|
||||
|
||||
def test_external_url_with_fragment_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_mailto_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_protocol_relative_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](//example.com/page#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_bare_hash_skipped(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](#)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_missing_file_still_reported(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](nonexistent.md#foo)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("broken relative link", problems[0])
|
||||
|
||||
def test_fragment_on_non_markdown_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](image.png#foo)\n",
|
||||
"docs/image.png": None,
|
||||
})
|
||||
# image.png is binary (text returns None) but it exists in the
|
||||
# file list, so the link itself resolves; fragment is not checked.
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
|
||||
class MarkerTests(unittest.TestCase):
|
||||
"""The conflict-marker check must catch all four markers, including the diff3 one."""
|
||||
|
||||
def _markers(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "f.md").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_markers({"f.md": text}, problems)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_every_marker_kind_is_reported(self):
|
||||
for line in ["<<<<<<< HEAD", "||||||| merged common ancestors", "=======", ">>>>>>> topic"]:
|
||||
problems = self._markers(line + "\n")
|
||||
self.assertEqual(len(problems), 1, f"{line!r} was not reported: {problems}")
|
||||
self.assertIn("f.md:1", problems[0])
|
||||
|
||||
def test_diff3_base_marker_is_reported(self):
|
||||
base = self._markers("||||||| merged common ancestors\n")
|
||||
self.assertEqual(len(base), 1, "the diff3 base marker must be reported")
|
||||
self.assertIn("conflict marker", base[0])
|
||||
|
||||
def test_a_diff3_block_reports_all_four_lines(self):
|
||||
block = "<<<<<<< HEAD\na\n||||||| merged common ancestors\nb\n=======\nc\n>>>>>>> topic\n"
|
||||
problems = self._markers(block)
|
||||
self.assertEqual(len(problems), 4, problems)
|
||||
|
||||
def test_ordinary_content_is_not_a_marker(self):
|
||||
for text in ["| a | b |\n", "||||||\n", "======\n", "prose with | pipes\n", "---\n"]:
|
||||
self.assertEqual(self._markers(text), [], f"{text!r} was wrongly reported")
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
"""check_workflows must reject unparseable YAML."""
|
||||
|
||||
def _check(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / ".github" / "workflows").mkdir(parents=True)
|
||||
(root / ".github" / "workflows" / "a.yml").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_workflows({".github/workflows/a.yml": text}, problems, require_yaml=True)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_parses_a_valid_workflow(self):
|
||||
self.assertEqual(self._check("on: push\njobs:\n b:\n runs-on: ubuntu-latest\n"), [])
|
||||
|
||||
def test_reports_invalid_yaml(self):
|
||||
problems = self._check("on: [push\n")
|
||||
self.assertEqual(len(problems), 1, problems)
|
||||
self.assertIn("a.yml", problems[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -29,13 +29,16 @@
|
||||
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
|
||||
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
|
||||
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
|
||||
//! so preparation does not copy it.
|
||||
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
|
||||
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
|
||||
//! size and stage metadata but does not classify as executable `DXIL`.
|
||||
//!
|
||||
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
|
||||
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
|
||||
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
|
||||
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
|
||||
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
|
||||
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
|
||||
//! including when an accompanying `FSPX` table is malformed, and logs only an
|
||||
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
|
||||
//! is not implemented.
|
||||
|
||||
mod c_abi;
|
||||
mod fspx;
|
||||
@@ -97,6 +100,55 @@ pub struct ShaderInspection {
|
||||
pub chunks: Vec<ChunkInfo>,
|
||||
}
|
||||
|
||||
impl ShaderInspection {
|
||||
/// Payload of the first chunk tagged `fourcc`, if present and fully
|
||||
/// inside the container. Returns `None` when absent, when the declared
|
||||
/// size would run past `container_size` or `container`, or when `offset`
|
||||
/// points into the DXBC header or chunk-offset table instead of a chunk
|
||||
/// header.
|
||||
///
|
||||
/// `container` must be the same bytes passed to [`inspect_dxbc`]; the
|
||||
/// inspection only stores chunk metadata, so the original container is
|
||||
/// required to slice out the payload. `ChunkInfo::offset` is relative to
|
||||
/// the start of the `DXBC` container and points at the 8-byte chunk
|
||||
/// header (fourcc + size), so the payload begins at `offset + 8`.
|
||||
///
|
||||
/// A zero-size chunk yields `Some(&[])`: the header is present and
|
||||
/// in-bounds, so an empty payload is a valid result rather than an
|
||||
/// absence. Callers that require a minimum size must check the returned
|
||||
/// slice length.
|
||||
///
|
||||
/// Only the already-parsed `self.chunks` table is consulted; the raw
|
||||
/// chunk table is not re-walked. When several chunks share `fourcc`,
|
||||
/// the first one in table order wins, matching the C++ `find_chunk`.
|
||||
pub fn chunk_payload<'a>(&self, container: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
let chunk = self.chunks.iter().find(|c| &c.fourcc == fourcc)?;
|
||||
let table_bytes = u64::try_from(self.chunks.len()).ok()?.checked_mul(4)?;
|
||||
let table_end = 32u64.checked_add(table_bytes)?;
|
||||
if u64::from(chunk.offset) < table_end {
|
||||
return None;
|
||||
}
|
||||
let start = u64::from(chunk.offset).checked_add(8)?;
|
||||
let end = start.checked_add(u64::from(chunk.size))?;
|
||||
if end > u64::from(self.container_size) {
|
||||
return None;
|
||||
}
|
||||
let start = usize::try_from(start).ok()?;
|
||||
let end = usize::try_from(end).ok()?;
|
||||
if end > container.len() {
|
||||
return None;
|
||||
}
|
||||
container.get(start..end)
|
||||
}
|
||||
|
||||
/// True when a chunk header tagged `fourcc` exists, whatever its
|
||||
/// declared size. Mirrors the C++ `has_chunk_tag`: presence without
|
||||
/// trusting the size.
|
||||
pub fn has_chunk_tag(&self, fourcc: &[u8; 4]) -> bool {
|
||||
self.chunks.iter().any(|c| &c.fourcc == fourcc)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
TooShort,
|
||||
@@ -264,14 +316,22 @@ fn record_fspx_stage(
|
||||
}
|
||||
}
|
||||
|
||||
enum DxilProgram {
|
||||
Executable((ShaderStage, u8, u8)),
|
||||
HeaderOnly((ShaderStage, u8, u8)),
|
||||
}
|
||||
|
||||
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
|
||||
///
|
||||
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
|
||||
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
|
||||
/// and must be at least 16. `BitcodeSize` must be non-zero, and
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
|
||||
/// bitcode bytes are not decoded.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
|
||||
///
|
||||
/// A bitcode payload beginning with `NOBC` is a header-only container (for
|
||||
/// example, reflection or signature metadata with bitcode stripped) and is
|
||||
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
|
||||
const PROGRAM_PREFIX: u64 = 8;
|
||||
const BITCODE_HEADER: u64 = 16;
|
||||
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
|
||||
@@ -300,7 +360,16 @@ fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
|
||||
if end > program_bytes {
|
||||
return Err(());
|
||||
}
|
||||
Ok(program_stage(program_version))
|
||||
let bitcode_start =
|
||||
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
|
||||
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
|
||||
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
|
||||
let stage = program_stage(program_version);
|
||||
if bitcode.starts_with(b"NOBC") {
|
||||
Ok(DxilProgram::HeaderOnly(stage))
|
||||
} else {
|
||||
Ok(DxilProgram::Executable(stage))
|
||||
}
|
||||
}
|
||||
|
||||
struct ContainerLimit {
|
||||
@@ -407,6 +476,37 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DxilChunkState {
|
||||
has_executable: bool,
|
||||
size: u32,
|
||||
executable_stage: Option<(ShaderStage, u8, u8)>,
|
||||
header_only_stage: Option<(ShaderStage, u8, u8)>,
|
||||
}
|
||||
|
||||
impl DxilChunkState {
|
||||
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
|
||||
/// header-only placeholders regardless of chunk order.
|
||||
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
|
||||
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
|
||||
DxilProgram::Executable(stage) => {
|
||||
self.has_executable = true;
|
||||
self.size = size;
|
||||
self.executable_stage = Some(stage);
|
||||
}
|
||||
DxilProgram::HeaderOnly(stage) => {
|
||||
if !self.has_executable {
|
||||
self.size = size;
|
||||
}
|
||||
if self.header_only_stage.is_none() {
|
||||
self.header_only_stage = Some(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
|
||||
/// keep chunk or section lists.
|
||||
pub(crate) struct DxbcSummary {
|
||||
@@ -425,24 +525,16 @@ pub(crate) struct DxbcSummary {
|
||||
///
|
||||
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
|
||||
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
let mut has_dxil = false;
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -463,36 +555,40 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil_stage
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil
|
||||
.executable_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
Ok(DxbcSummary {
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major,
|
||||
shader_model_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size,
|
||||
dxil_size: dxil.size,
|
||||
accc_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// `Ok(Some(container_size))` when the container is structurally valid and
|
||||
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
|
||||
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
|
||||
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no `DXIL` chunk.
|
||||
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
|
||||
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
|
||||
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
|
||||
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no executable `DXIL` chunk.
|
||||
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
|
||||
let mut has_dxil = false;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
|
||||
if &fourcc == b"DXIL" {
|
||||
if read_dxil_program(payload).is_err() {
|
||||
return Err(ParseError::BadDxilHeader { chunk: index });
|
||||
match read_dxil_program(payload) {
|
||||
Ok(DxilProgram::Executable(_)) => has_dxil = true,
|
||||
Ok(DxilProgram::HeaderOnly(_)) => {}
|
||||
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
|
||||
}
|
||||
has_dxil = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -512,27 +608,19 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
|
||||
/// container through.
|
||||
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
let mut chunks = Vec::new();
|
||||
let mut has_dxil = false;
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut accc_is_fspx = false;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let mut fspx = None;
|
||||
|
||||
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -570,21 +658,22 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let (stage, sm_major, sm_minor) =
|
||||
dxil_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
let (stage, sm_major, sm_minor) = dxil
|
||||
.executable_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
|
||||
Ok(ShaderInspection {
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major: sm_major,
|
||||
shader_model_minor: sm_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size,
|
||||
dxil_size: dxil.size,
|
||||
accc_size,
|
||||
accc_is_fspx,
|
||||
fspx,
|
||||
@@ -981,8 +1070,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn truncated_prefixes_do_not_panic() {
|
||||
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc_dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let blobs = [
|
||||
synthetic_dxil_blob(),
|
||||
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
|
||||
vec![0xFF; 64],
|
||||
@@ -990,6 +1082,8 @@ mod tests {
|
||||
for blob in blobs {
|
||||
for len in 0..=blob.len() {
|
||||
let _ = inspect_dxbc(&blob[..len]);
|
||||
let _ = summarize_dxbc(&blob[..len]);
|
||||
let _ = dxil_container_len(&blob[..len]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1469,6 +1563,245 @@ mod tests {
|
||||
assert!(log[0].contains("sm_minor=0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_is_not_classified_as_executable_dxil() {
|
||||
clear_shader_log();
|
||||
// Pixel shader (0), SM 6.6, with the four-byte NOBC placeholder instead of LLVM bitcode.
|
||||
let mut payload = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("valid DXBC with NOBC header-only DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
assert_eq!(info.stage, ShaderStage::Pixel);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert!(info.has_root_signature);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 0); // BX_SHADER_UNKNOWN
|
||||
assert_eq!(c_info.stage, 1); // BX_STAGE_PIXEL
|
||||
assert_eq!(c_info.shader_model_major, 6);
|
||||
assert_eq!(c_info.shader_model_minor, 6);
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_accc_is_classified_as_accc_only_and_rejected() {
|
||||
clear_shader_log();
|
||||
let mut dxil = minimal_dxil_program((1u32 << 16) | (6u32 << 4) | 6u32);
|
||||
dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let fspx = fspx_compute_stage();
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil), (b"ACCC", &fspx)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("NOBC + ACCC container");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert_eq!(info.accc_size, 40);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 3); // BX_SHADER_DXBC_ACCC
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
let log = shader_log_lines();
|
||||
assert_eq!(log.len(), 1);
|
||||
assert!(log[0].contains("kind=accc_only(3)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_padded_bitcode_is_still_header_only() {
|
||||
let mut payload = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
payload[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
payload[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[8..12].copy_from_slice(b"DXIL");
|
||||
payload[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
payload[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
payload[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("padded NOBC DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_executable_and_nobc_dxil_preserves_executable_metadata() {
|
||||
let exec = minimal_dxil_program((5u32 << 16) | (6u32 << 4) | 5u32);
|
||||
let mut nobc = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
nobc[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[8..12].copy_from_slice(b"DXIL");
|
||||
nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
nobc[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
nobc[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
|
||||
// Executable first, NOBC second: executable stage and size must win.
|
||||
let blob_exec_first = build_synthetic_dxbc(&[(b"DXIL", &exec), (b"DXIL", &nobc)]);
|
||||
let info = inspect_dxbc(&blob_exec_first).expect("mixed DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 5));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
bx_shader_inspect(blob_exec_first.as_ptr(), blob_exec_first.len(), &mut c_info)
|
||||
},
|
||||
BX_SHADER_OK
|
||||
);
|
||||
assert_eq!(c_info.kind, 1); // BX_SHADER_DXBC_DXIL
|
||||
assert_eq!(c_info.stage, 6); // BX_STAGE_COMPUTE
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob_exec_first),
|
||||
Ok(Some(blob_exec_first.len() as u32))
|
||||
);
|
||||
|
||||
// NOBC first, executable second: executable must still win.
|
||||
let blob_nobc_first = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"DXIL", &exec)]);
|
||||
let info2 = inspect_dxbc(&blob_nobc_first).expect("mixed DXIL reversed");
|
||||
assert_eq!(info2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info2.stage, ShaderStage::Compute);
|
||||
assert_eq!((info2.shader_model_major, info2.shader_model_minor), (6, 5));
|
||||
assert_eq!(info2.dxil_size, 28);
|
||||
let summary2 = summarize_dxbc(&blob_nobc_first).expect("mixed DXIL summary");
|
||||
assert_eq!(summary2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(summary2.stage, ShaderStage::Compute);
|
||||
assert_eq!(summary2.dxil_size, 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_malformed_fspx_returns_invalid_blob() {
|
||||
clear_shader_log();
|
||||
let mut nobc = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
let bad_fspx = fspx_header(99, 0, &[], 16);
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"ACCC", &bad_fspx)]);
|
||||
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxBadVersion {
|
||||
chunk: 1,
|
||||
version: 99,
|
||||
})
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob), Ok(None));
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxil_bitcode_bounds_and_offset_checks() {
|
||||
let prog = (5u32 << 16) | (6u32 << 4) | 6u32;
|
||||
|
||||
// Bitcode shorter than 4 bytes (`NOB`) must not misclassify as `NOBC` or read out of bounds.
|
||||
let mut short_bitcode = [0u8; 28];
|
||||
short_bitcode[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
short_bitcode[4..8].copy_from_slice(&7u32.to_le_bytes());
|
||||
short_bitcode[8..12].copy_from_slice(b"DXIL");
|
||||
short_bitcode[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
short_bitcode[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
short_bitcode[20..24].copy_from_slice(&3u32.to_le_bytes());
|
||||
short_bitcode[24..27].copy_from_slice(b"NOB");
|
||||
let blob_short = build_synthetic_dxbc(&[(b"DXIL", &short_bitcode)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_short).expect("3-byte bitcode").kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// `NOBC` check follows `BitcodeOffset`, not a fixed offset 24.
|
||||
let mut shifted_nobc = vec![0u8; 36];
|
||||
shifted_nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
shifted_nobc[4..8].copy_from_slice(&9u32.to_le_bytes());
|
||||
shifted_nobc[8..12].copy_from_slice(b"DXIL");
|
||||
shifted_nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
shifted_nobc[16..20].copy_from_slice(&24u32.to_le_bytes());
|
||||
shifted_nobc[20..24].copy_from_slice(&4u32.to_le_bytes());
|
||||
shifted_nobc[32..36].copy_from_slice(b"NOBC");
|
||||
let blob_shifted_nobc = build_synthetic_dxbc(&[(b"DXIL", &shifted_nobc)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_nobc).expect("shifted NOBC").kind,
|
||||
ShaderKind::Unknown
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob_shifted_nobc), Ok(None));
|
||||
|
||||
// Bytes before `BitcodeOffset` containing `NOBC` do not make executable bitcode header-only.
|
||||
let mut shifted_exec = shifted_nobc;
|
||||
shifted_exec[24..28].copy_from_slice(b"NOBC");
|
||||
shifted_exec[32..36].copy_from_slice(&[0xD1, 0x11, 0xC0, 0xDE]);
|
||||
let blob_shifted_exec = build_synthetic_dxbc(&[(b"DXIL", &shifted_exec)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_exec)
|
||||
.expect("shifted executable")
|
||||
.kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// Overflowing bitcode offset / size must reject cleanly as `BadDxilHeader`.
|
||||
for (bitcode_off, bitcode_sz) in [(16u32, u32::MAX), (u32::MAX - 4, 4u32)] {
|
||||
let mut overflow = minimal_dxil_program(prog);
|
||||
overflow[16..20].copy_from_slice(&bitcode_off.to_le_bytes());
|
||||
overflow[20..24].copy_from_slice(&bitcode_sz.to_le_bytes());
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &overflow)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
summarize_dxbc(&blob).map(|_| ()),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn fspx_table_with_sections(count: u32) -> Vec<u8> {
|
||||
let count_usize = count as usize;
|
||||
let table_end = 16 + count_usize * 12;
|
||||
@@ -1503,4 +1836,99 @@ mod tests {
|
||||
fn ptr_sentinel() -> *mut u8 {
|
||||
std::ptr::dangling_mut()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_returns_sfi0_and_psv0_bytes() {
|
||||
let sfi0: [u8; 8] = [0x00, 0x40, 0, 0, 0, 0, 0, 0];
|
||||
let psv0: [u8; 28] = [
|
||||
24, 0, 0, 0, // info_size = 24
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, // lanes_min
|
||||
64, 0, 0, 0, // lanes_max
|
||||
];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &sfi0), (b"PSV0", &psv0)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid container");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(sfi0.as_slice()));
|
||||
assert_eq!(info.chunk_payload(&blob, b"PSV0"), Some(psv0.as_slice()));
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
assert!(info.has_chunk_tag(b"PSV0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_rejects_declared_size_past_container() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4])]);
|
||||
let mut info = inspect_dxbc(&blob).expect("valid container");
|
||||
|
||||
// A declared size that runs past container_size must yield None, not
|
||||
// a panic and not a slice clipped to the container.
|
||||
info.chunks[0].size = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
// Presence without trusting the size still holds.
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
|
||||
// A forged public ChunkInfo must not treat the DXBC header or offset
|
||||
// table as a chunk header.
|
||||
info.chunks[0].size = 4;
|
||||
info.chunks[0].offset = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A header offset past the container must also yield None.
|
||||
info.chunks[0].offset = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A chunk header that would end exactly one byte past the container.
|
||||
info.chunks[0].offset = info.container_size - 7;
|
||||
info.chunks[0].size = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_absent_fourcc() {
|
||||
let blob = synthetic_dxil_blob();
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
assert!(!info.has_chunk_tag(b"SFI0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_zero_size_returns_empty_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
let payload = info.chunk_payload(&blob, b"SFI0");
|
||||
assert_eq!(payload, Some(&[][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_exact_fit_at_container_end() {
|
||||
let payload = [0xAA, 0xBB, 0xCC, 0xDD];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &payload)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// The chunk is the last thing in the container; payload ends exactly
|
||||
// at container_size.
|
||||
let chunk = &info.chunks[0];
|
||||
assert_eq!(
|
||||
u64::from(chunk.offset) + 8 + u64::from(chunk.size),
|
||||
u64::from(info.container_size)
|
||||
);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(payload.as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_truncated_container_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4, 5, 6, 7, 8])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// Pass a slice shorter than container_size.
|
||||
let short = &blob[..blob.len() - 4];
|
||||
assert_eq!(info.chunk_payload(short, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_first_duplicate_wins() {
|
||||
let first = [0x11, 0x22];
|
||||
let second = [0x33, 0x44, 0x55];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &first), (b"SFI0", &second)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunks.len(), 2);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(first.as_slice()));
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -47,19 +47,28 @@ HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
|
||||
// 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 S_OK;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
|
||||
return S_OK;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
// A zero-capacity heap must not report S_OK: it can never satisfy an
|
||||
// allocation, so creating it is a caller error (#580). ApuAlloc already
|
||||
// refused such requests with E_OUTOFMEMORY.
|
||||
if (uint64_t(cached) + non_cached == 0) return E_INVALIDARG;
|
||||
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
|
||||
used = 0;
|
||||
capacity = uint64_t(cached) + non_cached;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
d3d12_xs.cpp
|
||||
vmem.cpp
|
||||
presentx.cpp
|
||||
proxy.cpp
|
||||
proxy_generated.cpp
|
||||
shader_gate.cpp
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
#include "presentx.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
|
||||
#include "proxy.h"
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465). See presentx.h for the contract and for what this is not.
|
||||
* Host DXGI is loaded on demand, like the host d3d12.dll in d3d12_xs.cpp.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr HRESULT kWaitTimedOut = static_cast<HRESULT>(0x800705B4u); /* HRESULT_FROM_WIN32(ERROR_TIMEOUT) */
|
||||
|
||||
bool is_device_removed_hr(HRESULT hr) {
|
||||
return hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ||
|
||||
hr == DXGI_ERROR_DEVICE_RESET || hr == DXGI_ERROR_DRIVER_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
void log_hr(bx_log_level_t level, const char* event, 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(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
/* Releases an already acquired lock and records its owner, so re-entry can be refused. */
|
||||
class SrwOwner {
|
||||
public:
|
||||
SrwOwner(SRWLOCK& lock, std::atomic<DWORD>& owner) : lock_(lock), owner_(owner) { owner_ = GetCurrentThreadId(); }
|
||||
~SrwOwner() {
|
||||
owner_ = 0;
|
||||
ReleaseSRWLockExclusive(&lock_);
|
||||
}
|
||||
SrwOwner(const SrwOwner&) = delete;
|
||||
SrwOwner& operator=(const SrwOwner&) = delete;
|
||||
|
||||
private:
|
||||
SRWLOCK& lock_;
|
||||
std::atomic<DWORD>& owner_;
|
||||
};
|
||||
|
||||
class BxPresentSwapChain final : public IBxPresentSwapChain {
|
||||
public:
|
||||
/* `queue_proxy` is referenced for the lifetime of the chain; `host_queue` is its host object. */
|
||||
static HRESULT create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out);
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
|
||||
ULONG STDMETHODCALLTYPE AddRef() override;
|
||||
ULONG STDMETHODCALLTYPE Release() override;
|
||||
|
||||
HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) override;
|
||||
UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() override;
|
||||
HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) override;
|
||||
HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) override;
|
||||
HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) override;
|
||||
|
||||
private:
|
||||
BxPresentSwapChain() = default;
|
||||
~BxPresentSwapChain() = default;
|
||||
|
||||
HRESULT init(HWND window, const BxPresentDesc& desc);
|
||||
HRESULT signal_locked(UINT64* value);
|
||||
HRESULT wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT idle_locked(ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT post_present_failure(const char* event, const char* what, HRESULT hr, HRESULT live_device_result);
|
||||
HRESULT removed_reason();
|
||||
void destroy();
|
||||
|
||||
std::atomic<ULONG> refs_{1};
|
||||
SRWLOCK lock_ = SRWLOCK_INIT; /* guards the fence counter, the event and Present */
|
||||
ID3D12CommandQueue* queue_proxy_ = nullptr;
|
||||
ID3D12CommandQueue* host_queue_ = nullptr;
|
||||
HWND window_ = nullptr;
|
||||
IDXGISwapChain3* swap_ = nullptr;
|
||||
ID3D12Fence* fence_ = nullptr;
|
||||
HANDLE event_ = nullptr;
|
||||
std::atomic<DWORD> owner_{0}; /* thread holding lock_ */
|
||||
UINT64 last_signaled_ = 0;
|
||||
UINT64 presented_ = 0;
|
||||
bool needs_idle_ = false; /* post-present signal or wait failed; only an idle queue clears this */
|
||||
UINT64 buffer_value_[DXGI_MAX_SWAP_CHAIN_BUFFERS] = {};
|
||||
};
|
||||
|
||||
HRESULT BxPresentSwapChain::create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out) {
|
||||
auto* self = new (std::nothrow) BxPresentSwapChain();
|
||||
if (!self) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
queue_proxy->AddRef();
|
||||
self->queue_proxy_ = queue_proxy;
|
||||
host_queue->AddRef();
|
||||
self->host_queue_ = host_queue;
|
||||
self->window_ = window;
|
||||
|
||||
HRESULT hr = self->init(window, desc);
|
||||
if (FAILED(hr)) {
|
||||
self->destroy(); /* nothing was submitted, so every partially created object can go */
|
||||
return hr;
|
||||
}
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::init(HWND window, const BxPresentDesc& desc) {
|
||||
static HMODULE dxgi = LoadLibraryA("dxgi.dll");
|
||||
using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**);
|
||||
auto create_factory = dxgi
|
||||
? reinterpret_cast<CreateFactoryFn>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")))
|
||||
: nullptr;
|
||||
if (!create_factory) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_dxgi_missing", "dxgi.dll!CreateDXGIFactory1 not available");
|
||||
return DXGI_ERROR_UNSUPPORTED;
|
||||
}
|
||||
|
||||
IDXGIFactory4* factory = nullptr;
|
||||
HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateDXGIFactory1", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC1 sd = {};
|
||||
sd.Width = desc.width;
|
||||
sd.Height = desc.height;
|
||||
sd.Format = desc.format;
|
||||
sd.SampleDesc.Count = 1;
|
||||
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
sd.BufferCount = desc.buffer_count;
|
||||
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
|
||||
IDXGISwapChain1* swap1 = nullptr;
|
||||
/* For D3D12 the "device" argument of CreateSwapChainForHwnd is the command queue. */
|
||||
hr = factory->CreateSwapChainForHwnd(host_queue_, window, &sd, nullptr, nullptr, &swap1);
|
||||
if (SUCCEEDED(hr)) {
|
||||
/* Alt+Enter would require ResizeBuffers handling that the bridge does not have. */
|
||||
HRESULT assoc = factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER);
|
||||
if (FAILED(assoc)) {
|
||||
log_hr(BX_LOG_WARN, "present_window_association", "MakeWindowAssociation", assoc);
|
||||
}
|
||||
}
|
||||
factory->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateSwapChainForHwnd", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
hr = swap1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&swap_));
|
||||
swap1->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "QueryInterface(IDXGISwapChain3)", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence_));
|
||||
device->Release();
|
||||
}
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateFence", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
event_ = CreateEventA(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event_) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateEvent", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "width=%u height=%u format=%d buffers=%u",
|
||||
desc.width, desc.height, static_cast<int>(desc.format), desc.buffer_count);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_chain_created", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::removed_reason() {
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (FAILED(hr)) {
|
||||
return hr;
|
||||
}
|
||||
hr = device->GetDeviceRemovedReason();
|
||||
device->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::signal_locked(UINT64* value) {
|
||||
const UINT64 next = last_signaled_ + 1;
|
||||
HRESULT hr = host_queue_->Signal(fence_, next);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_signal_failed", "ID3D12CommandQueue::Signal", hr);
|
||||
return hr;
|
||||
}
|
||||
last_signaled_ = next;
|
||||
*value = next;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms) {
|
||||
for (;;) {
|
||||
const UINT64 completed = fence_->GetCompletedValue();
|
||||
if (completed == UINT64_MAX) { /* the documented value after device removal */
|
||||
HRESULT reason = removed_reason();
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", "fence", reason);
|
||||
return FAILED(reason) ? reason : DXGI_ERROR_DEVICE_REMOVED;
|
||||
}
|
||||
if (completed >= value) {
|
||||
return S_OK;
|
||||
}
|
||||
const ULONGLONG elapsed = GetTickCount64() - start;
|
||||
if (elapsed >= timeout_ms) {
|
||||
break;
|
||||
}
|
||||
HRESULT hr = fence_->SetEventOnCompletion(value, event_);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "SetEventOnCompletion", hr);
|
||||
return hr;
|
||||
}
|
||||
const ULONGLONG elapsed_after_registration = GetTickCount64() - start;
|
||||
if (elapsed_after_registration >= timeout_ms) {
|
||||
continue; /* Recheck the fence before reporting a timeout. */
|
||||
}
|
||||
/* The event can be left over from an earlier timed-out wait, so the loop re-reads the fence. */
|
||||
DWORD waited = WaitForSingleObject(event_, static_cast<DWORD>(timeout_ms - elapsed_after_registration));
|
||||
if (waited == WAIT_FAILED) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "WaitForSingleObject", hr);
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=%llu", static_cast<unsigned long>(timeout_ms),
|
||||
static_cast<unsigned long long>(value), static_cast<unsigned long long>(fence_->GetCompletedValue()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::post_present_failure(const char* event, const char* what, HRESULT hr,
|
||||
HRESULT live_device_result) {
|
||||
const HRESULT removed = removed_reason();
|
||||
if (FAILED(removed)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, removed);
|
||||
return removed;
|
||||
}
|
||||
needs_idle_ = true;
|
||||
if (event) {
|
||||
log_hr(BX_LOG_ERROR, event, what, hr);
|
||||
}
|
||||
if (is_device_removed_hr(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, hr);
|
||||
return hr;
|
||||
}
|
||||
return live_device_result;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::idle_locked(ULONGLONG start, DWORD timeout_ms) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=unknown; expired before Signal",
|
||||
static_cast<unsigned long>(timeout_ms), static_cast<unsigned long long>(last_signaled_ + 1));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
UINT64 value = 0;
|
||||
HRESULT hr = signal_locked(&value);
|
||||
return FAILED(hr) ? hr : wait_locked(value, start, timeout_ms);
|
||||
}
|
||||
|
||||
void BxPresentSwapChain::destroy() {
|
||||
if (swap_ && fence_ && event_) {
|
||||
HRESULT idle = idle_locked(GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(idle) && SUCCEEDED(removed_reason())) {
|
||||
/* The device is alive and the GPU may still be using the back buffers. */
|
||||
log_hr(BX_LOG_ERROR, "present_chain_leaked", "queue not idle; GPU-visible objects deliberately not released", idle);
|
||||
/*
|
||||
* swap_, fence_, event_ and host_queue_ stay: pending work may touch them. The proxy
|
||||
* is only BetterXen's wrapper; host_queue_ keeps the host queue alive without it.
|
||||
*/
|
||||
ID3D12CommandQueue* proxy = queue_proxy_;
|
||||
delete this;
|
||||
proxy->Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const bool had_swap = swap_ != nullptr;
|
||||
ULONG swap_refs = 0;
|
||||
if (swap_) swap_refs = swap_->Release();
|
||||
if (fence_) fence_->Release();
|
||||
if (event_) CloseHandle(event_);
|
||||
if (had_swap) {
|
||||
/*
|
||||
* The count the host's Release returned. Non-zero means something else still references
|
||||
* the swapchain: back buffers or host pointers the caller holds, or the host itself
|
||||
* (see docs/research/d3dmetal-swapchain-references.md). It is reported, never "fixed up"
|
||||
* by releasing references this object does not own.
|
||||
*/
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "presented=%llu swapchain_release_returned=%lu",
|
||||
static_cast<unsigned long long>(presented_), static_cast<unsigned long>(swap_refs));
|
||||
bx_log_emit(swap_refs ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "present_chain_destroyed", detail);
|
||||
}
|
||||
ID3D12CommandQueue* host_queue = host_queue_;
|
||||
ID3D12CommandQueue* queue_proxy = queue_proxy_;
|
||||
delete this;
|
||||
if (host_queue) host_queue->Release();
|
||||
if (queue_proxy) queue_proxy->Release();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::QueryInterface(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, __uuidof(IUnknown)) || IsEqualGUID(riid, IID_IBxPresentSwapChain)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentSwapChain*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::AddRef() {
|
||||
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::Release() {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
destroy();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetBuffer(UINT index, REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
HRESULT hr = swap_->GetBuffer(index, riid, ppv);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_WARN, "present_get_buffer_failed", "IDXGISwapChain::GetBuffer", hr);
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE BxPresentSwapChain::GetCurrentBackBufferIndex() {
|
||||
return swap_->GetCurrentBackBufferIndex();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::Present(UINT sync_interval, UINT flags) {
|
||||
BX_D3D_TRACE("IBxPresentSwapChain", "Present");
|
||||
if (sync_interval > 4 || flags != 0 || !IsWindow(window_)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x window_alive=%d", sync_interval, flags,
|
||||
IsWindow(window_) ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", detail);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", "re-entered on the same thread");
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
/*
|
||||
* Never wait for the lock. Its holder may be inside the host's Present, and DXGI can make that
|
||||
* call wait for the window's thread: the caller here.
|
||||
*/
|
||||
if (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_busy", "another call holds the swapchain; nothing presented");
|
||||
return BX_PRESENT_E_BUSY;
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
if (needs_idle_) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_needs_idle", "completion unconfirmed; nothing presented");
|
||||
return BX_PRESENT_E_NEEDS_IDLE;
|
||||
}
|
||||
const UINT presented_index = swap_->GetCurrentBackBufferIndex();
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
/* Busy only after an earlier BX_PRESENT_E_NEXT_BUFFER_BUSY. Nothing is presented then. */
|
||||
const HRESULT ready = wait_locked(buffer_value_[presented_index], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(ready)) {
|
||||
return ready;
|
||||
}
|
||||
}
|
||||
HRESULT hr = swap_->Present(sync_interval, flags);
|
||||
if (FAILED(hr)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x hr=0x%08lx device_removed_reason=0x%08lx", sync_interval,
|
||||
flags, static_cast<unsigned long>(hr), static_cast<unsigned long>(removed_reason()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_failed", detail);
|
||||
return hr;
|
||||
}
|
||||
++presented_;
|
||||
|
||||
UINT64 value = 0;
|
||||
HRESULT sync_hr = signal_locked(&value);
|
||||
if (FAILED(sync_hr)) {
|
||||
/* signal_locked already logged present_signal_failed when the device stays live. */
|
||||
return post_present_failure(nullptr, "signal after Present", sync_hr, BX_PRESENT_E_COMPLETION_UNCONFIRMED);
|
||||
}
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
buffer_value_[presented_index] = value;
|
||||
}
|
||||
const UINT next = swap_->GetCurrentBackBufferIndex();
|
||||
if (next < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
sync_hr = wait_locked(buffer_value_[next], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (sync_hr == kWaitTimedOut) {
|
||||
return BX_PRESENT_E_NEXT_BUFFER_BUSY;
|
||||
}
|
||||
if (FAILED(sync_hr)) {
|
||||
return post_present_failure("present_next_buffer_wait_failed", "wait_locked", sync_hr,
|
||||
BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::WaitForIdle(DWORD timeout_ms) {
|
||||
if (timeout_ms == 0 || timeout_ms == INFINITE) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
while (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", "swapchain busy in another call");
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
Sleep(1);
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
const HRESULT hr = idle_locked(start, timeout_ms);
|
||||
if (hr == S_OK) {
|
||||
/* A signal queued after every presented frame has completed. */
|
||||
needs_idle_ = false;
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetHostSwapChain(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return swap_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
bool desc_is_valid(const BxPresentDesc& d) {
|
||||
const bool format_ok = d.format == DXGI_FORMAT_R8G8B8A8_UNORM || d.format == DXGI_FORMAT_B8G8R8A8_UNORM ||
|
||||
d.format == DXGI_FORMAT_R10G10B10A2_UNORM || d.format == DXGI_FORMAT_R16G16B16A16_FLOAT;
|
||||
return format_ok && d.width >= 1 && d.width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.height >= 1 &&
|
||||
d.height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.buffer_count >= 2 &&
|
||||
d.buffer_count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
|
||||
}
|
||||
|
||||
/* COM tear-off: its own reference count, one reference on the queue, and the queue's identity. */
|
||||
class BxPresentQueue final : public IBxPresentQueue {
|
||||
public:
|
||||
explicit BxPresentQueue(ID3D12CommandQueue* queue_proxy) : queue_(queue_proxy) { queue_->AddRef(); }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentQueue*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
return queue_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; }
|
||||
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
ID3D12CommandQueue* queue = queue_;
|
||||
delete this;
|
||||
queue->Release();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) override {
|
||||
if (!out) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*out = nullptr;
|
||||
if (!desc) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (!window || !IsWindow(window) || !desc_is_valid(*desc)) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "invalid window or description", DXGI_ERROR_INVALID_CALL);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
ID3D12CommandQueue* host = nullptr;
|
||||
HRESULT hr = static_cast<IUnknown*>(bx_unwrap_raw(queue_))
|
||||
->QueryInterface(__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "host command queue", hr);
|
||||
return hr;
|
||||
}
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
|
||||
host->GetDesc(&queue_desc);
|
||||
if (queue_desc.Type != D3D12_COMMAND_LIST_TYPE_DIRECT) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "queue is not a DIRECT queue", DXGI_ERROR_INVALID_CALL);
|
||||
hr = DXGI_ERROR_INVALID_CALL;
|
||||
} else {
|
||||
hr = BxPresentSwapChain::create(queue_, host, window, *desc, out);
|
||||
}
|
||||
host->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
private:
|
||||
~BxPresentQueue() = default;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
ID3D12CommandQueue* queue_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
auto* bridge = new (std::nothrow) BxPresentQueue(queue_proxy);
|
||||
if (!bridge) {
|
||||
*ppv = nullptr;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*ppv = static_cast<IBxPresentQueue*>(bridge);
|
||||
return S_OK;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
#define BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465): the PresentX presentation bridge over host DXGI.
|
||||
*
|
||||
* THESE INTERFACES ARE DEFINED BY BETTERXEN. They are not the console's PresentX, whose
|
||||
* signature and structures are not defined in abi/, and no binary compatibility with any Xbox
|
||||
* interface is claimed. A guest that calls a console-only command queue slot still lands on the
|
||||
* proxy's logged stub.
|
||||
*
|
||||
* Use: QueryInterface the command queue returned by a D3D12XboxCreateDevice device for
|
||||
* IID_IBxPresentQueue, then create a swapchain on a Win32 window. No new DLL export is involved.
|
||||
*
|
||||
* This is a subset of the public DXGI flip model, not all of it: the caller records its own
|
||||
* resource transitions and every back buffer must be in D3D12_RESOURCE_STATE_PRESENT when it is
|
||||
* presented. D3D12 offers no way to query a resource's state, so the bridge cannot check this.
|
||||
* ResizeBuffers and fullscreen are not implemented.
|
||||
*/
|
||||
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
/* {34127279-2D93-4642-88A6-97B834217B8A} */
|
||||
inline const GUID IID_IBxPresentQueue = {0x34127279, 0x2d93, 0x4642, {0x88, 0xa6, 0x97, 0xb8, 0x34, 0x21, 0x7b, 0x8a}};
|
||||
/* {DEC9F73E-DE84-4F87-9167-26203B3A1152} */
|
||||
inline const GUID IID_IBxPresentSwapChain = {0xdec9f73e, 0xde84, 0x4f87, {0x91, 0x67, 0x26, 0x20, 0x3b, 0x3a, 0x11, 0x52}};
|
||||
|
||||
/* Longest single GPU wait Present() performs, and the destructor's wait for the GPU. */
|
||||
inline constexpr DWORD BX_PRESENT_WAIT_MS = 5000;
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the next back buffer is still busy.
|
||||
* Do not present that frame again. Call WaitForIdle until it returns S_OK before reusing a buffer.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_BUSY = static_cast<HRESULT>(0x80040201u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because another Present or WaitForIdle
|
||||
* on this swapchain is in progress. Present never waits for that call. Try again after it returns.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_BUSY = static_cast<HRESULT>(0x80040202u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the following fence signal failed on
|
||||
* a live device, so its completion is unknown. Do not present that frame again. Call WaitForIdle
|
||||
* until it returns S_OK before recording to any back buffer or presenting again. Device removal
|
||||
* returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_COMPLETION_UNCONFIRMED = static_cast<HRESULT>(0x80040203u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because an earlier Present returned
|
||||
* BX_PRESENT_E_COMPLETION_UNCONFIRMED or BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED and no WaitForIdle
|
||||
* has succeeded since.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEEDS_IDLE = static_cast<HRESULT>(0x80040204u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host and signaled, but waiting on the next back
|
||||
* buffer failed on a live device (for example SetEventOnCompletion or WaitForSingleObject). Do not
|
||||
* present that frame again. Call WaitForIdle until it returns S_OK before reusing any back buffer
|
||||
* or presenting again. Device removal returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED = static_cast<HRESULT>(0x80040205u);
|
||||
|
||||
struct BxPresentDesc {
|
||||
UINT width; /* 1..16384; 0 ("use the window size") is not accepted */
|
||||
UINT height; /* 1..16384 */
|
||||
DXGI_FORMAT format; /* R8G8B8A8_UNORM, B8G8R8A8_UNORM, R10G10B10A2_UNORM or R16G16B16A16_FLOAT */
|
||||
UINT buffer_count; /* 2..DXGI_MAX_SWAP_CHAIN_BUFFERS */
|
||||
};
|
||||
|
||||
/*
|
||||
* One swapchain. Holds a reference on the command queue it was created from.
|
||||
* The final Release waits (bounded) for the queue to go idle. If that fails and the device
|
||||
* reports it has not been removed, it logs and deliberately leaks what pending GPU work may
|
||||
* still touch (swapchain, fence, event, host queue) and releases its queue proxy reference.
|
||||
* After device removal everything is released. Time spent inside the host's own Release is not bounded: on the
|
||||
* wined3d/vkd3d path (not D3DMetal) an intermittent stall in it was observed.
|
||||
*/
|
||||
struct IBxPresentSwapChain : public IUnknown {
|
||||
/* Same rules as IDXGISwapChain::GetBuffer. The caller owns the returned reference. */
|
||||
virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) = 0;
|
||||
virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() = 0;
|
||||
/*
|
||||
* Waits (bounded) until the current back buffer is idle, calls IDXGISwapChain::Present,
|
||||
* signals a fence on the queue, then waits until the next back buffer is idle. It never waits
|
||||
* for another thread's call on this swapchain. Results:
|
||||
* - a DXGI success code, including DXGI_STATUS_OCCLUDED: presented, next buffer idle;
|
||||
* - HRESULT_FROM_WIN32(ERROR_TIMEOUT): NOT presented (the current buffer is still busy);
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_BUSY: presented, see its definition;
|
||||
* - BX_PRESENT_E_BUSY: NOT presented, another call holds the swapchain;
|
||||
* - BX_PRESENT_E_COMPLETION_UNCONFIRMED: presented, the fence signal failed on a live device;
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED: presented, waiting on the next back buffer failed
|
||||
* on a live device;
|
||||
* - BX_PRESENT_E_NEEDS_IDLE: NOT presented, WaitForIdle must succeed first;
|
||||
* - another failure: the host's Present failure, a pre-Present fence wait or device failure
|
||||
* (nothing was presented), or a device-removal HRESULT (such as DXGI_ERROR_DEVICE_REMOVED
|
||||
* or DXGI_ERROR_DEVICE_RESET) observed after host Present, returned unchanged. If the
|
||||
* device still reports itself as live, WaitForIdle must succeed before the next Present.
|
||||
* The bounds cover BetterXen's own waits, not time spent inside the host's Present.
|
||||
*
|
||||
* The bridge itself returns DXGI_ERROR_INVALID_CALL, without calling the host, for a
|
||||
* sync_interval above 4, for any flag (none is supported, including DXGI_PRESENT_TEST),
|
||||
* once the window is destroyed, and when Present or WaitForIdle is re-entered on a thread
|
||||
* already inside one of them. D3DMetal 3.0 was observed to answer S_OK to the first three.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) = 0;
|
||||
/*
|
||||
* Waits until everything submitted to the queue before this call has finished. S_OK also ends
|
||||
* the recovery state left by a post-Present synchronization failure on a live device.
|
||||
* Only positive, finite timeouts are supported. Zero and INFINITE return E_INVALIDARG
|
||||
* without signaling. A timeout returns HRESULT_FROM_WIN32(ERROR_TIMEOUT).
|
||||
* Lock acquisition, fence signaling, and fence waiting share timeout_ms; if lock acquisition
|
||||
* uses the whole budget, WaitForIdle times out without signaling. Time spent inside host calls
|
||||
* reduces the remaining wait, but the bridge cannot interrupt those calls.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) = 0;
|
||||
/*
|
||||
* The host DXGI swapchain, for diagnostics and tests. The caller owns the reference and must
|
||||
* not call Present or ResizeBuffers on it: the bridge's buffer tracking would not follow.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) = 0;
|
||||
};
|
||||
|
||||
/* Tear-off on the command queue proxy; QueryInterface for any other IID returns the queue's answer. */
|
||||
struct IBxPresentQueue : public IUnknown {
|
||||
/*
|
||||
* The queue must be a DIRECT queue and `window` an existing window. Argument errors return
|
||||
* E_POINTER or DXGI_ERROR_INVALID_CALL; host failures are returned unchanged and logged.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) = 0;
|
||||
};
|
||||
|
||||
/* Internal to d3d12_xs.dll: the command queue proxy answers IID_IBxPresentQueue with this. */
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv);
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_PRESENTX_H */
|
||||
+175
-6
@@ -4,6 +4,10 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "presentx.h"
|
||||
|
||||
#include "shader_gate.h"
|
||||
|
||||
@@ -429,6 +433,128 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateComputePipelineState(const D3D12_
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* Stream PSO subobjects (#576). A stream is a sequence of 8-byte-aligned records, each a
|
||||
* subobject type and a type-dependent payload. The real layout aligns the record, not the
|
||||
* payload: a payload whose type is only 4-byte aligned starts at offset 4, not 8. Measured
|
||||
* with the shim's own toolchain, that is the case for BLEND, SAMPLE_MASK, RASTERIZER,
|
||||
* DEPTH_STENCIL, DEPTH_STENCIL1, IB_STRIP_CUT_VALUE, PRIMITIVE_TOPOLOGY,
|
||||
* RENDER_TARGET_FORMATS, DEPTH_STENCIL_FORMAT, SAMPLE_DESC, NODE_MASK and FLAGS. Deriving
|
||||
* both the payload offset and the record size from the compiler keeps this table honest. */
|
||||
template<class Payload>
|
||||
struct alignas(void*) StreamRecord {
|
||||
/* alignas is on the CLASS, as in CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT: it pads the
|
||||
* whole record to 8 bytes but does not move a 4-byte-aligned payload off offset 4. */
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
Payload payload;
|
||||
};
|
||||
template<class Payload>
|
||||
constexpr size_t payload_at() { return offsetof(StreamRecord<Payload>, payload); }
|
||||
template<class Payload>
|
||||
constexpr size_t record_size() {
|
||||
return (offsetof(StreamRecord<Payload>, payload) + sizeof(Payload) + 7) & ~static_cast<size_t>(7);
|
||||
}
|
||||
|
||||
struct StreamSubobject {
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
size_t payload_offset;
|
||||
size_t record_size;
|
||||
const char* stage; /* non-null only for a shader subobject */
|
||||
};
|
||||
|
||||
#define BX_SUBOBJECT(tag, type, stage) \
|
||||
{tag, payload_at<type>(), record_size<type>(), stage}
|
||||
constexpr StreamSubobject kStreamSubobjects[] = {
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, void*, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE, "VS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE, "PS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, D3D12_SHADER_BYTECODE, "DS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, D3D12_SHADER_BYTECODE, "HS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, D3D12_SHADER_BYTECODE, "GS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, D3D12_SHADER_BYTECODE, "CS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, D3D12_STREAM_OUTPUT_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, D3D12_INPUT_LAYOUT_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, D3D12_CACHED_PIPELINE_STATE, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, D3D12_DEPTH_STENCIL_DESC1, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, D3D12_VIEW_INSTANCING_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE, "AS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE, "MS"),
|
||||
};
|
||||
#undef BX_SUBOBJECT
|
||||
|
||||
/* Pin the layout facts the walker depends on, measured with this toolchain. A header change
|
||||
* that moves a payload must fail to compile rather than desync the walk (#576 review). */
|
||||
static_assert(payload_at<D3D12_SHADER_BYTECODE>() == 8, "shader payloads sit at offset 8");
|
||||
static_assert(record_size<D3D12_SHADER_BYTECODE>() == 24, "a shader record is 24 bytes");
|
||||
static_assert(payload_at<UINT>() == 4, "4-byte payloads sit at offset 4, not 8");
|
||||
static_assert(record_size<UINT>() == 8, "a UINT record is 8 bytes");
|
||||
static_assert(payload_at<D3D12_BLEND_DESC>() == 4, "BLEND payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_RASTERIZER_DESC>() == 4, "RASTERIZER payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_RT_FORMAT_ARRAY>() == 4, "RT_FORMAT_ARRAY payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_DEPTH_STENCIL_DESC1>() == 4, "DEPTH_STENCIL1 payload sits at offset 4");
|
||||
static_assert(payload_at<void*>() == 8 && record_size<void*>() == 16, "root signature record");
|
||||
static_assert(payload_at<D3D12_INPUT_LAYOUT_DESC>() == 8, "INPUT_LAYOUT payload sits at offset 8");
|
||||
|
||||
const StreamSubobject* find_subobject(uint32_t type) {
|
||||
for (const StreamSubobject& entry : kStreamSubobjects) {
|
||||
if (static_cast<uint32_t>(entry.type) == type) return &entry;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* 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,
|
||||
* 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) {
|
||||
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);
|
||||
size_t offset = 0;
|
||||
while (offset < copy.size()) {
|
||||
if (copy.size() - offset < sizeof(SIZE_T)) return E_INVALIDARG;
|
||||
/* The tag is a 4-byte enum at the start of an 8-byte-aligned record; the rest of
|
||||
* those 8 bytes is padding a caller may leave uninitialized, so read only the enum
|
||||
* and step to the payload at offset sizeof(SIZE_T). */
|
||||
uint32_t raw = 0;
|
||||
std::memcpy(&raw, ©[offset], sizeof(raw));
|
||||
if (raw >= static_cast<uint32_t>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID)) return E_INVALIDARG;
|
||||
const StreamSubobject* entry = find_subobject(raw);
|
||||
if (!entry) return E_INVALIDARG;
|
||||
/* Microsoft's ID3D12Device2 rules reject a duplicated subobject type. */
|
||||
for (size_t seen = 0; seen < offset; ) {
|
||||
uint32_t prior = 0;
|
||||
std::memcpy(&prior, ©[seen], sizeof(prior));
|
||||
if (prior == raw) return E_INVALIDARG;
|
||||
const StreamSubobject* prior_entry = find_subobject(prior);
|
||||
if (!prior_entry) return E_INVALIDARG;
|
||||
seen += prior_entry->record_size;
|
||||
}
|
||||
const size_t payload = offset + entry->payload_offset;
|
||||
const size_t record = entry->record_size;
|
||||
if (copy.size() - offset < record) return E_INVALIDARG;
|
||||
if (entry->stage) {
|
||||
D3D12_SHADER_BYTECODE code{};
|
||||
std::memcpy(&code, ©[payload], sizeof(code));
|
||||
if (code.BytecodeLength != 0 && !code.pShaderBytecode) return E_INVALIDARG;
|
||||
stage_offsets.push_back(payload);
|
||||
stage_names.push_back(entry->stage);
|
||||
}
|
||||
offset += record;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("ID3D12Device2", "CreatePipelineState");
|
||||
if (!h_ID3D12Device2) {
|
||||
@@ -436,12 +562,50 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
|
||||
if (ppv) *ppv = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
/* The stream form is forwarded unparsed: only its size is recorded (sub-object walking is M2 work). */
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=1",
|
||||
static_cast<unsigned long long>(desc ? desc->SizeInBytes : 0));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
|
||||
HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
if (ppv) *ppv = nullptr;
|
||||
if (!desc) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", "pso=stream bytes=0 shaders_not_parsed=1");
|
||||
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* M2 shader format gate (#576): the stream form classifies its stages like the desc forms,
|
||||
* so an ACCC-only container is refused instead of reaching D3DMetal unparsed. */
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
const HRESULT copied = copy_stream(*desc, stream, offsets, names);
|
||||
{
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=%d",
|
||||
static_cast<unsigned long long>(desc->SizeInBytes), offsets.empty() ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
|
||||
}
|
||||
if (FAILED(copied) || offsets.empty()) {
|
||||
const HRESULT hr = FAILED(copied) ? copied : h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
BxShaderGate gate;
|
||||
HRESULT gated = S_OK;
|
||||
for (size_t i = 0; i < offsets.size() && SUCCEEDED(gated); ++i) {
|
||||
D3D12_SHADER_BYTECODE in{};
|
||||
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
|
||||
D3D12_SHADER_BYTECODE out = in;
|
||||
gated = gate.admit("stream", names[i], in, out);
|
||||
/* `out` is either the caller's bytes or the gate's copy, which lives until `gate`
|
||||
* is destroyed, so only the pointer/length inside our own copy change. */
|
||||
if (SUCCEEDED(gated)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
}
|
||||
if (FAILED(gated)) {
|
||||
log_created("stream pipeline state", gated);
|
||||
return gated;
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(&admitted, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
@@ -525,6 +689,11 @@ HRESULT STDMETHODCALLTYPE BxChildProxy<Gen>::QueryInterface(REFIID riid, void**
|
||||
*ppv = static_cast<Gen*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
if constexpr (std::is_same_v<Gen, BxCommandQueueProxyImpl>) {
|
||||
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
|
||||
return bx_present_query_queue(this, ppv); /* BetterXen's presentation bridge, presentx.h */
|
||||
}
|
||||
}
|
||||
return query_host_unproxied(host_identity_, Gen::kLeafName, riid, ppv);
|
||||
}
|
||||
|
||||
|
||||
@@ -149,13 +149,21 @@ constexpr uint64_t kAtomic64Typed = 0x400000;
|
||||
constexpr uint64_t kAtomic64GroupShared = 0x800000;
|
||||
constexpr uint64_t kAtomic64Heap = 0x10000000;
|
||||
|
||||
/* The [WaveSize(64)] case on its own (#591). A wider-than-32 wave is refused at PSO creation
|
||||
* rather than handed to a host that creates the pipeline and never runs it: the caller then
|
||||
* learns from a failed call instead of from a silently absent draw. Lowering 64 lanes to 32 is
|
||||
* a semantic transform (reductions, lane indices, 64-bit masks, cross-half permutes, barriers)
|
||||
* and is deferred. 64-bit atomics stay warn-only until their detection is complete (#589). */
|
||||
bool wave_wider_than_32(const Constraints& c) {
|
||||
return c.has_lanes && c.lanes_min > 32;
|
||||
}
|
||||
|
||||
/* Measured on D3DMetal (docs/research/d3dmetal-gpu-limits.md): pipelines that require a wave
|
||||
* wider than 32 lanes, or 64-bit atomics, are created but never run. */
|
||||
bool known_d3dmetal_gap(const Constraints& c) {
|
||||
const bool wide_wave = c.has_lanes && c.lanes_min > 32;
|
||||
return wide_wave || (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
|
||||
return wave_wider_than_32(c)
|
||||
|| (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
|
||||
}
|
||||
|
||||
const char* kind_name(bx_shader_kind_t kind) {
|
||||
switch (kind) {
|
||||
case BX_SHADER_DXBC_DXIL: return "dxil";
|
||||
@@ -254,6 +262,26 @@ HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12
|
||||
++copy_count_;
|
||||
out.pShaderBytecode = copy;
|
||||
out.BytecodeLength = copy_len;
|
||||
/* A wave wider than 32 lanes is refused here (#591): D3DMetal creates such a
|
||||
* pipeline and never runs it, so returning S_OK would leave the caller with a
|
||||
* silent no-op. The stage keeps its copy alive via `gate` until the caller's
|
||||
* PSO call returns. */
|
||||
if (wave_wider_than_32(constraints)) {
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "reject_wave_wide", E_NOTIMPL);
|
||||
/* Keep the established gap-detail shape: the consumer (#593) strips a trailing
|
||||
* colon from the last value and treats `atomic64_flags` as always present, so
|
||||
* `wave_lanes_min` must not be the final field. */
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"pso=%s stage=%s wave_lanes_min=%lu atomic64_flags=0x%llx: a wave wider "
|
||||
"than 32 lanes is created but never run on D3DMetal (#453); refused at "
|
||||
"PSO creation (#591)",
|
||||
pso_kind, stage, static_cast<unsigned long>(constraints.lanes_min),
|
||||
static_cast<unsigned long long>(
|
||||
constraints.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap)));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_d3dmetal_gap", detail);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "pass_dxil", S_OK);
|
||||
if (known_d3dmetal_gap(constraints)) {
|
||||
char detail[160];
|
||||
|
||||
+265
-68
@@ -5,6 +5,7 @@
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
/*
|
||||
@@ -52,6 +53,11 @@ constexpr GUID kPlacedResourceHeap = {0x3a652cbb, 0xb5b3, 0x4e09, {0xb3, 0x6c, 0
|
||||
|
||||
struct Record {
|
||||
bool configured = false;
|
||||
bool xbox_configured = false;
|
||||
uint32_t xbox_page_table_4mb_pages = 0;
|
||||
uint32_t xbox_frame_buffer_preserve_bytes = 0;
|
||||
/* D3D12ConfigureVirtualMemoryX fails with E_FAIL once a device exists. */
|
||||
bool device_created = false;
|
||||
bool backing_opt_in = false;
|
||||
bx_hardware_profile_t profile = BX_PROFILE_LOCKHART;
|
||||
uint64_t title_limit = 0;
|
||||
@@ -60,9 +66,10 @@ struct Record {
|
||||
uint64_t config_size = 0;
|
||||
uint64_t config_generation = 0;
|
||||
bx_xmem_region_info_t region{};
|
||||
/* Bytes of host heaps still alive. D3DMetal keeps freed memory in its own
|
||||
pool, so this counts live heaps only: charge on create, credit on the
|
||||
final Release. It does not assume the OS reclaimed the pages. */
|
||||
/* Diagnostic mirror of the external xmem charges for live host heaps.
|
||||
D3DMetal keeps freed memory in its own pool, so this counts live heaps
|
||||
only: charge on create, credit on the final Release. It does not assume
|
||||
the OS reclaimed the pages. xmem's external_bytes is authoritative. */
|
||||
uint64_t charged_private_bytes = 0;
|
||||
uint64_t cpu_pointer = 0;
|
||||
class BxChargedHeap* backing = nullptr;
|
||||
@@ -96,44 +103,43 @@ uint64_t title_limit() {
|
||||
return 8ull << 30;
|
||||
}
|
||||
|
||||
uint64_t active_cap(const bx_xmem_stats_t& stats) {
|
||||
uint64_t cap = title_limit();
|
||||
if (stats.title_limit_bytes != 0 && stats.title_limit_bytes < cap) {
|
||||
cap = stats.title_limit_bytes;
|
||||
}
|
||||
return cap;
|
||||
}
|
||||
|
||||
const char* profile_name(bx_hardware_profile_t profile) {
|
||||
return profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart";
|
||||
}
|
||||
|
||||
/* Private host heaps count against the same Lockhart/Anaconda cap as xmem. */
|
||||
/* Private host heaps count against the same Lockhart/Anaconda cap as xmem.
|
||||
* xmem's external_bytes is the authoritative ledger: bx_xmem_try_charge_external
|
||||
* admits atomically under usage_lock, against every owner, so no local pre-check
|
||||
* can add anything correct (a snapshot taken outside that lock would also count
|
||||
* live graphics heaps twice now that xmem's stats include external charges).
|
||||
* The local mirror is kept only for the gpu_heap_bytes diagnostic log; it cannot
|
||||
* wrap, because xmem has already admitted `bytes` under a cap <= UINT64_MAX.
|
||||
* The hook is called while g_section is held (lock order g_section ->
|
||||
* usage_lock, matching every other path in both DLLs). */
|
||||
bool try_charge(uint64_t bytes) {
|
||||
Guard guard(g_section);
|
||||
bx_xmem_stats_t stats{};
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
const uint64_t cap = active_cap(stats);
|
||||
const uint64_t xmem_used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
|
||||
if (bytes > cap || xmem_used > cap || g_record.charged_private_bytes > cap - xmem_used) {
|
||||
if (!bx_xmem_try_charge_external(bytes)) {
|
||||
return false;
|
||||
}
|
||||
const uint64_t room = cap - xmem_used - g_record.charged_private_bytes;
|
||||
if (bytes > room) {
|
||||
return false;
|
||||
}
|
||||
g_record.charged_private_bytes += bytes;
|
||||
g_record.charged_private_bytes += bytes; /* diagnostic mirror */
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Each heap wrapper calls this exactly once, on its final Release, which is what
|
||||
* keeps a heap from being released twice. The mirror check below is a coarse
|
||||
* guard on the total: it refuses a release larger than all outstanding graphics
|
||||
* charges (refusing leaves a charge in place, so the cap stays strict), but as a
|
||||
* single total it cannot tell one heap's double release from another heap's
|
||||
* charge. */
|
||||
void release_charge(uint64_t bytes) {
|
||||
Guard guard(g_section);
|
||||
if (bytes > g_record.charged_private_bytes) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "heap_budget", "GPU heap charge underflow on release");
|
||||
g_record.charged_private_bytes = 0;
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "heap_budget",
|
||||
"GPU heap charge underflow on release; xmem charge left unchanged");
|
||||
return;
|
||||
}
|
||||
g_record.charged_private_bytes -= bytes;
|
||||
bx_xmem_release_charge_external(bytes);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -698,48 +704,124 @@ struct ConfigHeader {
|
||||
};
|
||||
static_assert(sizeof(ConfigHeader) == 8, "config probe is the 8-byte header");
|
||||
|
||||
void write_cpu_pointer(void* config, uint64_t pointer) {
|
||||
std::memcpy(static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer), &pointer, sizeof(pointer));
|
||||
bool is_accessible_protect(DWORD protect, bool write) {
|
||||
if ((protect & (PAGE_GUARD | PAGE_NOACCESS)) != 0) {
|
||||
return false;
|
||||
}
|
||||
switch (protect & 0xFFu) {
|
||||
case PAGE_READWRITE:
|
||||
case PAGE_WRITECOPY:
|
||||
case PAGE_EXECUTE_READWRITE:
|
||||
case PAGE_EXECUTE_WRITECOPY:
|
||||
return true;
|
||||
case PAGE_READONLY:
|
||||
case PAGE_EXECUTE_READ:
|
||||
return !write;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
if (!config) {
|
||||
/* Titles call this before reserving memory and require S_OK. */
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
bool can_access_bytes(const void* ptr, size_t len, bool write) {
|
||||
if (!ptr || len == 0) {
|
||||
return false;
|
||||
}
|
||||
/*
|
||||
* PVOID has no size. Read 8 bytes, and only then the rest of a block that
|
||||
* names this struct. A mismatch is left untouched.
|
||||
*/
|
||||
ConfigHeader header{};
|
||||
std::memcpy(&header, config, sizeof(header));
|
||||
if (header.magic != BX_D3D12_VMEM_MAGIC || header.struct_size != sizeof(BxD3d12VirtualMemoryConfig)) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
|
||||
if (start > std::numeric_limits<uintptr_t>::max() - len) {
|
||||
return false;
|
||||
}
|
||||
const uintptr_t end = start + len;
|
||||
uintptr_t cursor = start;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
if (VirtualQuery(reinterpret_cast<LPCVOID>(cursor), &mbi, sizeof(mbi)) == 0) {
|
||||
return false;
|
||||
}
|
||||
if (mbi.State != MEM_COMMIT || !is_accessible_protect(mbi.Protect, write) || mbi.RegionSize == 0) {
|
||||
return false;
|
||||
}
|
||||
const uintptr_t region_base = reinterpret_cast<uintptr_t>(mbi.BaseAddress);
|
||||
if (region_base > cursor || mbi.RegionSize > std::numeric_limits<uintptr_t>::max() - region_base) {
|
||||
return false;
|
||||
}
|
||||
const uintptr_t region_end = region_base + mbi.RegionSize;
|
||||
if (region_end <= cursor) {
|
||||
return false;
|
||||
}
|
||||
cursor = region_end;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool copy_readable_bytes(const void* source, void* destination, size_t len) {
|
||||
if (!destination || !can_access_bytes(source, len, false)) {
|
||||
return false;
|
||||
}
|
||||
SIZE_T bytes_read = 0;
|
||||
return ReadProcessMemory(GetCurrentProcess(), source, destination, len, &bytes_read) != 0 && bytes_read == len;
|
||||
}
|
||||
|
||||
bool write_cpu_pointer(void* config, uint64_t pointer) {
|
||||
auto* destination = static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer);
|
||||
if (!can_access_bytes(destination, sizeof(pointer), true)) {
|
||||
return false;
|
||||
}
|
||||
SIZE_T bytes_written = 0;
|
||||
return WriteProcessMemory(GetCurrentProcess(), destination, &pointer, sizeof(pointer), &bytes_written) != 0 &&
|
||||
bytes_written == sizeof(pointer);
|
||||
}
|
||||
|
||||
/* Writes `len` bytes at `offset` in caller memory, after checking the range is writable. */
|
||||
bool write_config_bytes(void* config, size_t offset, const void* source, size_t len) {
|
||||
auto* destination = static_cast<char*>(config) + offset;
|
||||
if (!can_access_bytes(destination, len, true)) {
|
||||
return false;
|
||||
}
|
||||
SIZE_T bytes_written = 0;
|
||||
return WriteProcessMemory(GetCurrentProcess(), destination, source, len, &bytes_written) != 0 &&
|
||||
bytes_written == len;
|
||||
}
|
||||
|
||||
void log_vmem_fallback(const char* decoder, const char* reason) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "decoder=%s applied=0 reason=%s", decoder, reason);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_fallback", detail);
|
||||
}
|
||||
|
||||
void log_vmem_failed(const char* decoder, const char* reason, HRESULT hr) {
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "decoder=%s applied=0 reason=%s hr=0x%08lx", decoder, reason,
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_failed", detail);
|
||||
}
|
||||
|
||||
HRESULT decode_bxvm_config(void* config) {
|
||||
BxD3d12VirtualMemoryConfig in{};
|
||||
std::memcpy(&in, config, sizeof(in));
|
||||
if (!copy_readable_bytes(config, &in, sizeof(in))) {
|
||||
log_vmem_fallback("bxvm", "unreadable_tail");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const uint32_t unknown_flags = in.flags & ~BX_D3D12_VMEM_FLAG_BACKING_HEAP;
|
||||
if (in.version != kConfigVersion || unknown_flags != 0 || in.reserved != 0) {
|
||||
/* A console parameter block is not this struct. Leave those bytes alone. */
|
||||
log_vmem_fallback("bxvm", "unsupported_options");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
const uint64_t cap = title_limit();
|
||||
const auto profile = (cfg && cfg->profile == BX_PROFILE_ANACONDA) ? BX_PROFILE_ANACONDA : BX_PROFILE_LOCKHART;
|
||||
if (in.size_bytes != 0 && (in.size_bytes % k64K != 0 || in.size_bytes > cap)) {
|
||||
log_vmem_failed("bxvm", "invalid_size", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
if (in.size_bytes != 0 && stats.title_limit_bytes != 0 && in.size_bytes > stats.title_limit_bytes) {
|
||||
log_vmem_failed("bxvm", "exceeds_xmem_limit", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
@@ -749,16 +831,19 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
bx_xmem_region_info_t first{};
|
||||
if (!bx_xmem_query_region(in.base_va, &first) || first.size_bytes == 0 || first.base_va != in.base_va ||
|
||||
first.base_va % k64K != 0 || first.size_bytes % k64K != 0) {
|
||||
log_vmem_failed("bxvm", "unknown_xmem_region", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
const uint64_t span = in.size_bytes != 0 ? in.size_bytes : first.size_bytes;
|
||||
if (span < first.size_bytes || span % first.size_bytes != 0) {
|
||||
log_vmem_failed("bxvm", "unaligned_region_span", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
for (uint64_t offset = 0; offset < span; offset += first.size_bytes) {
|
||||
bx_xmem_region_info_t page{};
|
||||
if (!bx_xmem_query_region(first.base_va + offset, &page) || page.base_va != first.base_va + offset ||
|
||||
page.size_bytes != first.size_bytes) {
|
||||
log_vmem_failed("bxvm", "discontiguous_xmem_region", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
@@ -767,49 +852,60 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
have_region = true;
|
||||
}
|
||||
|
||||
if (!can_access_bytes(static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer),
|
||||
sizeof(in.cpu_pointer), true)) {
|
||||
log_vmem_fallback("bxvm", "unwritable_output");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const uint64_t new_base = have_region ? region.base_va : in.base_va;
|
||||
const uint64_t new_size = have_region ? region.size_bytes : in.size_bytes;
|
||||
const bool backing_opt_in = (in.flags & BX_D3D12_VMEM_FLAG_BACKING_HEAP) != 0;
|
||||
BxChargedHeap* old_heap = nullptr;
|
||||
ID3D12Resource* old_buffer = nullptr;
|
||||
uint64_t published = 0;
|
||||
bool output_written = false;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
const bool same = g_record.configured && g_record.config_base == new_base && g_record.config_size == new_size;
|
||||
if (!same) {
|
||||
take_cached_heap_locked(&old_heap, &old_buffer);
|
||||
published = same ? g_record.cpu_pointer : 0;
|
||||
output_written = write_cpu_pointer(config, published);
|
||||
if (output_written) {
|
||||
if (!same) {
|
||||
take_cached_heap_locked(&old_heap, &old_buffer);
|
||||
}
|
||||
if (!same || g_record.backing_opt_in != backing_opt_in || g_record.have_region != have_region) {
|
||||
++g_record.config_generation;
|
||||
}
|
||||
g_record.configured = true;
|
||||
g_record.backing_opt_in = backing_opt_in;
|
||||
g_record.profile = profile;
|
||||
g_record.title_limit = cap;
|
||||
g_record.have_region = have_region;
|
||||
g_record.config_base = new_base;
|
||||
g_record.config_size = new_size;
|
||||
g_record.region = have_region ? region : bx_xmem_region_info_t{};
|
||||
}
|
||||
if (!same || g_record.backing_opt_in != backing_opt_in || g_record.have_region != have_region) {
|
||||
++g_record.config_generation;
|
||||
}
|
||||
g_record.configured = true;
|
||||
g_record.backing_opt_in = backing_opt_in;
|
||||
g_record.profile = profile;
|
||||
g_record.title_limit = cap;
|
||||
g_record.have_region = have_region;
|
||||
g_record.config_base = new_base;
|
||||
g_record.config_size = new_size;
|
||||
g_record.region = have_region ? region : bx_xmem_region_info_t{};
|
||||
published = g_record.cpu_pointer;
|
||||
}
|
||||
/* The only write to caller memory, and it happens before this call returns. */
|
||||
write_cpu_pointer(config, published);
|
||||
if (old_buffer) {
|
||||
old_buffer->Unmap(0, nullptr);
|
||||
old_buffer->Release();
|
||||
}
|
||||
if (old_heap) {
|
||||
old_heap->Release();
|
||||
if (!output_written) {
|
||||
log_vmem_failed("bxvm", "unwritable_output", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
release_backing_pair(old_heap, old_buffer);
|
||||
uint64_t charged = 0;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
charged = g_record.charged_private_bytes;
|
||||
}
|
||||
|
||||
char detail[384];
|
||||
char detail[416];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"profile=%s title_limit=%llu xmem_used=%llu xmem_region=%d base=0x%llx region_bytes=%llu gpu_heap_bytes=%llu",
|
||||
/* cap_used is everything counted against the title cap, graphics heaps
|
||||
* included (xmem's stats include external charges); gpu_heap_bytes is the
|
||||
* graphics part of it, so the two must not be added. */
|
||||
"decoder=bxvm applied=1 profile=%s title_limit=%llu cap_used=%llu xmem_region=%d base=0x%llx region_bytes=%llu gpu_heap_bytes=%llu",
|
||||
profile_name(profile), static_cast<unsigned long long>(cap),
|
||||
static_cast<unsigned long long>(stats.committed_virtual_bytes + stats.allocated_physical_bytes),
|
||||
have_region ? 1 : 0, static_cast<unsigned long long>(have_region ? region.base_va : 0),
|
||||
@@ -819,6 +915,105 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT decode_xbox_config(void* config) {
|
||||
/* The structure has no size field, so all 32 bytes must be readable and writable. */
|
||||
BxXboxVirtualMemoryConfig in{};
|
||||
if (!copy_readable_bytes(config, &in, sizeof(in))) {
|
||||
log_vmem_failed("xbox", "unreadable_config", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (in.page_table_memory_4mb_page_count == 0u) {
|
||||
log_vmem_failed("xbox", "zero_page_table_pages", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
{
|
||||
Guard guard(g_section);
|
||||
if (g_record.device_created) {
|
||||
log_vmem_failed("xbox", "device_already_created", E_FAIL);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
const bool clamped = in.page_table_memory_4mb_page_count > BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES;
|
||||
const uint32_t pages = clamped ? BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES : in.page_table_memory_4mb_page_count;
|
||||
uint32_t preserve = in.frame_buffer_preserve_memory_size_bytes;
|
||||
if (preserve != BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY &&
|
||||
preserve > BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES) {
|
||||
preserve = BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES;
|
||||
}
|
||||
const uint64_t outputs[2] = {BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS,
|
||||
static_cast<uint64_t>(pages) * BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE};
|
||||
if (!write_config_bytes(config, offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address), outputs,
|
||||
sizeof(outputs))) {
|
||||
log_vmem_failed("xbox", "unwritable_output", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
/*
|
||||
* The host sizes no GPU page tables and keeps no cross-process frame buffer, so both
|
||||
* values are only recorded. This path leaves the BXVM record and its cached backing heap
|
||||
* untouched, reports applied=0 and keeps BX_STUB_LOG, so `bx-cli trace` still lists
|
||||
* D3D12ConfigureVirtualMemoryX as unimplemented.
|
||||
*/
|
||||
bool repeat = false;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
repeat = g_record.xbox_configured && g_record.xbox_page_table_4mb_pages == pages &&
|
||||
g_record.xbox_frame_buffer_preserve_bytes == preserve;
|
||||
g_record.xbox_configured = true;
|
||||
g_record.xbox_page_table_4mb_pages = pages;
|
||||
g_record.xbox_frame_buffer_preserve_bytes = preserve;
|
||||
}
|
||||
|
||||
char detail[320];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"decoder=xbox applied=0 recorded_only=1 page_table_4mb_pages=%u clamped=%d "
|
||||
"frame_buffer_preserve_bytes=%u min_gpu_va=0x%llx max_gpu_va=0x%llx max_estimated=%d "
|
||||
"repeat=%d reason=host_ignores_page_table_size",
|
||||
pages, clamped ? 1 : 0, preserve, static_cast<unsigned long long>(outputs[0]),
|
||||
static_cast<unsigned long long>(outputs[1]),
|
||||
pages == BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES ? 0 : 1, repeat ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_recorded", detail);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
if (!config) {
|
||||
/* Titles call this before reserving memory and require S_OK. */
|
||||
log_vmem_fallback("none", "null_config");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
/*
|
||||
* PVOID has no size. Verify 8 bytes are committed and readable before
|
||||
* probing the header, and let each decoder verify its own full length.
|
||||
*/
|
||||
ConfigHeader header{};
|
||||
if (!copy_readable_bytes(config, &header, sizeof(header))) {
|
||||
log_vmem_fallback("none", "unreadable_header");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
if (header.magic == BX_D3D12_VMEM_MAGIC && header.struct_size == sizeof(BxD3d12VirtualMemoryConfig)) {
|
||||
return decode_bxvm_config(config);
|
||||
}
|
||||
if (header.magic == 0u) {
|
||||
return decode_xbox_config(config);
|
||||
}
|
||||
|
||||
log_vmem_fallback("none", "unrecognized_header");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
bool bx_vmem_final_release(void* device_proxy) {
|
||||
Guard guard(g_section);
|
||||
auto* proxy = static_cast<BxDeviceProxy*>(device_proxy);
|
||||
@@ -856,6 +1051,7 @@ bool bx_vmem_install_device_hooks(void* device) {
|
||||
static bool installed = false;
|
||||
Guard guard(g_section);
|
||||
if (installed) {
|
||||
g_record.device_created = true;
|
||||
return true;
|
||||
}
|
||||
auto* proxy = static_cast<BxDeviceProxy*>(device);
|
||||
@@ -871,6 +1067,7 @@ bool bx_vmem_install_device_hooks(void* device) {
|
||||
DWORD ignored = 0;
|
||||
VirtualProtect(vtable + 28, sizeof(void*) * 2, old, &ignored);
|
||||
installed = true;
|
||||
g_record.device_created = true;
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "vmem_hook", "CreateHeap and CreatePlacedResource installed");
|
||||
return true;
|
||||
}
|
||||
+54
-6
@@ -9,17 +9,20 @@
|
||||
* BetterXen-defined parameter block for D3D12ConfigureVirtualMemoryX.
|
||||
*
|
||||
* The export is PVOID and the frozen ABI has no size argument (abi/ is out of
|
||||
* scope). The first 8 bytes are therefore the minimum dereference: magic then
|
||||
* the struct size. Magic is 'BXVM' (0x4D565842). struct_size must equal
|
||||
* sizeof(BxD3d12VirtualMemoryConfig). Any other pointer, including null, is not
|
||||
* this struct: the call logs the unimplemented-API stub and returns S_OK. It
|
||||
* does not read past those 8 bytes and it does not write.
|
||||
* scope). The first 8 bytes are therefore the initial probe: a magic word and
|
||||
* the following 32-bit value. Magic is 'BXVM' (0x4D565842); a matching header
|
||||
* and struct size select the full BetterXen block. A zero first word selects
|
||||
* the Xbox decoder, which checks the full block and may write its two address
|
||||
* outputs. Other headers (including unrecognized nonzero Xbox flags) fall
|
||||
* back with S_OK and no writes. A null pointer is not read.
|
||||
*
|
||||
* A block whose magic and size match is then checked in full. version is 1.
|
||||
* flags may be 0 or BX_D3D12_VMEM_FLAG_BACKING_HEAP. Any other flag bit, or a
|
||||
* non-zero reserved word, is not this struct either (logged S_OK, no write).
|
||||
* A recognised block with a bad size or a base_va that bx_xmem_query_region
|
||||
* does not resolve still returns E_INVALIDARG and is not written.
|
||||
* does not resolve returns E_INVALIDARG even if its output is read-only. Valid
|
||||
* inputs with an initially unwritable output fall back with S_OK and a stub
|
||||
* log. A failed write after the accessibility check returns E_INVALIDARG.
|
||||
*
|
||||
* base_va is 0, or an address bx_xmem_query_region resolves. It is not a GPU pointer.
|
||||
* size_bytes is 0 or a 64 KiB multiple that does not exceed the active title limit.
|
||||
@@ -87,6 +90,51 @@ static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_byte
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 32, "reserved offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_pointer offset");
|
||||
|
||||
/*
|
||||
* The Xbox virtual-memory configuration (D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION, d3d12_xs.h).
|
||||
*
|
||||
* Source: the authorized GDK documentation of D3D12ConfigureVirtualMemoryX and the
|
||||
* structure. Call-site observation of a project-authorized target build agrees with it: a
|
||||
* zero-initialized block with 3 or 4 in the page-table field and no flags.
|
||||
*
|
||||
* Documented: flags must be none (0); the GPU page table is sized in 4 MB units, at least 1
|
||||
* and clamped to 33 (default 5, 20 MB); the frame-buffer preserve size is 0 (none), -1 (the
|
||||
* legacy size, about 10 MB) or a byte count clamped to 64 MB; the two addresses are outputs,
|
||||
* the minimum always 2 GB; and the call fails with E_FAIL once a D3D12 device exists.
|
||||
*
|
||||
* The host does not size GPU page tables or keep a cross-process frame buffer, so the
|
||||
* decoder records both, writes the outputs and still logs BX_STUB_LOG. The maximum address
|
||||
* is documented only for the default size; for other sizes it is scaled linearly from that
|
||||
* value, an inference the log marks as max_estimated=1. A page count of 0 is refused: the
|
||||
* value of the header's DEFAULT constant is not documented.
|
||||
*/
|
||||
struct BxXboxVirtualMemoryConfig {
|
||||
uint32_t flags;
|
||||
uint32_t page_table_memory_4mb_page_count;
|
||||
uint32_t frame_buffer_preserve_memory_size_bytes;
|
||||
uint32_t padding;
|
||||
uint64_t minimum_valid_graphics_address;
|
||||
uint64_t maximum_valid_graphics_address;
|
||||
};
|
||||
static_assert(sizeof(BxXboxVirtualMemoryConfig) == 32, "Xbox config block is 32 bytes");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, flags) == 0, "flags offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, page_table_memory_4mb_page_count) == 4,
|
||||
"page_table_memory_4mb_page_count offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, frame_buffer_preserve_memory_size_bytes) == 8,
|
||||
"frame_buffer_preserve_memory_size_bytes offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address) == 16,
|
||||
"minimum_valid_graphics_address offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, maximum_valid_graphics_address) == 24,
|
||||
"maximum_valid_graphics_address offset");
|
||||
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES = 5u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES = 33u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY = 0xFFFFFFFFu;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES = 64u * 1024u * 1024u;
|
||||
constexpr uint64_t BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS = 2ull * 1024ull * 1024ull * 1024ull;
|
||||
/* 159.375 GiB at the default 5 pages (20 MB), so 31.875 GiB per 4 MB page. */
|
||||
constexpr uint64_t BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE = 0x7F8000000ull;
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config);
|
||||
|
||||
/* Patches the device proxy vtable so CreateHeap and CreatePlacedResource run the code in vmem.cpp. */
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
@@ -43,14 +45,38 @@ HRESULT unavailable(T* out) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
class GameInputDispatcher;
|
||||
|
||||
class GameInput final : public IUnknown {
|
||||
LONG refs = 0;
|
||||
SRWLOCK callback_lock_ = SRWLOCK_INIT;
|
||||
uint64_t next_token_ = 1;
|
||||
std::unordered_map<uint64_t, RegisteredDeviceCallback> callbacks_;
|
||||
std::atomic<uint32_t> focus_policy_{0};
|
||||
// Live IGameInputDispatcher reference count. >0 means GameInput is in
|
||||
// "manual dispatch" mode; 0 means "automatic dispatch" mode.
|
||||
std::atomic<uint32_t> dispatcher_refs_{0};
|
||||
|
||||
public:
|
||||
// Logs the manual/automatic dispatch mode transition. Purely atomic: it
|
||||
// never takes callback_lock_, so it cannot introduce lock ordering hazards.
|
||||
void note_dispatch_mode(const char* mode, uint32_t count) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "mode=%s live_dispatchers=%u", mode,
|
||||
static_cast<unsigned>(count));
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "dispatch_mode", detail);
|
||||
}
|
||||
|
||||
void on_dispatcher_created() {
|
||||
const uint32_t count = dispatcher_refs_.fetch_add(1, std::memory_order_acq_rel) + 1;
|
||||
if (count == 1) note_dispatch_mode("manual", count);
|
||||
}
|
||||
|
||||
void on_dispatcher_released() {
|
||||
const uint32_t count = dispatcher_refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (count == 0) note_dispatch_mode("automatic", count);
|
||||
}
|
||||
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
@@ -133,10 +159,9 @@ public:
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
return callbacks_.erase(token) > 0;
|
||||
}
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
return unavailable(out);
|
||||
}
|
||||
// Slot 14. Defined out of line below because it allocates
|
||||
// GameInputDispatcher, which in turn calls back into this class.
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out);
|
||||
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
|
||||
return unavailable(out);
|
||||
@@ -166,6 +191,93 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
// IGameInputDispatcher (GameInput v0): IUnknown + Dispatch + OpenWaitHandle.
|
||||
// Holding a reference puts GameInput in manual dispatch mode; releasing the
|
||||
// last one returns it to automatic dispatch mode.
|
||||
class GameInputDispatcher final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
GameInput* owner_ = nullptr;
|
||||
|
||||
public:
|
||||
explicit GameInputDispatcher(GameInput* owner) : owner_(owner) {}
|
||||
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid == IID_IUnknown) {
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
// The GameInput v0 IGameInputDispatcher IID is not published in the
|
||||
// public Microsoft Learn / GDK documentation, so it is NOT guessed
|
||||
// here. Only IID_IUnknown is served; every other queried id is logged
|
||||
// (never silently ignored) and answered with E_NOINTERFACE.
|
||||
char guid[40];
|
||||
std::snprintf(guid, sizeof(guid), "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
|
||||
static_cast<unsigned long>(iid.Data1), iid.Data2, iid.Data3,
|
||||
iid.Data4[0], iid.Data4[1], iid.Data4[2], iid.Data4[3],
|
||||
iid.Data4[4], iid.Data4[5], iid.Data4[6], iid.Data4[7]);
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"IGameInputDispatcher iid=%s unsupported (v0 dispatcher IID not publicly documented)",
|
||||
guid);
|
||||
bx_log_emit(BX_LOG_WARN, "gameinput", "qi_unsupported", detail);
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
const LONG count = InterlockedDecrement(&refs);
|
||||
if (count == 0) {
|
||||
GameInput* owner = owner_;
|
||||
owner_ = nullptr;
|
||||
if (owner) owner->on_dispatcher_released();
|
||||
delete this;
|
||||
}
|
||||
return static_cast<ULONG>(count);
|
||||
}
|
||||
|
||||
// Slot 3: bool Dispatch(uint64_t quotaInMicroseconds).
|
||||
// This shim has no real background input work, so the dispatch queue is
|
||||
// always empty. The documented "flush at least one item even at quota 0"
|
||||
// shape is honoured trivially: there is nothing to flush, so it returns
|
||||
// false (no work items remain) for every quota, including 0. No real work
|
||||
// is scheduled, and it never busy-waits or sleeps.
|
||||
virtual bool WINAPI Dispatch(uint64_t /*quota_us*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Slot 4: HRESULT OpenWaitHandle(HANDLE* waitHandle).
|
||||
// Returns a fresh manual-reset event on every call. The dispatcher owns
|
||||
// nothing after returning it: the caller closes it via CloseHandle.
|
||||
// LIMIT: the handle is created non-signaled and this shim never signals
|
||||
// it, because there is no background input work to make it ready. A
|
||||
// caller that waits on it with INFINITE will block forever; poll with a
|
||||
// timeout, or call Dispatch, instead.
|
||||
virtual HRESULT WINAPI OpenWaitHandle(HANDLE* out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
if (!handle) {
|
||||
return HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
*out = handle;
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
HRESULT WINAPI GameInput::CreateDispatcher(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
GameInputDispatcher* dispatcher = new (std::nothrow) GameInputDispatcher(this);
|
||||
if (!dispatcher) return E_OUTOFMEMORY;
|
||||
*out = dispatcher;
|
||||
// The GameInput singleton's own refcount is intentionally unchanged:
|
||||
// the dispatcher only moves the manual-dispatch mode counter.
|
||||
on_dispatcher_created();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
GameInput singleton;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <windows.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -23,10 +24,25 @@ struct SrwLockGuard {
|
||||
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
|
||||
};
|
||||
|
||||
// Exception-free open-addressed hash set backed by the Win32 process heap so
|
||||
// One accepted registration, stored beside the token that names it.
|
||||
//
|
||||
// The callback and its context are kept together because the PSM contract is a
|
||||
// callback plus a caller context: a caller passes `context` expecting the same
|
||||
// value back as the callback's second argument if that callback ever fires.
|
||||
// Dropping it would make even a future firing unable to deliver faithfully, so
|
||||
// the shim owns both values for exactly as long as the token is live.
|
||||
struct Entry {
|
||||
uintptr_t token; // kEmptySlot == unused, kTombstoneSlot == erased
|
||||
PVOID callback;
|
||||
PVOID context;
|
||||
};
|
||||
|
||||
// Exception-free open-addressed hash table backed by the Win32 process heap so
|
||||
// both PSM DLLs stay on -fno-exceptions and map OOM to ERROR_NOT_ENOUGH_MEMORY.
|
||||
// The record lives in the table slot, so an erase drops the callback with the
|
||||
// token and a reset (DllMain detach) frees them together.
|
||||
struct TokenSet {
|
||||
uintptr_t* slots = nullptr;
|
||||
Entry* slots = nullptr;
|
||||
size_t capacity = 0;
|
||||
size_t count = 0;
|
||||
size_t used = 0; // active entries + tombstones
|
||||
@@ -42,24 +58,24 @@ struct TokenSet {
|
||||
}
|
||||
|
||||
bool rehash(size_t new_capacity) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(uintptr_t)) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(Entry)) {
|
||||
return false;
|
||||
}
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
auto* fresh = static_cast<uintptr_t*>(
|
||||
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(uintptr_t)));
|
||||
auto* fresh = static_cast<Entry*>(
|
||||
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(Entry)));
|
||||
if (!fresh) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = new_capacity - 1;
|
||||
for (size_t i = 0; i < capacity; ++i) {
|
||||
const uintptr_t entry = slots[i];
|
||||
if (entry != kEmptySlot && entry != kTombstoneSlot) {
|
||||
size_t idx = hash(entry) & mask;
|
||||
while (fresh[idx] != kEmptySlot) {
|
||||
const Entry entry = slots[i];
|
||||
if (entry.token != kEmptySlot && entry.token != kTombstoneSlot) {
|
||||
size_t idx = hash(entry.token) & mask;
|
||||
while (fresh[idx].token != kEmptySlot) {
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
fresh[idx] = entry;
|
||||
@@ -74,13 +90,15 @@ struct TokenSet {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool insert(uintptr_t token) {
|
||||
// Inserts the token with its callback/context and returns the stored slot so
|
||||
// the caller can log back exactly what was retained. nullptr means OOM.
|
||||
Entry* insert(uintptr_t token, PVOID callback, PVOID context) {
|
||||
if (capacity == 0 || (used + 1) * 4 >= capacity * 3) {
|
||||
size_t next_capacity = 64;
|
||||
if (capacity != 0) {
|
||||
if (count * 2 >= capacity) {
|
||||
if (capacity > (SIZE_MAX / sizeof(uintptr_t)) / 2) {
|
||||
return false;
|
||||
if (capacity > (SIZE_MAX / sizeof(Entry)) / 2) {
|
||||
return nullptr;
|
||||
}
|
||||
next_capacity = capacity * 2;
|
||||
} else {
|
||||
@@ -89,28 +107,36 @@ struct TokenSet {
|
||||
}
|
||||
}
|
||||
if (!rehash(next_capacity)) {
|
||||
return false;
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
size_t first_tombstone = capacity;
|
||||
while (true) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == token) {
|
||||
return true;
|
||||
Entry& entry = slots[idx];
|
||||
if (entry.token == token) {
|
||||
entry.callback = callback;
|
||||
entry.context = context;
|
||||
return &entry;
|
||||
}
|
||||
if (entry == kEmptySlot) {
|
||||
if (entry.token == kEmptySlot) {
|
||||
if (first_tombstone != capacity) {
|
||||
slots[first_tombstone] = token;
|
||||
} else {
|
||||
slots[idx] = token;
|
||||
++used;
|
||||
Entry& reused = slots[first_tombstone];
|
||||
reused.token = token;
|
||||
reused.callback = callback;
|
||||
reused.context = context;
|
||||
++count;
|
||||
return &reused;
|
||||
}
|
||||
entry.token = token;
|
||||
entry.callback = callback;
|
||||
entry.context = context;
|
||||
++used;
|
||||
++count;
|
||||
return true;
|
||||
return &entry;
|
||||
}
|
||||
if (entry == kTombstoneSlot && first_tombstone == capacity) {
|
||||
if (entry.token == kTombstoneSlot && first_tombstone == capacity) {
|
||||
first_tombstone = idx;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
@@ -124,12 +150,16 @@ struct TokenSet {
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
for (size_t probed = 0; probed < capacity; ++probed) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == kEmptySlot) {
|
||||
Entry& entry = slots[idx];
|
||||
if (entry.token == kEmptySlot) {
|
||||
return false;
|
||||
}
|
||||
if (entry == token) {
|
||||
slots[idx] = kTombstoneSlot;
|
||||
if (entry.token == token) {
|
||||
// Drop the stored callback and context with the token, so a
|
||||
// later firing can never reach a retired registration.
|
||||
entry.token = kTombstoneSlot;
|
||||
entry.callback = nullptr;
|
||||
entry.context = nullptr;
|
||||
--count;
|
||||
return true;
|
||||
}
|
||||
@@ -166,7 +196,15 @@ struct Registrations {
|
||||
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
|
||||
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
|
||||
|
||||
ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
// Accepts a registration and records the callback and context that came with it.
|
||||
//
|
||||
// LIMITATION: the stored callbacks are currently NEVER INVOKED. This shim has
|
||||
// no source of app-state or constrained-change transitions of its own, so no
|
||||
// firing policy is invented here rather than firing the callback spuriously.
|
||||
// ERROR_SUCCESS therefore means "the registration was recorded (bookkeeping
|
||||
// only)", not "you will be notified". The JSONL detail says `callback_unfired`
|
||||
// for the same reason, so `bx-cli trace` states the limitation too.
|
||||
ULONG register_notification(Registrations& registrations, PVOID callback, PVOID context,
|
||||
PVOID* out_reg, const char* event) {
|
||||
if (!out_reg) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
@@ -177,6 +215,8 @@ ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
}
|
||||
|
||||
uintptr_t token = 0;
|
||||
PVOID stored_callback = nullptr;
|
||||
PVOID stored_context = nullptr;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
// Never recycle a token that a caller may still retain.
|
||||
@@ -184,14 +224,24 @@ ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
|
||||
if (!registrations.active.insert(token)) {
|
||||
const Entry* stored = registrations.active.insert(token, callback, context);
|
||||
if (!stored) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
// Log what the table actually retained for this token, not the
|
||||
// arguments, so the record is evidence of the stored state.
|
||||
stored_callback = stored->callback;
|
||||
stored_context = stored->context;
|
||||
++registrations.next_seq;
|
||||
}
|
||||
|
||||
*out_reg = reinterpret_cast<PVOID>(token);
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, "registered_offline");
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"registered_offline callback_unfired callback=0x%llx context=0x%llx",
|
||||
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(stored_callback)),
|
||||
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(stored_context)));
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
@@ -218,6 +268,8 @@ extern "C" {
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
|
||||
if (reason == DLL_PROCESS_DETACH && reserved == nullptr) {
|
||||
// reset() frees the slot table, so no stored callback or context
|
||||
// outlives process teardown to be invoked against a dying image.
|
||||
{
|
||||
const SrwLockGuard guard(g_state.lock);
|
||||
g_state.active.reset();
|
||||
@@ -230,16 +282,18 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, out_reg, "RegisterAppStateChangeNotification");
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID context, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, context, out_reg,
|
||||
"RegisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_constrained, callback, out_reg, "RegisterAppConstrainedChangeNotification");
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID context, PVOID* out_reg) {
|
||||
return register_notification(g_constrained, callback, context, out_reg,
|
||||
"RegisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID reg) {
|
||||
|
||||
+408
-11
@@ -913,6 +913,17 @@ bool reserved_fields_clear(const DSTORAGE_REQUEST_OPTIONS& options) {
|
||||
// (the header: an empty queue reports capacity - 1 empty slots), and requests
|
||||
// are submitted automatically once N / 2 are waiting (the header: "until the
|
||||
// queue is half full").
|
||||
// Maps the engine's command kind onto the header's DSTORAGE_COMMAND_TYPE for
|
||||
// RetrieveErrorRecord on the public PC queue.
|
||||
DSTORAGE_COMMAND_TYPE command_type(Kind kind) {
|
||||
switch (kind) {
|
||||
case Kind::status: return DSTORAGE_COMMAND_TYPE_STATUS;
|
||||
case Kind::signal: return DSTORAGE_COMMAND_TYPE_SIGNAL;
|
||||
case Kind::event: return DSTORAGE_COMMAND_TYPE_EVENT;
|
||||
default: return DSTORAGE_COMMAND_TYPE_REQUEST;
|
||||
}
|
||||
}
|
||||
|
||||
class PublicQueue final : public PublicObject<IDStorageQueue4> {
|
||||
public:
|
||||
PublicQueue(WorkQueue* queue, const DSTORAGE_QUEUE_DESC1& desc) : queue_(queue), desc_(desc) {
|
||||
@@ -1045,15 +1056,6 @@ private:
|
||||
|| IsEqualIID(riid, __uuidof(IDStorageQueue4));
|
||||
}
|
||||
|
||||
static DSTORAGE_COMMAND_TYPE command_type(Kind kind) {
|
||||
switch (kind) {
|
||||
case Kind::status: return DSTORAGE_COMMAND_TYPE_STATUS;
|
||||
case Kind::signal: return DSTORAGE_COMMAND_TYPE_SIGNAL;
|
||||
case Kind::event: return DSTORAGE_COMMAND_TYPE_EVENT;
|
||||
default: return DSTORAGE_COMMAND_TYPE_REQUEST;
|
||||
}
|
||||
}
|
||||
|
||||
// Maps a DSTORAGE_REQUEST onto the engine's Request. Only uncompressed
|
||||
// file/memory sources into memory or buffer destinations are supported.
|
||||
HRESULT translate(const DSTORAGE_REQUEST* request, Request* out) const {
|
||||
@@ -1264,11 +1266,400 @@ private:
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Xbox Series DirectStorage COM interfaces (IDStorage*X), inferred from call-site
|
||||
// observation of a project-authorized target build (provenance pending maintainer
|
||||
// review; not a public contract), layered over the same WorkQueue / StorageFile /
|
||||
// StatusArray engine. Unimplemented vtable slots log through BX_VTABLE_STUB_LOG
|
||||
// so any newly reached slot surfaces immediately in bx-cli trace.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
constexpr IID kXboxFactoryIid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
|
||||
constexpr IID kXboxFileIid{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
|
||||
constexpr IID kXboxStatusArrayIid{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
|
||||
constexpr IID kXboxQueueIid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
|
||||
|
||||
struct XboxQueueDesc {
|
||||
UINT64 source_type;
|
||||
UINT16 capacity;
|
||||
INT8 priority;
|
||||
UINT8 reserved_pad[5];
|
||||
PCSTR name;
|
||||
UINT64 flags;
|
||||
};
|
||||
static_assert(sizeof(XboxQueueDesc) == 32, "XboxQueueDesc must be 32 bytes");
|
||||
static_assert(offsetof(XboxQueueDesc, source_type) == 0x00, "source_type offset");
|
||||
static_assert(offsetof(XboxQueueDesc, capacity) == 0x08, "capacity offset");
|
||||
static_assert(offsetof(XboxQueueDesc, priority) == 0x0a, "priority offset");
|
||||
static_assert(offsetof(XboxQueueDesc, name) == 0x10, "name offset");
|
||||
static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
|
||||
|
||||
struct XboxRequest {
|
||||
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
|
||||
void* destination; // +0x08
|
||||
UINT64 destination_pad; // +0x10
|
||||
UINT32 destination_size; // +0x18
|
||||
UINT32 reserved1c; // +0x1c
|
||||
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
|
||||
UINT64 file_offset; // +0x28
|
||||
UINT32 source_size; // +0x30
|
||||
UINT32 reserved34; // +0x34
|
||||
};
|
||||
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
|
||||
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
|
||||
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
|
||||
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size offset");
|
||||
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;
|
||||
|
||||
struct IXboxDStorageFile : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageStatusArray : IUnknown {
|
||||
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageQueue : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) = 0;
|
||||
virtual void STDMETHODCALLTYPE Submit() = 0;
|
||||
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
|
||||
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(void* record) = 0;
|
||||
virtual void STDMETHODCALLTYPE Query(void* info) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot13() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot14() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot15() = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageFactory : IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
|
||||
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot11() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
|
||||
};
|
||||
|
||||
class XboxFile final : public PublicObject<IXboxDStorageFile> {
|
||||
public:
|
||||
explicit XboxFile(StorageFile* file) : file_(file) {}
|
||||
|
||||
void STDMETHODCALLTYPE Close() override { (void)file_->Close(); }
|
||||
HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) override {
|
||||
return file_->GetFileInformation(info);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot5() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFileX", 5u, "Slot5");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot6() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFileX", 6u, "Slot6");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
File* inner() const { return file_; }
|
||||
|
||||
private:
|
||||
~XboxFile() override { file_->Release(); }
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFileIid); }
|
||||
|
||||
StorageFile* file_;
|
||||
};
|
||||
|
||||
class XboxStatusArray final : public PublicObject<IXboxDStorageStatusArray> {
|
||||
public:
|
||||
explicit XboxStatusArray(StatusArray* array) : array_(array) {}
|
||||
|
||||
bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return array_->GetResult(index) != E_PENDING; }
|
||||
HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { return array_->GetResult(index); }
|
||||
HRESULT STDMETHODCALLTYPE StubSlot5() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 5u, "Slot5");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot6() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 6u, "Slot6");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
StatusArray* inner() const { return array_; }
|
||||
|
||||
private:
|
||||
~XboxStatusArray() override { array_->Release(); }
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxStatusArrayIid); }
|
||||
|
||||
StatusArray* array_;
|
||||
};
|
||||
|
||||
class XboxQueue final : public PublicObject<IXboxDStorageQueue> {
|
||||
public:
|
||||
XboxQueue(WorkQueue* queue, UINT64 source_type) : queue_(queue), source_type_(source_type) {}
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) override {
|
||||
if (!request) {
|
||||
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
const bool is_memory = (request->options & kXboxRequestSourceMemoryBit) != 0;
|
||||
if ((is_memory && source_type_ == 0) || (!is_memory && source_type_ != 0)) {
|
||||
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if ((request->options & kXboxRequestCompressedBit) != 0) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_compressed");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if (!request->destination || request->source_size != request->destination_size) {
|
||||
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
|
||||
Request translated{};
|
||||
translated.destination = request->destination;
|
||||
translated.size = request->source_size;
|
||||
if (is_memory) {
|
||||
if (!request->source_ptr) {
|
||||
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
translated.source = request->source_ptr;
|
||||
} else {
|
||||
auto* file = public_impl<XboxFile>(static_cast<IXboxDStorageFile*>(request->source_ptr));
|
||||
if (!file) {
|
||||
reject(E_DSTORAGE_FILE_NOT_OPEN, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
translated.file = file->inner();
|
||||
translated.file_offset = request->file_offset;
|
||||
}
|
||||
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) override {
|
||||
auto* array = public_impl<XboxStatusArray>(status_array);
|
||||
if (!array) {
|
||||
reject(E_DSTORAGE_INVALID_STATUS_ARRAY, Kind::status, "EnqueueStatus");
|
||||
return;
|
||||
}
|
||||
HRESULT hr = queue_->EnqueueStatus(array->inner(), index);
|
||||
if (hr == E_INVALIDARG) hr = E_DSTORAGE_INDEX_BOUND;
|
||||
accept(hr, Kind::status, "EnqueueStatus");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override {
|
||||
if (!fence) {
|
||||
reject(E_DSTORAGE_INVALID_FENCE, Kind::signal, "EnqueueSignal");
|
||||
return;
|
||||
}
|
||||
accept(queue_->EnqueueSignal(fence, value), Kind::signal, "EnqueueSignal");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE Submit() override {
|
||||
if (FAILED(queue_->Submit())) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "Submit after Close; nothing submitted");
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64, UINT64) override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 7u, "CancelRequestsWithTag");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE Close() override { (void)queue_->Close(); }
|
||||
|
||||
HANDLE STDMETHODCALLTYPE GetErrorEvent() override { return queue_->error_event(); }
|
||||
|
||||
void STDMETHODCALLTYPE RetrieveErrorRecord(void*) override {
|
||||
// The size and layout of the Xbox caller's output are unverified.
|
||||
// Do not write the public PC record into it.
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 10u, "RetrieveErrorRecord");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE Query(void*) override { BX_VTABLE_STUB_LOG("IDStorageQueueX", 11u, "Query"); }
|
||||
HRESULT STDMETHODCALLTYPE StubSlot12() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 12u, "Slot12");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot13() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 13u, "Slot13");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot14() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 14u, "Slot14");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot15() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 15u, "Slot15");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
~XboxQueue() override { queue_->Release(); }
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxQueueIid); }
|
||||
|
||||
void reject(HRESULT hr, Kind kind, const char* method) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "xbox %s hr=0x%08lx", method, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_enqueue_rejected", detail);
|
||||
if (FAILED(queue_->enqueue_failure(hr, kind))) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "enqueue after Close; command dropped");
|
||||
}
|
||||
}
|
||||
|
||||
void accept(HRESULT hr, Kind kind, const char* method) {
|
||||
if (SUCCEEDED(hr)) return;
|
||||
if (queue_->closed()) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "enqueue after Close; command dropped");
|
||||
return;
|
||||
}
|
||||
reject(hr, kind, method);
|
||||
}
|
||||
|
||||
WorkQueue* queue_;
|
||||
UINT64 source_type_;
|
||||
};
|
||||
|
||||
class XboxFactory final : public PublicObject<IXboxDStorageFactory> {
|
||||
public:
|
||||
HRESULT STDMETHODCALLTYPE CreateQueue(const void*, REFIID, void** ppv) override {
|
||||
if (ppv) *ppv = nullptr;
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 3u, "CreateQueue");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!path || !*path) return E_INVALIDARG;
|
||||
HANDLE handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_OVERLAPPED, nullptr);
|
||||
if (handle == INVALID_HANDLE_VALUE) return win32_error();
|
||||
auto* file = new (std::nothrow) StorageFile(handle);
|
||||
if (!file) {
|
||||
CloseHandle(handle);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
auto* wrapper = new (std::nothrow) XboxFile(file);
|
||||
if (!wrapper) {
|
||||
file->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!capacity || capacity > 65535) return E_INVALIDARG;
|
||||
auto* slots = new (std::nothrow) StatusArray::Slot[capacity];
|
||||
if (!slots) return E_OUTOFMEMORY;
|
||||
auto* array = new (std::nothrow) StatusArray(slots, capacity);
|
||||
if (!array) {
|
||||
delete[] slots;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
auto* wrapper = new (std::nothrow) XboxStatusArray(array);
|
||||
if (!wrapper) {
|
||||
array->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override {
|
||||
if (flags) BX_VTABLE_STUB_LOG("IDStorageFactoryX", 6u, "SetDebugFlags");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot7() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 7u, "Slot7");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override {
|
||||
char detail[80];
|
||||
/* Like the public factory: the engine has no staging buffer to size. */
|
||||
std::snprintf(detail, sizeof(detail), "xbox size=%lu has no effect", static_cast<unsigned long>(size));
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_staging_buffer_size", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot9() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 9u, "Slot9");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!desc) return E_INVALIDARG;
|
||||
if (desc->capacity < 2 || desc->capacity > DSTORAGE_MAX_QUEUE_CAPACITY) {
|
||||
return E_DSTORAGE_INVALID_QUEUE_CAPACITY;
|
||||
}
|
||||
if (desc->source_type > 1) {
|
||||
return E_DSTORAGE_INVALID_SOURCE_TYPE;
|
||||
}
|
||||
/* desc->priority is ignored on purpose: the Xbox priority range is not part of
|
||||
* the inferred contract, so no value is rejected (the public queue's
|
||||
* E_DSTORAGE_INVALID_QUEUE_PRIORITY range check is not assumed to apply). */
|
||||
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);
|
||||
if (!queue) {
|
||||
delete[] entries;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
if (!queue->create_work()) {
|
||||
const HRESULT error = win32_error();
|
||||
queue->Release();
|
||||
return error;
|
||||
}
|
||||
auto* wrapper = new (std::nothrow) XboxQueue(queue, desc->source_type);
|
||||
if (!wrapper) {
|
||||
queue->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot11() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 11u, "Slot11");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot12() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 12u, "Slot12");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFactoryIid); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// Accepts BetterXen's synthetic factory IID and IUnknown (the synthetic factory),
|
||||
// and the public PC IDStorageFactory / IDStorageFactory1. Any other IID is logged
|
||||
// with its value so `bx-cli trace` names the interface a guest asked for.
|
||||
// the public PC IDStorageFactory / IDStorageFactory1, and the inferred Xbox
|
||||
// IDStorageFactoryX IID. Any other IID is logged with its value so `bx-cli trace`
|
||||
// names the interface a guest asked for.
|
||||
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
@@ -1276,6 +1667,12 @@ extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
|
||||
auto* factory = new (std::nothrow) PublicFactory;
|
||||
return factory ? publish(factory, riid, ppv) : E_OUTOFMEMORY;
|
||||
}
|
||||
if (IsEqualIID(riid, kXboxFactoryIid)) {
|
||||
auto* factory = new (std::nothrow) XboxFactory;
|
||||
if (!factory) return E_OUTOFMEMORY;
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_get_factory", "dispatch xbox_com=IDStorageFactoryX");
|
||||
return publish(factory, riid, ppv);
|
||||
}
|
||||
if (!IsEqualIID(riid, factory_iid) && !IsEqualIID(riid, IID_IUnknown)) {
|
||||
char iid[40];
|
||||
format_iid(riid, iid);
|
||||
|
||||
+296
-26
@@ -104,7 +104,8 @@ struct Rdna2TileQuery {
|
||||
uint32_t texel_y;
|
||||
};
|
||||
|
||||
/* Named 64 KiB tiles. The address equation is intentionally absent. */
|
||||
/* Named 64 KiB tiles. Only SW_64KB_S has its address equation implemented; see
|
||||
* rdna2_sw64kb_prepare below for the sources and the exact scope. */
|
||||
constexpr Rdna2TileMode kRdna2TileModes[] = {
|
||||
{BX_XG_LAYOUT_SW_64KB_S, 64u * 1024u, "SW_64KB_S"},
|
||||
{BX_XG_LAYOUT_SW_64KB_D, 64u * 1024u, "SW_64KB_D"},
|
||||
@@ -304,8 +305,129 @@ static TextureComputer* impl_from(bx_xg_texture_computer* self) {
|
||||
return reinterpret_cast<TextureComputer*>(self);
|
||||
}
|
||||
|
||||
/* M3 placeholder. Validates the tile request and returns no address. */
|
||||
static HRESULT rdna2_sw64kb_prepare(const Rdna2TileQuery* query) {
|
||||
/*
|
||||
* SW_64KB_S (AMD ADDR_SW_64KB_S, enum 9) intra-block address, for the narrow
|
||||
* case public sources actually specify: TEXTURE2D, one array slice, one mip,
|
||||
* one sample.
|
||||
*
|
||||
* Sources, both public:
|
||||
* [1] Microsoft, D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE, 32-bpp masks
|
||||
* xBytesMask = 0xAA8F and yMask = 0x5570, combined with _pdep_u32.
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout
|
||||
* [2] AMD AddrLib (MIT), the GFX10 swizzle tables and equation:
|
||||
* src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h (GFX10_SW_64K_S_RBPLUS_PATINFO)
|
||||
* src/amd/addrlib/src/gfx10/gfx10addrlib.h (GetSwizzlePatternFromPatternInfo)
|
||||
* src/amd/addrlib/inc/addrtypes.h (ADDR_SW_64KB_S = 9)
|
||||
* https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib
|
||||
*
|
||||
* At 32 bpp the two agree bit-for-bit, which is why this mode is the one worth
|
||||
* implementing first. The RB+ table is used because gfx1030 is Navi2x. For
|
||||
* SW_64KB_S the choice does not matter: GFX10_SW_64K_S_PATINFO and
|
||||
* GFX10_SW_64K_S_RBPLUS_PATINFO select the same nibble indices at every
|
||||
* element size (2,3,3,0 at 4 B; 3,4,4,0 at 8 B; 4,5,5,0 at 16 B), so both
|
||||
* tables expand to the masks below. They differ for other tile modes, not
|
||||
* for this one.
|
||||
*
|
||||
* For a 64 KiB tile the intra-tile byte offset of texel (x, y) is the bit
|
||||
* interleave below, for a 32-bpp format whose tile is 128x128 texels:
|
||||
* pdep(x * 4, 0xAA8F) | pdep(y, 0x5570). x is multiplied by 4 because the
|
||||
* D3D12 mask is defined over xBytes, not over texel x.
|
||||
*
|
||||
* SW_64KB_D differs from S at 32 bpp (AddrLib nibble01 index 39 versus 2, i.e.
|
||||
* address bits 6 and 7 swapped), and SW_64KB_R has no public GFX10 form at all
|
||||
* (ADDR_SW_64KB_R is Reserved on GFX10; the render-target mode is
|
||||
* ADDR_SW_64KB_R_X, whose pipe/packer XOR is not public). Both stay E_NOTIMPL.
|
||||
*/
|
||||
/* SW_64KB_S is implemented for the element sizes the RB+ tables specify:
|
||||
* 4-byte (32-bpp RGBA8), 8-byte (BC1/BC4) and 16-byte (BC2/3/5/6H/7) blocks. */
|
||||
static bool sw64kb_s_supported(const Rdna2TileQuery* query) {
|
||||
if (query->mode != BX_XG_LAYOUT_SW_64KB_S) {
|
||||
return false;
|
||||
}
|
||||
return query->block_bytes == 4u || query->block_bytes == 8u || query->block_bytes == 16u;
|
||||
}
|
||||
|
||||
/* Bit-interleave one axis into a 32-bpp 64 KiB standard-swizzle tile. */
|
||||
static uint32_t sw64kb_s_pdep(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; bit != 0 && mask != 0; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & bit) {
|
||||
out |= lowest;
|
||||
}
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/*
|
||||
* Per-element-size SW_64KB_S parameters, derived from the AddrLib RB+ tables
|
||||
* (GFX10_SW_64K_S_RBPLUS_PATINFO, MIT). For a 64 KiB tile the intra-tile byte
|
||||
* offset of block (x, y) is pdep(x, x_mask) | pdep(y, y_mask), where x/y are
|
||||
* BLOCK indices (one 4x4 texel block for BC, one texel for 32 bpp).
|
||||
*
|
||||
* The masks below were expanded by hand from the nibble tables
|
||||
* GFX10_SW_PATTERN_NIBBLE01/2/3 at the patinfo indices the RB+ table selects
|
||||
* for each elemLog2 (2 -> 4 B, 3 -> 8 B, 4 -> 16 B). At 32 bpp the x mask
|
||||
* 0xAA8C equals Microsoft's public D3D12 xBytesMask 0xAA8F with the two
|
||||
* intra-texel byte bits (0x3) removed, and the y mask 0x5570 matches D3D12
|
||||
* exactly - two independent public sources agreeing, which is why S is the
|
||||
* mode implemented. The 8 B and 16 B rows come from AddrLib alone.
|
||||
*
|
||||
* Each row was checked to be a bijection over its tile: 4 B -> 128x128
|
||||
* texels, 8 B -> 128x64 blocks, 16 B -> 64x64 blocks, every offset distinct,
|
||||
* block-aligned and inside the 64 KiB tile.
|
||||
*/
|
||||
struct Sw64kbSParams {
|
||||
uint32_t block_bytes;
|
||||
uint32_t x_mask;
|
||||
uint32_t y_mask;
|
||||
uint32_t tile_blocks_x;
|
||||
uint32_t tile_blocks_y;
|
||||
};
|
||||
|
||||
static bool sw64kb_s_params(uint32_t block_bytes, Sw64kbSParams* out) {
|
||||
if (!out) {
|
||||
return false;
|
||||
}
|
||||
switch (block_bytes) {
|
||||
case 4u:
|
||||
*out = Sw64kbSParams{4u, 0xAA8Cu, 0x5570u, 128u, 128u};
|
||||
return true;
|
||||
case 8u:
|
||||
*out = Sw64kbSParams{8u, 0xAAC8u, 0x5530u, 128u, 64u};
|
||||
return true;
|
||||
case 16u:
|
||||
*out = Sw64kbSParams{16u, 0xAAC0u, 0x5530u, 64u, 64u};
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* Intra-64KiB-tile BYTE offset for SW_64KB_S, for any supported block size. */
|
||||
static uint32_t sw64kb_s_offset(const Sw64kbSParams* params, uint32_t x, uint32_t y) {
|
||||
return sw64kb_s_pdep(x, params->x_mask) | sw64kb_s_pdep(y, params->y_mask);
|
||||
}
|
||||
|
||||
static bool sw64kb_s_params_for(uint32_t block_bytes, Sw64kbSParams* out) {
|
||||
Sw64kbSParams ignored{};
|
||||
return sw64kb_s_params(block_bytes, out ? out : &ignored);
|
||||
}
|
||||
|
||||
/* The 64 KiB tile every named tiled mode occupies. */
|
||||
constexpr uint32_t kTileBytes = 64u * 1024u;
|
||||
|
||||
/* True when this object is a tiled resource whose addressing is implemented:
|
||||
* SW_64KB_S, exactly one mip and one array slice, over a supported element
|
||||
* size. Everything else stays E_NOTIMPL and is logged by reject_if_tiled. */
|
||||
static bool tiled_addressing_ok(const Resolved* resolved) {
|
||||
return resolved->layout == BX_XG_LAYOUT_SW_64KB_S && resolved->mip_levels == 1u &&
|
||||
resolved->array_size == 1u && sw64kb_s_params_for(resolved->block_bytes, nullptr);
|
||||
}
|
||||
|
||||
static HRESULT rdna2_sw64kb_prepare(const Rdna2TileQuery* query, uint32_t* offset) {
|
||||
if (offset) *offset = 0u;
|
||||
if (!query || query->mip_width == 0u || query->mip_height == 0u || query->block_bytes == 0u) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
@@ -319,34 +441,42 @@ static HRESULT rdna2_sw64kb_prepare(const Rdna2TileQuery* query) {
|
||||
if (!found || found->tile_bytes != (64u * 1024u) || found->name == nullptr) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
return E_NOTIMPL;
|
||||
if (!sw64kb_s_supported(query) || !offset) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
Sw64kbSParams params{};
|
||||
if (!sw64kb_s_params(query->block_bytes, ¶ms)) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
/* One 64 KiB tile covers params.tile_blocks_x * params.tile_blocks_y
|
||||
* blocks (texels for 32 bpp, 4x4 blocks for BC). */
|
||||
if (query->texel_x >= params.tile_blocks_x || query->texel_y >= params.tile_blocks_y) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
*offset = sw64kb_s_offset(¶ms, query->texel_x, query->texel_y);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
static HRESULT reject_if_tiled(const TextureComputer* obj, uint32_t slot, const char* method) {
|
||||
if (obj->resolved.layout == BX_XG_LAYOUT_LINEAR) {
|
||||
return S_OK;
|
||||
}
|
||||
Rdna2TileQuery query{};
|
||||
query.mode = obj->resolved.layout;
|
||||
query.mip_width = obj->resolved.width;
|
||||
query.mip_height = obj->resolved.height;
|
||||
query.block_bytes = obj->resolved.block_bytes;
|
||||
query.texel_x = 0u;
|
||||
query.texel_y = 0u;
|
||||
const HRESULT hr = rdna2_sw64kb_prepare(&query);
|
||||
if (hr == E_NOTIMPL) {
|
||||
const Rdna2TileMode* mode = nullptr;
|
||||
for (const Rdna2TileMode& candidate : kRdna2TileModes) {
|
||||
if (candidate.mode == obj->resolved.layout) {
|
||||
mode = &candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
char label[80];
|
||||
std::snprintf(label, sizeof(label), "%s %s", method, mode && mode->name ? mode->name : "SW_64KB");
|
||||
BX_VTABLE_STUB_LOG("IXGTextureAddressComputer", slot, label);
|
||||
/* SW_64KB_S, one mip, one slice, supported element size: implemented.
|
||||
* Everything else named is still E_NOTIMPL, and the log records which. */
|
||||
if (tiled_addressing_ok(&obj->resolved)) {
|
||||
return S_OK;
|
||||
}
|
||||
return hr;
|
||||
const Rdna2TileMode* mode = nullptr;
|
||||
for (const Rdna2TileMode& candidate : kRdna2TileModes) {
|
||||
if (candidate.mode == obj->resolved.layout) {
|
||||
mode = &candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
char label[80];
|
||||
std::snprintf(label, sizeof(label), "%s %s", method, mode && mode->name ? mode->name : "SW_64KB");
|
||||
BX_VTABLE_STUB_LOG("IXGTextureAddressComputer", slot, label);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
static HRESULT measure_mip(const Resolved* resolved, uint32_t mip, Placement* place) {
|
||||
@@ -425,6 +555,38 @@ static HRESULT build_linear_table(TextureComputer* obj) {
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
/*
|
||||
* Placement table for an implemented tiled resource. A single 64 KiB tile
|
||||
* holds one mip, so the "row" of the tile is one row of blocks and the tile's
|
||||
* slice stride is exactly kTileBytes. Choosing these numbers lets the existing
|
||||
* size, layout and offset code report the tile while the element addresses
|
||||
* still come from rdna2_sw64kb_prepare.
|
||||
*/
|
||||
static HRESULT build_tiled_table(TextureComputer* obj) {
|
||||
if (obj->resolved.layout == BX_XG_LAYOUT_LINEAR) {
|
||||
return S_OK;
|
||||
}
|
||||
if (!tiled_addressing_ok(&obj->resolved)) {
|
||||
return S_OK; /* rejected per call, with the stub log */
|
||||
}
|
||||
Sw64kbSParams params{};
|
||||
if (!sw64kb_s_params(obj->resolved.block_bytes, ¶ms)) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
MipInfo* info = &obj->mips[0];
|
||||
info->offset = 0u;
|
||||
info->logical_width = obj->resolved.width;
|
||||
info->logical_height = obj->resolved.height;
|
||||
info->footprint_width = params.tile_blocks_x * obj->resolved.block_w;
|
||||
info->footprint_height = params.tile_blocks_y * obj->resolved.block_h;
|
||||
info->row_pitch = params.tile_blocks_x * params.block_bytes;
|
||||
info->row_count = params.tile_blocks_y;
|
||||
info->row_bytes = info->row_pitch;
|
||||
obj->slice_stride = kTileBytes;
|
||||
obj->stored_mips = 1u;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
static HRESULT allocation_end_relative(const TextureComputer* obj, uint32_t index, uint64_t* end) {
|
||||
if (obj->stored_mips == 0u || index >= obj->resolved.subresource_count) {
|
||||
return E_INVALIDARG;
|
||||
@@ -706,6 +868,68 @@ static HRESULT image_and_resource_pitch(
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
/*
|
||||
* Copy one subresource of an implemented tiled SW_64KB_S resource, in swizzle
|
||||
* order. The image is tight rows of blocks (4x4 blocks for BC, one texel per
|
||||
* block for 32 bpp); each block lands at its AddrLib S offset inside the
|
||||
* 64 KiB tile. `to_resource` selects the direction.
|
||||
*/
|
||||
static HRESULT copy_tiled_sw64kb_s(
|
||||
const Resolved* resolved,
|
||||
bool to_resource,
|
||||
uint8_t* resource,
|
||||
uint64_t resource_size,
|
||||
const uint8_t* image,
|
||||
uint64_t image_size,
|
||||
uint64_t image_row_pitch,
|
||||
uint64_t image_depth_pitch
|
||||
) {
|
||||
Sw64kbSParams params{};
|
||||
if (!sw64kb_s_params(resolved->block_bytes, ¶ms)) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
const uint32_t blocks_w = div_up_u32(resolved->width, resolved->block_w);
|
||||
const uint32_t blocks_h = div_up_u32(resolved->height, resolved->block_h);
|
||||
if (blocks_w == 0u || blocks_h == 0u || blocks_w > params.tile_blocks_x ||
|
||||
blocks_h > params.tile_blocks_y) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
const uint64_t tight_row = uint64_t(blocks_w) * resolved->block_bytes;
|
||||
const uint64_t row_pitch = image_row_pitch == 0u ? tight_row : image_row_pitch;
|
||||
if (row_pitch < tight_row) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
/* One slice spans blocks_h rows at the caller's row pitch, not at the tight
|
||||
* row, so a depth pitch between the two would leave the last row outside
|
||||
* the slice. Only the single-slice case is implemented, but the bound must
|
||||
* still describe a slice. */
|
||||
if (image_depth_pitch != 0u && image_depth_pitch < uint64_t(blocks_h) * row_pitch) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
/* CopyFromSubresource passes the caller's image as `resource` and the tiled
|
||||
* resource as `image`, so the bound for each offset follows the direction. */
|
||||
const uint64_t tiled_size = to_resource ? resource_size : image_size;
|
||||
const uint64_t linear_size = to_resource ? image_size : resource_size;
|
||||
for (uint32_t by = 0; by < blocks_h; ++by) {
|
||||
for (uint32_t bx = 0; bx < blocks_w; ++bx) {
|
||||
const uint64_t byte_col = uint64_t(bx) * resolved->block_bytes;
|
||||
const uint64_t image_off = uint64_t(by) * row_pitch + byte_col;
|
||||
const uint64_t tile_off = uint64_t(sw64kb_s_offset(¶ms, bx, by));
|
||||
const uint64_t end = image_off + resolved->block_bytes;
|
||||
if (end > linear_size || tile_off + resolved->block_bytes > tiled_size ||
|
||||
tile_off + resolved->block_bytes > kTileBytes) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (to_resource) {
|
||||
std::memcpy(resource + tile_off, image + image_off, resolved->block_bytes);
|
||||
} else {
|
||||
std::memcpy(resource + image_off, image + tile_off, resolved->block_bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
static ULONG WINAPI computer_add_ref(bx_xg_texture_computer* self) {
|
||||
if (!self) {
|
||||
return 0u;
|
||||
@@ -819,7 +1043,9 @@ static HRESULT WINAPI computer_get_resource_base_alignment_bytes(bx_xg_texture_c
|
||||
if (tiled != S_OK) {
|
||||
return tiled;
|
||||
}
|
||||
*alignment_bytes = kPlacementAlignment;
|
||||
/* An implemented tiled resource must start on a tile boundary; a linear
|
||||
* one only needs the placement alignment. */
|
||||
*alignment_bytes = tiled_addressing_ok(&obj->resolved) ? kTileBytes : kPlacementAlignment;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
@@ -873,6 +1099,31 @@ static HRESULT WINAPI computer_get_texel_element_offset_bytes(
|
||||
if (z != 0u || array_slice >= obj->resolved.array_size || mip_level >= obj->resolved.mip_levels) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (obj->resolved.layout != BX_XG_LAYOUT_LINEAR) {
|
||||
/* Tiled: a single 64 KiB tile at offset 0, so the element offset is the
|
||||
* intra-tile swizzled offset. Only SW_64KB_S reaches here (32 bpp and
|
||||
* the BC block sizes); reject_if_tiled already returned E_NOTIMPL for
|
||||
* every other tiled mode. */
|
||||
if (array_slice != 0u || mip_level != 0u) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
Rdna2TileQuery query{};
|
||||
query.mode = obj->resolved.layout;
|
||||
query.mip_width = obj->resolved.width;
|
||||
query.mip_height = obj->resolved.height;
|
||||
query.block_bytes = obj->resolved.block_bytes;
|
||||
const uint32_t block_x = x / obj->resolved.block_w;
|
||||
const uint32_t block_y = y / obj->resolved.block_h;
|
||||
query.texel_x = block_x;
|
||||
query.texel_y = block_y;
|
||||
uint32_t offset = 0u;
|
||||
const HRESULT hr = rdna2_sw64kb_prepare(&query, &offset);
|
||||
if (hr != S_OK) {
|
||||
return hr;
|
||||
}
|
||||
*offset_bytes = offset;
|
||||
return S_OK;
|
||||
}
|
||||
const uint32_t index = mip_level + array_slice * obj->resolved.mip_levels;
|
||||
Placement place{};
|
||||
const HRESULT hr = placement_from_index(obj, index, 0, &place);
|
||||
@@ -913,6 +1164,14 @@ static HRESULT WINAPI computer_copy_into_subresource(
|
||||
if (tiled != S_OK) {
|
||||
return tiled;
|
||||
}
|
||||
if (tiled_addressing_ok(&obj->resolved)) {
|
||||
if (subresource != 0u) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
return copy_tiled_sw64kb_s(
|
||||
&obj->resolved, true, static_cast<uint8_t*>(destination), destination_size,
|
||||
static_cast<const uint8_t*>(source), source_size, source_row_pitch, source_depth_pitch);
|
||||
}
|
||||
Placement place{};
|
||||
const HRESULT placed = placement_from_index(obj, subresource, 0, &place);
|
||||
if (placed != S_OK) {
|
||||
@@ -958,6 +1217,14 @@ static HRESULT WINAPI computer_copy_from_subresource(
|
||||
if (tiled != S_OK) {
|
||||
return tiled;
|
||||
}
|
||||
if (tiled_addressing_ok(&obj->resolved)) {
|
||||
if (subresource != 0u) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
return copy_tiled_sw64kb_s(
|
||||
&obj->resolved, false, static_cast<uint8_t*>(destination), destination_size,
|
||||
static_cast<const uint8_t*>(source), source_size, destination_row_pitch, destination_depth_pitch);
|
||||
}
|
||||
Placement place{};
|
||||
const HRESULT placed = placement_from_index(obj, subresource, 0, &place);
|
||||
if (placed != S_OK) {
|
||||
@@ -1020,7 +1287,10 @@ HRESULT WINAPI XGCreateTextureComputer(const bx_xg_resource_desc* desc, void** c
|
||||
obj->iface.lpVtbl = &kVtbl;
|
||||
obj->refcount = 1;
|
||||
obj->resolved = resolved;
|
||||
const HRESULT built = build_linear_table(obj);
|
||||
HRESULT built = build_linear_table(obj);
|
||||
if (built == S_OK) {
|
||||
built = build_tiled_table(obj);
|
||||
}
|
||||
if (built != S_OK) {
|
||||
HeapFree(GetProcessHeap(), 0, obj);
|
||||
return built;
|
||||
|
||||
@@ -34,6 +34,8 @@ HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, vo
|
||||
void WINAPI XTaskQueueCloseHandle(void*);
|
||||
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
|
||||
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
|
||||
void (CALLBACK*)(void*, bool));
|
||||
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
|
||||
|
||||
HRESULT WINAPI XAsyncGetStatus(void*, bool);
|
||||
@@ -184,9 +186,11 @@ HRESULT WINAPI core_tq_submit(void*, void* queue, Port port, void* ctx, void (CA
|
||||
HRESULT WINAPI core_tq_submit_delayed(void*, void* queue, Port port, uint32_t delay_ms, void* ctx,
|
||||
void (CALLBACK* cb)(void*, bool)) {
|
||||
if (delay_ms > 0) {
|
||||
BX_VTABLE_STUB_LOG("IXGameRuntimeCore", 19, "XTaskQueueSubmitDelayedCallback(nonzero_delay)");
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "queued delay_ms=%lu", static_cast<unsigned long>(delay_ms));
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XTaskQueueSubmitDelayedCallback", detail);
|
||||
}
|
||||
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
|
||||
return XTaskQueueSubmitDelayedCallback(queue, port, delay_ms, ctx, cb);
|
||||
}
|
||||
bool WINAPI core_tq_get_process(void*, void** out) {
|
||||
return XTaskQueueGetCurrentProcessTaskQueue(out);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "task_queue.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
@@ -43,7 +44,11 @@ public:
|
||||
std::unique_lock lock(mutex);
|
||||
if (closed && !is_completion) return false;
|
||||
if (mode == DispatchMode::immediate || (closed && mode == DispatchMode::manual)) {
|
||||
// No lane storage on these paths, so the submitting thread waits out
|
||||
// the remainder of the delay and then runs the callback itself.
|
||||
const uint64_t due_ms = task->due_ms;
|
||||
lock.unlock();
|
||||
wait_until(due_ms);
|
||||
task->run(owner->shared_from_this());
|
||||
return true;
|
||||
}
|
||||
@@ -62,6 +67,30 @@ public:
|
||||
SubmitThreadpoolWork(worker);
|
||||
}
|
||||
|
||||
bool due() const { return first && (first->due_ms == 0 || GetTickCount64() >= first->due_ms); }
|
||||
|
||||
// Sleep out the remainder of a GetTickCount64 deadline. Saturating: the
|
||||
// deadline can pass between the check and the clock read, and an unsigned
|
||||
// subtraction there would wrap to ~584 million years.
|
||||
static void wait_until(uint64_t due_ms) {
|
||||
for (;;) {
|
||||
const uint64_t now = GetTickCount64();
|
||||
if (due_ms == 0 || now >= due_ms) return;
|
||||
const uint64_t left = due_ms - now;
|
||||
// INFINITE would mean "wait forever", so a `left` of exactly
|
||||
// 0xFFFFFFFF would never wake to re-check the deadline.
|
||||
Sleep(finite_sleep_chunk_ms(left));
|
||||
}
|
||||
}
|
||||
|
||||
// FIFO: the head holds the lane until it is due, so a later task never
|
||||
// overtakes a delayed one. Wait only until that deadline, never spin.
|
||||
std::chrono::steady_clock::time_point head_due() const {
|
||||
const uint64_t now = GetTickCount64();
|
||||
const uint64_t left = first->due_ms > now ? first->due_ms - now : 0;
|
||||
return std::chrono::steady_clock::now() + std::chrono::milliseconds(left);
|
||||
}
|
||||
|
||||
void schedule_serial() {
|
||||
if (mode == DispatchMode::serialized && first && !serial_running && workers == 0) {
|
||||
schedule();
|
||||
@@ -92,11 +121,25 @@ public:
|
||||
bool dispatch(uint32_t timeout) {
|
||||
if (mode == DispatchMode::immediate) return false;
|
||||
std::unique_lock lock(mutex);
|
||||
const auto has_task = [this] { return closed || (first && !serial_running); };
|
||||
const auto has_task = [this] { return closed || (due() && !serial_running); };
|
||||
if (timeout == INFINITE) {
|
||||
ready.wait(lock, has_task);
|
||||
} else if (!ready.wait_for(lock, std::chrono::milliseconds(timeout), has_task)) {
|
||||
return false;
|
||||
while (!has_task()) {
|
||||
if (first && !serial_running) {
|
||||
ready.wait_until(lock, head_due());
|
||||
} else {
|
||||
ready.wait(lock);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout);
|
||||
while (!has_task()) {
|
||||
if (std::chrono::steady_clock::now() >= deadline) return false;
|
||||
auto wake = deadline;
|
||||
if (first && !serial_running) {
|
||||
wake = std::min(wake, head_due());
|
||||
}
|
||||
ready.wait_until(lock, wake);
|
||||
}
|
||||
}
|
||||
if (closed) return false;
|
||||
auto task = pop();
|
||||
@@ -118,6 +161,14 @@ public:
|
||||
std::unique_lock lock(lane.mutex);
|
||||
queue = lane.worker_owner;
|
||||
while (lane.first && !lane.serial_running) {
|
||||
// A delayed head must not run early. Wait on the condition variable
|
||||
// until its deadline (or a push changes the head) instead of popping
|
||||
// it, so FIFO order holds and nothing is dropped. Close drains what
|
||||
// was already accepted, as it did before delays existed.
|
||||
if (!lane.closed && !lane.due()) {
|
||||
lane.ready.wait_until(lock, lane.head_due());
|
||||
continue;
|
||||
}
|
||||
auto task = lane.pop();
|
||||
const bool serial = lane.mode == DispatchMode::serialized;
|
||||
lane.serial_running = serial;
|
||||
@@ -190,6 +241,7 @@ bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool i
|
||||
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
}
|
||||
|
||||
|
||||
} // namespace bx::gdk
|
||||
|
||||
using namespace bx::gdk;
|
||||
@@ -237,12 +289,23 @@ bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
|
||||
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
}
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
||||
CallbackTask::Callback callback);
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitCallback(void* handle, Port port, void* context, CallbackTask::Callback callback) {
|
||||
return XTaskQueueSubmitDelayedCallback(handle, port, 0, context, callback);
|
||||
}
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
||||
CallbackTask::Callback callback) {
|
||||
if (!handle || port > Port::completion || !callback) return E_INVALIDARG;
|
||||
const auto queue = acquire_queue(handle);
|
||||
if (!queue) return E_HANDLE;
|
||||
auto task = std::unique_ptr<Task>(new (std::nothrow) CallbackTask(callback, context));
|
||||
if (!task) return E_OUTOFMEMORY;
|
||||
// delay_ms == 0 is due now, which is the common case and matches the old
|
||||
// immediate-submit behaviour. A nonzero delay is a GetTickCount64 deadline.
|
||||
task->due_ms = delay_ms == 0 ? 0 : GetTickCount64() + delay_ms;
|
||||
return submit(queue, port, std::move(task)) ? S_OK : E_HANDLE;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,10 +17,26 @@ struct Task {
|
||||
virtual void run(const QueueRef& queue) = 0;
|
||||
virtual void cancel(const QueueRef& queue) { run(queue); }
|
||||
|
||||
// GetTickCount64 deadline; zero means due immediately.
|
||||
uint64_t due_ms = 0;
|
||||
std::unique_ptr<Task> next;
|
||||
};
|
||||
|
||||
QueueRef acquire_queue(void* handle);
|
||||
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion = false);
|
||||
|
||||
// Largest finite Sleep() chunk. INFINITE (0xFFFFFFFF) means "wait forever", so
|
||||
// a delay whose remaining time is exactly INFINITE must never be passed to
|
||||
// Sleep: the wait would never wake to re-check the deadline, and the callback
|
||||
// would never run. Clamp every chunk to at most INFINITE - 1.
|
||||
inline constexpr uint32_t kMaxFiniteSleepMs = INFINITE - 1;
|
||||
|
||||
// Split a GetTickCount64 remainder into one finite Sleep() chunk. `left` is
|
||||
// uint64_t because a deadline subtraction can exceed 32 bits; the result is
|
||||
// always in [1, INFINITE - 1] for any positive `left`, so the caller's loop
|
||||
// always wakes up and re-checks the deadline.
|
||||
inline uint32_t finite_sleep_chunk_ms(uint64_t left) {
|
||||
return static_cast<uint32_t>(left < kMaxFiniteSleepMs ? left : kMaxFiniteSleepMs);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -798,6 +798,8 @@ HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, vo
|
||||
void WINAPI XTaskQueueCloseHandle(void*);
|
||||
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
|
||||
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
|
||||
void (CALLBACK*)(void*, bool));
|
||||
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
|
||||
|
||||
HRESULT WINAPI InitializeApiImpl(uint32_t gdk_ver, uint32_t gs_ver) {
|
||||
|
||||
+37
-4
@@ -63,6 +63,10 @@ CommitTable virtual_commits;
|
||||
uint64_t heap_bytes = 0;
|
||||
uint64_t virtual_bytes = 0;
|
||||
uint64_t physical_bytes = 0;
|
||||
/* Bytes admitted through bx_xmem_try_charge_external() on behalf of other
|
||||
* DLLs (e.g. d3d12_xs private host heaps). Counted in can_commit so both
|
||||
* allocation orders (graphics-first or xmem-first) obey one title cap. */
|
||||
uint64_t external_bytes = 0;
|
||||
uint64_t peak_bytes = 0;
|
||||
|
||||
uint64_t title_limit() {
|
||||
@@ -72,12 +76,12 @@ uint64_t title_limit() {
|
||||
|
||||
bool can_commit(uint64_t bytes) {
|
||||
const uint64_t limit = title_limit();
|
||||
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;
|
||||
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes + external_bytes;
|
||||
return used <= limit && bytes <= limit - used;
|
||||
}
|
||||
|
||||
void update_peak() {
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes + external_bytes);
|
||||
}
|
||||
|
||||
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
|
||||
@@ -290,7 +294,7 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
|
||||
std::memset(out_stats, 0, stats_size);
|
||||
std::memcpy(out_stats, &stats, sizeof(stats));
|
||||
return TRUE;
|
||||
@@ -306,10 +310,39 @@ void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
|
||||
// The internal ABI has no error return. Preserve the most recent
|
||||
// accounting snapshot if refreshing it runs out of bookkeeping memory.
|
||||
std::lock_guard guard(usage_lock);
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
|
||||
}
|
||||
}
|
||||
|
||||
int bx_xmem_try_charge_external(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!can_commit(bytes)) {
|
||||
if (!refresh_virtual_commits()) {
|
||||
// Bookkeeping ran out of memory: not a budget decision, so say so.
|
||||
bx_log_emit(BX_LOG_ERROR, "xmem", "external_charge",
|
||||
"refresh_virtual_commits failed; charge refused without a budget check");
|
||||
return 0;
|
||||
}
|
||||
if (!can_commit(bytes)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
external_bytes += bytes;
|
||||
update_peak();
|
||||
return 1;
|
||||
}
|
||||
|
||||
void bx_xmem_release_charge_external(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (bytes > external_bytes) {
|
||||
// Refuse: zeroing would also drop other owners' outstanding charges.
|
||||
bx_log_emit(BX_LOG_ERROR, "xmem", "external_charge",
|
||||
"release exceeds outstanding external charge; counter left unchanged");
|
||||
return;
|
||||
}
|
||||
external_bytes -= bytes;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
@@ -10,3 +10,65 @@ Every directory matching `test_*/CMakeLists.txt` is **auto-discovered** by `test
|
||||
```sh
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_<shim>.exe
|
||||
```
|
||||
|
||||
## Exit Status: Pass, Fail, and Unavailable
|
||||
|
||||
`bx-cli run` normally returns the guest's exit status. A timeout returns 124, a signal
|
||||
returns 128 plus its number, and a cleanup failure raises an otherwise successful status
|
||||
to at least 1. Fixtures that cannot reach a conclusion on the host report **exit 77**
|
||||
and print `SKIP: <reason>` on stdout; for example
|
||||
`test_d3dmetal_gpu_limits` skips when `d3d12.dll`, device creation, or shader model 6.6 is
|
||||
unavailable.
|
||||
|
||||
A skip is **not** a pass and **not** a failure. AGENTS.md §5 forbids counting a skipped test
|
||||
as a pass, so record the three outcomes separately:
|
||||
|
||||
```sh
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin \
|
||||
--log /tmp/bx-test.jsonl --exe build-shims/bin/test_<shim>.exe
|
||||
status=$?
|
||||
case $status in
|
||||
0) echo "PASS: test_<shim>" ;;
|
||||
77) echo "UNAVAILABLE (skip): test_<shim> — see the SKIP line above" ;;
|
||||
*) echo "FAIL: test_<shim> (exit $status)" ;;
|
||||
esac
|
||||
```
|
||||
|
||||
`bx-cli` does not itself reinterpret 77 (it is the guest's own status, and other fixtures use
|
||||
their own conventions), so always read the status before reporting a run. For a fixture that
|
||||
adopts this protocol, printing a `SKIP:` line without exit 77, or exiting 77 without one, is a
|
||||
defect. Older per-check skip conventions, such as `test_d3d12_xs`, are separate: its `SKIP:`
|
||||
lines are informational and the fixture exits according to `g_failures`.
|
||||
|
||||
## M2 First-Frame Fixture
|
||||
|
||||
The M2 fixture requires both the placed-resource and PresentX headers. Its CMake target fails
|
||||
configuration if either provider contract is missing; the fixture must not be silently skipped.
|
||||
Run it with a D3DMetal bottle:
|
||||
|
||||
```sh
|
||||
target/debug/bx-cli run --bottle <d3dmetal_bottle> --backend d3dmetal \
|
||||
--shims build-shims/bin --log /tmp/bx-m2-first-frame.jsonl \
|
||||
--exe build-shims/bin/test_m2_first_frame.exe
|
||||
```
|
||||
|
||||
Replace `<d3dmetal_bottle>` with the installed CrossOver bottle name.
|
||||
|
||||
To verify that the pixel comparison detects a mismatch, set the injection variable in the
|
||||
launcher environment and opt into environment inheritance. `env -i` keeps this test-only
|
||||
variable and the listed runtime essentials from exposing unrelated host environment values to
|
||||
the guest:
|
||||
|
||||
```sh
|
||||
env -i HOME="$HOME" USER="$USER" LOGNAME="$LOGNAME" TMPDIR=/tmp LANG=C \
|
||||
PATH=/usr/bin:/bin:/usr/sbin:/sbin \
|
||||
BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1 \
|
||||
target/debug/bx-cli run --inherit-env --bottle <d3dmetal_bottle> --backend d3dmetal \
|
||||
--shims build-shims/bin --log /tmp/bx-m2-first-frame-negative.jsonl \
|
||||
--exe build-shims/bin/test_m2_first_frame.exe
|
||||
```
|
||||
|
||||
Replace `<d3dmetal_bottle>` with the installed CrossOver bottle name.
|
||||
|
||||
The negative control should print `NOTE: pixel mismatch control armed` and exit 1.
|
||||
The `pixel_readback` checkpoint should report `pixel (0,0) expected 01234567 got 9f598b46`.
|
||||
@@ -3,10 +3,14 @@
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI AcpHalCreate(void**);
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*);
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void);
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuFree(void*);
|
||||
@@ -29,9 +33,105 @@ HRESULT WINAPI XDspDisconnect(void*);
|
||||
|
||||
namespace {
|
||||
void WINAPI dummy_device_callback(uint64_t, void*, void*, uint64_t, uint32_t, uint32_t) {}
|
||||
|
||||
bool file_contains(const char* path, uint64_t offset, const char* needle_a, const char* needle_b) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
return false;
|
||||
}
|
||||
bool found = false;
|
||||
LARGE_INTEGER size = {};
|
||||
if (GetFileSizeEx(f, &size) && size.QuadPart >= 0 &&
|
||||
offset <= static_cast<uint64_t>(size.QuadPart) &&
|
||||
static_cast<uint64_t>(size.QuadPart) - offset < (64ull << 20)) {
|
||||
LARGE_INTEGER pos{};
|
||||
pos.QuadPart = static_cast<LONGLONG>(offset);
|
||||
if (!SetFilePointerEx(f, pos, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return false;
|
||||
}
|
||||
const DWORD remaining = static_cast<DWORD>(static_cast<uint64_t>(size.QuadPart) - offset);
|
||||
auto* buf = static_cast<char*>(HeapAlloc(GetProcessHeap(), 0, static_cast<SIZE_T>(remaining) + 1));
|
||||
DWORD total = 0;
|
||||
while (buf && total < remaining) {
|
||||
DWORD got = 0;
|
||||
if (!ReadFile(f, buf + total, remaining - total, &got, nullptr) || got == 0) break;
|
||||
total += got;
|
||||
}
|
||||
if (buf && total == remaining) {
|
||||
buf[total] = '\0';
|
||||
/* Both needles must sit on the same JSONL line. */
|
||||
for (char* line = buf; line && *line && !found;) {
|
||||
char* end = std::strchr(line, '\n');
|
||||
if (end) *end = '\0';
|
||||
found = std::strstr(line, needle_a) && std::strstr(line, needle_b);
|
||||
line = end ? end + 1 : nullptr;
|
||||
}
|
||||
}
|
||||
if (buf) HeapFree(GetProcessHeap(), 0, buf);
|
||||
}
|
||||
CloseHandle(f);
|
||||
return found;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
|
||||
// Read the JSONL log the shim wrote, so the dispatcher's live-reference
|
||||
// count can be checked rather than assumed. The log is the only place the
|
||||
// count is observable: `Release` returning 0 proves the reference count
|
||||
// reached zero, and the `dispatch_mode` lines prove the live-dispatcher
|
||||
// counter followed it. They do not prove the object was freed: `Release`
|
||||
// updates the counter before `delete this`, so a leak would not show here.
|
||||
// `bx-cli run` appends to the supplied BX_LOG_FILE, so a re-run with the
|
||||
// same log can pass from stale lines even if this run emits none. Capture
|
||||
// the file's size before the run and assert only on the bytes appended by
|
||||
// this run.
|
||||
static uint64_t log_file_size(const char* path) {
|
||||
if (!path || !*path) return 0;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return 0;
|
||||
LARGE_INTEGER size{};
|
||||
const BOOL ok = GetFileSizeEx(f, &size);
|
||||
CloseHandle(f);
|
||||
return ok ? static_cast<uint64_t>(size.QuadPart) : 0;
|
||||
}
|
||||
|
||||
static std::string read_log_file_from(const char* path, uint64_t offset) {
|
||||
std::string text;
|
||||
if (!path || !*path) return text;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return text;
|
||||
LARGE_INTEGER pos{};
|
||||
pos.QuadPart = static_cast<LONGLONG>(offset);
|
||||
if (!SetFilePointerEx(f, pos, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
char buf[4096];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got > 0) {
|
||||
text.append(buf, got);
|
||||
}
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
|
||||
int main() {
|
||||
// The dispatcher checks below read the shim's JSONL log, so BX_LOG_FILE
|
||||
// must name it before the process starts (`bx-cli run --log`). Setting it
|
||||
// here would be too late: AcpHal.dll imports bx_runtime_veh.dll, which
|
||||
// reads BX_LOG_FILE once in DLL_PROCESS_ATTACH, before main runs.
|
||||
char dispatcher_log_path[MAX_PATH]{};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", dispatcher_log_path, sizeof(dispatcher_log_path));
|
||||
if (n == 0 || n >= sizeof(dispatcher_log_path)) {
|
||||
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
const uint64_t log_start = log_file_size(dispatcher_log_path);
|
||||
|
||||
void* object = nullptr;
|
||||
CHECK(AcpHalCreate(&object) == S_OK && object);
|
||||
auto* hal = static_cast<IUnknown*>(object);
|
||||
@@ -40,6 +140,10 @@ int main() {
|
||||
void *va = nullptr, *second = nullptr;
|
||||
uint32_t base = 0, other = 0;
|
||||
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
|
||||
// A zero-capacity heap must not report S_OK: it can never satisfy an
|
||||
// allocation (#580). ApuAlloc still refuses with E_OUTOFMEMORY.
|
||||
CHECK(ApuCreateHeap(0, 0) == E_INVALIDARG);
|
||||
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
|
||||
CHECK(ApuCreateHeap(64, 64) == S_OK);
|
||||
CHECK(ApuAlloc(&va, nullptr, 64, 64) == S_OK && va);
|
||||
CHECK(ApuFree(va) == S_OK);
|
||||
@@ -63,6 +167,25 @@ int main() {
|
||||
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
|
||||
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
|
||||
|
||||
// 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);
|
||||
|
||||
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"));
|
||||
} 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.
|
||||
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
|
||||
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
|
||||
unsigned result = 0;
|
||||
@@ -186,8 +309,51 @@ int main() {
|
||||
CHECK(!unreg_cb(v0, tok2, 0));
|
||||
set_focus(v0, 0x2);
|
||||
|
||||
// Slot 14: IGameInput::CreateDispatcher. The singleton refcount is checked
|
||||
// below via the pre-existing GameInput release sequence, which must be
|
||||
// unchanged by dispatcher creation.
|
||||
using CreateDispatcherFn = HRESULT (WINAPI*)(IUnknown*, void**);
|
||||
using DispatchFn = bool (WINAPI*)(IUnknown*, uint64_t);
|
||||
using OpenWaitHandleFn = HRESULT (WINAPI*)(IUnknown*, HANDLE*);
|
||||
auto create_dispatcher = reinterpret_cast<CreateDispatcherFn>(table[14]);
|
||||
CHECK(create_dispatcher(v0, nullptr) == E_POINTER);
|
||||
void* dispatcher = reinterpret_cast<void*>(uintptr_t{1});
|
||||
CHECK(create_dispatcher(v0, &dispatcher) == S_OK && dispatcher);
|
||||
auto* disp_unknown = static_cast<IUnknown*>(dispatcher);
|
||||
auto** disp_table = *reinterpret_cast<void***>(disp_unknown);
|
||||
void* disp_qi = nullptr;
|
||||
CHECK(reinterpret_cast<HRESULT (WINAPI*)(IUnknown*, REFIID, void**)>(disp_table[0])(
|
||||
disp_unknown, IID_IUnknown, &disp_qi) == S_OK && disp_qi == dispatcher);
|
||||
CHECK(disp_unknown->Release() == 1);
|
||||
void* disp_other = reinterpret_cast<void*>(uintptr_t{1});
|
||||
CHECK(reinterpret_cast<HRESULT (WINAPI*)(IUnknown*, REFIID, void**)>(disp_table[0])(
|
||||
disp_unknown, kUnknownIid, &disp_other) == E_NOINTERFACE && !disp_other);
|
||||
auto dispatch = reinterpret_cast<DispatchFn>(disp_table[3]);
|
||||
CHECK(!dispatch(disp_unknown, 0));
|
||||
CHECK(!dispatch(disp_unknown, 1000000));
|
||||
auto open_wait = reinterpret_cast<OpenWaitHandleFn>(disp_table[4]);
|
||||
CHECK(open_wait(disp_unknown, nullptr) == E_POINTER);
|
||||
HANDLE wait1 = nullptr, wait2 = nullptr;
|
||||
CHECK(open_wait(disp_unknown, &wait1) == S_OK && wait1);
|
||||
CHECK(WaitForSingleObject(wait1, 0) == WAIT_TIMEOUT);
|
||||
CHECK(open_wait(disp_unknown, &wait2) == S_OK && wait2 && wait2 != wait1);
|
||||
CHECK(CloseHandle(wait1) && CloseHandle(wait2));
|
||||
CHECK(disp_unknown->Release() == 0);
|
||||
|
||||
// `dispatch_mode` logs each manual/automatic transition with the live
|
||||
// dispatcher count. These checks catch a Release that never calls
|
||||
// `on_dispatcher_released` (no `live_dispatchers=0` line). They cannot
|
||||
// catch a missing `delete this`, which runs after the counter update.
|
||||
{
|
||||
const std::string log = read_log_file_from(dispatcher_log_path, log_start);
|
||||
CHECK(log.find("live_dispatchers=1") != std::string::npos);
|
||||
CHECK(log.find("live_dispatchers=0") != std::string::npos);
|
||||
CHECK(log.find("mode=manual") != std::string::npos);
|
||||
CHECK(log.find("mode=automatic") != std::string::npos);
|
||||
}
|
||||
|
||||
CHECK(v0->Release() == 1);
|
||||
CHECK(input->Release() == 0);
|
||||
FreeLibrary(dll);
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1 and device callbacks");
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1, device callbacks, dispatcher");
|
||||
}
|
||||
@@ -26,11 +26,22 @@
|
||||
extern "C" {
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(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 XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size);
|
||||
}
|
||||
|
||||
struct bx_xmem_stats_t {
|
||||
uint64_t title_limit_bytes;
|
||||
uint64_t committed_virtual_bytes;
|
||||
uint64_t allocated_physical_bytes;
|
||||
uint64_t peak_committed_bytes;
|
||||
};
|
||||
static_assert(sizeof(bx_xmem_stats_t) == 32, "xmem stats struct is 32 bytes");
|
||||
|
||||
struct BxD3d12VirtualMemoryConfig {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
@@ -77,6 +88,7 @@ static_assert(kFootprint <= kAlign, "texture footprint fits in one 64 KiB page")
|
||||
static_assert(kRegionBytes == 128ull * 1024ull, "configured region is 128 KiB");
|
||||
|
||||
int g_checks = 0;
|
||||
int g_skipped = 0;
|
||||
int g_failures = 0;
|
||||
|
||||
__attribute__((format(gnu_printf, 2, 3)))
|
||||
@@ -414,6 +426,51 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
|
||||
}
|
||||
}
|
||||
|
||||
/* #552: graphics-first / xmem-first pairing through the public exports.
|
||||
* With a 512 MiB cap, a 300 MiB D3D12 heap registers an external charge in
|
||||
* xmem. A 300 MiB XMemAlloc must then fail (300+300 > 512), and a 200 MiB
|
||||
* XMemAlloc must succeed (300+200 <= 512). After releasing the heap the
|
||||
* 300 MiB XMemAlloc must succeed. This is the graphics-first overcommit
|
||||
* that the private-ledger version allowed. */
|
||||
void check_graphics_xmem_pairing(ID3D12Device* device, uint64_t cap) {
|
||||
if (cap != (512ull << 20)) {
|
||||
/* The pairing sizes are fixed against a 512 MiB cap, so at any other cap the
|
||||
* cross-DLL budget check does not run. Say so rather than pass silently. */
|
||||
++g_skipped;
|
||||
std::printf("SKIP: graphics/xmem pairing needs a 512 MiB cap "
|
||||
"(BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env ...); this run's cap is %llu MiB\n",
|
||||
static_cast<unsigned long long>(cap >> 20));
|
||||
return;
|
||||
}
|
||||
const uint64_t heap_bytes = 300ull << 20;
|
||||
const auto heap_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, heap_bytes, D3D12_HEAP_FLAG_NONE);
|
||||
ID3D12Heap* heap = nullptr;
|
||||
HRESULT hr = device->CreateHeap(&heap_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
|
||||
if (!check(hr == S_OK && heap, "pairing: 300 MiB graphics heap hr=0x%08lx", ul(hr))) {
|
||||
return;
|
||||
}
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
check(XMemGetWorkingSetStatistics(&stats, sizeof(stats)) != 0, "pairing: xmem stats readable");
|
||||
|
||||
/* 300 MiB heap + 300 MiB xmem = 600 MiB > 512 MiB cap. */
|
||||
void* too_much = XMemAlloc(300ull << 20, 0);
|
||||
check(too_much == nullptr, "pairing: 300 MiB XMemAlloc on top of 300 MiB heap exceeds the 512 MiB cap");
|
||||
if (too_much) XMemFree(too_much, 0);
|
||||
|
||||
/* 300 MiB heap + 200 MiB xmem = 500 MiB <= 512 MiB cap. */
|
||||
void* fits = XMemAlloc(200ull << 20, 0);
|
||||
check(fits != nullptr, "pairing: 200 MiB XMemAlloc fits beside the 300 MiB heap");
|
||||
if (fits) XMemFree(fits, 0);
|
||||
|
||||
heap->Release();
|
||||
|
||||
/* After the heap charge is released the 300 MiB allocation must fit. */
|
||||
void* after = XMemAlloc(300ull << 20, 0);
|
||||
check(after != nullptr, "pairing: 300 MiB XMemAlloc fits after releasing the graphics heap");
|
||||
if (after) XMemFree(after, 0);
|
||||
}
|
||||
|
||||
/* CreatePlacedResource1 must accept a heap from CreateHeap. CreatePlacedResource2
|
||||
is checked only when the host device implements ID3D12Device10. */
|
||||
void check_newer_placement(ID3D12Device* device) {
|
||||
@@ -571,6 +628,9 @@ int main() {
|
||||
return 1;
|
||||
}
|
||||
const char* profile = cfg->profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart";
|
||||
char log_path[MAX_PATH];
|
||||
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
|
||||
|
||||
check(D3D12ConfigureVirtualMemoryX(nullptr) == S_OK, "null configuration is a logged stub that returns S_OK");
|
||||
|
||||
@@ -1239,9 +1299,6 @@ int main() {
|
||||
}
|
||||
}
|
||||
|
||||
char log_path[MAX_PATH];
|
||||
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
|
||||
std::printf("RESULT: cpu_va=0x%llx map=0x%llx buffer_gpu_va=0x%llx flush=%d copy_buffer=%u/%u copy_texture=%u/%u "
|
||||
"texture_path=%s cpu_after_gpu=%u/%u small_align=%llu upload_100000=%llu\n",
|
||||
static_cast<unsigned long long>(cpu_va), static_cast<unsigned long long>(map_pointer),
|
||||
@@ -1294,6 +1351,10 @@ int main() {
|
||||
check_placed_heap_charge(device, log_path, region_base, cfg->title_memory_limit_bytes);
|
||||
}
|
||||
|
||||
if (device) {
|
||||
check_graphics_xmem_pairing(device, cfg->title_memory_limit_bytes);
|
||||
}
|
||||
|
||||
/*
|
||||
* An ordinary heap AddRefs its device, matching BxChildProxy. Releasing the
|
||||
* caller's device reference must leave the proxy alive for GetDevice.
|
||||
@@ -1339,6 +1400,9 @@ int main() {
|
||||
*/
|
||||
check_newer_placement(device);
|
||||
|
||||
uint64_t host_before = 0;
|
||||
uint64_t host_ignored = 0;
|
||||
int host_before_count = 0;
|
||||
if (backing) {
|
||||
BxD3d12VirtualMemoryConfig detached = make_block(0, 0, kFlagBacking);
|
||||
const HRESULT away = D3D12ConfigureVirtualMemoryX(&detached);
|
||||
@@ -1370,6 +1434,10 @@ int main() {
|
||||
SetEnvironmentVariableA("BX_D3D12_FORCE_BACKING_REPLACE", nullptr);
|
||||
check(hr == S_OK && replaced && !same_object(replaced, backing),
|
||||
"forced host replacement publishes a different backing heap hr=0x%08lx", ul(hr));
|
||||
if (have_log) {
|
||||
/* Capture the device whose forced replacement heap remains in the cache. */
|
||||
log_u64_ends(log_path, "host_device=", &host_ignored, &host_before, &host_before_count);
|
||||
}
|
||||
check(get_device_closed(backing), "GetDevice on the heap replaced by another host device fails closed");
|
||||
const ULONG left = device->Release();
|
||||
check(left == 0, "proxy released to zero while the replaced heap is still held (refs=%lu)", left);
|
||||
@@ -1405,11 +1473,9 @@ int main() {
|
||||
if (dead) dead->Release();
|
||||
}
|
||||
|
||||
uint64_t host_before = 0;
|
||||
uint64_t host_ignored = 0;
|
||||
int host_before_count = 0;
|
||||
uint64_t latest_host_before_b = 0;
|
||||
if (have_log) {
|
||||
log_u64_ends(log_path, "host_device=", &host_ignored, &host_before, &host_before_count);
|
||||
log_u64_ends(log_path, "host_device=", &host_ignored, &latest_host_before_b, &host_before_count);
|
||||
}
|
||||
check(SetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", "1") != 0,
|
||||
"test hook BX_D3D12_REUSE_BACKING_HOST=1 is set");
|
||||
@@ -1468,9 +1534,9 @@ int main() {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_placed (%d of %d checks failed)\n", g_failures, g_checks);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_d3d12_placed (%d checks passed, buffer %u/%u bytes, texture %u/%u bytes, "
|
||||
std::printf("PASS: test_d3d12_placed (%d checks passed, %d skipped, buffer %u/%u bytes, texture %u/%u bytes, "
|
||||
"texture_path=%s, cpu_after_gpu %u/%u, small_align=%llu, upload_100000=%llu)\n",
|
||||
g_checks, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes,
|
||||
g_checks, g_skipped, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes,
|
||||
static_cast<unsigned long long>(small_align), static_cast<unsigned long long>(odd_size));
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# M2-C2 (#465): rendered frames through d3d12_xs.dll's presentation bridge, verified by readback.
|
||||
add_executable(test_d3d12_presentx main.cpp)
|
||||
target_include_directories(test_d3d12_presentx PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/d3d12_xs")
|
||||
target_link_libraries(test_d3d12_presentx PRIVATE d3d12_xs bx_runtime_veh user32 kernel32)
|
||||
File diff suppressed because it is too large.
Load diff
+64
@@ -0,0 +1,64 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Runs test_d3d12_presentx once normally and once per negative control, and checks that each
|
||||
# control fails in its own stage with its own evidence. Needs build-shims/ and bx-cli built.
|
||||
# Usage (from the repository root): tests/conformance/test_d3d12_presentx/run_controls.sh <bottle>
|
||||
set -u
|
||||
|
||||
bottle=${1:?usage: run_controls.sh <d3dmetal_bottle>}
|
||||
dir=$(mktemp -d) || exit 1
|
||||
bad=0
|
||||
|
||||
run() { # name injection
|
||||
BX_PRESENTX_INJECT=$2 target/debug/bx-cli run --inherit-env --bottle "$bottle" --backend d3dmetal \
|
||||
--shims build-shims/bin --log "$dir/$1.jsonl" --timeout 90 \
|
||||
--exe build-shims/bin/test_d3d12_presentx.exe >"$dir/$1.out" 2>&1
|
||||
status=$?
|
||||
}
|
||||
expect() { # name file pattern
|
||||
grep -aq -- "$3" "$dir/$1.$2" || { echo "$1: missing in $2: $3"; bad=1; }
|
||||
}
|
||||
must_fail() { # name stage
|
||||
[ "$status" -ne 0 ] || { echo "$1: exited 0"; bad=1; }
|
||||
expect "$1" out "first failing stage: $2)"
|
||||
}
|
||||
|
||||
run normal ""
|
||||
[ "$status" -eq 0 ] || { echo "normal: exit $status"; bad=1; }
|
||||
expect normal out "^PASS: test_d3d12_presentx (.* 0 skipped)"
|
||||
|
||||
run bad-window bad-window
|
||||
must_fail bad-window create
|
||||
expect bad-window out "FAIL \[create\]: CreateSwapChain hr=0x887a0001"
|
||||
# The contract stage logs seven argument rejections; the injected window must add the eighth.
|
||||
n=$(grep -ac '"event":"present_create_rejected".*invalid window or description' "$dir/bad-window.jsonl")
|
||||
[ "$n" -eq 8 ] || { echo "bad-window: $n argument rejections logged, expected 8"; bad=1; }
|
||||
|
||||
run skip-draw skip-draw
|
||||
must_fail skip-draw pixels
|
||||
expect skip-draw out "frame 5: 2432 of 6000 pixels differ"
|
||||
expect skip-draw out "pixels_wrong=2432 "
|
||||
|
||||
run wrong-expectation wrong-expectation
|
||||
must_fail wrong-expectation pixels
|
||||
expect wrong-expectation out "pixels_wrong=29184 "
|
||||
|
||||
run skip-wait-fault skip-wait-fault
|
||||
must_fail skip-wait-fault sync
|
||||
expect skip-wait-fault out "SetEventOnCompletion fault was not injected"
|
||||
|
||||
run wrong-removed-hr wrong-removed-hr
|
||||
must_fail wrong-removed-hr sync
|
||||
expect wrong-removed-hr out "post-present device reset must return DXGI_ERROR_DEVICE_RESET: hr=0x80040205"
|
||||
|
||||
run zero-timeout-overrun zero-timeout-overrun
|
||||
must_fail zero-timeout-overrun sync
|
||||
expect zero-timeout-overrun out "WaitForIdle(0) must reject zero without signaling:"
|
||||
|
||||
if [ "$bad" -ne 0 ]; then
|
||||
echo "FAIL: run_controls (output kept in $dir)"
|
||||
exit 1
|
||||
fi
|
||||
rm -rf "$dir"
|
||||
echo "PASS: run_controls (1 normal run, 6 negative controls)"
|
||||
@@ -0,0 +1,4 @@
|
||||
# Synthetic conformance test for the Xbox 32-byte D3D12ConfigureVirtualMemoryX decoder.
|
||||
add_executable(test_d3d12_vmem_xbox main.cpp)
|
||||
target_include_directories(test_d3d12_vmem_xbox PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_d3d12_vmem_xbox PRIVATE d3d12_xs xmem bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,527 @@
|
||||
/*
|
||||
* Conformance test for the Xbox virtual-memory configuration decoder in
|
||||
* d3d12_xs.dll!D3D12ConfigureVirtualMemoryX (D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION).
|
||||
*
|
||||
* Expected values come from the authorized GDK documentation of the function and the
|
||||
* structure, written out here rather than taken from the shim's header:
|
||||
* - the default page-table size (5 x 4 MB) reports a minimum graphics address of 2 GiB and
|
||||
* a maximum of 159.375 GiB; the input fields are left as the caller set them;
|
||||
* - the page-table size is clamped to 33, the frame-buffer preserve size to 64 MiB, and -1
|
||||
* (the legacy size) is kept;
|
||||
* - after a D3D12 device exists the call fails with E_FAIL and writes nothing;
|
||||
* - every accepted configuration is recorded only (applied=0) and still emits the
|
||||
* unimplemented-API stub, and leaves a cached BXVM backing heap untouched.
|
||||
* Inferred, and marked as such in the log: the maximum for other page-table sizes scales
|
||||
* linearly (max_estimated=1), and a page-table size of 0, an unreadable configuration and
|
||||
* unwritable outputs fail with E_INVALIDARG.
|
||||
*
|
||||
* Several fixtures share one BX_LOG_FILE, so every log check reads only the
|
||||
* bytes appended since the step it checks began.
|
||||
*/
|
||||
#include <d3d12.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void* params, REFIID riid, void** ppv);
|
||||
__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);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kBxvmMagic = 0x4D565842u;
|
||||
constexpr uint32_t kBxvmFlagBacking = 0x1u;
|
||||
constexpr uint64_t k64K = 64ull * 1024ull;
|
||||
|
||||
struct BxvmConfig {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
uint32_t version;
|
||||
uint32_t flags;
|
||||
uint64_t base_va;
|
||||
uint64_t size_bytes;
|
||||
uint64_t reserved;
|
||||
uint64_t cpu_pointer;
|
||||
};
|
||||
|
||||
struct XboxConfig {
|
||||
uint32_t flags;
|
||||
uint32_t page_table_4mb_pages;
|
||||
uint32_t frame_buffer_preserve_bytes;
|
||||
uint32_t padding;
|
||||
uint64_t min_gpu_va;
|
||||
uint64_t max_gpu_va;
|
||||
};
|
||||
static_assert(sizeof(BxvmConfig) == 48);
|
||||
static_assert(offsetof(BxvmConfig, magic) == 0);
|
||||
static_assert(offsetof(BxvmConfig, struct_size) == 4);
|
||||
static_assert(offsetof(BxvmConfig, version) == 8);
|
||||
static_assert(offsetof(BxvmConfig, flags) == 12);
|
||||
static_assert(offsetof(BxvmConfig, base_va) == 16);
|
||||
static_assert(offsetof(BxvmConfig, size_bytes) == 24);
|
||||
static_assert(offsetof(BxvmConfig, reserved) == 32);
|
||||
static_assert(offsetof(BxvmConfig, cpu_pointer) == 40);
|
||||
static_assert(sizeof(XboxConfig) == 32);
|
||||
static_assert(offsetof(XboxConfig, flags) == 0);
|
||||
static_assert(offsetof(XboxConfig, page_table_4mb_pages) == 4);
|
||||
static_assert(offsetof(XboxConfig, frame_buffer_preserve_bytes) == 8);
|
||||
static_assert(offsetof(XboxConfig, padding) == 12);
|
||||
static_assert(offsetof(XboxConfig, min_gpu_va) == 16);
|
||||
static_assert(offsetof(XboxConfig, max_gpu_va) == 24);
|
||||
|
||||
/* From the documentation: 2 GB minimum, about 159.375 GB maximum at the default size. */
|
||||
constexpr uint64_t kMinGpuVa = 0x80000000ull;
|
||||
constexpr uint64_t kDefaultMaxGpuVa = 0x27D8000000ull;
|
||||
constexpr uint64_t kOutputSentinel = 0xA5A5A5A5A5A5A5A5ull;
|
||||
|
||||
int g_failed = 0;
|
||||
|
||||
void check(bool cond, const char* fmt, ...) {
|
||||
if (cond) {
|
||||
return;
|
||||
}
|
||||
++g_failed;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
std::fprintf(stderr, "FAIL: ");
|
||||
std::vfprintf(stderr, fmt, args);
|
||||
std::fprintf(stderr, "\n");
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
unsigned long ul(HRESULT hr) {
|
||||
return static_cast<unsigned long>(hr);
|
||||
}
|
||||
|
||||
bool read_file_from(const char* path, long start, std::string& out) {
|
||||
out.clear();
|
||||
FILE* f = std::fopen(path, "rb");
|
||||
if (!f) {
|
||||
return false;
|
||||
}
|
||||
if (start > 0 && std::fseek(f, start, SEEK_SET) != 0) {
|
||||
std::fclose(f);
|
||||
return false;
|
||||
}
|
||||
char buf[4096];
|
||||
size_t n = 0;
|
||||
while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0) {
|
||||
out.append(buf, n);
|
||||
}
|
||||
std::fclose(f);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Current size of the log, used as the start offset of the next step. */
|
||||
long log_size(const char* path) {
|
||||
FILE* f = std::fopen(path, "rb");
|
||||
if (!f) {
|
||||
return 0;
|
||||
}
|
||||
long size = 0;
|
||||
if (std::fseek(f, 0, SEEK_END) == 0) {
|
||||
size = std::ftell(f);
|
||||
}
|
||||
std::fclose(f);
|
||||
return size < 0 ? 0 : size;
|
||||
}
|
||||
|
||||
bool log_contains_since(const char* path, long start, const char* needle) {
|
||||
std::string text;
|
||||
return read_file_from(path, start, text) && text.find(needle) != std::string::npos;
|
||||
}
|
||||
|
||||
constexpr const char* kStubNeedle = "d3d12_xs.dll!D3D12ConfigureVirtualMemoryX";
|
||||
|
||||
BxvmConfig make_bxvm(uint64_t base_va, uint64_t size_bytes, uint32_t flags) {
|
||||
BxvmConfig cfg{};
|
||||
cfg.magic = kBxvmMagic;
|
||||
cfg.struct_size = sizeof(BxvmConfig);
|
||||
cfg.version = 1;
|
||||
cfg.flags = flags;
|
||||
cfg.base_va = base_va;
|
||||
cfg.size_bytes = size_bytes;
|
||||
cfg.reserved = 0;
|
||||
cfg.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
XboxConfig make_xbox(uint32_t pages, uint32_t preserve = 0) {
|
||||
XboxConfig cfg{};
|
||||
cfg.page_table_4mb_pages = pages;
|
||||
cfg.frame_buffer_preserve_bytes = preserve;
|
||||
cfg.min_gpu_va = kOutputSentinel;
|
||||
cfg.max_gpu_va = kOutputSentinel;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/* The caller's input fields, which the decoder must not change. */
|
||||
bool inputs_unchanged(const XboxConfig& after, const XboxConfig& before) {
|
||||
return after.flags == before.flags && after.page_table_4mb_pages == before.page_table_4mb_pages &&
|
||||
after.frame_buffer_preserve_bytes == before.frame_buffer_preserve_bytes &&
|
||||
after.padding == before.padding;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
if (!cfg) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_vmem_xbox (no runtime config)\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char log_path[MAX_PATH] = {};
|
||||
const DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
|
||||
check(have_log, "BX_LOG_FILE must be set");
|
||||
|
||||
long mark = have_log ? log_size(log_path) : 0;
|
||||
const long test_start = mark;
|
||||
|
||||
/* 1. The default configuration reports the documented address range. */
|
||||
XboxConfig def = make_xbox(5);
|
||||
const XboxConfig def_before = def;
|
||||
HRESULT hr = D3D12ConfigureVirtualMemoryX(&def);
|
||||
check(hr == S_OK, "default Xbox config must return S_OK (hr=0x%08lx)", ul(hr));
|
||||
check(inputs_unchanged(def, def_before), "Xbox decoder must not change the input fields");
|
||||
check(def.min_gpu_va == kMinGpuVa, "minimum graphics address must be 2 GiB (got 0x%llx)",
|
||||
static_cast<unsigned long long>(def.min_gpu_va));
|
||||
check(def.max_gpu_va == kDefaultMaxGpuVa, "default maximum graphics address must be 159.375 GiB (got 0x%llx)",
|
||||
static_cast<unsigned long long>(def.max_gpu_va));
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark,
|
||||
"decoder=xbox applied=0 recorded_only=1 page_table_4mb_pages=5 clamped=0 "
|
||||
"frame_buffer_preserve_bytes=0 min_gpu_va=0x80000000 max_gpu_va=0x27d8000000 "
|
||||
"max_estimated=0 repeat=0"),
|
||||
"log must record the default Xbox config as recorded only");
|
||||
check(log_contains_since(log_path, mark, kStubNeedle),
|
||||
"a recorded-only Xbox config must still emit the unimplemented-API stub");
|
||||
check(!log_contains_since(log_path, mark, "applied=1"),
|
||||
"a recorded-only Xbox config must not report applied=1");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/* 2. Repeated identical call (repeat=1). */
|
||||
hr = D3D12ConfigureVirtualMemoryX(&def);
|
||||
check(hr == S_OK, "repeated identical Xbox config must return S_OK (hr=0x%08lx)", ul(hr));
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark, "page_table_4mb_pages=5 clamped=0") &&
|
||||
log_contains_since(log_path, mark, "repeat=1"),
|
||||
"repeated identical Xbox config must log repeat=1");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/* 3. The page-table sizes observed at title startup, 4 and 3: the maximum is estimated. */
|
||||
for (uint32_t pages : {4u, 3u}) {
|
||||
XboxConfig cfg = make_xbox(pages);
|
||||
const XboxConfig before = cfg;
|
||||
hr = D3D12ConfigureVirtualMemoryX(&cfg);
|
||||
check(hr == S_OK, "Xbox config with %u pages must return S_OK (hr=0x%08lx)", pages, ul(hr));
|
||||
check(inputs_unchanged(cfg, before), "%u-page config input fields must stay unchanged", pages);
|
||||
check(cfg.min_gpu_va == kMinGpuVa, "%u-page config minimum must be 2 GiB", pages);
|
||||
check(cfg.max_gpu_va == kDefaultMaxGpuVa / 5u * pages, "%u-page config maximum must scale from the default",
|
||||
pages);
|
||||
if (have_log) {
|
||||
char needle[96];
|
||||
std::snprintf(needle, sizeof(needle), "page_table_4mb_pages=%u clamped=0", pages);
|
||||
check(log_contains_since(log_path, mark, needle) &&
|
||||
log_contains_since(log_path, mark, "max_estimated=1 repeat=0"),
|
||||
"%u-page config must log its size, max_estimated=1 and repeat=0", pages);
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
}
|
||||
|
||||
/* 4. Documented clamps: page table to 33, frame-buffer preserve to 64 MiB; -1 is the legacy size. */
|
||||
XboxConfig big = make_xbox(100u, 128u * 1024u * 1024u);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&big);
|
||||
check(hr == S_OK, "oversized Xbox config must be clamped, not refused (hr=0x%08lx)", ul(hr));
|
||||
check(big.page_table_4mb_pages == 100u, "clamping must not rewrite the caller's page count");
|
||||
check(big.max_gpu_va == kDefaultMaxGpuVa / 5u * 33u, "clamped maximum must use 33 pages");
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark,
|
||||
"page_table_4mb_pages=33 clamped=1 frame_buffer_preserve_bytes=67108864"),
|
||||
"oversized config must log the clamped page count and preserve size");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
XboxConfig legacy = make_xbox(5u, 0xFFFFFFFFu);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&legacy);
|
||||
check(hr == S_OK, "legacy frame-buffer preserve size must be accepted (hr=0x%08lx)", ul(hr));
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark, "frame_buffer_preserve_bytes=4294967295"),
|
||||
"the legacy preserve size (-1) must be recorded as given");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/* 5. Refused configurations write nothing. */
|
||||
XboxConfig zero = make_xbox(0);
|
||||
const XboxConfig zero_before = zero;
|
||||
hr = D3D12ConfigureVirtualMemoryX(&zero);
|
||||
check(hr == E_INVALIDARG, "a page-table size of 0 must fail with E_INVALIDARG (hr=0x%08lx)", ul(hr));
|
||||
check(std::memcmp(&zero, &zero_before, sizeof(zero)) == 0, "a refused config must not be written");
|
||||
|
||||
SYSTEM_INFO ro_sys{};
|
||||
GetSystemInfo(&ro_sys);
|
||||
const SIZE_T ro_bytes = ro_sys.dwPageSize ? ro_sys.dwPageSize : 4096;
|
||||
void* ro_page = VirtualAlloc(nullptr, ro_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(ro_page != nullptr, "VirtualAlloc for the read-only Xbox probe must succeed");
|
||||
if (ro_page) {
|
||||
const XboxConfig ro_cfg = make_xbox(5);
|
||||
std::memcpy(ro_page, &ro_cfg, sizeof(ro_cfg));
|
||||
DWORD old_protect = 0;
|
||||
if (VirtualProtect(ro_page, ro_bytes, PAGE_READONLY, &old_protect)) {
|
||||
hr = D3D12ConfigureVirtualMemoryX(ro_page);
|
||||
check(hr == E_INVALIDARG, "read-only Xbox outputs must fail with E_INVALIDARG (hr=0x%08lx)", ul(hr));
|
||||
check(std::memcmp(ro_page, &ro_cfg, sizeof(ro_cfg)) == 0, "read-only Xbox config must stay unchanged");
|
||||
DWORD ignored = 0;
|
||||
VirtualProtect(ro_page, ro_bytes, old_protect, &ignored);
|
||||
} else {
|
||||
check(false, "Xbox config page must become read-only");
|
||||
}
|
||||
VirtualFree(ro_page, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
void* edge_mem = VirtualAlloc(nullptr, ro_bytes * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(edge_mem != nullptr, "VirtualAlloc for the Xbox page-edge probe must succeed");
|
||||
if (edge_mem) {
|
||||
auto* edge_base = static_cast<uint8_t*>(edge_mem);
|
||||
DWORD old_prot = 0;
|
||||
check(VirtualProtect(edge_base + ro_bytes, ro_bytes, PAGE_NOACCESS, &old_prot) != 0,
|
||||
"second page must be PAGE_NOACCESS");
|
||||
uint8_t* edge = edge_base + ro_bytes - 8;
|
||||
const uint32_t header[2] = {0u, 5u};
|
||||
std::memcpy(edge, header, sizeof(header));
|
||||
hr = D3D12ConfigureVirtualMemoryX(edge);
|
||||
check(hr == E_INVALIDARG, "an Xbox config cut off by an unreadable page must fail (hr=0x%08lx)", ul(hr));
|
||||
VirtualProtect(edge_base + ro_bytes, ro_bytes, PAGE_READWRITE, &old_prot);
|
||||
VirtualFree(edge_mem, 0, MEM_RELEASE);
|
||||
}
|
||||
if (have_log) {
|
||||
for (const char* needle : {"decoder=xbox applied=0 reason=zero_page_table_pages hr=0x80070057",
|
||||
"decoder=xbox applied=0 reason=unwritable_output hr=0x80070057",
|
||||
"decoder=xbox applied=0 reason=unreadable_config hr=0x80070057"}) {
|
||||
check(log_contains_since(log_path, mark, needle), "missing refused-config log: %s", needle);
|
||||
}
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/*
|
||||
* 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);
|
||||
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");
|
||||
}
|
||||
|
||||
/*
|
||||
* 5. Configure a BXVM backing heap, create and cache it, then apply an Xbox
|
||||
* configuration. The Xbox path does not apply a backing configuration, so the
|
||||
* cached BXVM backing heap, its cpu_pointer and its device link must
|
||||
* survive.
|
||||
*/
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
check(hr == S_OK && device != nullptr, "D3D12XboxCreateDevice must succeed (hr=0x%08lx)", ul(hr));
|
||||
|
||||
SIZE_T page_count = 2;
|
||||
ULONG_PTR pages[2] = {};
|
||||
const BOOL phys_ok = XMemAllocatePhysicalPages(&page_count, pages, 0);
|
||||
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;
|
||||
check(mapped_region != nullptr, "XMemMapPhysicalPages(2) must succeed");
|
||||
|
||||
if (device && mapped_region) {
|
||||
const uint64_t region_va = reinterpret_cast<uint64_t>(mapped_region);
|
||||
const uint64_t region_bytes = 2ull * k64K;
|
||||
|
||||
BxvmConfig bxvm = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&bxvm);
|
||||
check(hr == S_OK, "BXVM backing config must succeed (hr=0x%08lx)", ul(hr));
|
||||
check(bxvm.cpu_pointer == 0, "BXVM cpu_pointer must start at 0 before CreateHeap");
|
||||
|
||||
D3D12_HEAP_DESC backing_desc{};
|
||||
backing_desc.SizeInBytes = region_bytes;
|
||||
backing_desc.Alignment = k64K;
|
||||
backing_desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
backing_desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
backing_desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
backing_desc.Flags = D3D12_HEAP_FLAG_NONE;
|
||||
|
||||
ID3D12Heap* backing_heap = nullptr;
|
||||
hr = device->CreateHeap(&backing_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&backing_heap));
|
||||
check(hr == S_OK && backing_heap != nullptr, "CreateHeap for BXVM backing must succeed (hr=0x%08lx)", ul(hr));
|
||||
|
||||
BxvmConfig query = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&query);
|
||||
check(hr == S_OK && query.cpu_pointer != 0,
|
||||
"BXVM query after CreateHeap must return non-zero cached cpu_pointer (hr=0x%08lx)", ul(hr));
|
||||
|
||||
/* Once a device exists the Xbox call fails, writes nothing and leaves the cached heap alone. */
|
||||
XboxConfig switch_cfg = make_xbox(4);
|
||||
const XboxConfig switch_before = switch_cfg;
|
||||
const long switch_mark = have_log ? log_size(log_path) : 0;
|
||||
hr = D3D12ConfigureVirtualMemoryX(&switch_cfg);
|
||||
check(hr == E_FAIL, "Xbox config after device creation must fail with E_FAIL (hr=0x%08lx)", ul(hr));
|
||||
check(std::memcmp(&switch_cfg, &switch_before, sizeof(switch_cfg)) == 0,
|
||||
"Xbox config refused after device creation must not be written");
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, switch_mark,
|
||||
"decoder=xbox applied=0 reason=device_already_created hr=0x80004005"),
|
||||
"Xbox config after device creation must log device_already_created");
|
||||
}
|
||||
|
||||
if (backing_heap) {
|
||||
ID3D12Device* still_dev = nullptr;
|
||||
const HRESULT dev_hr = backing_heap->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&still_dev));
|
||||
check(SUCCEEDED(dev_hr) && still_dev != nullptr,
|
||||
"cached BXVM backing heap must keep its device after an Xbox config (hr=0x%08lx)", ul(dev_hr));
|
||||
if (still_dev) {
|
||||
still_dev->Release();
|
||||
}
|
||||
}
|
||||
|
||||
BxvmConfig after_xbox = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&after_xbox);
|
||||
check(hr == S_OK && after_xbox.cpu_pointer == query.cpu_pointer,
|
||||
"BXVM cpu_pointer must be unchanged after an Xbox config (hr=0x%08lx)", ul(hr));
|
||||
|
||||
if (backing_heap) {
|
||||
backing_heap->Release();
|
||||
backing_heap = nullptr;
|
||||
}
|
||||
|
||||
/* Ordinary D3D12 heap creation still works after the refused Xbox call. */
|
||||
D3D12_HEAP_DESC ordinary_desc{};
|
||||
ordinary_desc.SizeInBytes = k64K;
|
||||
ordinary_desc.Alignment = k64K;
|
||||
ordinary_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
ordinary_desc.Flags = D3D12_HEAP_FLAG_NONE;
|
||||
ID3D12Heap* ordinary_heap = nullptr;
|
||||
hr = device->CreateHeap(&ordinary_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&ordinary_heap));
|
||||
check(hr == S_OK && ordinary_heap != nullptr,
|
||||
"ordinary CreateHeap must succeed after a refused Xbox config (hr=0x%08lx)", ul(hr));
|
||||
if (ordinary_heap) {
|
||||
ordinary_heap->Release();
|
||||
}
|
||||
}
|
||||
|
||||
if (mapped_region) {
|
||||
XMemMapPhysicalPages(mapped_region, 2, 0, nullptr);
|
||||
}
|
||||
if (phys_ok) {
|
||||
SIZE_T free_count = 2;
|
||||
XMemFreePhysicalPages(&free_count, pages, 0);
|
||||
}
|
||||
if (device) {
|
||||
device->Release();
|
||||
}
|
||||
|
||||
/* 6. Malformed and page-edge unreadable inputs to the shared entry point. */
|
||||
if (have_log) {
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
check(D3D12ConfigureVirtualMemoryX(nullptr) == S_OK, "null config must fall back with S_OK");
|
||||
|
||||
uint32_t unknown_hdr[8] = {0x11223344u, 4u, 0u, 0u, 0u, 0u, 0u, 0u};
|
||||
uint32_t unknown_hdr_before[8];
|
||||
std::memcpy(unknown_hdr_before, unknown_hdr, sizeof(unknown_hdr));
|
||||
check(D3D12ConfigureVirtualMemoryX(unknown_hdr) == S_OK, "unrecognized header must fall back with S_OK");
|
||||
check(std::memcmp(unknown_hdr, unknown_hdr_before, sizeof(unknown_hdr)) == 0,
|
||||
"unrecognized header bytes must stay unchanged");
|
||||
|
||||
BxvmConfig readonly_bxvm = make_bxvm(0, 0, 0);
|
||||
SYSTEM_INFO readonly_sys{};
|
||||
GetSystemInfo(&readonly_sys);
|
||||
const SIZE_T readonly_page_bytes = readonly_sys.dwPageSize ? readonly_sys.dwPageSize : 4096;
|
||||
void* readonly_page =
|
||||
VirtualAlloc(nullptr, readonly_page_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(readonly_page != nullptr, "VirtualAlloc for read-only BXVM probe must succeed");
|
||||
if (readonly_page) {
|
||||
std::memcpy(readonly_page, &readonly_bxvm, sizeof(readonly_bxvm));
|
||||
DWORD old_protect = 0;
|
||||
const bool protected_readonly =
|
||||
VirtualProtect(readonly_page, readonly_page_bytes, PAGE_READONLY, &old_protect) != 0;
|
||||
check(protected_readonly, "BXVM config page must become read-only");
|
||||
if (protected_readonly) {
|
||||
check(D3D12ConfigureVirtualMemoryX(readonly_page) == S_OK,
|
||||
"read-only BXVM output must fall back with S_OK");
|
||||
check(std::memcmp(readonly_page, &readonly_bxvm, sizeof(readonly_bxvm)) == 0,
|
||||
"read-only BXVM config bytes must stay unchanged");
|
||||
DWORD ignored_protect = 0;
|
||||
const bool writable =
|
||||
VirtualProtect(readonly_page, readonly_page_bytes, old_protect, &ignored_protect) != 0;
|
||||
check(writable, "make the BXVM page writable for the invalid-size case");
|
||||
if (writable) {
|
||||
const BxvmConfig invalid_bxvm = make_bxvm(0, 1, 0);
|
||||
std::memcpy(readonly_page, &invalid_bxvm, sizeof(invalid_bxvm));
|
||||
const bool readonly_again =
|
||||
VirtualProtect(readonly_page, readonly_page_bytes, PAGE_READONLY, &ignored_protect) != 0;
|
||||
check(readonly_again, "protect the invalid-size BXVM page");
|
||||
if (readonly_again) {
|
||||
check(D3D12ConfigureVirtualMemoryX(readonly_page) == E_INVALIDARG,
|
||||
"invalid BXVM size must be rejected before the read-only fallback");
|
||||
check(std::memcmp(readonly_page, &invalid_bxvm, sizeof(invalid_bxvm)) == 0,
|
||||
"rejected BXVM config bytes must stay unchanged");
|
||||
}
|
||||
}
|
||||
}
|
||||
VirtualFree(readonly_page, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
SYSTEM_INFO sys{};
|
||||
GetSystemInfo(&sys);
|
||||
const SIZE_T page_bytes = sys.dwPageSize ? sys.dwPageSize : 4096;
|
||||
void* guard_mem = VirtualAlloc(nullptr, page_bytes * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(guard_mem != nullptr, "VirtualAlloc for page-edge probe must succeed");
|
||||
if (guard_mem) {
|
||||
DWORD old_prot = 0;
|
||||
auto* base = static_cast<uint8_t*>(guard_mem);
|
||||
check(VirtualProtect(base + page_bytes, page_bytes, PAGE_NOACCESS, &old_prot) != 0,
|
||||
"second page must be PAGE_NOACCESS");
|
||||
|
||||
/* Unreadable header directly on NOACCESS page. */
|
||||
check(D3D12ConfigureVirtualMemoryX(base + page_bytes) == S_OK,
|
||||
"unreadable header must not fault and must return S_OK");
|
||||
|
||||
VirtualProtect(base + page_bytes, page_bytes, PAGE_READWRITE, &old_prot);
|
||||
VirtualFree(guard_mem, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
if (have_log) {
|
||||
constexpr const char* expected_fallbacks[] = {
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=null_config\"",
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=unrecognized_header\"",
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=unreadable_header\"",
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=bxvm applied=0 reason=unwritable_output\"",
|
||||
};
|
||||
for (const char* needle : expected_fallbacks) {
|
||||
check(log_contains_since(log_path, mark, needle), "missing expected fallback log: %s", needle);
|
||||
}
|
||||
check(log_contains_since(log_path, test_start, "\"event\":\"vmem_config_recorded\""),
|
||||
"the Xbox path must log vmem_config_recorded");
|
||||
}
|
||||
|
||||
if (g_failed != 0) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_vmem_xbox (%d failed)\n", g_failed);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_d3d12_vmem_xbox\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -68,6 +68,38 @@ bool vtable_in_shim(IUnknown* obj) {
|
||||
/* An IID that no interface uses (generated for this test). */
|
||||
const GUID kUnusedIid = {0x4f0c2f6b, 0x91d3, 0x4d7e, {0xb2, 0x1a, 0x7e, 0x55, 0x03, 0xc9, 0x6a, 0x18}};
|
||||
|
||||
/*
|
||||
* #547: the generator (shims/d3d12_xs/tools/gen_proxy.py, PAD_SLOTS = 32) appends
|
||||
* 32 `BxBeyondPublicVtableNN` stubs after each generated proxy's public vtable so
|
||||
* that a caller indexing past the interface it was handed lands on a logged
|
||||
* E_NOTIMPL stub. The first padded slot sits at index `kPublicSlotCount`
|
||||
* (gen_proxy.py emits `slot + k` for k in [0, 32)); the last is
|
||||
* `kPublicSlotCount + 31`. The expected indices below are derived from the
|
||||
* public D3D12 interface inheritance chains (IUnknown + every level up to the
|
||||
* leaf), which is exactly what the generator walks; they match the
|
||||
* `kPublicSlotCount` constants in proxy_generated.h.
|
||||
*
|
||||
* Each stub is `HRESULT STDMETHODCALLTYPE fn()` with no arguments, so it is
|
||||
* callable through the vtable as `HRESULT (WINAPI*)()`. The stub logs
|
||||
* BX_VTABLE_STUB_LOG("<leaf>", <slot>u, "beyond_public_vtable"), which
|
||||
* bx_log_unimpl_vtable writes as
|
||||
* {"sub":"com_vtable","event":"unimpl_vtable","detail":"<leaf>[<slot>]::beyond_public_vtable"}
|
||||
*/
|
||||
struct PaddedVtableExpectation {
|
||||
const char* what; /* fixture-facing name for messages */
|
||||
const char* leaf; /* generator's leaf interface name, used in the log detail */
|
||||
unsigned first_slot; /* index of BxBeyondPublicVtable00 */
|
||||
};
|
||||
|
||||
/* PAD_SLOTS in gen_proxy.py. */
|
||||
constexpr unsigned kPaddedSlotCount = 32;
|
||||
|
||||
HRESULT call_vtable_slot(IUnknown* obj, unsigned index) {
|
||||
void** vtbl = *reinterpret_cast<void***>(obj);
|
||||
auto fn = reinterpret_cast<HRESULT(WINAPI*)()>(vtbl[index]);
|
||||
return fn();
|
||||
}
|
||||
|
||||
bool file_contains(const char* path, const char* needle_a, const char* needle_b) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
@@ -297,7 +329,51 @@ int main() {
|
||||
skip("BX_LOG_FILE is not set; pso_shader log record not verified");
|
||||
}
|
||||
|
||||
/* --- 10. Teardown: every reference must come back ------------------------------------------- */
|
||||
/* --- 10. Padded vtable slots (#547) ---------------------------------------------------------- */
|
||||
/*
|
||||
* First padded slot = 3 (IUnknown) + every public method in the leaf's
|
||||
* inheritance chain, which is how gen_proxy.py counts `slot`. Derived
|
||||
* natively from the toolchain's d3d12.h with the generator's own
|
||||
* chain_of()/parse_interfaces(); matches kPublicSlotCount in
|
||||
* proxy_generated.h (79/19/9/81).
|
||||
*/
|
||||
const PaddedVtableExpectation padded[] = {
|
||||
{"device", "ID3D12Device10", 79u},
|
||||
{"command queue", "ID3D12CommandQueue", 19u},
|
||||
{"command allocator", "ID3D12CommandAllocator", 9u},
|
||||
{"command list", "ID3D12GraphicsCommandList7", 81u},
|
||||
};
|
||||
IUnknown* const padded_objs[] = {device, queue, allocator, list};
|
||||
for (unsigned i = 0; i < 4; ++i) {
|
||||
IUnknown* obj = padded_objs[i];
|
||||
if (!obj) {
|
||||
check(false, "%s proxy missing; padded vtable slots not callable", padded[i].what);
|
||||
continue;
|
||||
}
|
||||
const unsigned first = padded[i].first_slot;
|
||||
const unsigned last = first + kPaddedSlotCount - 1;
|
||||
hr = call_vtable_slot(obj, first);
|
||||
check(hr == E_NOTIMPL, "%s padded vtable slot %u (BxBeyondPublicVtable00) hr=0x%08lx, want E_NOTIMPL",
|
||||
padded[i].what, first, ul(hr));
|
||||
hr = call_vtable_slot(obj, last);
|
||||
check(hr == E_NOTIMPL, "%s padded vtable slot %u (BxBeyondPublicVtable%02u, the %u-th) hr=0x%08lx, want E_NOTIMPL",
|
||||
padded[i].what, last, kPaddedSlotCount - 1, kPaddedSlotCount, ul(hr));
|
||||
}
|
||||
|
||||
if (log_len > 0 && log_len < sizeof(log_path)) {
|
||||
for (unsigned i = 0; i < 4; ++i) {
|
||||
if (!padded_objs[i]) continue;
|
||||
char needle[96];
|
||||
std::snprintf(needle, sizeof(needle), "%s[%u]::beyond_public_vtable", padded[i].leaf,
|
||||
padded[i].first_slot);
|
||||
check(file_contains(log_path, "\"event\":\"unimpl_vtable\"", needle),
|
||||
"BX_LOG_FILE must contain an unimpl_vtable record with %s", needle);
|
||||
}
|
||||
} else {
|
||||
skip("BX_LOG_FILE is not set; beyond_public_vtable log records not verified");
|
||||
}
|
||||
|
||||
/* --- 11. Teardown: every reference must come back ------------------------------------------- */
|
||||
if (rs_error) rs_error->Release();
|
||||
if (rs_blob) rs_blob->Release();
|
||||
if (root_signature) root_signature->Release();
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
set(d3d12_xs_headers "${BX_ROOT_DIR}/shims/d3d12_xs")
|
||||
if(NOT EXISTS "${d3d12_xs_headers}/vmem.h" OR NOT EXISTS "${d3d12_xs_headers}/presentx.h")
|
||||
message(FATAL_ERROR "test_m2_first_frame requires the placed-resource and PresentX contracts (#486 and #471)")
|
||||
endif()
|
||||
|
||||
add_executable(test_m2_first_frame main.cpp)
|
||||
target_include_directories(test_m2_first_frame PRIVATE
|
||||
"${BX_ABI_INCLUDE_DIR}"
|
||||
"${d3d12_xs_headers}"
|
||||
"${BX_ROOT_DIR}/shader-transpiler/crates/d3dmetal-harness/probe/shaders"
|
||||
)
|
||||
target_link_libraries(test_m2_first_frame PRIVATE d3d12_xs xmem bx_runtime_veh user32)
|
||||
target_compile_options(test_m2_first_frame PRIVATE -fexceptions)
|
||||
@@ -0,0 +1,360 @@
|
||||
// Original synthetic M2 workload. The compute output is copied into the flip
|
||||
// buffer and read back through a placed D3D12 buffer before the host flip.
|
||||
//
|
||||
// Limitations: the frame is a compute write copied into the back buffer, not a
|
||||
// rasterized draw. The shader-gate stage covers only the DXIL fast path. The
|
||||
// pixel compare reads pre-flip back-buffer contents, not what reached the
|
||||
// screen. The readback lives in the D3D12 WRITE_BACK backing heap's own map;
|
||||
// the xmem page only names the configured region and is checked to stay
|
||||
// untouched, so this does not show xmem-backed placed memory (#469).
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
#include <wrl/client.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include "bx_log.h"
|
||||
#include "fill_cs66.h"
|
||||
#include "presentx.h"
|
||||
#include "vmem.h"
|
||||
|
||||
using Microsoft::WRL::ComPtr;
|
||||
extern "C" {
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void*);
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void*, REFIID, void**);
|
||||
__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);
|
||||
}
|
||||
|
||||
namespace {
|
||||
const char* stage = "gdk_boot";
|
||||
unsigned seq = 0;
|
||||
void checkpoint(bool ok, const char* detail) {
|
||||
std::printf(
|
||||
"{\"bx_checkpoint\":\"test_m2_first_frame\",\"seq\":%u,\"stage\":\"%s\",\"status\":\"%s\",\"detail\":\"%s\"}\n",
|
||||
++seq, stage, ok ? "pass" : "fail", detail);
|
||||
std::fflush(stdout);
|
||||
char message[384];
|
||||
std::snprintf(message, sizeof(message), "%s: %s", stage, detail);
|
||||
bx_log_emit(ok ? BX_LOG_INFO : BX_LOG_ERROR, "m2_first_frame", ok ? "stage_pass" : "stage_fail", message);
|
||||
}
|
||||
bool cleanup_ok = true;
|
||||
void cleanup(bool ok, const char* call) {
|
||||
if (!ok) {
|
||||
cleanup_ok = false;
|
||||
checkpoint(false, call);
|
||||
}
|
||||
}
|
||||
struct Failure {};
|
||||
void require(bool ok, const char* detail) {
|
||||
if (!ok) {
|
||||
checkpoint(false, detail);
|
||||
throw Failure{};
|
||||
}
|
||||
}
|
||||
void checked(HRESULT hr, const char* call) {
|
||||
if (FAILED(hr)) {
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", call, static_cast<unsigned long>(hr));
|
||||
require(false, detail);
|
||||
}
|
||||
}
|
||||
template <class T> T symbol(HMODULE module, const char* name) {
|
||||
auto address = GetProcAddress(module, name);
|
||||
require(address != nullptr, name);
|
||||
T result;
|
||||
std::memcpy(&result, &address, sizeof(result));
|
||||
return result;
|
||||
}
|
||||
struct Runtime {
|
||||
HMODULE module = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
HRESULT(WINAPI* uninit)() = nullptr;
|
||||
bool active = false;
|
||||
~Runtime() {
|
||||
if (active)
|
||||
cleanup(uninit() == S_OK, "UninitializeApiImpl");
|
||||
if (module)
|
||||
cleanup(FreeLibrary(module), "FreeLibrary");
|
||||
}
|
||||
};
|
||||
struct Region {
|
||||
static constexpr size_t page_bytes = 65536;
|
||||
static constexpr unsigned char sentinel = 0xa5;
|
||||
SIZE_T count = 1;
|
||||
ULONG_PTR page = 0;
|
||||
void* view = nullptr;
|
||||
BxD3d12VirtualMemoryConfig config = [] {
|
||||
// Assigned by name so a field reorder in vmem.h cannot compile silently.
|
||||
BxD3d12VirtualMemoryConfig c{};
|
||||
c.magic = BX_D3D12_VMEM_MAGIC;
|
||||
c.struct_size = sizeof(BxD3d12VirtualMemoryConfig);
|
||||
c.version = 1;
|
||||
c.flags = BX_D3D12_VMEM_FLAG_BACKING_HEAP;
|
||||
c.base_va = 0;
|
||||
c.size_bytes = page_bytes;
|
||||
c.reserved = 0;
|
||||
c.cpu_pointer = 0;
|
||||
return c;
|
||||
}();
|
||||
~Region() {
|
||||
if (config.base_va) {
|
||||
config.base_va = config.size_bytes = 0;
|
||||
cleanup(D3D12ConfigureVirtualMemoryX(&config) == S_OK, "clear configured region");
|
||||
}
|
||||
if (view)
|
||||
cleanup(XMemMapPhysicalPages(view, count, 0, nullptr) == view, "unmap physical page");
|
||||
if (page)
|
||||
cleanup(XMemFreePhysicalPages(&count, &page, 0), "free physical page");
|
||||
}
|
||||
};
|
||||
// Declared just before ExecuteCommandLists, so on a failure after the submit it is
|
||||
// destroyed before the queue, back buffer and output resource it protects: it
|
||||
// signals the queue and waits (bounded) so nothing is released while the GPU may
|
||||
// still be using it. Disarmed once the readback fence has completed.
|
||||
struct GpuDrain {
|
||||
ID3D12CommandQueue* queue = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
bool armed = false;
|
||||
~GpuDrain() {
|
||||
if (!armed) return;
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
bool drained = done && SUCCEEDED(queue->Signal(fence, 2)) &&
|
||||
(fence->GetCompletedValue() >= 2 ||
|
||||
(SUCCEEDED(fence->SetEventOnCompletion(2, done)) &&
|
||||
WaitForSingleObject(done, 5000) == WAIT_OBJECT_0));
|
||||
if (done) CloseHandle(done);
|
||||
cleanup(drained, "drain the queue before releasing resources after a failure");
|
||||
}
|
||||
};
|
||||
struct Window {
|
||||
HWND hwnd = CreateWindowExW(0, L"STATIC", L"BetterXen M2", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT,
|
||||
CW_USEDEFAULT, 320, 240, nullptr, nullptr, nullptr, nullptr);
|
||||
~Window() {
|
||||
if (hwnd)
|
||||
cleanup(DestroyWindow(hwnd), "destroy window");
|
||||
}
|
||||
};
|
||||
|
||||
void run(bool inject_pixel_mismatch) {
|
||||
Runtime rt;
|
||||
require(rt.module, "LoadLibraryExW system32");
|
||||
auto init = symbol<HRESULT(WINAPI*)(uint32_t, uint32_t)>(rt.module, "InitializeApiImpl");
|
||||
rt.uninit = symbol<decltype(rt.uninit)>(rt.module, "UninitializeApiImpl");
|
||||
auto query = symbol<HRESULT(WINAPI*)(const GUID*, const GUID*, void**)>(rt.module, "QueryApiImpl");
|
||||
checked(init(1, 1), "InitializeApiImpl");
|
||||
rt.active = true;
|
||||
const GUID core_guid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
|
||||
const GUID sys_clsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
|
||||
const GUID sys_iid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
|
||||
const GUID user_guid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
|
||||
ComPtr<IUnknown> core, system, user;
|
||||
checked(query(&core_guid, &core_guid, reinterpret_cast<void**>(core.GetAddressOf())), "IXGameRuntimeCore");
|
||||
checked(query(&sys_clsid, &sys_iid, reinterpret_cast<void**>(system.GetAddressOf())), "IXSystem");
|
||||
checked(query(&user_guid, &user_guid, reinterpret_cast<void**>(user.GetAddressOf())), "IXUser");
|
||||
require(core && system && user, "GDK COM interfaces");
|
||||
checkpoint(true, "runtime initialized and three public interfaces acquired");
|
||||
|
||||
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(region.view, "map physical page");
|
||||
std::memset(region.view, Region::sentinel, Region::page_bytes);
|
||||
region.config.base_va = reinterpret_cast<uintptr_t>(region.view);
|
||||
checked(D3D12ConfigureVirtualMemoryX(®ion.config), "configure xmem region");
|
||||
ComPtr<ID3D12Device> device;
|
||||
checked(D3D12XboxCreateDevice(nullptr, IID_PPV_ARGS(&device)), "create Xbox device");
|
||||
D3D12_HEAP_DESC hd{};
|
||||
hd.SizeInBytes = region.config.size_bytes;
|
||||
hd.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
hd.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
ComPtr<ID3D12Heap> heap;
|
||||
checked(device->CreateHeap(&hd, IID_PPV_ARGS(&heap)), "create configured heap");
|
||||
checked(D3D12ConfigureVirtualMemoryX(®ion.config), "query backing map");
|
||||
require(region.config.cpu_pointer != 0, "configured heap must publish its backing map");
|
||||
require(region.config.cpu_pointer != reinterpret_cast<uintptr_t>(region.view),
|
||||
"D3D12 backing map must be distinct from the xmem region view");
|
||||
constexpr UINT width = 64, height = 4, pitch = 256;
|
||||
D3D12_RESOURCE_DESC buffer{};
|
||||
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer.Width = height * pitch;
|
||||
buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1;
|
||||
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ComPtr<ID3D12Resource> readback;
|
||||
checked(device->CreatePlacedResource(heap.Get(), 0, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
IID_PPV_ARGS(&readback)),
|
||||
"place readback buffer");
|
||||
checkpoint(true, "xmem region configured; readback placed in a separate D3D12 WRITE_BACK heap");
|
||||
|
||||
stage = "shader_gate";
|
||||
char path[MAX_PATH];
|
||||
DWORD length = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
require(length && length < sizeof(path), "BX_LOG_FILE required");
|
||||
// Start at EOF before PSO creation so stale shader_gate records cannot pass this check.
|
||||
std::ifstream log(path, std::ios::binary | std::ios::ate);
|
||||
require(log.good(), "open launch log");
|
||||
D3D12_ROOT_PARAMETER param{};
|
||||
param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC signature{};
|
||||
signature.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
signature.Desc_1_0.NumParameters = 1;
|
||||
signature.Desc_1_0.pParameters = ¶m;
|
||||
ComPtr<ID3DBlob> blob;
|
||||
checked(D3D12SerializeVersionedRootSignature(&signature, &blob, nullptr), "serialize root signature");
|
||||
ComPtr<ID3D12RootSignature> root;
|
||||
checked(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)),
|
||||
"root signature");
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC ps{};
|
||||
ps.pRootSignature = root.Get();
|
||||
ps.CS = {g_fill_cs66, sizeof(g_fill_cs66)};
|
||||
ComPtr<ID3D12PipelineState> pso;
|
||||
checked(device->CreateComputePipelineState(&ps, IID_PPV_ARGS(&pso)), "SM 6.6 compute PSO");
|
||||
bool inspected = false;
|
||||
for (std::string line; std::getline(log, line);) {
|
||||
if (line.find("\"event\":\"shader_gate\"") != line.npos && line.find("decision=pass_dxil") != line.npos &&
|
||||
line.find("pso=compute") != line.npos && line.find("sm=6.6") != line.npos)
|
||||
inspected = true;
|
||||
}
|
||||
require(inspected, "missing SM 6.6 pass_dxil telemetry for PSO");
|
||||
checkpoint(true, "inspected SM 6.6 compute PSO");
|
||||
|
||||
stage = "present";
|
||||
Window window;
|
||||
require(window.hwnd, "create window");
|
||||
D3D12_COMMAND_QUEUE_DESC qd{};
|
||||
ComPtr<ID3D12CommandQueue> queue;
|
||||
checked(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue)), "direct queue");
|
||||
ComPtr<IBxPresentQueue> bridge;
|
||||
checked(queue->QueryInterface(IID_IBxPresentQueue, reinterpret_cast<void**>(bridge.GetAddressOf())),
|
||||
"PresentX queue interface");
|
||||
BxPresentDesc desc{width, height, DXGI_FORMAT_R8G8B8A8_UNORM, 2};
|
||||
ComPtr<IBxPresentSwapChain> chain;
|
||||
checked(bridge->CreateSwapChain(window.hwnd, &desc, &chain), "create flip chain");
|
||||
ComPtr<ID3D12Resource> back;
|
||||
checked(chain->GetBuffer(chain->GetCurrentBackBufferIndex(), IID_PPV_ARGS(&back)), "get current backbuffer");
|
||||
D3D12_HEAP_PROPERTIES props{};
|
||||
props.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
ComPtr<ID3D12Resource> output;
|
||||
checked(device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &buffer,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&output)),
|
||||
"shader output");
|
||||
ComPtr<ID3D12CommandAllocator> alloc;
|
||||
ComPtr<ID3D12GraphicsCommandList> list;
|
||||
checked(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc)), "command allocator");
|
||||
checked(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), pso.Get(), IID_PPV_ARGS(&list)),
|
||||
"command list");
|
||||
list->SetComputeRootSignature(root.Get());
|
||||
list->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress());
|
||||
list->Dispatch(height, 1, 1);
|
||||
auto transition = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) {
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to};
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
};
|
||||
transition(output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
transition(back.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
D3D12_TEXTURE_COPY_LOCATION texture{}, linear{};
|
||||
texture.pResource = back.Get();
|
||||
texture.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
linear.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
linear.PlacedFootprint.Footprint = {desc.format, width, height, 1, pitch};
|
||||
linear.pResource = output.Get();
|
||||
list->CopyTextureRegion(&texture, 0, 0, 0, &linear, nullptr);
|
||||
if (inject_pixel_mismatch) {
|
||||
const D3D12_BOX second_pixel{1, 0, 0, 2, 1, 1};
|
||||
list->CopyTextureRegion(&texture, 0, 0, 0, &linear, &second_pixel);
|
||||
}
|
||||
transition(back.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
linear.pResource = readback.Get();
|
||||
list->CopyTextureRegion(&linear, 0, 0, 0, &texture, nullptr);
|
||||
transition(back.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_PRESENT);
|
||||
checked(list->Close(), "close command list");
|
||||
ID3D12CommandList* commands[] = {list.Get()};
|
||||
ComPtr<IDXGISwapChain1> host;
|
||||
checked(chain->GetHostSwapChain(IID_PPV_ARGS(&host)), "get host swapchain");
|
||||
UINT before = 0, after = 0;
|
||||
checked(host->GetLastPresentCount(&before), "initial host present count");
|
||||
ComPtr<ID3D12Fence> fence;
|
||||
checked(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "readback fence");
|
||||
GpuDrain drain{queue.Get(), fence.Get(), true};
|
||||
queue->ExecuteCommandLists(1, commands);
|
||||
const HRESULT present_hr = chain->Present(0, 0);
|
||||
if (present_hr != S_OK) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "PresentX hr=0x%08lx", static_cast<unsigned long>(present_hr));
|
||||
require(false, detail);
|
||||
}
|
||||
checked(chain->WaitForIdle(5000), "wait for frame");
|
||||
// Wait on our own queue fence before the CPU reads the backing map, so the
|
||||
// readback does not depend on what WaitForIdle covers.
|
||||
checked(queue->Signal(fence.Get(), 1), "signal readback fence");
|
||||
if (fence->GetCompletedValue() < 1) {
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
require(done != nullptr, "readback fence event");
|
||||
const HRESULT wait_hr = fence->SetEventOnCompletion(1, done);
|
||||
const DWORD waited = SUCCEEDED(wait_hr) ? WaitForSingleObject(done, 5000) : WAIT_FAILED;
|
||||
cleanup(CloseHandle(done) != 0, "close readback fence event");
|
||||
checked(wait_hr, "readback fence SetEventOnCompletion");
|
||||
require(waited == WAIT_OBJECT_0, "readback fence wait timed out");
|
||||
}
|
||||
drain.armed = false; // everything submitted has completed
|
||||
checked(host->GetLastPresentCount(&after), "final host present count");
|
||||
require(after == before + 1, "host must present exactly once");
|
||||
checkpoint(true, "one host present completed");
|
||||
|
||||
stage = "pixel_readback";
|
||||
auto pixels = reinterpret_cast<const uint32_t*>(region.config.cpu_pointer);
|
||||
for (UINT i = 0; i < width * height; ++i) {
|
||||
// Mirrors fill_cs66.hlsl in shader-transpiler/crates/d3dmetal-harness/probe/shaders;
|
||||
// a change to that shader must change this formula too.
|
||||
uint32_t v = i * 0x9e3779b1u;
|
||||
uint32_t expected = (v ^ (v >> 15)) + 0x01234567u;
|
||||
if (pixels[i] != expected) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "pixel (%u,%u) expected %08x got %08x", i % width, i / width,
|
||||
expected, pixels[i]);
|
||||
require(false, detail);
|
||||
}
|
||||
}
|
||||
const auto* xmem_bytes = static_cast<const unsigned char*>(region.view);
|
||||
require(std::all_of(xmem_bytes, xmem_bytes + Region::page_bytes,
|
||||
[](unsigned char byte) { return byte == Region::sentinel; }),
|
||||
"xmem region bytes changed during frame readback");
|
||||
checkpoint(true, "256 pre-flip RGBA8 pixels matched in the D3D12 map; xmem region sentinel intact");
|
||||
stage = "teardown";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// The mismatch control is armed only by exactly "1". Any other value is a
|
||||
// configuration error rather than a silently ignored control, so a run that
|
||||
// meant to arm it cannot pass as an ordinary run.
|
||||
char inject[16];
|
||||
const DWORD inject_len =
|
||||
GetEnvironmentVariableA("BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH", inject, sizeof(inject));
|
||||
const bool inject_pixel_mismatch = inject_len == 1 && inject[0] == '1';
|
||||
if (inject_len != 0 && !inject_pixel_mismatch) {
|
||||
std::fprintf(stderr, "FAIL: BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH must be unset or exactly 1\n");
|
||||
return 1;
|
||||
}
|
||||
if (inject_pixel_mismatch) {
|
||||
std::printf("NOTE: pixel mismatch control armed; this run must fail at pixel_readback\n");
|
||||
}
|
||||
try {
|
||||
run(inject_pixel_mismatch);
|
||||
} catch (const Failure&) {
|
||||
return 1;
|
||||
}
|
||||
if (!cleanup_ok)
|
||||
return 1;
|
||||
checkpoint(true, "resources released and runtime shut down");
|
||||
return 0;
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
* with no object and no call reaching the host device;
|
||||
* 3. creates PSOs from the #453 [WaveSize(64)] and 64-bit typed-atomic blobs and requires the
|
||||
* gate to log their constraints;
|
||||
* 4. checks the structured `shader_gate` JSONL records.
|
||||
* 4. checks the structured `shader_gate` JSONL records, including the field order and
|
||||
* space-free values bx-telemetry's key=value parser relies on (#535).
|
||||
*
|
||||
* It then runs a copy of itself with --no-bridge from a directory holding d3d12_xs.dll but not
|
||||
* the bridge, which must still run DXIL and refuse ACCC-only with E_NOTIMPL.
|
||||
@@ -140,6 +141,51 @@ bool log_has(const std::string& log, std::initializer_list<const char*> needles)
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Every JSONL line whose text holds `needle`, so shape checks can loop over
|
||||
* the records the shim actually wrote rather than the lines typed by hand in
|
||||
* the trace-summary fixtures. */
|
||||
std::vector<std::string> log_lines_with(const std::string& log, const char* needle) {
|
||||
std::vector<std::string> lines;
|
||||
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(needle) != std::string::npos) lines.push_back(line);
|
||||
start = end + 1;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/* The `detail` value of one JSONL line, or empty when there is none. */
|
||||
std::string detail_of(const std::string& line) {
|
||||
const char* key = "\"detail\":\"";
|
||||
const size_t at = line.find(key);
|
||||
if (at == std::string::npos) return {};
|
||||
const size_t begin = at + std::strlen(key);
|
||||
size_t end = begin;
|
||||
while (end < line.size() && !(line[end] == '"' && line[end - 1] != '\\')) ++end;
|
||||
return line.substr(begin, end - begin);
|
||||
}
|
||||
|
||||
/* The structured part of a `shader_gate` detail: everything before the first
|
||||
* token that has no `=`. The gap record ends in prose, so it stops there. */
|
||||
std::vector<std::string> structured_tokens(const std::string& detail, bool stop_at_free_text) {
|
||||
std::vector<std::string> tokens;
|
||||
size_t i = 0;
|
||||
while (i < detail.size()) {
|
||||
while (i < detail.size() && detail[i] == ' ') ++i;
|
||||
if (i >= detail.size()) break;
|
||||
size_t end = detail.find(' ', i);
|
||||
if (end == std::string::npos) end = detail.size();
|
||||
const std::string token = detail.substr(i, end - i);
|
||||
if (token.find('=') == std::string::npos && stop_at_free_text) break;
|
||||
tokens.push_back(token);
|
||||
i = end;
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
ID3D12RootSignature* make_root(ID3D12Device* device, const D3D12_ROOT_PARAMETER& param) {
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = {};
|
||||
desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
@@ -188,6 +234,49 @@ HRESULT create_compute(ID3D12Device* device, ID3D12RootSignature* root, const vo
|
||||
return device->CreateComputePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso));
|
||||
}
|
||||
|
||||
/* Builds a stream PSO using the REAL subobject layout: alignas(void*) on the class, so a
|
||||
* 4-byte-aligned payload sits at offset 4, not 8. Encoding the layout from the compiler,
|
||||
* rather than from the shim's own assumption, is what lets these tests catch a desync in the
|
||||
* shim's walker (#576 review). */
|
||||
template<class Payload>
|
||||
struct alignas(void*) TestSubobject {
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
Payload payload;
|
||||
};
|
||||
|
||||
struct StreamBuilder {
|
||||
std::vector<uint8_t> bytes;
|
||||
template<class Payload>
|
||||
void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const Payload& payload) {
|
||||
using Record = TestSubobject<Payload>;
|
||||
const size_t at = bytes.size();
|
||||
bytes.resize(at + sizeof(Record), 0);
|
||||
std::memcpy(bytes.data() + at + offsetof(Record, type), &type, sizeof(type));
|
||||
std::memcpy(bytes.data() + at + offsetof(Record, payload), &payload, sizeof(payload));
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC desc() const {
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC d = {};
|
||||
d.SizeInBytes = bytes.size();
|
||||
d.pPipelineStateSubobjectStream = const_cast<uint8_t*>(bytes.data());
|
||||
return d;
|
||||
}
|
||||
};
|
||||
|
||||
StreamBuilder compute_stream(const void* code, size_t size, ID3D12RootSignature* root) {
|
||||
StreamBuilder stream;
|
||||
D3D12_SHADER_BYTECODE cs = {code, size};
|
||||
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, cs);
|
||||
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root);
|
||||
return stream;
|
||||
}
|
||||
|
||||
HRESULT create_stream(ID3D12Device* device, const D3D12_PIPELINE_STATE_STREAM_DESC& desc,
|
||||
ID3D12PipelineState** pso) {
|
||||
*pso = nullptr;
|
||||
auto* device2 = static_cast<ID3D12Device2*>(device);
|
||||
return device2->CreatePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso));
|
||||
}
|
||||
|
||||
/* Runs fill_cs66 and checks every output word. */
|
||||
void run_dxil(ID3D12Device* device, ID3D12RootSignature* root, ID3D12PipelineState* pso) {
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
|
||||
@@ -302,6 +391,12 @@ int no_bridge_main() {
|
||||
hr = device->CreateGraphicsPipelineState(&graphics, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
|
||||
check(hr == E_NOTIMPL && !pso, "no-bridge: ACCC-only graphics VS hr=0x%08lx (want E_NOTIMPL)", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
// The stream form refuses ACCC-only with or without the bridge (#576).
|
||||
StreamBuilder accc_stream = compute_stream(accc.data(), accc.size(), root);
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC accc_desc = accc_stream.desc();
|
||||
hr = create_stream(device, accc_desc, &pso);
|
||||
check(hr == E_NOTIMPL && !pso, "no-bridge: ACCC-only stream CS hr=0x%08lx (want E_NOTIMPL)", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
root->Release();
|
||||
device->Release();
|
||||
return finish();
|
||||
@@ -425,9 +520,88 @@ int main() {
|
||||
check(SUCCEEDED(hr) && pso, "DXIL PSO after a refusal hr=0x%08lx", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
|
||||
// 2b. The stream form (ID3D12Device2::CreatePipelineState) is gated too (#576): the same
|
||||
// ACCC-only container is refused through the stream, and DXIL passes and runs.
|
||||
{
|
||||
StreamBuilder refused = compute_stream(accc.data(), accc.size(), root_uav);
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC stream = refused.desc();
|
||||
hr = create_stream(device, stream, &pso);
|
||||
check(hr == E_NOTIMPL && !pso,
|
||||
"ACCC-only stream PSO: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr), static_cast<void*>(pso));
|
||||
if (pso) pso->Release();
|
||||
|
||||
StreamBuilder accepted = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC stream_dxil = accepted.desc();
|
||||
hr = create_stream(device, stream_dxil, &pso);
|
||||
check(SUCCEEDED(hr) && pso, "DXIL stream PSO hr=0x%08lx", ul(hr));
|
||||
if (pso) {
|
||||
run_dxil(device, root_uav, pso);
|
||||
pso->Release();
|
||||
}
|
||||
|
||||
// A truncated stream, and an unknown subobject type, are rejected before the host.
|
||||
StreamBuilder truncated = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC short_desc = truncated.desc();
|
||||
short_desc.SizeInBytes -= 8;
|
||||
hr = create_stream(device, short_desc, &pso);
|
||||
check(hr == E_INVALIDARG && !pso, "truncated stream hr=0x%08lx (want E_INVALIDARG)", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
|
||||
StreamBuilder unknown = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
|
||||
/* Append a record whose type tag is not a known subobject. */
|
||||
const size_t at = unknown.bytes.size();
|
||||
const uint32_t bogus = 0x7f;
|
||||
unknown.bytes.resize(at + 8, 0);
|
||||
std::memcpy(unknown.bytes.data() + at, &bogus, sizeof(bogus));
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC bogus_desc = unknown.desc();
|
||||
hr = create_stream(device, bogus_desc, &pso);
|
||||
check(hr == E_INVALIDARG && !pso, "unknown-subobject stream hr=0x%08lx (want E_INVALIDARG)", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
|
||||
// A graphics stream whose non-shader payloads are 4-byte aligned (SAMPLE_MASK,
|
||||
// RENDER_TARGET_FORMATS, RASTERIZER, BLEND, FLAGS) must still reach the host. The
|
||||
// first version of this change assumed every payload sat at offset 8 and desynced
|
||||
// here, rejecting a valid stream with E_INVALIDARG (#576 review).
|
||||
{
|
||||
// A *compute* stream carrying 4-byte-aligned payloads. The first version used
|
||||
// `g_fill_cs66` as a VS, which is a compute execution model and not a valid
|
||||
// vertex shader, so the host could reject it for a reason unrelated to payload
|
||||
// alignment (review on #577). NODE_MASK and FLAGS are UINT payloads at offset 4
|
||||
// and are legal subobjects for a compute PSO, so this exercises the layout
|
||||
// without depending on a vertex-stage fixture.
|
||||
StreamBuilder aligned_stream;
|
||||
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root_uav);
|
||||
D3D12_SHADER_BYTECODE cs = {g_fill_cs66, sizeof(g_fill_cs66)};
|
||||
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, cs);
|
||||
UINT node_mask = 0;
|
||||
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, node_mask);
|
||||
UINT stream_flags = 0;
|
||||
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, stream_flags);
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC aligned_desc = aligned_stream.desc();
|
||||
hr = create_stream(device, aligned_desc, &pso);
|
||||
check(SUCCEEDED(hr) && pso, "compute stream with 4-byte-aligned payloads hr=0x%08lx", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
}
|
||||
|
||||
// A duplicated subobject type is rejected by ID3D12Device2's own rules.
|
||||
StreamBuilder duplicate = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
|
||||
D3D12_SHADER_BYTECODE again = {g_fill_cs66, sizeof(g_fill_cs66)};
|
||||
duplicate.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, again);
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC dup_desc = duplicate.desc();
|
||||
hr = create_stream(device, dup_desc, &pso);
|
||||
check(hr == E_INVALIDARG && !pso, "duplicate-CS stream hr=0x%08lx (want E_INVALIDARG)", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
}
|
||||
|
||||
// 3. Constraint-carrying DXIL still passes; its constraints are logged (results not dispatched).
|
||||
// A wave wider than 32 lanes is refused at creation (#591): D3DMetal creates the PSO
|
||||
// and never runs it, so an S_OK here would be a silent no-op. The fixture asserts the
|
||||
// failure rather than only reading the log, because the log alone cannot tell a caller
|
||||
// what happened.
|
||||
hr = create_compute(device, root_uav, g_wave64_lanes_cs, sizeof(g_wave64_lanes_cs), &pso);
|
||||
std::printf("wave64 PSO hr=0x%08lx\n", ul(hr));
|
||||
check(hr == E_NOTIMPL && !pso,
|
||||
"wave64 PSO is refused at creation: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr),
|
||||
static_cast<void*>(pso));
|
||||
if (pso) pso->Release();
|
||||
hr = create_compute(device, root_table, g_atomic64_image_cs, sizeof(g_atomic64_image_cs), &pso);
|
||||
std::printf("atomic64 typed PSO hr=0x%08lx\n", ul(hr));
|
||||
@@ -438,6 +612,81 @@ int main() {
|
||||
|
||||
// 5. The JSONL records.
|
||||
const std::string log = read_log();
|
||||
// The trace-summary fixtures in bx-telemetry/bx-cli are typed by hand from
|
||||
// reading shader_gate.cpp. These checks pin the shape the parser assumes,
|
||||
// against the log this fixture actually wrote, so the two cannot drift
|
||||
// apart silently (#535).
|
||||
{
|
||||
const std::vector<std::string> gate_lines = log_lines_with(log, "\"event\":\"shader_gate\"");
|
||||
check(!gate_lines.empty(), "the fixture wrote at least one shader_gate record");
|
||||
|
||||
bool order_ok = true;
|
||||
bool classified_has_kind = true;
|
||||
bool unclassified_lacks_kind = true;
|
||||
bool values_have_no_space = true;
|
||||
for (const std::string& line : gate_lines) {
|
||||
const std::string detail = detail_of(line);
|
||||
const size_t pso = detail.find("pso=");
|
||||
const size_t stage = detail.find("stage=");
|
||||
const size_t decision = detail.find("decision=");
|
||||
const size_t hr = detail.find("hr=");
|
||||
// The summarizer extracts these by key, so the order the emitter
|
||||
// writes them is the order it relies on. Every key must be present:
|
||||
// a missing one is npos, the largest value, which would satisfy `<`.
|
||||
const bool all_present = pso != std::string::npos && stage != std::string::npos &&
|
||||
decision != std::string::npos && hr != std::string::npos;
|
||||
if (!(all_present && pso < stage && stage < decision && decision < hr)) {
|
||||
order_ok = false;
|
||||
}
|
||||
const bool unclassified = detail.find("unclassified") != std::string::npos;
|
||||
const bool has_kind = detail.find("kind=") != std::string::npos;
|
||||
/* A record with an inspection always logs a kind; the no-bridge records
|
||||
* (`*_unclassified`) and `pass_uninspected` have none. */
|
||||
const bool classified = !unclassified &&
|
||||
(detail.find("decision=pass_dxil") != std::string::npos ||
|
||||
detail.find("decision=reject_accc_only") != std::string::npos ||
|
||||
detail.find("decision=pass_original") != std::string::npos ||
|
||||
detail.find("decision=prepare_failed") != std::string::npos ||
|
||||
detail.find("decision=copy_limit") != std::string::npos);
|
||||
if (unclassified && has_kind) unclassified_lacks_kind = false;
|
||||
if (classified && !has_kind) classified_has_kind = false;
|
||||
for (const std::string& token : structured_tokens(detail, false)) {
|
||||
if (token.find('=') == std::string::npos) values_have_no_space = false;
|
||||
}
|
||||
}
|
||||
check(order_ok, "every shader_gate record writes pso, stage, decision, hr in that order");
|
||||
check(classified_has_kind, "a classified shader_gate record carries kind=");
|
||||
check(unclassified_lacks_kind, "an unclassified record carries no kind=");
|
||||
check(values_have_no_space,
|
||||
"no key=value in a shader_gate record is split by a space, which is what "
|
||||
"parse_key_values(..., false) assumes");
|
||||
|
||||
const std::vector<std::string> gap_lines = log_lines_with(log, "\"event\":\"shader_d3dmetal_gap\"");
|
||||
check(!gap_lines.empty(), "the fixture wrote at least one gap record");
|
||||
bool gap_ok = true;
|
||||
bool gap_values_have_no_space = true;
|
||||
for (const std::string& line : gap_lines) {
|
||||
const std::string detail = detail_of(line);
|
||||
if (detail.find("pso=") == std::string::npos ||
|
||||
detail.find("stage=") == std::string::npos ||
|
||||
detail.find("wave_lanes_min=") == std::string::npos ||
|
||||
detail.find(':') == std::string::npos) {
|
||||
gap_ok = false;
|
||||
}
|
||||
// parse_key_values(..., true) stops at the first token without
|
||||
// '=', so every structured token must be a key=value pair.
|
||||
for (const std::string& token : structured_tokens(detail, true)) {
|
||||
if (token.find('=') == std::string::npos) gap_values_have_no_space = false;
|
||||
}
|
||||
}
|
||||
check(gap_ok,
|
||||
"every gap record carries pso=, stage=, wave_lanes_min= and the colon "
|
||||
"that ends its structured part");
|
||||
check(gap_values_have_no_space,
|
||||
"no key=value in a gap record's structured part is split by a space, which is "
|
||||
"what parse_key_values(..., true) assumes");
|
||||
}
|
||||
|
||||
char fill_bytes[32];
|
||||
std::snprintf(fill_bytes, sizeof(fill_bytes), "bytes=%u ", static_cast<unsigned>(sizeof(g_fill_cs66)));
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=pass_dxil", "kind=dxil", "sm=6.6",
|
||||
@@ -448,8 +697,19 @@ int main() {
|
||||
"shader_gate record rejecting the ACCC-only compute shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=graphics", "stage=VS", "decision=reject_accc_only"}),
|
||||
"shader_gate record rejecting the ACCC-only vertex shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=pass_dxil", "wave_ops=1", "wave_lanes=64-64"}),
|
||||
"shader_gate record with WaveSize(64)");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=stream", "stage=CS", "decision=reject_accc_only"}),
|
||||
"shader_gate record rejecting the ACCC-only stream compute shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=stream", "stage=CS", "decision=pass_dxil"}),
|
||||
"shader_gate record passing the DXIL stream compute shader");
|
||||
check(log_has(log, {"\"event\":\"pso_stream\"", "shaders_not_parsed=0"}),
|
||||
"pso_stream record says the stream's shaders were parsed");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=reject_wave_wide", "hr=0x80004001"}),
|
||||
"shader_gate record refusing the wave64 stage");
|
||||
// The wave64 stage is now refused before `pass_dxil` is logged (#591), so the record to
|
||||
// assert is the rejection, carrying the same wave constraints the gap was measured on.
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=reject_wave_wide", "wave_ops=1",
|
||||
"wave_lanes=64-64"}),
|
||||
"shader_gate record with WaveSize(64), refused");
|
||||
check(log_has(log, {"\"event\":\"shader_d3dmetal_gap\"", "wave_lanes_min=64"}),
|
||||
"shader_d3dmetal_gap record for WaveSize(64)");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=pass_dxil", "int64_ops=1", "atomic64=typed,"}),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include <windows.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
struct ShimExpectation {
|
||||
const char* dll;
|
||||
@@ -32,8 +33,31 @@ static const ShimExpectation kChecks[] = {
|
||||
{"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll", "PeekMessageA"},
|
||||
{"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow"},
|
||||
{"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA"},
|
||||
/* The 17th shipped DLL: the Rust-built bridge from abi/defs/bx_shader_bridge.def. */
|
||||
{"bx_shader_bridge.dll", "bx_shader_inspect"},
|
||||
{"bx_shader_bridge.dll", "bx_shader_prepare_for_d3dmetal"},
|
||||
{"bx_shader_bridge.dll", "bx_shader_free_buffer"},
|
||||
};
|
||||
|
||||
/* Distinct DLLs named in kChecks, so the summary reports a counted number. */
|
||||
static size_t DistinctDllCount() {
|
||||
const size_t count = sizeof(kChecks) / sizeof(kChecks[0]);
|
||||
size_t distinct = 0;
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
bool seen = false;
|
||||
for (size_t j = 0; j < i; ++j) {
|
||||
if (std::strcmp(kChecks[i].dll, kChecks[j].dll) == 0) {
|
||||
seen = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!seen) {
|
||||
++distinct;
|
||||
}
|
||||
}
|
||||
return distinct;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int failures = 0;
|
||||
for (const auto& check : kChecks) {
|
||||
@@ -56,6 +80,7 @@ int main() {
|
||||
std::fprintf(stderr, "FAIL: %d shim export check(s) failed\n", failures);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_shim_exports (%zu checks verified)\n", sizeof(kChecks) / sizeof(kChecks[0]));
|
||||
std::printf("PASS: test_shim_exports (%zu checks verified across %zu shim DLLs)\n",
|
||||
sizeof(kChecks) / sizeof(kChecks[0]), DistinctDllCount());
|
||||
return 0;
|
||||
}
|
||||
@@ -2,7 +2,10 @@
|
||||
#include <immintrin.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
@@ -15,6 +18,132 @@ VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
|
||||
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t flags);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BX_LOG_FILE reader. BX_LOG_FILE must name the log before the process
|
||||
// starts (`bx-cli run --log`): this EXE imports bx_runtime_veh.dll, which reads
|
||||
// the variable once in DLL_PROCESS_ATTACH, before main runs, so setting it here
|
||||
// would be too late and the checks would read an empty file.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct LogReader {
|
||||
char path[MAX_PATH]{};
|
||||
int64_t start_offset = 0;
|
||||
|
||||
bool init() {
|
||||
const DWORD existing_len =
|
||||
GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (existing_len == 0 || existing_len >= sizeof(path)) {
|
||||
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
|
||||
return false;
|
||||
}
|
||||
start_offset = query_file_size(path);
|
||||
return true;
|
||||
}
|
||||
|
||||
static int64_t query_file_size(const char* p) {
|
||||
HANDLE f = CreateFileA(p, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
return 0;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
const bool ok = GetFileSizeEx(f, &size) != 0;
|
||||
CloseHandle(f);
|
||||
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
|
||||
}
|
||||
|
||||
// Read only the bytes appended after start_offset.
|
||||
bool read_new(std::string& out) const {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
std::fprintf(stderr, "FAIL: could not open CLWB log %s (error %lu)\n",
|
||||
path, GetLastError());
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
if (!GetFileSizeEx(f, &size) || size.QuadPart < start_offset) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: invalid CLWB log size for %s\n", path);
|
||||
return false;
|
||||
}
|
||||
const int64_t delta = size.QuadPart - start_offset;
|
||||
if (delta < 0 || delta > (64LL << 20)) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: unexpected CLWB log delta (%lld bytes)\n",
|
||||
static_cast<long long>(delta));
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER seek{};
|
||||
seek.QuadPart = start_offset;
|
||||
if (!SetFilePointerEx(f, seek, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return false;
|
||||
}
|
||||
out.assign(static_cast<size_t>(delta), '\0');
|
||||
size_t total_read = 0;
|
||||
while (total_read < out.size()) {
|
||||
DWORD chunk = 0;
|
||||
const DWORD want = static_cast<DWORD>(out.size() - total_read);
|
||||
if (!ReadFile(f, out.data() + total_read, want, &chunk, nullptr) || chunk == 0) {
|
||||
break;
|
||||
}
|
||||
total_read += chunk;
|
||||
}
|
||||
CloseHandle(f);
|
||||
out.resize(total_read);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// One parsed `clwb_trapped` record.
|
||||
struct ClwbRecord {
|
||||
uint64_t total_traps = 0;
|
||||
size_t len = 0;
|
||||
};
|
||||
|
||||
// Parse every `"event":"clwb_trapped"` line for `len=` and `total_traps=`.
|
||||
static std::vector<ClwbRecord> parse_clwb_records(const std::string& data) {
|
||||
std::vector<ClwbRecord> records;
|
||||
size_t pos = 0;
|
||||
while (pos < data.size()) {
|
||||
size_t nl = data.find('\n', pos);
|
||||
if (nl == std::string::npos) {
|
||||
nl = data.size();
|
||||
}
|
||||
const std::string line = data.substr(pos, nl - pos);
|
||||
pos = nl + 1;
|
||||
|
||||
if (line.find("\"event\":\"clwb_trapped\"") == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
ClwbRecord rec{};
|
||||
// len=%zu
|
||||
const size_t len_key = line.find("len=");
|
||||
if (len_key == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
// strtoull, not stoull: a malformed record must not throw past the FAIL message.
|
||||
char* len_end = nullptr;
|
||||
rec.len = std::strtoull(line.c_str() + len_key + 4, &len_end, 10);
|
||||
if (len_end == line.c_str() + len_key + 4) {
|
||||
continue;
|
||||
}
|
||||
// total_traps=%llu
|
||||
const size_t tt_key = line.find("total_traps=");
|
||||
if (tt_key == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
char* tt_end = nullptr;
|
||||
rec.total_traps = std::strtoull(line.c_str() + tt_key + 12, &tt_end, 10);
|
||||
if (tt_end == line.c_str() + tt_key + 12) {
|
||||
continue;
|
||||
}
|
||||
records.push_back(rec);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
int main() {
|
||||
/* 1. Verify AVX2 + FMA execution under Rosetta 2 */
|
||||
__m256 a = _mm256_set1_ps(3.0f);
|
||||
@@ -29,6 +158,15 @@ int main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Set up the log reader BEFORE the clwb block so we capture every
|
||||
// clwb_trapped record the VEH emits. The AVX2/FMA block above runs
|
||||
// first but does not trap (bx_veh_get_clwb_trap_count counts only
|
||||
// clwb), so the first clwb below is trap #1.
|
||||
LogReader log;
|
||||
if (!log.init()) {
|
||||
return 5;
|
||||
}
|
||||
|
||||
// Fixed registers ensure the assembler emits the intended ModRM/REX forms.
|
||||
alignas(64) uint8_t buf[512] = {0x42};
|
||||
const uint64_t before = bx_veh_get_clwb_trap_count();
|
||||
@@ -49,6 +187,92 @@ int main() {
|
||||
}
|
||||
std::printf("CLWB traps observed: %llu\n", static_cast<unsigned long long>(delta));
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Verify the decoded instruction length (`len=`) that the VEH logs and
|
||||
// uses to advance RIP. A wrong `len` lands the guest mid-instruction
|
||||
// while `delta` still reads 6, so this is the field that decides whether
|
||||
// the guest resumes correctly.
|
||||
//
|
||||
// log_sampled_trap() logs only when count == 1 or count is a power of
|
||||
// two, i.e. traps 1, 2, 4, 8, ... Six traps therefore produce exactly
|
||||
// three records with total_traps = 1, 2, 4. We assert on those three
|
||||
// sampled records only (option (a)); we do NOT see a `len=` for forms
|
||||
// 3, 5, 6 and make no claim about them here.
|
||||
//
|
||||
// Expected lengths, re-verified by assembling with
|
||||
// x86_64-w64-mingw32-as and disassembling with
|
||||
// x86_64-w64-mingw32-objdump -d:
|
||||
//
|
||||
// 0: 66 0f ae 30 clwb (%rax) -> 4
|
||||
// 4: 66 0f ae 70 40 clwb 0x40(%rax) -> 5
|
||||
// 9: 66 0f ae b0 00 01 00 00 clwb 0x100(%rax) -> 8
|
||||
// 11: 66 41 0f ae 30 clwb (%r8) -> 5 (REX.B, ModRM 0x30)
|
||||
// 16: 66 0f ae 74 88 40 clwb 0x40(%rax,%rcx,4) -> 6 (SIB + disp8)
|
||||
// 1c: 66 0f ae 35 00 00 00 00 clwb 0x0(%rip) -> 7 (disp32)
|
||||
//
|
||||
// Mapping sampled count -> ordinal -> expected len:
|
||||
// total_traps=1 -> ordinal 1 -> clwb (%rax) -> len 4
|
||||
// total_traps=2 -> ordinal 2 -> clwb 0x40(%rax)-> len 5
|
||||
// total_traps=4 -> ordinal 4 -> clwb (%r8) -> len 5
|
||||
// -----------------------------------------------------------------------
|
||||
{
|
||||
std::string log_data;
|
||||
if (!log.read_new(log_data)) {
|
||||
return 6;
|
||||
}
|
||||
const std::vector<ClwbRecord> records = parse_clwb_records(log_data);
|
||||
if (records.empty()) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: no clwb_trapped records found in log %s "
|
||||
"(BX_LOG_FILE must be readable)\n", log.path);
|
||||
return 7;
|
||||
}
|
||||
|
||||
// Every observed record must have len >= 4 (the shortest form,
|
||||
// 66 0F AE /6 with ModRM mod=00 rm=000, is 4 bytes).
|
||||
for (const auto& r : records) {
|
||||
if (r.len < 4) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: clwb_trapped total_traps=%llu has len=%zu < 4\n",
|
||||
static_cast<unsigned long long>(r.total_traps), r.len);
|
||||
return 8;
|
||||
}
|
||||
}
|
||||
|
||||
// Exact expectations for the three sampled counts.
|
||||
struct Expected { uint64_t total_traps; size_t len; const char* form; };
|
||||
static const Expected kExpected[] = {
|
||||
{1, 4, "clwb (%rax)"},
|
||||
{2, 5, "clwb 0x40(%rax)"},
|
||||
{4, 5, "clwb (%r8)"},
|
||||
};
|
||||
for (const auto& exp : kExpected) {
|
||||
bool found = false;
|
||||
for (const auto& r : records) {
|
||||
if (r.total_traps == exp.total_traps) {
|
||||
found = true;
|
||||
if (r.len != exp.len) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: clwb_trapped total_traps=%llu (%s): "
|
||||
"expected len=%zu, got len=%zu\n",
|
||||
static_cast<unsigned long long>(exp.total_traps),
|
||||
exp.form, exp.len, r.len);
|
||||
return 9;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: missing clwb_trapped record with total_traps=%llu (%s)\n",
|
||||
static_cast<unsigned long long>(exp.total_traps), exp.form);
|
||||
return 10;
|
||||
}
|
||||
}
|
||||
std::printf("CLWB decoded lengths verified for sampled traps 1, 2, 4 "
|
||||
"(%zu records)\n", records.size());
|
||||
}
|
||||
|
||||
/* 3. Verify basic XMem allocation + transfer + stats contract */
|
||||
void* src = XMemAlloc(4096, 0);
|
||||
void* dst = XMemAlloc(4096, 0);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -138,8 +139,44 @@ struct PsmLogCounts {
|
||||
size_t constrained_unregistered = 0;
|
||||
size_t constrained_foreign = 0;
|
||||
size_t constrained_unknown = 0;
|
||||
size_t state_callback_unfired = 0;
|
||||
size_t constrained_callback_unfired = 0;
|
||||
};
|
||||
|
||||
// Observed `context=0x...` values from the JSONL registration records. The
|
||||
// shim logs the context pointer it actually stored for each token, so these
|
||||
// are evidence of the round-trip, not of the arguments the test passed.
|
||||
struct PsmContextObservations {
|
||||
std::unordered_set<uintptr_t> state_contexts;
|
||||
std::unordered_set<uintptr_t> constrained_contexts;
|
||||
bool saw_context_field = false;
|
||||
bool parse_error = false;
|
||||
// The current shim's unregister records only carry a detail string, so no
|
||||
// context is observable there. Record it instead of asserting the invisible.
|
||||
bool unregister_carries_context = false;
|
||||
};
|
||||
|
||||
// Extract the `context=0x<hex>` value from a single JSONL line. `%llx` prints
|
||||
// lowercase hex with a `0x` prefix and no leading zeros, so strtoull base 16
|
||||
// (which accepts the optional `0x`) parses it exactly. Returns false when the
|
||||
// field is absent or malformed; `value` is only written on success.
|
||||
bool parse_context_field(const std::string& line, uintptr_t& value) {
|
||||
const size_t key = line.find("context=0x");
|
||||
if (key == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
// Parse from the value, after "context=". Starting at the key would make
|
||||
// strtoull read the hex digit 'c' from "context" and stop at 'o' (#520).
|
||||
const char* start = line.c_str() + key + std::strlen("context=");
|
||||
char* end = nullptr;
|
||||
const unsigned long long parsed = std::strtoull(start, &end, 16);
|
||||
if (end == start) {
|
||||
return false;
|
||||
}
|
||||
value = static_cast<uintptr_t>(parsed);
|
||||
return true;
|
||||
}
|
||||
|
||||
int64_t query_file_size(const char* path) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
@@ -152,7 +189,8 @@ int64_t query_file_size(const char* path) {
|
||||
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
|
||||
}
|
||||
|
||||
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out) {
|
||||
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out,
|
||||
PsmContextObservations& contexts) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
@@ -204,12 +242,37 @@ bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts&
|
||||
continue;
|
||||
}
|
||||
if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
|
||||
line.find("callback_unfired") != std::string::npos) {
|
||||
++out.state_callback_unfired;
|
||||
++out.state_registered;
|
||||
uintptr_t ctx = 0;
|
||||
if (parse_context_field(line, ctx)) {
|
||||
contexts.saw_context_field = true;
|
||||
contexts.state_contexts.insert(ctx);
|
||||
} else {
|
||||
contexts.parse_error = true;
|
||||
}
|
||||
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
|
||||
line.find("callback_unfired") != std::string::npos) {
|
||||
++out.constrained_callback_unfired;
|
||||
++out.constrained_registered;
|
||||
uintptr_t ctx = 0;
|
||||
if (parse_context_field(line, ctx)) {
|
||||
contexts.saw_context_field = true;
|
||||
contexts.constrained_contexts.insert(ctx);
|
||||
} else {
|
||||
contexts.parse_error = true;
|
||||
}
|
||||
} else if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.state_registered;
|
||||
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.constrained_registered;
|
||||
} else if (line.find("\"event\":\"UnregisterAppStateChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("context=0x") != std::string::npos) {
|
||||
contexts.unregister_carries_context = true;
|
||||
}
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.state_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
@@ -218,6 +281,9 @@ bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts&
|
||||
++out.state_unknown;
|
||||
}
|
||||
} else if (line.find("\"event\":\"UnregisterAppConstrainedChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("context=0x") != std::string::npos) {
|
||||
contexts.unregister_carries_context = true;
|
||||
}
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.constrained_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
@@ -324,7 +390,9 @@ bool test_psm() {
|
||||
}
|
||||
|
||||
PsmLogCounts counts{};
|
||||
const bool log_read_ok = count_psm_log_events(log_path, log_start_offset, counts);
|
||||
PsmContextObservations contexts{};
|
||||
const bool log_read_ok =
|
||||
count_psm_log_events(log_path, log_start_offset, counts, contexts);
|
||||
const bool counts_ok = log_read_ok &&
|
||||
counts.state_registered == kPerFamily &&
|
||||
counts.constrained_registered == kPerFamily &&
|
||||
@@ -345,7 +413,113 @@ bool test_psm() {
|
||||
counts.constrained_foreign, counts.constrained_unknown);
|
||||
}
|
||||
|
||||
ok = success.load() && unique_ok && !g_callback_called.load() && counts_ok;
|
||||
/* The callbacks are accepted and stored but never invoked, so the
|
||||
* JSONL detail must say so: ERROR_SUCCESS is bookkeeping only. */
|
||||
const bool fired_never = !g_callback_called.load();
|
||||
if (!fired_never) {
|
||||
std::fprintf(stderr, "FAIL: a PSM callback fired; the shim has no event source\n");
|
||||
}
|
||||
if (counts.state_callback_unfired != counts.state_registered) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: %zu of %zu state registrations omit 'callback_unfired'\n",
|
||||
counts.state_registered - counts.state_callback_unfired,
|
||||
counts.state_registered);
|
||||
}
|
||||
if (counts.constrained_callback_unfired != counts.constrained_registered) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: %zu of %zu constrained registrations omit 'callback_unfired'\n",
|
||||
counts.constrained_registered - counts.constrained_callback_unfired,
|
||||
counts.constrained_registered);
|
||||
}
|
||||
const bool limitation_logged = counts.state_callback_unfired == counts.state_registered &&
|
||||
counts.constrained_callback_unfired ==
|
||||
counts.constrained_registered;
|
||||
|
||||
/* Context round-trip: the JSONL registration record must print
|
||||
* the exact context pointer the test passed (&entry), non-zero,
|
||||
* on BOTH families. A dropped (context=0x0), swapped, or
|
||||
* mis-tagged context would fail here. */
|
||||
std::unordered_set<uintptr_t> expected_contexts;
|
||||
for (const auto& entries : tokens) {
|
||||
for (const auto& entry : entries) {
|
||||
expected_contexts.insert(reinterpret_cast<uintptr_t>(&entry));
|
||||
}
|
||||
}
|
||||
bool context_roundtrip_ok = contexts.saw_context_field && !contexts.parse_error;
|
||||
if (!contexts.saw_context_field) {
|
||||
std::fprintf(stderr, "FAIL: no context=0x field observed in PSM registration records\n");
|
||||
}
|
||||
if (contexts.parse_error) {
|
||||
std::fprintf(stderr, "FAIL: a PSM registration record had a missing/malformed context=\n");
|
||||
}
|
||||
// (1) Every context logged on the state family must be a real
|
||||
// &entry the test passed, and non-zero.
|
||||
for (const uintptr_t ctx : contexts.state_contexts) {
|
||||
if (ctx == 0) {
|
||||
std::fprintf(stderr, "FAIL: state registration logged context=0x0 (dropped context)\n");
|
||||
context_roundtrip_ok = false;
|
||||
} else if (expected_contexts.find(ctx) == expected_contexts.end()) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: state registration logged context=0x%llx that matches no &entry\n",
|
||||
static_cast<unsigned long long>(ctx));
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
}
|
||||
// (1b) Same for the constrained family.
|
||||
for (const uintptr_t ctx : contexts.constrained_contexts) {
|
||||
if (ctx == 0) {
|
||||
std::fprintf(stderr, "FAIL: constrained registration logged context=0x0 (dropped context)\n");
|
||||
context_roundtrip_ok = false;
|
||||
} else if (expected_contexts.find(ctx) == expected_contexts.end()) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: constrained registration logged context=0x%llx that matches no &entry\n",
|
||||
static_cast<unsigned long long>(ctx));
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
}
|
||||
// (2) At least two distinct context pointers must appear per
|
||||
// family, so one registration cannot overwrite another's.
|
||||
if (contexts.state_contexts.size() < 2) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: only %zu distinct state context pointer(s) logged; expected >=2\n",
|
||||
contexts.state_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
if (contexts.constrained_contexts.size() < 2) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: only %zu distinct constrained context pointer(s) logged; expected >=2\n",
|
||||
contexts.constrained_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
// (3) Family tagging: the test passes the SAME &entry to both
|
||||
// families, so the constrained record for an entry must
|
||||
// carry that entry's pointer too. With 64 registrations per
|
||||
// family the full set of &entry pointers must round-trip on
|
||||
// each family independently.
|
||||
if (contexts.state_contexts != expected_contexts) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: state contexts (%zu) do not cover all %zu &entry pointers\n",
|
||||
contexts.state_contexts.size(), expected_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
if (contexts.constrained_contexts != expected_contexts) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: constrained contexts (%zu) do not cover all %zu &entry pointers\n",
|
||||
contexts.constrained_contexts.size(), expected_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
// (4) Unregister context: the shim's unregister records carry
|
||||
// only a detail string, so context-drop on unregister is
|
||||
// not observable in the log. Assert nothing invisible; just
|
||||
// document the limitation.
|
||||
if (contexts.unregister_carries_context) {
|
||||
std::fprintf(stderr,
|
||||
"NOTE: unregister records unexpectedly carry context=; "
|
||||
"context-drop on unregister is now observable\n");
|
||||
}
|
||||
|
||||
ok = success.load() && unique_ok && fired_never && counts_ok && limitation_logged &&
|
||||
context_roundtrip_ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -367,6 +541,7 @@ int main() {
|
||||
std::fprintf(stderr, "FAIL: PSM bridge registration lifecycle\n");
|
||||
return 2;
|
||||
}
|
||||
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, per-event log verified)");
|
||||
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, "
|
||||
"per-event log + context round-trip verified)");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_xbox_drives main.cpp)
|
||||
target_link_libraries(test_xbox_drives PRIVATE kernel32)
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Check BetterXen's inferred Xbox drive layout through synthetic file operations.
|
||||
*
|
||||
* The project-authorized target title we traced opens its package on G: and writes crash logs
|
||||
* to T:, and stops at startup when either is missing; that these roles hold for Xbox titles in
|
||||
* general is an inference. The fixture checks the resulting layout. The expected contents
|
||||
* of G: come from this program's own path (GetModuleFileNameW).
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <vector>
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "FAIL: test_xbox_drives:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
static bool read_all(const wchar_t* path, std::vector<char>& out) {
|
||||
HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file == INVALID_HANDLE_VALUE) return false;
|
||||
LARGE_INTEGER size{};
|
||||
bool ok = GetFileSizeEx(file, &size) && size.QuadPart > 0 && size.QuadPart < (1 << 28);
|
||||
if (ok) {
|
||||
out.resize(static_cast<size_t>(size.QuadPart));
|
||||
DWORD got = 0;
|
||||
ok = ReadFile(file, out.data(), static_cast<DWORD>(out.size()), &got, nullptr) &&
|
||||
got == out.size();
|
||||
}
|
||||
CloseHandle(file);
|
||||
return ok;
|
||||
}
|
||||
|
||||
int main() {
|
||||
wchar_t self[MAX_PATH]{};
|
||||
DWORD len = GetModuleFileNameW(nullptr, self, MAX_PATH);
|
||||
CHECK(len > 0 && len < MAX_PATH);
|
||||
const wchar_t* name = std::wcsrchr(self, L'\\');
|
||||
CHECK(name != nullptr);
|
||||
++name;
|
||||
|
||||
// G: resolves to this executable's directory: the same file, byte for byte.
|
||||
wchar_t on_g[MAX_PATH]{};
|
||||
std::swprintf(on_g, MAX_PATH, L"G:\\%ls", name);
|
||||
std::vector<char> expected, actual;
|
||||
CHECK(read_all(self, expected));
|
||||
CHECK(read_all(on_g, actual));
|
||||
CHECK(actual == expected);
|
||||
|
||||
// T: is a directory a title can create, read back and delete a file in.
|
||||
DWORD attrs = GetFileAttributesW(L"T:\\");
|
||||
CHECK(attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY));
|
||||
wchar_t probe[MAX_PATH]{};
|
||||
std::swprintf(probe, MAX_PATH, L"T:\\bx_drive_probe_%lu.tmp",
|
||||
static_cast<unsigned long>(GetCurrentProcessId()));
|
||||
static const char payload[] = "bx-drive-probe";
|
||||
HANDLE file = CreateFileW(probe, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
CHECK(file != INVALID_HANDLE_VALUE);
|
||||
DWORD wrote = 0;
|
||||
BOOL written = WriteFile(file, payload, sizeof(payload), &wrote, nullptr);
|
||||
CloseHandle(file);
|
||||
CHECK(written && wrote == sizeof(payload));
|
||||
std::vector<char> back;
|
||||
CHECK(read_all(probe, back));
|
||||
CHECK(back.size() == sizeof(payload) && std::memcmp(back.data(), payload, sizeof(payload)) == 0);
|
||||
CHECK(DeleteFileW(probe));
|
||||
|
||||
std::printf("PASS: test_xbox_drives\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
add_executable(test_xcrdapi_abi main.cpp)
|
||||
target_compile_definitions(test_xcrdapi_abi PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_include_directories(test_xcrdapi_abi PRIVATE "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
|
||||
target_link_libraries(test_xcrdapi_abi PRIVATE xcrdapi kernel32 uuid)
|
||||
@@ -0,0 +1,722 @@
|
||||
// XCRDAPI.dll public DirectStorage ABI conformance (#597).
|
||||
//
|
||||
// Every call below goes through a hand-typed C vtable read out of the object
|
||||
// itself: `slots(object)[n]` is the n-th function pointer, and each function
|
||||
// pointer is cast to a signature typed here. The slot numbers and signatures
|
||||
// are transcribed from the DECLARE_INTERFACE_IID_ blocks of the vendored
|
||||
// shims/xcrdapi/dstorage/dstorage.h (SDK 1.4.0, MIT) in declaration order,
|
||||
// including the inherited IUnknown slots 0..2, so the expected slot comes
|
||||
// from a different code path than the shim's C++ class declarations.
|
||||
//
|
||||
// The header is included for its structure layouts, enumerations and error
|
||||
// codes only; no interface method is called through a C++ interface pointer.
|
||||
//
|
||||
// Slot tables (header order, IUnknown = 0..2 in every interface):
|
||||
//
|
||||
// IDStorageFile 3 Close, 4 GetFileInformation (5 slots)
|
||||
// IDStorageFactory 3 CreateQueue, 4 OpenFile, 5 CreateStatusArray,
|
||||
// 6 SetDebugFlags, 7 SetStagingBufferSize (8)
|
||||
// IDStorageFactory1 8 CreateQueue1 (9)
|
||||
// IDStorageStatusArray 3 IsComplete, 4 GetHResult (5)
|
||||
// IDStorageQueue 3 EnqueueRequest, 4 EnqueueStatus, 5 EnqueueSignal,
|
||||
// 6 Submit, 7 CancelRequestsWithTag, 8 Close,
|
||||
// 9 GetErrorEvent, 10 RetrieveErrorRecord, 11 Query (12)
|
||||
// IDStorageQueue1 12 EnqueueSetEvent (13)
|
||||
// IDStorageQueue2 13 GetCompressionSupport (14)
|
||||
// IDStorageQueue3 14 EnqueueRequests (15)
|
||||
// IDStorageQueue4 15 Query1 (16)
|
||||
//
|
||||
// Cross-checked against Silk.NET's DirectStorage bindings (MIT): they bind the
|
||||
// factory's CreateQueue/OpenFile/CreateStatusArray/SetDebugFlags/
|
||||
// SetStagingBufferSize to LpVtbl[3..7], the file's Close/GetFileInformation to
|
||||
// [3..4], the status array's IsComplete/GetHResult to [3..4], the queue's
|
||||
// EnqueueRequest..Query to [3..11], EnqueueSetEvent to [12],
|
||||
// GetCompressionSupport to [13] and EnqueueRequests to [14]. Silk.NET 1.3.0
|
||||
// predates IDStorageFactory1 and IDStorageQueue4, so slots 8 and 15 are fixed
|
||||
// by the header's inheritance chain alone.
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#include "dstorage.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
|
||||
namespace {
|
||||
|
||||
int failures = 0;
|
||||
|
||||
void fail(int line, const char* what) {
|
||||
std::fprintf(stderr, "xcrdapi_abi:%d: %s (Win32 error %lu)\n", line, what, static_cast<unsigned long>(GetLastError()));
|
||||
++failures;
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
fail(__LINE__, #condition); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hand-typed IIDs. dstorage.h attaches them with __declspec(uuid(...)), which
|
||||
// MinGW ignores, and dstorage_mingw.h restates them for the shim; the values
|
||||
// here are typed independently from the header text and cross-checked against
|
||||
// Silk.NET's [Guid] attributes.
|
||||
// ---------------------------------------------------------------------------
|
||||
const IID kIID_File{0x5de95e7b, 0x955a, 0x4868, {0xa7, 0x3c, 0x24, 0x3b, 0x29, 0xf4, 0xb8, 0xda}};
|
||||
const IID kIID_Factory{0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}};
|
||||
const IID kIID_Factory1{0x1e0da17e, 0xb6d9, 0x4c17, {0x91, 0xb0, 0xe5, 0x7a, 0xe9, 0xbd, 0xa1, 0x2e}};
|
||||
const IID kIID_StatusArray{0x82397587, 0x7cd5, 0x453b, {0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56}};
|
||||
const IID kIID_Queue{0xcfdbd83f, 0x9e06, 0x4fda, {0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b}};
|
||||
const IID kIID_Queue1{0xdd2f482c, 0x5eff, 0x41e8, {0x9c, 0x9e, 0xd2, 0x37, 0x4b, 0x27, 0x81, 0x28}};
|
||||
const IID kIID_Queue2{0xb1c9d643, 0x3a49, 0x44a2, {0xb4, 0x6f, 0x65, 0x36, 0x49, 0x47, 0x0d, 0x18}};
|
||||
const IID kIID_Queue3{0xdeb54c52, 0xeca8, 0x46b3, {0x82, 0xa7, 0x03, 0x1b, 0x72, 0x26, 0x26, 0x53}};
|
||||
const IID kIID_Queue4{0x639ff1a7, 0x739e, 0x4291, {0xb6, 0x72, 0xc7, 0x21, 0xc5, 0xf2, 0xa3, 0xda}};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Slot numbers, transcribed from the header's declaration order.
|
||||
// ---------------------------------------------------------------------------
|
||||
enum : size_t { kSlotQueryInterface = 0, kSlotAddRef = 1, kSlotRelease = 2 };
|
||||
|
||||
namespace file_slot {
|
||||
enum : size_t { kClose = 3, kGetFileInformation = 4, kCount = 5 };
|
||||
}
|
||||
namespace factory_slot {
|
||||
enum : size_t {
|
||||
kCreateQueue = 3,
|
||||
kOpenFile = 4,
|
||||
kCreateStatusArray = 5,
|
||||
kSetDebugFlags = 6,
|
||||
kSetStagingBufferSize = 7,
|
||||
kCount = 8,
|
||||
};
|
||||
}
|
||||
namespace factory1_slot {
|
||||
enum : size_t { kCreateQueue1 = 8, kCount = 9 };
|
||||
}
|
||||
namespace status_slot {
|
||||
enum : size_t { kIsComplete = 3, kGetHResult = 4, kCount = 5 };
|
||||
}
|
||||
namespace queue_slot {
|
||||
enum : size_t {
|
||||
kEnqueueRequest = 3,
|
||||
kEnqueueStatus = 4,
|
||||
kEnqueueSignal = 5,
|
||||
kSubmit = 6,
|
||||
kCancelRequestsWithTag = 7,
|
||||
kClose = 8,
|
||||
kGetErrorEvent = 9,
|
||||
kRetrieveErrorRecord = 10,
|
||||
kQuery = 11,
|
||||
kCount = 12,
|
||||
};
|
||||
}
|
||||
namespace queue1_slot {
|
||||
enum : size_t { kEnqueueSetEvent = 12, kCount = 13 };
|
||||
}
|
||||
namespace queue2_slot {
|
||||
enum : size_t { kGetCompressionSupport = 13, kCount = 14 };
|
||||
}
|
||||
namespace queue3_slot {
|
||||
enum : size_t { kEnqueueRequests = 14, kCount = 15 };
|
||||
}
|
||||
namespace queue4_slot {
|
||||
enum : size_t { kQuery1 = 15, kCount = 16 };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The C vtable: slots are read straight out of the object.
|
||||
// ---------------------------------------------------------------------------
|
||||
void** slots(void* object) {
|
||||
return *static_cast<void***>(object);
|
||||
}
|
||||
|
||||
template<class Fn>
|
||||
Fn method(void* object, size_t slot) {
|
||||
return reinterpret_cast<Fn>(slots(object)[slot]);
|
||||
}
|
||||
|
||||
// IUnknown, and the (UINT64, UINT64) pair shared by CancelRequestsWithTag.
|
||||
using QueryInterfaceFn = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**);
|
||||
using AddRefFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
|
||||
using FileCloseFn = void(STDMETHODCALLTYPE*)(void*);
|
||||
using GetFileInformationFn = HRESULT(STDMETHODCALLTYPE*)(void*, BY_HANDLE_FILE_INFORMATION*);
|
||||
|
||||
using CreateQueueFn = HRESULT(STDMETHODCALLTYPE*)(void*, const DSTORAGE_QUEUE_DESC*, REFIID, void**);
|
||||
using OpenFileFn = HRESULT(STDMETHODCALLTYPE*)(void*, const WCHAR*, REFIID, void**);
|
||||
using CreateStatusArrayFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT32, PCSTR, REFIID, void**);
|
||||
using SetDebugFlagsFn = void(STDMETHODCALLTYPE*)(void*, UINT32);
|
||||
using SetStagingBufferSizeFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT32);
|
||||
using CreateQueue1Fn = HRESULT(STDMETHODCALLTYPE*)(void*, const DSTORAGE_QUEUE_DESC1*, REFIID, void**);
|
||||
|
||||
using IsCompleteFn = bool(STDMETHODCALLTYPE*)(void*, UINT32);
|
||||
using GetHResultFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT32);
|
||||
|
||||
using EnqueueRequestFn = void(STDMETHODCALLTYPE*)(void*, const DSTORAGE_REQUEST*);
|
||||
using EnqueueStatusFn = void(STDMETHODCALLTYPE*)(void*, IDStorageStatusArray*, UINT32);
|
||||
using EnqueueSignalFn = void(STDMETHODCALLTYPE*)(void*, ID3D12Fence*, UINT64);
|
||||
using SubmitFn = void(STDMETHODCALLTYPE*)(void*);
|
||||
using CancelRequestsWithTagFn = void(STDMETHODCALLTYPE*)(void*, UINT64, UINT64);
|
||||
using QueueCloseFn = void(STDMETHODCALLTYPE*)(void*);
|
||||
using GetErrorEventFn = HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using RetrieveErrorRecordFn = void(STDMETHODCALLTYPE*)(void*, DSTORAGE_ERROR_RECORD*);
|
||||
using QueryFn = void(STDMETHODCALLTYPE*)(void*, DSTORAGE_QUEUE_INFO*);
|
||||
using EnqueueSetEventFn = void(STDMETHODCALLTYPE*)(void*, HANDLE);
|
||||
using GetCompressionSupportFn = DSTORAGE_COMPRESSION_SUPPORT(STDMETHODCALLTYPE*)(
|
||||
void*, DSTORAGE_COMPRESSION_FORMAT);
|
||||
using EnqueueRequestsFn = void(STDMETHODCALLTYPE*)(void*, const DSTORAGE_REQUEST*, UINT,
|
||||
ID3D12Fence*, UINT64,
|
||||
DSTORAGE_ENQUEUE_REQUEST_FLAGS);
|
||||
using Query1Fn = void(STDMETHODCALLTYPE*)(void*, DSTORAGE_QUEUE_INFO1*);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes reached through hand-built C vtables: no C++ class is involved, so a
|
||||
// wrong slot in the shim cannot be absorbed by a matching C++ declaration.
|
||||
// ---------------------------------------------------------------------------
|
||||
struct FakeStatusArray {
|
||||
void** vtbl;
|
||||
};
|
||||
|
||||
HRESULT STDMETHODCALLTYPE fake_status_qi(void*, REFIID, void** out) {
|
||||
if (out) *out = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE fake_status_addref(void*) { return 1; }
|
||||
ULONG STDMETHODCALLTYPE fake_status_release(void*) { return 1; }
|
||||
bool STDMETHODCALLTYPE fake_status_is_complete(void*, UINT32) { return false; }
|
||||
HRESULT STDMETHODCALLTYPE fake_status_get_hresult(void*, UINT32) { return E_PENDING; }
|
||||
|
||||
void* fake_status_vtbl[] = {
|
||||
reinterpret_cast<void*>(static_cast<QueryInterfaceFn>(fake_status_qi)),
|
||||
reinterpret_cast<void*>(static_cast<AddRefFn>(fake_status_addref)),
|
||||
reinterpret_cast<void*>(static_cast<ReleaseFn>(fake_status_release)),
|
||||
reinterpret_cast<void*>(static_cast<IsCompleteFn>(fake_status_is_complete)),
|
||||
reinterpret_cast<void*>(static_cast<GetHResultFn>(fake_status_get_hresult)),
|
||||
};
|
||||
|
||||
// ID3D12Fence, in the public d3d12.h order: IUnknown 0..2, GetPrivateData 3,
|
||||
// SetPrivateData 4, SetPrivateDataInterface 5, SetName 6, GetDevice 7,
|
||||
// GetCompletedValue 8, SetEventOnCompletion 9, Signal 10.
|
||||
struct FakeFence {
|
||||
void** vtbl;
|
||||
LONG refs;
|
||||
UINT64 signalled;
|
||||
LONG signals;
|
||||
};
|
||||
|
||||
HRESULT STDMETHODCALLTYPE fence_qi(void*, REFIID, void** out) {
|
||||
if (out) *out = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE fence_addref(void* self) {
|
||||
return static_cast<ULONG>(InterlockedIncrement(&static_cast<FakeFence*>(self)->refs));
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE fence_release(void* self) {
|
||||
return static_cast<ULONG>(InterlockedDecrement(&static_cast<FakeFence*>(self)->refs));
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE fence_private(void*, REFGUID, UINT, const void*) { return E_NOTIMPL; }
|
||||
HRESULT STDMETHODCALLTYPE fence_private_set(void*, REFGUID, UINT, const void*) { return E_NOTIMPL; }
|
||||
HRESULT STDMETHODCALLTYPE fence_private_interface(void*, REFGUID, const IUnknown*) { return E_NOTIMPL; }
|
||||
HRESULT STDMETHODCALLTYPE fence_set_name(void*, LPCWSTR) { return E_NOTIMPL; }
|
||||
HRESULT STDMETHODCALLTYPE fence_get_device(void*, REFIID, void**) { return E_NOTIMPL; }
|
||||
UINT64 STDMETHODCALLTYPE fence_completed(void*, UINT64) { return 0; }
|
||||
HRESULT STDMETHODCALLTYPE fence_set_event(void*, UINT64, HANDLE) { return E_NOTIMPL; }
|
||||
HRESULT STDMETHODCALLTYPE fence_signal(void* self, UINT64 value) {
|
||||
auto* fence = static_cast<FakeFence*>(self);
|
||||
fence->signalled = value;
|
||||
InterlockedIncrement(&fence->signals);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
void* fake_fence_vtbl[] = {
|
||||
reinterpret_cast<void*>(static_cast<QueryInterfaceFn>(fence_qi)),
|
||||
reinterpret_cast<void*>(static_cast<AddRefFn>(fence_addref)),
|
||||
reinterpret_cast<void*>(static_cast<ReleaseFn>(fence_release)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<HRESULT(STDMETHODCALLTYPE*)(void*, REFGUID, UINT, const void*)>(
|
||||
fence_private)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<HRESULT(STDMETHODCALLTYPE*)(void*, REFGUID, UINT, const void*)>(
|
||||
fence_private_set)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<HRESULT(STDMETHODCALLTYPE*)(void*, REFGUID, const IUnknown*)>(
|
||||
fence_private_interface)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<HRESULT(STDMETHODCALLTYPE*)(void*, LPCWSTR)>(fence_set_name)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**)>(
|
||||
fence_get_device)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<UINT64(STDMETHODCALLTYPE*)(void*, UINT64)>(fence_completed)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE)>(
|
||||
fence_set_event)),
|
||||
reinterpret_cast<void*>(reinterpret_cast<HRESULT(STDMETHODCALLTYPE*)(void*, UINT64)>(fence_signal)),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers.
|
||||
// ---------------------------------------------------------------------------
|
||||
struct SlotName {
|
||||
size_t slot;
|
||||
const char* name;
|
||||
};
|
||||
|
||||
// Reads the current reference count through slots 1 and 2, leaving it as it was.
|
||||
ULONG live_refs(void* object, AddRefFn add_ref, ReleaseFn release) {
|
||||
const ULONG held = add_ref(object);
|
||||
release(object);
|
||||
return held - 1;
|
||||
}
|
||||
|
||||
// Every slot of one interface must be a different function: a vtable that
|
||||
// repeats one pointer cannot serve the header's method order.
|
||||
int check_distinct(const char* interface_name, void* object, size_t count) {
|
||||
void** vtbl = slots(object);
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
for (size_t j = i + 1; j < count; ++j) {
|
||||
if (vtbl[i] == vtbl[j]) {
|
||||
std::fprintf(stderr, "xcrdapi_abi: %s slots %zu and %zu share a method\n",
|
||||
interface_name, i, j);
|
||||
++failures;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void print_table(const char* interface_name, const SlotName* names, size_t count) {
|
||||
std::printf("%s: %zu slots\n", interface_name, count);
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
std::printf(" [%2zu] %s\n", names[i].slot, names[i].name);
|
||||
}
|
||||
}
|
||||
|
||||
const SlotName kFileSlots[] = {
|
||||
{kSlotQueryInterface, "QueryInterface"}, {kSlotAddRef, "AddRef"},
|
||||
{kSlotRelease, "Release"}, {file_slot::kClose, "Close"},
|
||||
{file_slot::kGetFileInformation, "GetFileInformation"},
|
||||
};
|
||||
const SlotName kFactorySlots[] = {
|
||||
{kSlotQueryInterface, "QueryInterface"}, {kSlotAddRef, "AddRef"},
|
||||
{kSlotRelease, "Release"}, {factory_slot::kCreateQueue, "CreateQueue"},
|
||||
{factory_slot::kOpenFile, "OpenFile"},
|
||||
{factory_slot::kCreateStatusArray, "CreateStatusArray"},
|
||||
{factory_slot::kSetDebugFlags, "SetDebugFlags"},
|
||||
{factory_slot::kSetStagingBufferSize, "SetStagingBufferSize"},
|
||||
{factory1_slot::kCreateQueue1, "CreateQueue1"},
|
||||
};
|
||||
const SlotName kStatusSlots[] = {
|
||||
{kSlotQueryInterface, "QueryInterface"}, {kSlotAddRef, "AddRef"},
|
||||
{kSlotRelease, "Release"}, {status_slot::kIsComplete, "IsComplete"},
|
||||
{status_slot::kGetHResult, "GetHResult"},
|
||||
};
|
||||
const SlotName kQueueSlots[] = {
|
||||
{kSlotQueryInterface, "QueryInterface"},
|
||||
{kSlotAddRef, "AddRef"},
|
||||
{kSlotRelease, "Release"},
|
||||
{queue_slot::kEnqueueRequest, "EnqueueRequest"},
|
||||
{queue_slot::kEnqueueStatus, "EnqueueStatus"},
|
||||
{queue_slot::kEnqueueSignal, "EnqueueSignal"},
|
||||
{queue_slot::kSubmit, "Submit"},
|
||||
{queue_slot::kCancelRequestsWithTag, "CancelRequestsWithTag"},
|
||||
{queue_slot::kClose, "Close"},
|
||||
{queue_slot::kGetErrorEvent, "GetErrorEvent"},
|
||||
{queue_slot::kRetrieveErrorRecord, "RetrieveErrorRecord"},
|
||||
{queue_slot::kQuery, "Query"},
|
||||
{queue1_slot::kEnqueueSetEvent, "EnqueueSetEvent"},
|
||||
{queue2_slot::kGetCompressionSupport, "GetCompressionSupport"},
|
||||
{queue3_slot::kEnqueueRequests, "EnqueueRequests"},
|
||||
{queue4_slot::kQuery1, "Query1"},
|
||||
};
|
||||
|
||||
DSTORAGE_REQUEST memory_to_memory(const void* source, void* destination, UINT32 size) {
|
||||
DSTORAGE_REQUEST request{};
|
||||
request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;
|
||||
request.Source.Memory.Source = source;
|
||||
request.Source.Memory.Size = size;
|
||||
request.Destination.Memory.Buffer = destination;
|
||||
request.Destination.Memory.Size = size;
|
||||
return request;
|
||||
}
|
||||
|
||||
struct TemporaryFile {
|
||||
WCHAR name[MAX_PATH]{};
|
||||
~TemporaryFile() {
|
||||
if (*name) DeleteFileW(name);
|
||||
}
|
||||
};
|
||||
|
||||
int write_file(TemporaryFile* file, const char* contents, DWORD size) {
|
||||
WCHAR directory[MAX_PATH];
|
||||
const DWORD length = GetTempPathW(MAX_PATH, directory);
|
||||
CHECK(length && length < MAX_PATH);
|
||||
CHECK(GetTempFileNameW(directory, L"bxa", 0, file->name));
|
||||
const HANDLE writer = CreateFileW(file->name, GENERIC_WRITE, 0, nullptr, TRUNCATE_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
CHECK(writer != INVALID_HANDLE_VALUE);
|
||||
DWORD written = 0;
|
||||
const BOOL wrote = WriteFile(writer, contents, size, &written, nullptr);
|
||||
CloseHandle(writer);
|
||||
CHECK(wrote && written == size);
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct Event {
|
||||
HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
~Event() {
|
||||
if (handle) CloseHandle(handle);
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IDStorageFactory / IDStorageFactory1.
|
||||
// ---------------------------------------------------------------------------
|
||||
int check_factory(void* factory, TemporaryFile* file, const char* contents) {
|
||||
// Slot 0/1/2: IUnknown. The factory answers Identity for its own IIDs and
|
||||
// for the private "same implementation" IID the shim's wrappers use, so
|
||||
// QueryInterface(IDStorageFactory1) returns the same object.
|
||||
auto query_interface = method<QueryInterfaceFn>(factory, kSlotQueryInterface);
|
||||
auto add_ref = method<AddRefFn>(factory, kSlotAddRef);
|
||||
auto release = method<ReleaseFn>(factory, kSlotRelease);
|
||||
|
||||
// Refcount arithmetic is checked against a read of the count itself, not
|
||||
// against an absolute number that depends on how DStorageGetFactory
|
||||
// returned the object.
|
||||
const ULONG base = live_refs(factory, add_ref, release);
|
||||
|
||||
void* as_factory1 = nullptr;
|
||||
CHECK(query_interface(factory, kIID_Factory1, &as_factory1) == S_OK && as_factory1 == factory);
|
||||
CHECK(live_refs(factory, add_ref, release) == base + 1);
|
||||
CHECK(query_interface(factory, kIID_Factory, &as_factory1) == S_OK && as_factory1 == factory);
|
||||
CHECK(live_refs(factory, add_ref, release) == base + 2);
|
||||
const IID unknown{0x0badf00d, 0x1234, 0x4abc, {0x80, 1, 2, 3, 4, 5, 6, 7}};
|
||||
void* refused = reinterpret_cast<void*>(1);
|
||||
CHECK(query_interface(factory, unknown, &refused) == E_NOINTERFACE && !refused);
|
||||
CHECK(live_refs(factory, add_ref, release) == base + 2);
|
||||
CHECK(release(factory) == base + 1);
|
||||
CHECK(release(factory) == base);
|
||||
|
||||
auto create_queue = method<CreateQueueFn>(factory, factory_slot::kCreateQueue);
|
||||
auto open_file = method<OpenFileFn>(factory, factory_slot::kOpenFile);
|
||||
auto create_status = method<CreateStatusArrayFn>(factory, factory_slot::kCreateStatusArray);
|
||||
auto set_debug_flags = method<SetDebugFlagsFn>(factory, factory_slot::kSetDebugFlags);
|
||||
auto set_staging = method<SetStagingBufferSizeFn>(factory, factory_slot::kSetStagingBufferSize);
|
||||
auto create_queue1 = method<CreateQueue1Fn>(factory, factory1_slot::kCreateQueue1);
|
||||
|
||||
DSTORAGE_QUEUE_DESC desc{};
|
||||
desc.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
desc.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
|
||||
desc.Priority = DSTORAGE_PRIORITY_NORMAL;
|
||||
desc.Name = "xcrdapi abi";
|
||||
|
||||
// Slot 3 must be CreateQueue: it validates capacity (127 is below the
|
||||
// header's DSTORAGE_MIN_QUEUE_CAPACITY) and priority.
|
||||
DSTORAGE_QUEUE_DESC bad = desc;
|
||||
bad.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY - 1;
|
||||
void* rejected = reinterpret_cast<void*>(1);
|
||||
CHECK(create_queue(factory, &bad, kIID_Queue, &rejected) == E_DSTORAGE_INVALID_QUEUE_CAPACITY
|
||||
&& !rejected);
|
||||
bad = desc;
|
||||
bad.Priority = static_cast<DSTORAGE_PRIORITY>(DSTORAGE_PRIORITY_LAST + 1);
|
||||
CHECK(create_queue(factory, &bad, kIID_Queue, &rejected) == E_DSTORAGE_INVALID_QUEUE_PRIORITY);
|
||||
|
||||
// Slot 4 must be OpenFile: a missing path is a Win32 file error, not a
|
||||
// queue-capacity error, which is what distinguishes the two slots.
|
||||
void* no_file = reinterpret_cast<void*>(1);
|
||||
const HRESULT missing = open_file(factory, L"Z:\\bx597\\does-not-exist.bin", kIID_File, &no_file);
|
||||
CHECK(FAILED(missing) && missing != E_DSTORAGE_INVALID_QUEUE_CAPACITY && !no_file);
|
||||
CHECK(open_file(factory, nullptr, kIID_File, &no_file) == E_INVALIDARG);
|
||||
|
||||
// Slot 5 must be CreateStatusArray: capacity first, then the optional
|
||||
// name, then the IID and the out pointer.
|
||||
void* no_status = nullptr;
|
||||
CHECK(create_status(factory, 0, "abi", kIID_StatusArray, &no_status) == E_INVALIDARG && !no_status);
|
||||
|
||||
// Slot 6 must be SetDebugFlags: void, one UINT32. It has no observable
|
||||
// state in the shim, so the check is that the factory still works.
|
||||
set_debug_flags(factory, DSTORAGE_DEBUG_SHOW_ERRORS | DSTORAGE_DEBUG_BREAK_ON_ERROR);
|
||||
|
||||
// Slot 7 must be SetStagingBufferSize: HRESULT, one UINT32.
|
||||
CHECK(set_staging(factory, DSTORAGE_STAGING_BUFFER_SIZE_32MB) == S_OK);
|
||||
|
||||
// Slot 8 (IDStorageFactory1) must be CreateQueue1: UsesGaclShuffleTransform
|
||||
// exists only on DSTORAGE_QUEUE_DESC1, and a queue created by slot 3 can
|
||||
// never see it.
|
||||
DSTORAGE_QUEUE_DESC1 desc1{};
|
||||
desc1.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
desc1.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
|
||||
desc1.Priority = DSTORAGE_PRIORITY_NORMAL;
|
||||
desc1.CompressionFormat = DSTORAGE_COMPRESSION_FORMAT_NONE;
|
||||
desc1.UsesGaclShuffleTransform = TRUE;
|
||||
void* no_queue = nullptr;
|
||||
CHECK(create_queue1(factory, &desc1, kIID_Queue, &no_queue) == E_NOTIMPL && !no_queue);
|
||||
desc1.UsesGaclShuffleTransform = FALSE;
|
||||
DSTORAGE_QUEUE_DESC1 short_queue = desc1;
|
||||
short_queue.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY - 1;
|
||||
CHECK(create_queue1(factory, &short_queue, kIID_Queue, &no_queue)
|
||||
== E_DSTORAGE_INVALID_QUEUE_CAPACITY);
|
||||
|
||||
// Slot 4 produces a real IDStorageFile; its own table is checked next.
|
||||
void* opened = nullptr;
|
||||
CHECK(open_file(factory, file->name, kIID_File, &opened) == S_OK && opened);
|
||||
|
||||
auto file_close = method<FileCloseFn>(opened, file_slot::kClose);
|
||||
auto file_info = method<GetFileInformationFn>(opened, file_slot::kGetFileInformation);
|
||||
auto file_release = method<ReleaseFn>(opened, kSlotRelease);
|
||||
CHECK(check_distinct("IDStorageFile", opened, file_slot::kCount) == 0);
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
CHECK(file_info(opened, &info) == S_OK && info.nFileSizeLow == std::strlen(contents));
|
||||
CHECK(file_info(opened, nullptr) == E_POINTER);
|
||||
// Slot 3 is void Close(); afterwards slot 4 reports an invalid handle.
|
||||
file_close(opened);
|
||||
CHECK(file_info(opened, &info) == HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE));
|
||||
CHECK(file_release(opened) == 0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IDStorageStatusArray.
|
||||
// ---------------------------------------------------------------------------
|
||||
int check_status_array(void* factory) {
|
||||
auto create_status = method<CreateStatusArrayFn>(factory, factory_slot::kCreateStatusArray);
|
||||
void* status = nullptr;
|
||||
CHECK(create_status(factory, 2, "xcrdapi abi", kIID_StatusArray, &status) == S_OK && status);
|
||||
CHECK(check_distinct("IDStorageStatusArray", status, status_slot::kCount) == 0);
|
||||
|
||||
auto is_complete = method<IsCompleteFn>(status, status_slot::kIsComplete);
|
||||
auto get_hresult = method<GetHResultFn>(status, status_slot::kGetHResult);
|
||||
// The header: "This is equivalent to GetHResult(index) != E_PENDING".
|
||||
CHECK(get_hresult(status, 0) == E_PENDING);
|
||||
CHECK(is_complete(status, 0) == false);
|
||||
CHECK(get_hresult(status, 2) == E_INVALIDARG);
|
||||
CHECK(is_complete(status, 2) == true);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// IDStorageQueue … IDStorageQueue4.
|
||||
// ---------------------------------------------------------------------------
|
||||
int check_queue(void* factory, void* status) {
|
||||
auto create_queue = method<CreateQueueFn>(factory, factory_slot::kCreateQueue);
|
||||
DSTORAGE_QUEUE_DESC desc{};
|
||||
desc.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
desc.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
|
||||
desc.Priority = DSTORAGE_PRIORITY_NORMAL;
|
||||
desc.Name = "xcrdapi abi queue";
|
||||
void* queue = nullptr;
|
||||
CHECK(create_queue(factory, &desc, kIID_Queue, &queue) == S_OK && queue);
|
||||
CHECK(check_distinct("IDStorageQueue4", queue, queue4_slot::kCount) == 0);
|
||||
|
||||
auto query_interface = method<QueryInterfaceFn>(queue, kSlotQueryInterface);
|
||||
auto add_ref = method<AddRefFn>(queue, kSlotAddRef);
|
||||
auto release = method<ReleaseFn>(queue, kSlotRelease);
|
||||
|
||||
// One implementation serves every queue level, so each IID resolves to the
|
||||
// same object and therefore the same vtable. A wrong slot here would call
|
||||
// a different method with a REFIID and a void** out pointer.
|
||||
const ULONG base = live_refs(queue, add_ref, release);
|
||||
for (const IID* iid : {&kIID_Queue, &kIID_Queue1, &kIID_Queue2, &kIID_Queue3, &kIID_Queue4}) {
|
||||
void* level = nullptr;
|
||||
CHECK(query_interface(queue, *iid, &level) == S_OK && level == queue);
|
||||
release(level);
|
||||
}
|
||||
CHECK(live_refs(queue, add_ref, release) == base);
|
||||
void* refused = reinterpret_cast<void*>(1);
|
||||
const IID unknown{0x0badf00d, 0x1234, 0x4abc, {0x80, 1, 2, 3, 4, 5, 6, 7}};
|
||||
CHECK(query_interface(queue, unknown, &refused) == E_NOINTERFACE && !refused);
|
||||
CHECK(live_refs(queue, add_ref, release) == base);
|
||||
|
||||
auto enqueue_request = method<EnqueueRequestFn>(queue, queue_slot::kEnqueueRequest);
|
||||
auto enqueue_status = method<EnqueueStatusFn>(queue, queue_slot::kEnqueueStatus);
|
||||
auto enqueue_signal = method<EnqueueSignalFn>(queue, queue_slot::kEnqueueSignal);
|
||||
auto submit = method<SubmitFn>(queue, queue_slot::kSubmit);
|
||||
auto cancel = method<CancelRequestsWithTagFn>(queue, queue_slot::kCancelRequestsWithTag);
|
||||
auto close = method<QueueCloseFn>(queue, queue_slot::kClose);
|
||||
auto error_event = method<GetErrorEventFn>(queue, queue_slot::kGetErrorEvent);
|
||||
auto error_record = method<RetrieveErrorRecordFn>(queue, queue_slot::kRetrieveErrorRecord);
|
||||
auto query = method<QueryFn>(queue, queue_slot::kQuery);
|
||||
auto set_event = method<EnqueueSetEventFn>(queue, queue1_slot::kEnqueueSetEvent);
|
||||
auto compression = method<GetCompressionSupportFn>(queue, queue2_slot::kGetCompressionSupport);
|
||||
auto enqueue_requests = method<EnqueueRequestsFn>(queue, queue3_slot::kEnqueueRequests);
|
||||
auto query1 = method<Query1Fn>(queue, queue4_slot::kQuery1);
|
||||
|
||||
// Slot 11: DSTORAGE_QUEUE_INFO. The header: a queue with capacity N
|
||||
// reports N - 1 empty slots and auto-submits at half capacity.
|
||||
DSTORAGE_QUEUE_INFO info{};
|
||||
query(queue, &info);
|
||||
CHECK(info.Desc.Capacity == DSTORAGE_MIN_QUEUE_CAPACITY);
|
||||
CHECK(info.Desc.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY);
|
||||
CHECK(info.Desc.Priority == DSTORAGE_PRIORITY_NORMAL);
|
||||
CHECK(info.Desc.Name && std::strcmp(info.Desc.Name, "xcrdapi abi queue") == 0);
|
||||
CHECK(info.EmptySlotCount == DSTORAGE_MIN_QUEUE_CAPACITY - 1);
|
||||
CHECK(info.RequestCountUntilAutoSubmit == DSTORAGE_MIN_QUEUE_CAPACITY / 2);
|
||||
query(queue, nullptr);
|
||||
|
||||
// Slot 15: DSTORAGE_QUEUE_INFO1, which slot 11 cannot write (its
|
||||
// DSTORAGE_QUEUE_INFO is shorter, so an EnqueueStatus there would have
|
||||
// crashed on the flag word below).
|
||||
DSTORAGE_QUEUE_INFO1 info1{};
|
||||
std::memset(&info1, 0xCD, sizeof(info1));
|
||||
query1(queue, &info1);
|
||||
CHECK(info1.Desc.Capacity == DSTORAGE_MIN_QUEUE_CAPACITY);
|
||||
CHECK(info1.Desc.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY);
|
||||
CHECK(info1.Desc.UsesGaclShuffleTransform == FALSE);
|
||||
CHECK(info1.EmptySlotCount == DSTORAGE_MIN_QUEUE_CAPACITY - 1);
|
||||
CHECK(info1.RequestCountUntilAutoSubmit == DSTORAGE_MIN_QUEUE_CAPACITY / 2);
|
||||
query1(queue, nullptr);
|
||||
|
||||
// Slot 13: GetCompressionSupport returns DSTORAGE_COMPRESSION_SUPPORT.
|
||||
CHECK(compression(queue, DSTORAGE_COMPRESSION_FORMAT_GDEFLATE) == DSTORAGE_COMPRESSION_SUPPORT_NONE);
|
||||
CHECK(compression(queue, DSTORAGE_COMPRESSION_FORMAT_ZSTD) == DSTORAGE_COMPRESSION_SUPPORT_NONE);
|
||||
|
||||
// Slot 9/10: the error event and its record. A fresh queue has neither.
|
||||
const HANDLE event = error_event(queue);
|
||||
CHECK(event && event != INVALID_HANDLE_VALUE);
|
||||
CHECK(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
|
||||
DSTORAGE_ERROR_RECORD record{};
|
||||
std::memset(&record, 0xA5, sizeof(record));
|
||||
error_record(queue, &record);
|
||||
CHECK(record.FailureCount == 0);
|
||||
CHECK(record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_NONE);
|
||||
CHECK(record.FirstFailure.HResult == S_OK);
|
||||
error_record(queue, nullptr);
|
||||
|
||||
// Slot 3: EnqueueRequest, then slot 4: EnqueueStatus with the index as a
|
||||
// separate argument, then slot 12: EnqueueSetEvent. Nothing runs before
|
||||
// slot 6 Submit.
|
||||
const char source[4] = {'a', 'b', 'c', 'd'};
|
||||
char first[4] = {};
|
||||
char second[4] = {};
|
||||
char third[4] = {};
|
||||
char fourth[4] = {};
|
||||
Event done;
|
||||
CHECK(done.handle);
|
||||
DSTORAGE_REQUEST one = memory_to_memory(source, first, 4);
|
||||
enqueue_request(queue, &one);
|
||||
enqueue_request(queue, nullptr); // rejected, recorded in queue order
|
||||
FakeStatusArray foreign{fake_status_vtbl};
|
||||
enqueue_status(queue, reinterpret_cast<IDStorageStatusArray*>(&foreign), 1);
|
||||
enqueue_status(queue, static_cast<IDStorageStatusArray*>(status), 0);
|
||||
DSTORAGE_REQUEST two = memory_to_memory(source + 0, second, 4);
|
||||
enqueue_requests(queue, &two, 1, nullptr, 0, DSTORAGE_ENQUEUE_REQUEST_FLAG_NONE);
|
||||
FakeFence fence{fake_fence_vtbl, 1, 0, 0};
|
||||
enqueue_signal(queue, reinterpret_cast<ID3D12Fence*>(&fence), 7);
|
||||
set_event(queue, done.handle);
|
||||
|
||||
auto is_complete = method<IsCompleteFn>(status, status_slot::kIsComplete);
|
||||
auto get_hresult = method<GetHResultFn>(status, status_slot::kGetHResult);
|
||||
CHECK(is_complete(status, 0) == false);
|
||||
CHECK(get_hresult(status, 0) == E_PENDING);
|
||||
CHECK(std::memcmp(first, "\0\0\0\0", 4) == 0 && std::memcmp(second, "\0\0\0\0", 4) == 0);
|
||||
|
||||
submit(queue);
|
||||
if (WaitForSingleObject(done.handle, 10000) != WAIT_OBJECT_0) {
|
||||
// A vtable that swaps slot 6 with another void method (for example
|
||||
// CancelRequestsWithTag) never runs the batch: this is where it shows.
|
||||
std::fprintf(stderr, "xcrdapi_abi: queue slot 6 (Submit) did not submit\n");
|
||||
++failures;
|
||||
return 1;
|
||||
}
|
||||
CHECK(is_complete(status, 0) == true);
|
||||
// The header: the status entry reports "the failure code of the first failed
|
||||
// request in the enqueue order" since the previous status entry, so the null
|
||||
// request enqueued between the two status entries gives entry 0 E_INVALIDARG.
|
||||
CHECK(get_hresult(status, 0) == E_INVALIDARG);
|
||||
CHECK(std::memcmp(first, source, 4) == 0);
|
||||
CHECK(std::memcmp(second, source, 4) == 0);
|
||||
// Slot 5 EnqueueSignal reached the fence through ID3D12Fence slot 10, and
|
||||
// the queue balanced its AddRef.
|
||||
CHECK(fence.signalled == 7 && fence.signals == 1 && fence.refs == 1);
|
||||
|
||||
// Slot 9 and 10: the two rejected commands (a null request, then a foreign
|
||||
// status array) are reported with the first one's HRESULT and kind, and
|
||||
// retrieving the record clears the event.
|
||||
CHECK(WaitForSingleObject(event, 0) == WAIT_OBJECT_0);
|
||||
error_record(queue, &record);
|
||||
CHECK(record.FailureCount == 2);
|
||||
CHECK(record.FirstFailure.HResult == E_INVALIDARG);
|
||||
CHECK(record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_REQUEST);
|
||||
CHECK(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
|
||||
|
||||
// Slot 7: CancelRequestsWithTag is accepted and, in this shim, cancels
|
||||
// nothing; the next request still copies.
|
||||
cancel(queue, 0xFFFFFFFFFFFFFFFFull, 0);
|
||||
DSTORAGE_REQUEST three = memory_to_memory(source, third, 4);
|
||||
enqueue_request(queue, &three);
|
||||
enqueue_status(queue, static_cast<IDStorageStatusArray*>(status), 1);
|
||||
set_event(queue, done.handle);
|
||||
submit(queue);
|
||||
CHECK(WaitForSingleObject(done.handle, 10000) == WAIT_OBJECT_0);
|
||||
CHECK(get_hresult(status, 1) == S_OK);
|
||||
CHECK(std::memcmp(third, source, 4) == 0);
|
||||
|
||||
// Slot 8: Close drains, and later enqueues are dropped.
|
||||
close(queue);
|
||||
DSTORAGE_REQUEST four = memory_to_memory(source, fourth, 4);
|
||||
enqueue_request(queue, &four);
|
||||
submit(queue);
|
||||
CHECK(std::memcmp(fourth, "\0\0\0\0", 4) == 0);
|
||||
close(queue);
|
||||
|
||||
release(queue);
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// Unbuffered, so the slot table and every failure line survive an abort.
|
||||
std::setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
std::setvbuf(stderr, nullptr, _IONBF, 0);
|
||||
std::printf("xcrdapi_abi: slot tables (dstorage.h 1.4.0 declaration order)\n");
|
||||
print_table("IDStorageFile", kFileSlots, file_slot::kCount);
|
||||
print_table("IDStorageFactory1", kFactorySlots, factory1_slot::kCount);
|
||||
print_table("IDStorageStatusArray", kStatusSlots, status_slot::kCount);
|
||||
print_table("IDStorageQueue4", kQueueSlots, queue4_slot::kCount);
|
||||
|
||||
// DStorageGetFactory creates a factory per call; both public factory IIDs
|
||||
// must be served, and the object must answer its own table.
|
||||
void* factory = nullptr;
|
||||
if (DStorageGetFactory(kIID_Factory, &factory) != S_OK || !factory) {
|
||||
std::fprintf(stderr, "xcrdapi_abi: DStorageGetFactory failed\n");
|
||||
return 1;
|
||||
}
|
||||
void* direct = nullptr;
|
||||
if (DStorageGetFactory(kIID_Factory1, &direct) != S_OK || !direct) {
|
||||
std::fprintf(stderr, "xcrdapi_abi: DStorageGetFactory(IDStorageFactory1) failed\n");
|
||||
return 1;
|
||||
}
|
||||
if (check_distinct("IDStorageFactory1 (direct)", direct, factory1_slot::kCount) != 0) return 1;
|
||||
if (method<ReleaseFn>(direct, kSlotRelease)(direct) != 0) {
|
||||
std::fprintf(stderr, "xcrdapi_abi: direct factory release did not reach zero\n");
|
||||
return 1;
|
||||
}
|
||||
if (check_distinct("IDStorageFactory1", factory, factory1_slot::kCount) != 0) return 1;
|
||||
if (check_distinct("IDStorageFactory", factory, factory_slot::kCount) != 0) return 1;
|
||||
|
||||
TemporaryFile file;
|
||||
constexpr char contents[] = "ABI597!";
|
||||
if (write_file(&file, contents, sizeof(contents) - 1) != 0) return 1;
|
||||
|
||||
if (check_factory(factory, &file, contents) != 0) return 1;
|
||||
if (check_status_array(factory) != 0) return 1;
|
||||
|
||||
// A second status array is created here so that the queue test can assert
|
||||
// one index per array index the header documents.
|
||||
auto create_status = method<CreateStatusArrayFn>(factory, factory_slot::kCreateStatusArray);
|
||||
void* status = nullptr;
|
||||
CHECK(create_status(factory, 2, "queue status", kIID_StatusArray, &status) == S_OK && status);
|
||||
if (check_queue(factory, status) != 0) return 1;
|
||||
|
||||
method<ReleaseFn>(status, kSlotRelease)(status);
|
||||
CHECK(method<ReleaseFn>(factory, kSlotRelease)(factory) == 0);
|
||||
|
||||
if (failures) {
|
||||
std::fprintf(stderr, "xcrdapi_abi: %d failure(s)\n", failures);
|
||||
return 1;
|
||||
}
|
||||
std::printf("test_xcrdapi_abi: passed\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Synthetic conformance test for Xbox Series DirectStorage COM interfaces (IDStorage*X).
|
||||
add_executable(test_xcrdapi_xbox main.cpp)
|
||||
target_compile_definitions(test_xcrdapi_xbox PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_include_directories(test_xcrdapi_xbox PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
|
||||
target_link_libraries(test_xcrdapi_xbox PRIVATE xcrdapi bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,390 @@
|
||||
/*
|
||||
* Synthetic conformance test for the inferred Xbox Series DirectStorage COM
|
||||
* interfaces (IDStorageFactoryX, IDStorageFileX, IDStorageStatusArrayX,
|
||||
* IDStorageQueueX) in XCRDAPI.dll.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "bx_log.h"
|
||||
/* Public DirectStorage header (SDK 1.4.0, MIT): used here only for the
|
||||
* PC-sized canary and the existing public DirectStorage error constants. */
|
||||
#include "dstorage.h"
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv);
|
||||
|
||||
struct XboxQueueDesc {
|
||||
UINT64 source_type;
|
||||
UINT16 capacity;
|
||||
INT8 priority;
|
||||
UINT8 reserved_pad[5];
|
||||
PCSTR name;
|
||||
UINT64 flags;
|
||||
};
|
||||
|
||||
struct XboxRequest {
|
||||
UINT64 options;
|
||||
void* destination;
|
||||
UINT64 destination_pad;
|
||||
UINT32 destination_size;
|
||||
UINT32 reserved1c;
|
||||
void* source_ptr;
|
||||
UINT64 file_offset;
|
||||
UINT32 source_size;
|
||||
UINT32 reserved34;
|
||||
};
|
||||
|
||||
struct IXboxDStorageFile : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageStatusArray : IUnknown {
|
||||
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageQueue : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueSignal(void* fence, UINT64 value) = 0;
|
||||
virtual void STDMETHODCALLTYPE Submit() = 0;
|
||||
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
|
||||
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(void* record) = 0;
|
||||
virtual void STDMETHODCALLTYPE Query(void* info) = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageFactory : IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
|
||||
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr IID kXboxFactoryIid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
|
||||
constexpr IID kXboxFileIid{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
|
||||
constexpr IID kXboxStatusArrayIid{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
|
||||
constexpr IID kXboxQueueIid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
|
||||
|
||||
int g_failed = 0;
|
||||
|
||||
void check(bool cond, const char* fmt, ...) {
|
||||
if (cond) return;
|
||||
++g_failed;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
std::fprintf(stderr, "FAIL: ");
|
||||
std::vfprintf(stderr, fmt, args);
|
||||
std::fprintf(stderr, "\n");
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
bool wait_complete(IXboxDStorageStatusArray* status, UINT32 index) {
|
||||
for (int i = 0; i < 500; ++i) {
|
||||
if (status->IsComplete(index)) return true;
|
||||
Sleep(10);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Reads only what this run appended: bx-cli run appends to a supplied BX_LOG_FILE,
|
||||
* so records from an earlier run must not satisfy these checks. */
|
||||
long g_log_start = 0;
|
||||
|
||||
long log_size(const char* path) {
|
||||
FILE* f = std::fopen(path, "rb");
|
||||
if (!f) return 0;
|
||||
std::fseek(f, 0, SEEK_END);
|
||||
const long size = std::ftell(f);
|
||||
std::fclose(f);
|
||||
return size < 0 ? 0 : size;
|
||||
}
|
||||
|
||||
bool file_contains(const char* path, const char* needle) {
|
||||
FILE* f = std::fopen(path, "rb");
|
||||
if (!f) return false;
|
||||
std::fseek(f, g_log_start, SEEK_SET);
|
||||
std::string text;
|
||||
char buf[4096];
|
||||
size_t n = 0;
|
||||
while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0) {
|
||||
text.append(buf, n);
|
||||
}
|
||||
std::fclose(f);
|
||||
return text.find(needle) != std::string::npos;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
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. */
|
||||
char log_path[MAX_PATH] = {};
|
||||
const DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (log_len == 0 || log_len >= sizeof(log_path)) {
|
||||
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
g_log_start = log_size(log_path);
|
||||
|
||||
IXboxDStorageFactory* factory = nullptr;
|
||||
HRESULT hr = DStorageGetFactory(kXboxFactoryIid, reinterpret_cast<void**>(&factory));
|
||||
check(hr == S_OK && factory != nullptr, "DStorageGetFactory(Xbox) must succeed (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
if (!factory) return 1;
|
||||
|
||||
/* Slot 8: SetStagingBufferSize (32 MiB, the size observed at target-build startup). */
|
||||
hr = factory->SetStagingBufferSize(0x2000000u);
|
||||
check(hr == S_OK, "SetStagingBufferSize(32 MiB) must return S_OK (hr=0x%08lx)", static_cast<unsigned long>(hr));
|
||||
|
||||
/* Negative queue creation checks. */
|
||||
XboxQueueDesc bad_cap{};
|
||||
bad_cap.source_type = 0;
|
||||
bad_cap.capacity = 1;
|
||||
IXboxDStorageQueue* bad_q = nullptr;
|
||||
check(FAILED(factory->CreateQueueX(&bad_cap, kXboxQueueIid, reinterpret_cast<void**>(&bad_q))) && !bad_q,
|
||||
"CreateQueueX with capacity 1 must fail");
|
||||
|
||||
XboxQueueDesc bad_src{};
|
||||
bad_src.source_type = 2;
|
||||
bad_src.capacity = 64;
|
||||
check(FAILED(factory->CreateQueueX(&bad_src, kXboxQueueIid, reinterpret_cast<void**>(&bad_q))) && !bad_q,
|
||||
"CreateQueueX with source_type 2 must fail");
|
||||
|
||||
/* Create temp file for file-to-memory read test. */
|
||||
WCHAR temp_dir[MAX_PATH] = {};
|
||||
WCHAR temp_file[MAX_PATH] = {};
|
||||
check(GetTempPathW(MAX_PATH, temp_dir) > 0, "GetTempPathW must succeed");
|
||||
check(GetTempFileNameW(temp_dir, L"bxx", 0, temp_file) != 0, "GetTempFileNameW must succeed");
|
||||
|
||||
uint8_t payload[256];
|
||||
for (size_t i = 0; i < sizeof(payload); ++i) {
|
||||
payload[i] = static_cast<uint8_t>((i * 37u + 11u) & 0xFFu);
|
||||
}
|
||||
HANDLE raw = CreateFileW(temp_file, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
check(raw != INVALID_HANDLE_VALUE, "CreateFileW for test payload must succeed");
|
||||
if (raw != INVALID_HANDLE_VALUE) {
|
||||
DWORD written = 0;
|
||||
check(WriteFile(raw, payload, sizeof(payload), &written, nullptr) && written == sizeof(payload),
|
||||
"WriteFile must write full payload");
|
||||
CloseHandle(raw);
|
||||
}
|
||||
|
||||
/* Slot 4: OpenFile. */
|
||||
IXboxDStorageFile* file = nullptr;
|
||||
hr = factory->OpenFile(temp_file, kXboxFileIid, reinterpret_cast<void**>(&file));
|
||||
check(hr == S_OK && file != nullptr, "OpenFile(Xbox) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
|
||||
if (file) {
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
hr = file->GetFileInformation(&info);
|
||||
check(hr == S_OK && info.nFileSizeLow == sizeof(payload) && info.nFileSizeHigh == 0,
|
||||
"GetFileInformation must report exact payload size");
|
||||
}
|
||||
|
||||
/* Slot 5: CreateStatusArray. */
|
||||
IXboxDStorageStatusArray* status = nullptr;
|
||||
hr = factory->CreateStatusArray(2, "xbox_test_status", kXboxStatusArrayIid, reinterpret_cast<void**>(&status));
|
||||
check(hr == S_OK && status != nullptr, "CreateStatusArray(Xbox) must succeed (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
if (status) {
|
||||
check(!status->IsComplete(0) && status->GetHResult(0) == E_PENDING,
|
||||
"fresh status slot must be pending");
|
||||
}
|
||||
|
||||
/* Slot 10: CreateQueueX (file source) and file-to-memory transfer. */
|
||||
XboxQueueDesc file_q_desc{};
|
||||
file_q_desc.source_type = 0;
|
||||
file_q_desc.capacity = 64;
|
||||
file_q_desc.priority = 0;
|
||||
file_q_desc.name = "xbox_file_queue";
|
||||
file_q_desc.flags = 1;
|
||||
IXboxDStorageQueue* file_q = nullptr;
|
||||
hr = factory->CreateQueueX(&file_q_desc, kXboxQueueIid, reinterpret_cast<void**>(&file_q));
|
||||
check(hr == S_OK && file_q != nullptr, "CreateQueueX(file) must succeed (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
if (file_q && file && status) {
|
||||
uint8_t dest[128] = {};
|
||||
XboxRequest req{};
|
||||
req.options = 0;
|
||||
req.destination = dest;
|
||||
req.destination_size = sizeof(dest);
|
||||
req.source_ptr = file;
|
||||
req.file_offset = 64;
|
||||
req.source_size = sizeof(dest);
|
||||
file_q->EnqueueRequest(&req);
|
||||
file_q->EnqueueStatus(status, 0);
|
||||
file_q->Submit();
|
||||
check(wait_complete(status, 0), "file read status must complete");
|
||||
check(status->GetHResult(0) == S_OK, "file read status must be S_OK (hr=0x%08lx)",
|
||||
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);
|
||||
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)",
|
||||
static_cast<unsigned long>(status->GetHResult(1)));
|
||||
|
||||
/* 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;
|
||||
std::memset(&record, 0xa5, sizeof(record));
|
||||
unsigned char before[sizeof(record)];
|
||||
std::memcpy(before, &record, sizeof(record));
|
||||
file_q->RetrieveErrorRecord(&record);
|
||||
check(std::memcmp(&record, before, sizeof(record)) == 0,
|
||||
"Xbox RetrieveErrorRecord must leave the caller's buffer unchanged");
|
||||
file_q->Close();
|
||||
file_q->Release();
|
||||
}
|
||||
|
||||
/* Slot 10: CreateQueueX (memory source) and memory-to-memory transfer. */
|
||||
XboxQueueDesc mem_q_desc{};
|
||||
mem_q_desc.source_type = 1;
|
||||
mem_q_desc.capacity = 64;
|
||||
mem_q_desc.priority = 1;
|
||||
mem_q_desc.name = "xbox_mem_queue";
|
||||
mem_q_desc.flags = 1;
|
||||
IXboxDStorageQueue* mem_q = nullptr;
|
||||
hr = factory->CreateQueueX(&mem_q_desc, kXboxQueueIid, reinterpret_cast<void**>(&mem_q));
|
||||
check(hr == S_OK && mem_q != nullptr, "CreateQueueX(memory) must succeed (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
if (mem_q && status) {
|
||||
uint8_t dest[64] = {};
|
||||
XboxRequest req{};
|
||||
req.options = 0x400000ull;
|
||||
req.destination = dest;
|
||||
req.destination_size = sizeof(dest);
|
||||
req.source_ptr = payload + 32;
|
||||
req.source_size = sizeof(dest);
|
||||
mem_q->EnqueueRequest(&req);
|
||||
mem_q->EnqueueStatus(status, 0);
|
||||
mem_q->Submit();
|
||||
check(wait_complete(status, 0), "memory copy status must complete");
|
||||
check(status->GetHResult(0) == S_OK, "memory copy status must be S_OK (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(status->GetHResult(0)));
|
||||
check(std::memcmp(dest, payload + 32, sizeof(dest)) == 0, "memory copy bytes must match payload[32..96]");
|
||||
|
||||
/* A rejected null fence still signals the queue's error event. */
|
||||
mem_q->EnqueueSignal(nullptr, 1);
|
||||
mem_q->Submit();
|
||||
const HANDLE error_event = mem_q->GetErrorEvent();
|
||||
check(error_event != nullptr && WaitForSingleObject(error_event, 5000) == WAIT_OBJECT_0,
|
||||
"the error event must signal after the rejected signal is processed");
|
||||
|
||||
XboxRequest null_src = req;
|
||||
null_src.source_ptr = nullptr;
|
||||
mem_q->EnqueueRequest(&null_src);
|
||||
mem_q->EnqueueStatus(status, 1);
|
||||
mem_q->Submit();
|
||||
check(wait_complete(status, 1) && status->GetHResult(1) == E_INVALIDARG,
|
||||
"a null memory source must report E_INVALIDARG through queue status");
|
||||
mem_q->Close();
|
||||
mem_q->Release();
|
||||
}
|
||||
|
||||
/* Error paths on a fresh file queue. The fixture checks exact rejected
|
||||
* methods and HRESULTs in the fresh log without using an Xbox record layout. */
|
||||
IXboxDStorageQueue* err_q = nullptr;
|
||||
XboxQueueDesc err_desc = file_q_desc;
|
||||
err_desc.name = "xbox_error_queue";
|
||||
hr = factory->CreateQueueX(&err_desc, kXboxQueueIid, reinterpret_cast<void**>(&err_q));
|
||||
check(hr == S_OK && err_q != nullptr, "CreateQueueX(error paths) must succeed (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
if (err_q && status) {
|
||||
const HANDLE error_event = err_q->GetErrorEvent();
|
||||
/* A memory-source request (option 0x400000, as on the memory queue above) on a
|
||||
* file queue is rejected before its source pointer is touched. */
|
||||
uint8_t dest[16] = {};
|
||||
XboxRequest bad_src{};
|
||||
bad_src.options = 0x400000ull;
|
||||
bad_src.destination = dest;
|
||||
bad_src.destination_size = sizeof(dest);
|
||||
bad_src.source_ptr = payload;
|
||||
bad_src.source_size = sizeof(dest);
|
||||
err_q->EnqueueRequest(&bad_src);
|
||||
err_q->Submit();
|
||||
check(error_event != nullptr && WaitForSingleObject(error_event, 5000) == WAIT_OBJECT_0,
|
||||
"error event must signal for a memory request on a file queue");
|
||||
|
||||
/* A source/destination size mismatch on an otherwise valid file request. */
|
||||
XboxRequest mismatch{};
|
||||
mismatch.destination = dest;
|
||||
mismatch.destination_size = sizeof(dest);
|
||||
mismatch.source_ptr = file;
|
||||
mismatch.source_size = sizeof(dest) - 1;
|
||||
err_q->EnqueueRequest(&mismatch);
|
||||
err_q->Submit();
|
||||
|
||||
/* A status index past the array's capacity (2). */
|
||||
err_q->EnqueueStatus(status, 5);
|
||||
err_q->Submit();
|
||||
|
||||
/* An enqueue after Close is dropped and logged, not run. */
|
||||
err_q->Close();
|
||||
uint8_t after_close[16] = {};
|
||||
XboxRequest late{};
|
||||
late.destination = after_close;
|
||||
late.destination_size = sizeof(after_close);
|
||||
late.source_ptr = file;
|
||||
late.source_size = sizeof(after_close);
|
||||
err_q->EnqueueRequest(&late);
|
||||
err_q->Release();
|
||||
}
|
||||
|
||||
if (status) status->Release();
|
||||
if (file) {
|
||||
file->Close();
|
||||
file->Release();
|
||||
}
|
||||
factory->Release();
|
||||
DeleteFileW(temp_file);
|
||||
|
||||
{
|
||||
check(file_contains(log_path, "\"event\":\"dstorage_get_factory\",\"detail\":\"dispatch xbox_com=IDStorageFactoryX\""),
|
||||
"log must record Xbox factory dispatch");
|
||||
check(file_contains(log_path, "xbox size=33554432 has no effect"),
|
||||
"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[10]::RetrieveErrorRecord"),
|
||||
"log must record the unimplemented Xbox error-record output");
|
||||
const auto check_rejection = [&](const char* method, HRESULT hr) {
|
||||
char needle[96];
|
||||
std::snprintf(needle, sizeof(needle), "xbox %s hr=0x%08lx", method, static_cast<unsigned long>(hr));
|
||||
check(file_contains(log_path, needle), "log must record: %s", needle);
|
||||
};
|
||||
check_rejection("EnqueueSignal", E_DSTORAGE_INVALID_FENCE);
|
||||
check_rejection("EnqueueRequest", E_DSTORAGE_INVALID_SOURCE_TYPE);
|
||||
check_rejection("EnqueueRequest", E_DSTORAGE_INVALID_DESTINATION_SIZE);
|
||||
check_rejection("EnqueueStatus", E_DSTORAGE_INDEX_BOUND);
|
||||
}
|
||||
|
||||
if (g_failed != 0) {
|
||||
std::fprintf(stderr, "FAIL: test_xcrdapi_xbox (%d failed)\n", g_failed);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_xcrdapi_xbox\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "xg_texture.h"
|
||||
|
||||
@@ -468,7 +469,9 @@ static void test_copies() {
|
||||
}
|
||||
|
||||
static void test_swizzle_placeholder() {
|
||||
const uint32_t modes[] = {BX_XG_LAYOUT_SW_64KB_S, BX_XG_LAYOUT_SW_64KB_D, BX_XG_LAYOUT_SW_64KB_R};
|
||||
/* SW_64KB_S is implemented (32 bpp + the BC family); only D and R remain
|
||||
* E_NOTIMPL for every tiled query. */
|
||||
const uint32_t modes[] = {BX_XG_LAYOUT_SW_64KB_D, BX_XG_LAYOUT_SW_64KB_R};
|
||||
for (uint32_t mode : modes) {
|
||||
bx_xg_resource_desc desc = desc_2d(DXGI_FORMAT_BC7_UNORM, 32, 32, 1, 0, mode);
|
||||
void* object = nullptr;
|
||||
@@ -515,6 +518,370 @@ static void test_swizzle_placeholder() {
|
||||
"suggest stays on the implemented mode");
|
||||
}
|
||||
|
||||
/*
|
||||
* SW_64KB_S at 32 bpp, the one tiled mode BetterXen implements (#505).
|
||||
*
|
||||
* The expected byte offsets below are re-derived here from Microsoft's public
|
||||
* D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE 32-bpp masks - xBytes pdep mask
|
||||
* 0xAA8F, y pdep mask 0x5570 - using this file's own pdep, NOT read out of the
|
||||
* shim. The two sources agree at 32 bpp, which is why this mode is the one
|
||||
* implemented (AddrLib is the other; MIT).
|
||||
*/
|
||||
static uint32_t test_pdep(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; bit != 0 && mask != 0; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & bit) {
|
||||
out |= lowest;
|
||||
}
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Expected byte offset of texel (x, y) inside a 64 KiB 32-bpp S tile. */
|
||||
static uint64_t expected_sw64kb_s_32bpp(uint32_t x, uint32_t y) {
|
||||
return uint64_t(test_pdep(x * 4u, 0xAA8Fu) | test_pdep(y, 0x5570u));
|
||||
}
|
||||
|
||||
static void test_sw64kb_s_32bpp() {
|
||||
bx_xg_resource_desc desc = desc_2d(DXGI_FORMAT_R8G8B8A8_UNORM, 128, 128, 1, 1, BX_XG_LAYOUT_SW_64KB_S);
|
||||
void* object = nullptr;
|
||||
check_hr("s64 create", XGCreateTextureComputer(&desc, &object), S_OK);
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
if (!computer) {
|
||||
return;
|
||||
}
|
||||
|
||||
check_hr("s64 align", computer->lpVtbl->GetResourceBaseAlignmentBytes(computer, nullptr), E_POINTER);
|
||||
|
||||
/* An implemented tiled resource reports the 64 KiB tile: base alignment,
|
||||
* size, and the single-subresource layout all describe that one tile. */
|
||||
uint64_t align = 0;
|
||||
check_hr("s64 align value", computer->lpVtbl->GetResourceBaseAlignmentBytes(computer, &align), S_OK);
|
||||
check(align == 65536u, "s64 base alignment is the 64 KiB tile");
|
||||
uint64_t size = 0;
|
||||
check_hr("s64 size", computer->lpVtbl->GetResourceSizeBytes(computer, &size), S_OK);
|
||||
check(size == 65536u, "s64 resource size is the 64 KiB tile");
|
||||
bx_xg_placed_footprint layout{};
|
||||
uint32_t rows = 0;
|
||||
uint64_t row_bytes = 0;
|
||||
uint64_t total = 0;
|
||||
check_hr("s64 layout",
|
||||
computer->lpVtbl->GetResourceLayout(computer, 0, 1, 0, &layout, &rows, &row_bytes, &total), S_OK);
|
||||
check(layout.offset == 0u && total == 65536u, "s64 layout describes the single tile");
|
||||
uint64_t mip_offset = 0;
|
||||
check_hr("s64 mip offset", computer->lpVtbl->GetMipLevelOffsetBytes(computer, 0, 0, &mip_offset), S_OK);
|
||||
check(mip_offset == 0u, "s64 single mip starts at the tile base");
|
||||
check_hr("s64 mip out of range",
|
||||
computer->lpVtbl->GetMipLevelOffsetBytes(computer, 0, 1, &mip_offset), E_INVALIDARG);
|
||||
|
||||
/* A spread of texels, including the axes, the corners and a few interior
|
||||
* points, checked against the independently computed expectation. */
|
||||
const uint32_t points[][2] = {
|
||||
{0, 0}, {1, 0}, {4, 0}, {8, 0}, {16, 0}, {64, 0}, {127, 0},
|
||||
{0, 1}, {0, 4}, {0, 8}, {0, 16}, {0, 64}, {0, 127},
|
||||
{3, 3}, {17, 5}, {127, 127}, {64, 64}, {100, 27},
|
||||
};
|
||||
for (const auto& point : points) {
|
||||
uint64_t offset = 0xEEEEEEEEEEEEEEEEull;
|
||||
check_hr("s64 texel",
|
||||
computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, point[0], point[1], 0, &offset),
|
||||
S_OK);
|
||||
check(offset == expected_sw64kb_s_32bpp(point[0], point[1]), "s64 texel offset matches D3D12 masks");
|
||||
}
|
||||
|
||||
/* Distinct texels must map to distinct, in-tile, 4-byte-aligned offsets. */
|
||||
bool bijective = true;
|
||||
bool aligned = true;
|
||||
std::vector<uint8_t> seen(65536, 0);
|
||||
for (uint32_t y = 0; y < 128 && bijective; ++y) {
|
||||
for (uint32_t x = 0; x < 128 && bijective; ++x) {
|
||||
uint64_t offset = 0;
|
||||
if (computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, x, y, 0, &offset) != S_OK) {
|
||||
bijective = false;
|
||||
break;
|
||||
}
|
||||
if (offset >= 65536u || seen[size_t(offset)] != 0) {
|
||||
bijective = false;
|
||||
break;
|
||||
}
|
||||
if (offset % 4u != 0) {
|
||||
aligned = false;
|
||||
}
|
||||
seen[size_t(offset)] = 1;
|
||||
}
|
||||
}
|
||||
check(bijective, "s64 is a bijection over the 128x128 tile");
|
||||
check(aligned, "s64 offsets stay 4-byte aligned");
|
||||
|
||||
/* Out-of-tile texels are rejected. */
|
||||
uint64_t offset = 0;
|
||||
check_hr("s64 x out of tile",
|
||||
computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, 128, 0, 0, &offset), E_INVALIDARG);
|
||||
check_hr("s64 y out of tile",
|
||||
computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, 0, 128, 0, &offset), E_INVALIDARG);
|
||||
|
||||
release_computer(computer);
|
||||
|
||||
/* The modes and shapes that stay unimplemented must still say so. */
|
||||
bx_xg_resource_desc d_desc = desc_2d(DXGI_FORMAT_R8G8B8A8_UNORM, 128, 128, 1, 1, BX_XG_LAYOUT_SW_64KB_D);
|
||||
void* d_object = nullptr;
|
||||
check_hr("s64 D create", XGCreateTextureComputer(&d_desc, &d_object), S_OK);
|
||||
auto* d_computer = static_cast<bx_xg_texture_computer*>(d_object);
|
||||
if (d_computer) {
|
||||
uint64_t d_offset = 0;
|
||||
check_hr("s64 D still notimpl",
|
||||
d_computer->lpVtbl->GetTexelElementOffsetBytes(d_computer, 0, 0, 0, 0, 0, &d_offset), E_NOTIMPL);
|
||||
release_computer(d_computer);
|
||||
}
|
||||
|
||||
check(XGSuggestSwizzleMode(BX_XG_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 128, 128, 1, 0, 1, 0) ==
|
||||
BX_XG_LAYOUT_LINEAR,
|
||||
"suggest still stays on the linear mode");
|
||||
}
|
||||
|
||||
/*
|
||||
* SW_64KB_S for the BC family (#505). One "texel" element is a 4x4 block, so
|
||||
* elemLog2 = log2(block_bytes): 8-byte blocks (BC1/BC4) and 16-byte blocks
|
||||
* (BC2/3/5/6H/7).
|
||||
*
|
||||
* The expected byte offsets are re-derived here from AMD's public AddrLib
|
||||
* (MIT) RB+ tables - GFX10_SW_64K_S_RBPLUS_PATINFO expanded through
|
||||
* GFX10_SW_PATTERN_NIBBLE01/2/3 - using this file's own pdep, NOT read out of
|
||||
* the shim. The masks below were expanded by hand from those nibble tables:
|
||||
* 8-byte (elemLog2=3): x 0xAAC8, y 0x5530, tile 128x64 blocks
|
||||
* 16-byte (elemLog2=4): x 0xAAC0, y 0x5530, tile 64x64 blocks
|
||||
* Each was checked to be a bijection over its 64 KiB tile.
|
||||
*/
|
||||
static uint64_t expected_sw64kb_s_bc(uint32_t block_bytes, uint32_t x, uint32_t y) {
|
||||
uint32_t x_mask = 0;
|
||||
uint32_t y_mask = 0;
|
||||
switch (block_bytes) {
|
||||
case 4u:
|
||||
x_mask = 0xAA8Cu;
|
||||
y_mask = 0x5570u;
|
||||
break;
|
||||
case 8u:
|
||||
x_mask = 0xAAC8u;
|
||||
y_mask = 0x5530u;
|
||||
break;
|
||||
default:
|
||||
x_mask = 0xAAC0u;
|
||||
y_mask = 0x5530u;
|
||||
break;
|
||||
}
|
||||
return uint64_t(test_pdep(x, x_mask) | test_pdep(y, y_mask));
|
||||
}
|
||||
|
||||
static void test_sw64kb_s_bc_format(uint32_t format, uint32_t block_bytes, uint32_t tile_bx, uint32_t tile_by, const char* name) {
|
||||
/* Size the texture to exactly one 64 KiB tile: tile_bx*4 x tile_by*4 texels. */
|
||||
bx_xg_resource_desc desc = desc_2d(format, tile_bx * 4u, tile_by * 4u, 1, 1, BX_XG_LAYOUT_SW_64KB_S);
|
||||
void* object = nullptr;
|
||||
check_hr(name, XGCreateTextureComputer(&desc, &object), S_OK);
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
if (!computer) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* An implemented tiled resource reports the 64 KiB tile: base alignment,
|
||||
* size, and the single-subresource layout all describe that one tile. */
|
||||
uint64_t align = 0;
|
||||
check_hr(name, computer->lpVtbl->GetResourceBaseAlignmentBytes(computer, &align), S_OK);
|
||||
check(align == 65536u, "s64 BC base alignment is the 64 KiB tile");
|
||||
uint64_t size = 0;
|
||||
check_hr(name, computer->lpVtbl->GetResourceSizeBytes(computer, &size), S_OK);
|
||||
check(size == 65536u, "s64 BC resource size is the 64 KiB tile");
|
||||
bx_xg_placed_footprint layout{};
|
||||
uint32_t rows = 0;
|
||||
uint64_t row_bytes = 0;
|
||||
uint64_t total = 0;
|
||||
check_hr(name,
|
||||
computer->lpVtbl->GetResourceLayout(computer, 0, 1, 0, &layout, &rows, &row_bytes, &total), S_OK);
|
||||
check(layout.offset == 0u && total == 65536u, "s64 BC layout describes the single tile");
|
||||
uint64_t mip_offset = 0;
|
||||
check_hr(name, computer->lpVtbl->GetMipLevelOffsetBytes(computer, 0, 0, &mip_offset), S_OK);
|
||||
check(mip_offset == 0u, "s64 BC single mip starts at the tile base");
|
||||
|
||||
/* A spread of block coordinates, including the axes, the corners and a few
|
||||
* interior points, checked against the independently computed expectation.
|
||||
* x/y are TEXEL coordinates; the block index is x/4, y/4. */
|
||||
const uint32_t points[][2] = {
|
||||
{0, 0}, {4, 0}, {8, 0}, {16, 0}, {32, 0},
|
||||
{0, 4}, {0, 8}, {0, 16}, {0, 32},
|
||||
{12, 12}, {20, 8}, {36, 24},
|
||||
};
|
||||
for (const auto& point : points) {
|
||||
if (point[0] >= tile_bx * 4u || point[1] >= tile_by * 4u) {
|
||||
continue;
|
||||
}
|
||||
const uint32_t bx = point[0] / 4u;
|
||||
const uint32_t by = point[1] / 4u;
|
||||
uint64_t offset = 0xEEEEEEEEEEEEEEEEull;
|
||||
check_hr(name,
|
||||
computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, point[0], point[1], 0, &offset),
|
||||
S_OK);
|
||||
check(offset == expected_sw64kb_s_bc(block_bytes, bx, by), "s64 BC texel offset matches AddrLib masks");
|
||||
/* Intra-block texels (the 4x4 texels inside one BC block) all share the
|
||||
* block's byte offset. */
|
||||
for (uint32_t dy = 0; dy < 4u; ++dy) {
|
||||
for (uint32_t dx = 0; dx < 4u; ++dx) {
|
||||
uint64_t intra = 0xEEEEEEEEEEEEEEEEull;
|
||||
check_hr(name,
|
||||
computer->lpVtbl->GetTexelElementOffsetBytes(
|
||||
computer, 0, 0, bx * 4u + dx, by * 4u + dy, 0, &intra),
|
||||
S_OK);
|
||||
check(intra == offset, "s64 BC intra-block texels share the block offset");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Distinct blocks must map to distinct, in-tile, block-aligned offsets. */
|
||||
bool bijective = true;
|
||||
bool aligned = true;
|
||||
std::vector<uint8_t> seen(65536, 0);
|
||||
for (uint32_t by = 0; by < tile_by && bijective; ++by) {
|
||||
for (uint32_t bx = 0; bx < tile_bx && bijective; ++bx) {
|
||||
uint64_t offset = 0;
|
||||
if (computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, bx * 4u, by * 4u, 0, &offset) != S_OK) {
|
||||
bijective = false;
|
||||
break;
|
||||
}
|
||||
if (offset >= 65536u || seen[size_t(offset)] != 0) {
|
||||
bijective = false;
|
||||
break;
|
||||
}
|
||||
if (offset % block_bytes != 0) {
|
||||
aligned = false;
|
||||
}
|
||||
seen[size_t(offset)] = 1;
|
||||
}
|
||||
}
|
||||
check(bijective, "s64 BC is a bijection over the tile");
|
||||
check(aligned, "s64 BC offsets stay block-aligned");
|
||||
|
||||
/* Out-of-tile texels are rejected. */
|
||||
uint64_t offset = 0;
|
||||
check_hr("s64 BC x out of tile",
|
||||
computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, tile_bx * 4u, 0, 0, &offset), E_INVALIDARG);
|
||||
check_hr("s64 BC y out of tile",
|
||||
computer->lpVtbl->GetTexelElementOffsetBytes(computer, 0, 0, 0, tile_by * 4u, 0, &offset), E_INVALIDARG);
|
||||
|
||||
release_computer(computer);
|
||||
}
|
||||
|
||||
static void test_sw64kb_s_bc() {
|
||||
/* 8-byte blocks: BC1 and BC4. Tile is 128x64 blocks = 512x256 texels. */
|
||||
test_sw64kb_s_bc_format(DXGI_FORMAT_BC1_UNORM, 8u, 128u, 64u, "s64 BC1");
|
||||
test_sw64kb_s_bc_format(DXGI_FORMAT_BC4_UNORM, 8u, 128u, 64u, "s64 BC4");
|
||||
/* 16-byte blocks: BC2/3/5/6H/7. Tile is 64x64 blocks = 256x256 texels. */
|
||||
test_sw64kb_s_bc_format(DXGI_FORMAT_BC2_UNORM, 16u, 64u, 64u, "s64 BC2");
|
||||
test_sw64kb_s_bc_format(DXGI_FORMAT_BC3_UNORM, 16u, 64u, 64u, "s64 BC3");
|
||||
test_sw64kb_s_bc_format(DXGI_FORMAT_BC5_UNORM, 16u, 64u, 64u, "s64 BC5");
|
||||
test_sw64kb_s_bc_format(DXGI_FORMAT_BC6H_UF16, 16u, 64u, 64u, "s64 BC6H");
|
||||
test_sw64kb_s_bc_format(DXGI_FORMAT_BC7_UNORM, 16u, 64u, 64u, "s64 BC7");
|
||||
}
|
||||
|
||||
/*
|
||||
* CopyIntoSubresource / CopyFromSubresource round trip for an implemented
|
||||
* SW_64KB_S resource (#505). The image is tight rows of blocks; the resource
|
||||
* is one 64 KiB tile. After the copy, every block's byte offset inside the
|
||||
* tile must equal the independently derived AddrLib S offset, and the
|
||||
* readback must be byte-identical to the image.
|
||||
*/
|
||||
static void test_sw64kb_s_round_trip(uint32_t format, uint32_t block_bytes, uint32_t block_dim, uint32_t tile_bx, uint32_t tile_by, const char* name) {
|
||||
bx_xg_resource_desc desc = desc_2d(format, tile_bx * block_dim, tile_by * block_dim, 1, 1, BX_XG_LAYOUT_SW_64KB_S);
|
||||
void* object = nullptr;
|
||||
check_hr(name, XGCreateTextureComputer(&desc, &object), S_OK);
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
if (!computer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const size_t image_bytes = size_t(tile_bx) * size_t(tile_by) * block_bytes;
|
||||
uint8_t* image = alloc_bytes(image_bytes, 0);
|
||||
uint8_t* resource = alloc_bytes(65536u + 32u, 0);
|
||||
uint8_t* readback = alloc_bytes(image_bytes + 32u, 0xA5);
|
||||
if (!image || !resource || !readback) {
|
||||
std::free(image);
|
||||
std::free(resource);
|
||||
std::free(readback);
|
||||
release_computer(computer);
|
||||
return;
|
||||
}
|
||||
std::memset(resource + 65536u, 0xA5, 32u);
|
||||
for (size_t i = 0; i < image_bytes; ++i) {
|
||||
image[i] = static_cast<uint8_t>((i * 13u + 7u) & 0xFFu);
|
||||
}
|
||||
|
||||
check_hr(name,
|
||||
computer->lpVtbl->CopyIntoSubresource(
|
||||
computer, resource, 65536u, 0, image, image_bytes, static_cast<uint32_t>(tile_bx * block_bytes), 0),
|
||||
S_OK);
|
||||
check(bytes_are(resource + 65536u, 32u, 0xA5), "s64 copy leaves the canary");
|
||||
|
||||
/* Every block's byte offset inside the tile must match the AddrLib S
|
||||
* offset, and the bytes there must be the image's block. */
|
||||
bool offsets_ok = true;
|
||||
for (uint32_t by = 0; by < tile_by && offsets_ok; ++by) {
|
||||
for (uint32_t bx = 0; bx < tile_bx && offsets_ok; ++bx) {
|
||||
const uint64_t expected = expected_sw64kb_s_bc(block_bytes, bx, by);
|
||||
const uint64_t image_off = (uint64_t(by) * tile_bx + bx) * block_bytes;
|
||||
if (expected >= 65536u || std::memcmp(resource + expected, image + image_off, block_bytes) != 0) {
|
||||
offsets_ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
check(offsets_ok, "s64 copy lands each block at its AddrLib S offset");
|
||||
|
||||
std::memset(readback, 0xA5, image_bytes + 32u);
|
||||
check_hr(name,
|
||||
computer->lpVtbl->CopyFromSubresource(
|
||||
computer, readback, image_bytes, static_cast<uint32_t>(tile_bx * block_bytes), 0, resource, 65536u, 0),
|
||||
S_OK);
|
||||
check(std::memcmp(readback, image, image_bytes) == 0, "s64 round trip is byte identical");
|
||||
check(bytes_are(readback + image_bytes, 32u, 0xA5), "s64 readback leaves its canary");
|
||||
|
||||
std::free(image);
|
||||
std::free(resource);
|
||||
std::free(readback);
|
||||
release_computer(computer);
|
||||
}
|
||||
|
||||
/*
|
||||
* CopyFromSubresource into an image buffer too small for the caller's row
|
||||
* pitch must be refused before any byte lands past the buffer. 2x2 RGBA8 with
|
||||
* a 1000-byte pitch needs 1008 bytes; the buffer holds 1004 plus a canary.
|
||||
* Before the direction-aware bounds check this wrote 4 bytes past the buffer.
|
||||
*/
|
||||
static void test_sw64kb_s_copy_from_bounds() {
|
||||
bx_xg_resource_desc desc = desc_2d(DXGI_FORMAT_R8G8B8A8_UNORM, 2u, 2u, 1, 1, BX_XG_LAYOUT_SW_64KB_S);
|
||||
void* object = nullptr;
|
||||
check_hr("s64 short readback create", XGCreateTextureComputer(&desc, &object), S_OK);
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
if (!computer) {
|
||||
return;
|
||||
}
|
||||
uint8_t* resource = alloc_bytes(65536u, 0x11);
|
||||
uint8_t* readback = alloc_bytes(1004u + 32u, 0xA5);
|
||||
if (resource && readback) {
|
||||
check_hr("s64 short readback",
|
||||
computer->lpVtbl->CopyFromSubresource(computer, readback, 1004u, 1000u, 0, resource, 65536u, 0),
|
||||
E_INVALIDARG);
|
||||
check(bytes_are(readback + 1004u, 32u, 0xA5), "s64 short readback leaves its canary");
|
||||
}
|
||||
std::free(resource);
|
||||
std::free(readback);
|
||||
release_computer(computer);
|
||||
}
|
||||
|
||||
static void test_sw64kb_s_round_trips() {
|
||||
test_sw64kb_s_round_trip(DXGI_FORMAT_R8G8B8A8_UNORM, 4u, 1u, 128u, 128u, "s64 rgba round trip");
|
||||
test_sw64kb_s_round_trip(DXGI_FORMAT_BC1_UNORM, 8u, 4u, 128u, 64u, "s64 bc1 round trip");
|
||||
test_sw64kb_s_round_trip(DXGI_FORMAT_BC7_UNORM, 16u, 4u, 64u, 64u, "s64 bc7 round trip");
|
||||
test_sw64kb_s_copy_from_bounds();
|
||||
}
|
||||
|
||||
static bool row_is(const uint8_t* row, uint8_t value) {
|
||||
return row[0] == value && row[1] == value && row[2] == value && row[3] == value;
|
||||
}
|
||||
@@ -642,6 +1009,9 @@ int main() {
|
||||
test_overlapping_copies();
|
||||
test_large_array_offsets();
|
||||
test_swizzle_placeholder();
|
||||
test_sw64kb_s_32bpp();
|
||||
test_sw64kb_s_bc();
|
||||
test_sw64kb_s_round_trips();
|
||||
test_refcount();
|
||||
|
||||
if (g_failures != 0) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
add_executable(test_xgameruntime main.cpp)
|
||||
target_include_directories(test_xgameruntime PRIVATE "${BX_ROOT_DIR}/shims/xgameruntime")
|
||||
target_link_libraries(test_xgameruntime PRIVATE xgameruntime kernel32)
|
||||
|
||||
# Keep the same executable name to exercise the marker check and storage isolation.
|
||||
add_executable(test_xgameruntime_unentitled main.cpp)
|
||||
target_compile_definitions(test_xgameruntime_unentitled PRIVATE BX_TEST_UNENTITLED)
|
||||
target_include_directories(test_xgameruntime_unentitled PRIVATE "${BX_ROOT_DIR}/shims/xgameruntime")
|
||||
target_link_libraries(test_xgameruntime_unentitled PRIVATE xgameruntime kernel32)
|
||||
set_target_properties(test_xgameruntime_unentitled PROPERTIES
|
||||
OUTPUT_NAME test_xgameruntime
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include "task_queue.h"
|
||||
|
||||
namespace {
|
||||
|
||||
struct Async {
|
||||
@@ -163,6 +165,201 @@ bool valid_utf8(const unsigned char* s, size_t n) {
|
||||
extern "C" __declspec(dllexport) void BetterXenSyntheticStoreFixture() {}
|
||||
#endif
|
||||
|
||||
// A non-zero delay must not run early, and must run once it is due. The delayed
|
||||
// entry point is IXGameRuntimeCore slot 19, reached through QueryApiImpl; it is
|
||||
// not an export, so it is called through the COM vtable exactly as a title
|
||||
// would. Margins are generous so a slow host does not make this flaky: assert
|
||||
// "not run" while the deadline is far away, then require it to run after a
|
||||
// margin that is well past the deadline.
|
||||
struct DelayRecord {
|
||||
std::atomic<unsigned> runs{0};
|
||||
std::atomic<unsigned> cancels{0};
|
||||
unsigned char canary = 0xA5;
|
||||
};
|
||||
|
||||
void CALLBACK record_delay(void* context, bool canceled) {
|
||||
auto& record = *static_cast<DelayRecord*>(context);
|
||||
CHECK(record.canary == 0xA5);
|
||||
if (canceled) ++record.cancels;
|
||||
else ++record.runs;
|
||||
}
|
||||
|
||||
// Records the order in which callbacks run, so FIFO can be checked directly.
|
||||
struct OrderRecord {
|
||||
std::atomic<unsigned> next{0};
|
||||
unsigned first = ~0u;
|
||||
unsigned second = ~0u;
|
||||
};
|
||||
|
||||
void CALLBACK record_order(void* context, bool canceled) {
|
||||
CHECK(!canceled);
|
||||
auto& record = *static_cast<OrderRecord*>(context);
|
||||
const unsigned slot = record.next.fetch_add(1);
|
||||
if (slot == 0) record.first = 1;
|
||||
else if (slot == 1) record.second = 2;
|
||||
}
|
||||
|
||||
void check_delayed_callback(HRESULT(WINAPI* query_api)(const GUID*, const GUID*, void**)) {
|
||||
constexpr GUID kCore = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
|
||||
void* core = nullptr;
|
||||
CHECK(SUCCEEDED(query_api(&kCore, &kCore, &core)) && core);
|
||||
auto** vtbl = *static_cast<void***>(core);
|
||||
using SubmitDelayed = HRESULT(WINAPI*)(void*, void*, uint32_t, uint32_t, void*, void (CALLBACK*)(void*, bool));
|
||||
auto submit_delayed = reinterpret_cast<SubmitDelayed>(vtbl[19]);
|
||||
// A 100 ms delay leaves a wide band in which "not yet" is unambiguous, and a
|
||||
// 250 ms sleep is 2.5x the deadline, so a slow host still passes. Every
|
||||
// scenario gets its own queue, so a long-delay case cannot hold the head of
|
||||
// a later one.
|
||||
constexpr uint32_t delay_ms = 100;
|
||||
constexpr DWORD early_margin_ms = 10;
|
||||
constexpr DWORD late_margin_ms = 250;
|
||||
|
||||
// delay_ms == 0 keeps the old immediate behaviour: due now, runs on the
|
||||
// next dispatch pass.
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
DelayRecord zero{};
|
||||
CHECK(submit_delayed(core, queue, work, 0, &zero, record_delay) == S_OK);
|
||||
CHECK(XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(zero.runs.load() == 1 && zero.cancels.load() == 0);
|
||||
XTaskQueueCloseHandle(queue);
|
||||
}
|
||||
|
||||
// A non-zero delay must not run before its deadline, and must run after it.
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
DelayRecord delayed{};
|
||||
CHECK(submit_delayed(core, queue, work, delay_ms, &delayed, record_delay) == S_OK);
|
||||
CHECK(!XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(delayed.runs.load() == 0 && delayed.cancels.load() == 0);
|
||||
Sleep(early_margin_ms);
|
||||
CHECK(!XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(delayed.runs.load() == 0);
|
||||
Sleep(late_margin_ms);
|
||||
CHECK(XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(delayed.runs.load() == 1 && delayed.cancels.load() == 0 && delayed.canary == 0xA5);
|
||||
XTaskQueueCloseHandle(queue);
|
||||
}
|
||||
|
||||
// A timeout that expires well before the deadline reports "nothing ran" and
|
||||
// returns without spinning: the 500 ms wait ends at the timeout, five times
|
||||
// short of the 2500 ms delay.
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
DelayRecord timed{};
|
||||
CHECK(submit_delayed(core, queue, work, 2500, &timed, record_delay) == S_OK);
|
||||
const DWORD before = GetTickCount();
|
||||
CHECK(!XTaskQueueDispatch(queue, work, timeout_ms / 10));
|
||||
CHECK(GetTickCount() - before < timeout_ms / 2);
|
||||
CHECK(timed.runs.load() == 0);
|
||||
XTaskQueueCloseHandle(queue);
|
||||
}
|
||||
|
||||
// FIFO: a delayed head holds the lane, so a task queued behind it does not
|
||||
// overtake it. Both run, in submission order.
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
OrderRecord fifo{};
|
||||
CHECK(submit_delayed(core, queue, work, delay_ms, &fifo, record_order) == S_OK);
|
||||
CHECK(submit_delayed(core, queue, work, 0, &fifo, record_order) == S_OK);
|
||||
CHECK(!XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(fifo.next.load() == 0);
|
||||
Sleep(early_margin_ms);
|
||||
CHECK(!XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(fifo.next.load() == 0);
|
||||
Sleep(late_margin_ms);
|
||||
CHECK(XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(fifo.next.load() == 1 && fifo.first == 1);
|
||||
CHECK(XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(fifo.next.load() == 2 && fifo.second == 2);
|
||||
CHECK(!XTaskQueueDispatch(queue, work, 0));
|
||||
XTaskQueueCloseHandle(queue);
|
||||
}
|
||||
|
||||
// A delayed submission cancelled before its due time runs as cancelled, not
|
||||
// as a normal run: closing a manual queue drains it through Task::cancel.
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
DelayRecord cancelled{};
|
||||
CHECK(submit_delayed(core, queue, work, 60000, &cancelled, record_delay) == S_OK);
|
||||
CHECK(!XTaskQueueDispatch(queue, work, 0));
|
||||
CHECK(cancelled.cancels.load() == 0 && cancelled.runs.load() == 0);
|
||||
XTaskQueueCloseHandle(queue);
|
||||
CHECK(cancelled.cancels.load() == 1 && cancelled.runs.load() == 0);
|
||||
}
|
||||
|
||||
// The pool path must honour the delay too. A parallel work lane runs tasks
|
||||
// on a threadpool worker as soon as they are pushed, so this is the case
|
||||
// where an ungated worker would fire early.
|
||||
{
|
||||
void* pooled = nullptr;
|
||||
CHECK(XTaskQueueCreate(pool, manual, &pooled) == S_OK && pooled);
|
||||
DelayRecord async{};
|
||||
CHECK(submit_delayed(core, pooled, work, delay_ms, &async, record_delay) == S_OK);
|
||||
Sleep(early_margin_ms);
|
||||
CHECK(async.runs.load() == 0);
|
||||
Sleep(late_margin_ms);
|
||||
for (int i = 0; i < 200 && async.runs.load() == 0; ++i) Sleep(1);
|
||||
CHECK(async.runs.load() == 1 && async.cancels.load() == 0);
|
||||
XTaskQueueCloseHandle(pooled);
|
||||
}
|
||||
|
||||
// delay_ms == 0xFFFFFFFF is a valid uint32_t delay (~49.7 days). The wait
|
||||
// loop must never pass INFINITE to Sleep, because that is an infinite wait:
|
||||
// the loop would never re-check the deadline. Assert the chunk helper
|
||||
// clamps the maximum delay to a finite, positive chunk, then show the
|
||||
// callback still fires for that delay on a lane that only holds it until
|
||||
// the queue is closed (a full 49-day wait is obviously not run here).
|
||||
{
|
||||
using bx::gdk::finite_sleep_chunk_ms;
|
||||
using bx::gdk::kMaxFiniteSleepMs;
|
||||
CHECK(kMaxFiniteSleepMs == INFINITE - 1);
|
||||
CHECK(kMaxFiniteSleepMs == 0xFFFFFFFEu);
|
||||
// The exact remainder that used to be passed to Sleep as INFINITE.
|
||||
const uint32_t max_chunk = finite_sleep_chunk_ms(0xFFFFFFFFull);
|
||||
CHECK(max_chunk <= 0xFFFFFFFEu && max_chunk > 0);
|
||||
CHECK(max_chunk == 0xFFFFFFFEu);
|
||||
// Never INFINITE, whatever the remainder, and never a zero chunk.
|
||||
CHECK(finite_sleep_chunk_ms(0x100000000ull) == 0xFFFFFFFEu);
|
||||
CHECK(finite_sleep_chunk_ms(~0ull) == 0xFFFFFFFEu);
|
||||
CHECK(finite_sleep_chunk_ms(1) == 1);
|
||||
CHECK(finite_sleep_chunk_ms(0xFFFFFFFEull) == 0xFFFFFFFEu);
|
||||
CHECK(finite_sleep_chunk_ms(0xFFFFFFFDull) == 0xFFFFFFFDu);
|
||||
}
|
||||
|
||||
// The maximum delay is accepted and its callback still fires. A parallel
|
||||
// lane holds the task until its deadline, and closing the queue drains it
|
||||
// on a worker, so the callback runs without waiting out the 49 days.
|
||||
{
|
||||
void* pooled = nullptr;
|
||||
CHECK(XTaskQueueCreate(pool, manual, &pooled) == S_OK && pooled);
|
||||
DelayRecord record{};
|
||||
CHECK(submit_delayed(core, pooled, work, 0xFFFFFFFFu, &record, record_delay) == S_OK);
|
||||
Sleep(early_margin_ms);
|
||||
CHECK(record.runs.load() == 0 && record.cancels.load() == 0);
|
||||
XTaskQueueCloseHandle(pooled);
|
||||
for (int i = 0; i < 500 && record.runs.load() == 0; ++i) Sleep(1);
|
||||
CHECK(record.runs.load() == 1 && record.cancels.load() == 0 && record.canary == 0xA5);
|
||||
}
|
||||
|
||||
// Same maximum delay on a manual lane: closing it cancels the pending
|
||||
// task, which must still reach the callback rather than being lost.
|
||||
{
|
||||
void* queue = nullptr;
|
||||
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
|
||||
DelayRecord record{};
|
||||
CHECK(submit_delayed(core, queue, work, 0xFFFFFFFFu, &record, record_delay) == S_OK);
|
||||
CHECK(record.runs.load() == 0 && record.cancels.load() == 0);
|
||||
XTaskQueueCloseHandle(queue);
|
||||
CHECK(record.runs.load() == 0 && record.cancels.load() == 1 && record.canary == 0xA5);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
char profile[16]{};
|
||||
CHECK(GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile)) > 0);
|
||||
@@ -568,6 +765,8 @@ int main() {
|
||||
CHECK(SUCCEEDED(reg_ev(com_user, nullptr, nullptr, reinterpret_cast<void*>(+dummy_cb), &ev_tok)) && ev_tok != 0);
|
||||
CHECK(unreg_ev(com_user, ev_tok, false));
|
||||
CHECK(!unreg_ev(com_user, ev_tok, false));
|
||||
|
||||
check_delayed_callback(query_api);
|
||||
}
|
||||
|
||||
XGameRuntimeUninitialize();
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_xmem_external_charge main.cpp)
|
||||
target_include_directories(test_xmem_external_charge PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_xmem_external_charge PRIVATE xmem bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,71 @@
|
||||
// Synthetic check for bx_xmem_try_charge_external / bx_xmem_release_charge_external
|
||||
// (#550): an external charge counts against the same title cap as XMem's own
|
||||
// allocations, shows up in the reported stats, and an over-release is refused.
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xmem_external:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, \
|
||||
static_cast<unsigned long>(GetLastError())); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
int main() {
|
||||
SYSTEM_INFO sys{};
|
||||
GetSystemInfo(&sys);
|
||||
const SIZE_T page = sys.dwPageSize;
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
const uint64_t used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
|
||||
CHECK(used < stats.title_limit_bytes);
|
||||
// Only bookkeeping is charged; nothing of this size is allocated on the host.
|
||||
const uint64_t headroom = stats.title_limit_bytes - used;
|
||||
|
||||
// Graphics-first order: an external charge fills the cap...
|
||||
CHECK(bx_xmem_try_charge_external(headroom) == 1);
|
||||
CHECK(bx_xmem_try_charge_external(1) == 0);
|
||||
|
||||
// ...is visible in the reported usage, and peak never exceeds it...
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.committed_virtual_bytes + stats.allocated_physical_bytes == stats.title_limit_bytes);
|
||||
CHECK(stats.peak_committed_bytes <= stats.title_limit_bytes);
|
||||
bx_xmem_stats_t internal{};
|
||||
bx_xmem_get_internal_stats(&internal);
|
||||
CHECK(internal.committed_virtual_bytes == stats.committed_virtual_bytes);
|
||||
|
||||
// ...and a later XMem commit is refused against the same cap.
|
||||
SetLastError(0);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
|
||||
// An over-release is refused and leaves the outstanding charge in place.
|
||||
bx_xmem_release_charge_external(headroom + 1);
|
||||
CHECK(bx_xmem_try_charge_external(1) == 0);
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.committed_virtual_bytes + stats.allocated_physical_bytes == stats.title_limit_bytes);
|
||||
|
||||
// Releasing the real charge admits the same XMem commit again.
|
||||
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);
|
||||
CHECK(block != nullptr);
|
||||
CHECK(VirtualFree(block, 0, MEM_RELEASE));
|
||||
|
||||
std::printf("PASS: test_xmem_external_charge\n");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user